Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python Request for an exercise from homework

pythonenjoyer

New Coder
Hello! There is a task I'm not able to solve:
lzJKutP.png

I manage to put the corresponding number between the down and up boundary, but what I can't do is related to the printed result - I print a new row for every number while the task requires to print all numbers between the boundaries on one row.
 
Hello! There is a task I'm not able to solve:
lzJKutP.png

I manage to put the corresponding number between the down and up boundary, but what I can't do is related to the printed result - I print a new row for every number while the task requires to print all numbers between the boundaries on one row.
Hi there, can you post up what you have already done?
 
Hi there, can you post up what you have already done?
Python:
list_of_numbers = list(map(int, input().split(", ")))
index = 0
boundary = 0
boundary_numbers = []

while index != len(list_of_numbers):
    index += 1

    for number in list_of_numbers:
        if number <= boundary:
            boundary_numbers.append(number)
        else:
            boundary += 10
        print(f"Group of {boundary}'s: {boundary_numbers}")
 
You don't really need a while loop or use an index. A simple for loop will work.
Here is your example using a dict

Python:
boundry_dict = {} # Create a dict to hold key/value
boundry_num = 10 # Boundry starts at 10
numlist = [] # A list to hold the numbers
numbers = list(map(int, input('>> ').split(','))) # Get input separated by comma
numbers.sort() # Sort the numbers in case not sequenced
# Loop through the input
for number in numbers:
    if number < boundry_num: # If a number is less than boundry append to list
        numlist.append(number)
    else: # If all numbers less than boundry then increase boundry by 10
        boundry_num += 10
        numlist = [] # Clear the list
        numlist.append(number) if number < boundry_num else False # Without this it will miss a number
    boundry_dict[boundry_num] = numlist # Add the boundry number and list to dict
# Loop through the dict and display
for key, value in boundry_dict.items():
    print(f'Group of {key}\'s: {value}')

output
Code:
>> 3,5,9,10,15,18,22,29,30,45
Group of 10's: [3, 5, 9]
Group of 20's: [10, 15, 18]
Group of 30's: [22, 29]
Group of 40's: [30]
Group of 50's: [45]
 
Last edited:
You don't really need a while loop or use an index. A simple for loop will work.
Here is your example using a dict

Python:
boundry_dict = {} # Create a dict to hold key/value
boundry_num = 10 # Boundry starts at 10
numlist = [] # A list to hold the numbers
numbers = list(map(int, input('>> ').split(','))) # Get input separated by comma
numbers.sort() # Sort the numbers in case not sequenced
# Loop through the input
for number in numbers:
    if number < boundry_num: # If a number is less than boundry append to list
        numlist.append(number)
    else: # If all numbers less than boundry then increase boundry by 10
        boundry_num += 10
        numlist = [] # Clear the list
        numlist.append(number) if number < boundry_num else False # Without this it will miss a number
    boundry_dict[boundry_num] = numlist # Add the boundry number and list to dict
# Loop through the dict and display
for key, value in boundry_dict.items():
    print(f'Group of {key}\'s: {value}')

output
Code:
>> 3,5,9,10,15,18,22,29,30,45
Group of 10's: [3, 5, 9]
Group of 20's: [10, 15, 18]
Group of 30's: [22, 29]
Group of 40's: [30]
Group of 50's: [45]
There should be no sorting. And here is the result:
 

Attachments

  • Screenshot_1.png
    Screenshot_1.png
    37.7 KB · Views: 10
I'm going to post the code but still would like to see what you've tried.
Python:
# Set the first boundry
boundry = 10

# Set an empty list
group = []

# Set a dict with boundry as key and value as None
numdict = {boundry: None}

# This while loop is for some simple error checking of format entered.
# Needs to be whole numbers seperated by a comma
while True:
    try:
        # Get a list of numbers
        print('Enter a list of numbers seperated by a comma')
        numbers = list(map(int, input('>> ').split(',')))
        break
    except ValueError:
        print('Please use the correct format')

# Get a copy of the numbers list as you are not supposed to edit a list you are iteratiing over
num_cp = numbers.copy()

# Start the loop / will run as long as numbers list has a length > 0
while len(numbers) > 0:
    for number in num_cp:  # Loop through the list copy
        if number <= boundry: # If number is less than or equal to the boundry append to group
            group.append(number)
            numbers.remove(number) # Numbers has been used remove from original numbers list
    num_cp = numbers.copy() # update num_cp to reflect numbers list
    numdict[boundry] = group # Add group to dict using boundry as key
    boundry += 10 # Increase boundry by 10 for next group
    group = [] # Clear group list

# Display groups and list
for key, value in numdict.items():
    print(f'Group of {key}\'s: {value}')

output
Code:
Enter a list of numbers seperated by a comma
>> 8,12,38,3,17,19,25,35,50
Group of 10's: [8, 3]
Group of 20's: [12, 17, 19]
Group of 30's: [25]
Group of 40's: [38, 35]
Group of 50's: [50]


Enter a list of numbers seperated by a comma
>> 1,3,3,4,34,35,25,21,33
Group of 10's: [1, 3, 3, 4]
Group of 20's: []
Group of 30's: [25, 21]
Group of 40's: [34, 35, 33]
 
Here's my solution.. not elegant but it does work and I'm working on a second version that's
going to be much cleaner

Python:
import os
#Define variables
group10, group20, group30, group40, group50 = [], [], [], [], [] #Output lists
input1Str = "8,12,38,3,17,19,25,35,50"
input2Str = "1,3,3,4,34,35,25,21,33"

#main logic
def main():
    os.system('cls')
    #convert strings to lists
    count = 0
    input1Lst = (input1Str.split(","))
    input2Lst = (input2Str.split(","))

    #Loop through list #1
    for item1 in input1Lst:
        count = count + 1
        if int(item1) >= 1 and int(item1) <=10:
            group10.insert(count,item1)
        elif int(item1) >= 11 and int(item1) <= 20:
            group20.insert(count,item1)
        elif int(item1) >= 21 and int(item1) <= 30:
            group30.insert(count,item1)
        elif int(item1) >= 31 and int(item1) <= 40:
            group40.insert(count,item1)
        else:
            if int(item1) >= 41 and int(item1) <=50:
                group50.insert(count,item1)

    #Print out results.
    print ("String to group", input1Str)
    print ("Group of 10's",group10)
    print ("Group of 20's",group20)
    print ("Group of 30's",group30)
    print ("Group of 40's",group40)
    print ("Group of 50's",group50)

    #Loop through list #2
    #reset variables
    count = 0
    group10.clear()
    group20.clear()
    group30.clear()
    group40.clear()
    group50.clear()

    for item2 in input2Lst:
        count = count + 1
        if int(item2) >= 1 and int(item2) <=10:
            group10.insert(count,item2)
        elif int(item2) >= 11 and int(item2) <= 20:
            group20.insert(count,item2)
        elif int(item2) >= 21 and int(item2) <= 30:
            group30.insert(count,item2)
        elif int(item2) >= 31 and int(item2) <= 40:
            group40.insert(count,item2)
        else:
            if int(item2) >= 41 and int(item2) <=50:
                group50.insert(count,item2)

    #Print out results.
    print("==================================")
    print ("String to group", input2Str)
    print ("Group of 10's",group10)
    print ("Group of 20's",group20)
    print ("Group of 30's",group30)
    print ("Group of 40's",group40)
    print ("Group of 50's",group50)

if __name__ == '__main__':
    main()
Result
Code:
String to group 8,12,38,3,17,19,25,35,50
Group of 10's ['8', '3']
Group of 20's ['12', '17', '19']
Group of 30's ['25']
Group of 40's ['38', '35']
Group of 50's ['50']
==================================
String to group 1,3,3,4,34,35,25,21,33
Group of 10's ['1', '3', '3', '4']
Group of 20's []
Group of 30's ['25', '21']
Group of 40's ['34', '35', '33']
Group of 50's []
>>>
 
Last edited:
Final version..
I put a function and then I set it up so it randomly pics the numbers in the string
This was a fun exercise..
Jeff

Python:
from random import *
#Define variables
group10, group20, group30, group40, group50 = [], [], [], [], [] #Output lists

def processList(inputList,inputstr):
    count = 0
    #Loop through list #1
    for item1 in inputList:
        count = count + 1
        if int(item1) >= 1 and int(item1) <=10:
            group10.insert(count,item1)
        elif int(item1) >= 11 and int(item1) <= 20:
            group20.insert(count,item1)
        elif int(item1) >= 21 and int(item1) <= 30:
            group30.insert(count,item1)
        elif int(item1) >= 31 and int(item1) <= 40:
            group40.insert(count,item1)
        else:
            if int(item1) >= 41 and int(item1) <=50:
                group50.insert(count,item1)

    #Print out results..
    print ("String to group", inputstr)
    print ("Group of 10's",group10)
    print ("Group of 20's",group20)
    print ("Group of 30's",group30)
    print ("Group of 40's",group40)
    print ("Group of 50's",group50)
    print()

#start program
z = 1
while z <= 4:
    #convert strings to lists
    input1str = ""
    x = 1
    while x <= 11:
        y = (randint(1, 50))
        input1str = input1str + str(y) + " "
        x += 1

    input1Lst = (input1str.split(" "))
    del input1Lst[11]

    #Process List #1..
    processList(input1Lst,input1str)
    z += 1

The Results:
Code:
String to group 30 34 25 25 40 21 15 31 7 37 28
Group of 10's ['7']
Group of 20's ['15']
Group of 30's ['30', '25', '25', '21', '28']
Group of 40's ['34', '40', '31', '37']
Group of 50's []

String to group 37 29 1 14 43 43 50 22 36 19 24
Group of 10's ['7', '1']
Group of 20's ['15', '14', '19']
Group of 30's ['30', '25', '29', '25', '21', '28', '22', '24']
Group of 40's ['34', '37', '40', '31', '37', '36']
Group of 50's ['43', '43', '50']

String to group 31 6 23 45 50 41 7 25 16 2 6
Group of 10's ['7', '1', '6', '7', '2', '6']
Group of 20's ['15', '14', '19', '16']
Group of 30's ['30', '25', '29', '23', '25', '21', '28', '22', '25', '24']
Group of 40's ['34', '31', '37', '40', '31', '37', '36']
Group of 50's ['43', '43', '50', '45', '50', '41']

String to group 38 37 21 10 38 49 45 38 17 29 13
Group of 10's ['7', '1', '6', '7', '10', '2', '6']
Group of 20's ['15', '14', '19', '16', '17', '13']
Group of 30's ['30', '25', '29', '21', '23', '25', '21', '28', '22', '25', '29', '24']
Group of 40's ['34', '38', '37', '31', '37', '38', '40', '31', '38', '37', '36']
Group of 50's ['43', '43', '50', '45', '50', '41', '49', '45']
 
@Jeff61 You should rethink your approach.
A program should be generic in nature.
Right now this one is restricted by the number of list that are set eg group10, group40 = [], [] and so forth
Have a look at the way I set up groups. Groups list are created on as needed basis.
You are clearing each group list. I do it once after I set the value for the dict and then reuse.
There are more ways to improve the code. There are many ways to improve the code I wrote.
I often rewrite code several times before I'm satisfied. Even then I'll still rewrite.
Read through the comments I wrote on the code. It's a brief description of what each section is doing
Just my 2 cents.
 
@Jeff61 You should rethink your approach.
A program should be generic in nature.
Right now this one is restricted by the number of list that are set eg group10, group40 = [], [] and so forth
Have a look at the way I set up groups. Groups list are created on as needed basis.
You are clearing each group list. I do it once after I set the value for the dict and then reuse.
There are more ways to improve the code. There are many ways to improve the code I wrote.
I often rewrite code several times before I'm satisfied. Even then I'll still rewrite.
Read through the comments I wrote on the code. It's a brief description of what each section is doing
Just my 2 cents.
I'll look that over and adjust mine accordingly. Thanks for the input
Jeff
 
One more quick example using a class and dunder method. Overkill much

Python:
from random import sample

boundry = 10 # Starting boundry
group = [] # Empty list
groupdict = {boundry: None} # groupdict


# def a function to generate some random numbers
def rnd_numbers():
    rnd_numbers = [i for i in range(1, 100)] # A list of numbers from 1 - 100
    return sample(rnd_numbers, 30) # Return a random sample of 30 numbers

class Groups:
    '''
    Class using dunder method for comparison
    '''
    def __init__(self, number):
        self.number = number   

    def __le__(self, other):
        return self.number <= other.number


numbers = rnd_numbers() # List of random numbers

numbers_copy = numbers.copy() # Create a copy of our list to work with

while len(numbers) > 0:
    for number in numbers_copy:
        if Groups(number) <= Groups(boundry):
            group.append(number)
            numbers.remove(number)
    numbers_copy = numbers.copy()
    groupdict[boundry] = group
    boundry += 10
    group = []

for k,v in groupdict.items():
    print(f'{k}: {v}')

output
Code:
Groups of 10's: [5, 7, 4]
Groups of 20's: [16, 19, 11, 17, 18]
Groups of 30's: [28, 26]
Groups of 40's: [36, 37, 39]
Groups of 50's: [43, 41, 45]
Groups of 60's: [52, 53]
Groups of 70's: [69, 70, 67]
Groups of 80's: [80, 76, 78]
Groups of 90's: [89, 88, 81, 87]
Groups of 100's: [94, 93]
 
I'm a little late to the game but I thought I'd add a slightly different approach. A simple mathematical calculation can reduce each number to a group number, which can then be used to aggregate the individual numbers into a list. Here's the code.

Python:
"""
Take a string of a list of comma separated integers and
report the numbers by groups based on ranges.

Instead of repeated tests for boundaries, calculate the
appropriate group using a mathematical formula. The list
of numbers is maintained in a dictionary with one list
entry for each group. Try various numbers with the formula
to get an idea of how the group number results.
"""

strlist = '8, 12, 38, 3, 17, 19, 25, 35, 50'
groups = {}

for item in strlist.split(','):

    num = int(item)
    grp = 10 * (1 + (num-1) // 10)

    if not grp in groups:
        groups[grp] = []
    groups[grp].append(num)

for grp in sorted(groups):
    print(f'Group of {grp}s: {sorted(groups[grp])}')
   
'''
Output:

Group of 10s: [3, 8]
Group of 20s: [12, 17, 19]
Group of 30s: [25]
Group of 40s: [35, 38]
Group of 50s: [50]
'''
 
One built-in function (BIF) that you might find useful is enumerate.
It comes with a built-in counter that you can deconstruct in the for loop. I good way to know when you reach the end of a group.

Here's an example of how it works:

Code:
list = "asdasdasd"
for x, letter in enumerate(list):
      print("\ncount: ", x)
      print("\ncodepoint: ", ord(letter))

Output:

count: 0

codepoint: 97

count: 1

codepoint: 115

count: 2

codepoint: 100

count: 3

codepoint: 97

count: 4

codepoint: 115

count: 5

codepoint: 100

count: 6

codepoint: 97

count: 7

codepoint: 115

count: 8

codepoint: 100
>>>
 
Back
Top Bottom