Simple Python Assistance - python

two fixes:, main should sort the returned list, and the for loop should print all numbers on one line.
This is the question I am answering, Thought I got it all but the two errors I have explained above need help:
In main, generate a random integer that is greater than 5 and less than 13. print this number on its own line.
Call the makelist function with the random integer as sole argument.
Make an empty list inside the makelist function.
Use a loop to append to the list a number of elements equal to the random integer argument. All new list elements must be random integers ranging from 1 to 100, inclusive. Duplicates are okay.
Return the list to main.
Back in main, catch the returned list and sort it.
Finally, use a for loop to display the sorted list elements, all on one line, separated by single spaces.
List size will be 7
Here is the sorted list:
8 28 35 41 51 62 72
ANOTHER SAMPLE OUTPUT
List size will be 10
Here is the sorted list:
3 3 9 20 36 43 48 50 81 93
Any help with my code is very much appreciated. Im a beginner and have tried tutorials.
Here is my code
import random
def main():
random_int = random.randint(6, 12)
print (random_int)
elements = makelist(random_int)
for n in sorted(elements):
print (n,)
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 101))
return number_list
main()

print (n,) if you want to print your items like your samples output, Your comma placement is where the problem lies. You see, parenthesis in python are used both for enclosing mathematical / logical expressions and for tuples. What happens if you want a 1-item tuple? (n) is the same as n. To solve that, python understands (n,)as a tuple.
So to print your items like you want, use:
for n in sorted(elements):
print (n),
print() # This last one is only to go down a line
# for any further prints
Edit: also, if you want a random_intbetween 1 and 100, use random.randint(1, 100), not 101

I would sort the list in the makelist function. In addition to this, you should remove the comma from print (n,). Otherwise your code pretty much solves the problem. Just be more specific with your question next time.
Edit: Calling each print() on each element on the list will print each element on a newline (Vertically). Since you needed to get rid of the commas, ' '.join(map(str, sorted(elements)) will convert the list to a string, with each element separated by an empty space.
import random
def main():
random_int = random.randint(6, 12)
print ("The list size will be %d" %random_int)
elements = makelist(random_int)
print("This sorted list is %s" %' '.join(map(str, sorted(elements))) )
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 100))
return number_list

Do it like this
import random
def main():
random_int = random.randint(6, 12)
print ('List size will be %d' % random_int)
elements = makelist(random_int)
print('Here is the sorted list:')
print( ' '.join(map(str, sorted(elements))) )
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 100))
return number_list
main()
The line of interest is
print( ' '.join(map(str, sorted(elements))) )
Which does a few things.
sorted(elements)
Return a sorted copy of the list.
map(str, sorted(elements))
Map (convert) the integer elements to strings. This just calls str on each element in the list. Its needed because join requires an iterable of strings.
' '.join(map(str, sorted(elements)))
This funny looking syntax will create one long string out of all the values. It will use ' ' (space character) as the value between each element and will join all the elements which have been sorted and converted to strings into one long string which can be printed.

Related

Trying to compare return values to list

randomgenerator() is a function that yields 6 random integers, the user is prompted to also enter 6 values which are added to lucky[].
I want to compare each yield value to the lucky[] list for a match, but the if condition is not being met.
for x in randomgenerator():
print(f"\n{x} is a winning number.")
if x in lucky:
print(f"There is a match with number {x}")
match.append(x)
def randomgenerator():
for i in range(5):
yield random.randint(1,2)
yield random.randint(1,2)
You said randomgenerator returns a tuple containing ints.
randomgenerator() is a function that yields 6 random values
I guess by "values" you meant integers, since it's very strange to generate random strings.
Then lucky is filled with input() returned values, which are strings.
if str(x) in lucky: # This should work, since it will convert the int x to a string
a similar solution would be:
lucky = list(map(int, lucky)) # all the elements are converted to integers

How to have my program list every item off of a list randomly and only once

I'm trying to have a function that uses the random import to randomly select a value from the list [0, 1, 2, 3, 4, 5, 6, 7, 8], print that value, then repeat itself until all the numbers are selected. The problem I'm having is then making sure when it repeats itself it won't choose that number again. What I've tried is:
def ListArranger():
randomPick = random.choices(list)
if len(list) > 0:
if list[randomPick] != " ":
print(list[randomPick])
list[randomPick] = " "
ListArranger()
else:
ListArranger()
I run into the problem that says list indices must be integers or slices, not list. I'm assuming it's having a problem because I'm trying to set the list value to a string, but I can't figure out how to work around this
The obvious choice that nobody seems to mention is random.sample:
def ListArranger(lst):
return random.sample(lst, len(lst))
for pick in ListArranger(range(9)):
print(pick)
4
0
8
1
2
3
7
6
5
Here is the solution:
import random
def ListArranger(list):
if len(list) > 0:
randomPick = random.choice(list)
print(randomPick)
list.remove(randomPick)
ListArranger(list)
list = [0,1,2,3,4,5,6,7,8]
ListArranger(list)
Output:
2
8
7
1
3
4
0
5
6
This function takes a list as an argument an calls itself until the list is empty.
It removes a random element of the list in each recursive call while printing out the removed element.
You can shuffle() copy (quote from docs: "All slice operations return a new list containing the requested elements.") of given list once and yield from (PEP 380) shuffled list from generator function.
from random import shuffle
def ListArranger(lst):
lst_copy = lst[:]
shuffle(lst_copy)
yield from lst_copy
You can iterate over this function which will return you every time new random element from lst.
If you don't need to keep source list untouched, you can omit copying, shuffle list itself and iterate over it.
The error comes from line lines 3,4,5
Because you are indexing your list with a list in all those lines.
randomPick is a list not an integer or a slice that's what the error indicates.
Example:
print(randomPick[ **[1,2,3,4]** ] here is the actual problem.
You can only index a list by an integer or a slice.
Solution:
import random
lst = [1,2,3,4,5,6,7,8]
check_lst = []
while True:
random_num = random.choice(lst)
if random_num in check_lst:
continue
elif random_num not in check_lst:
check_lst.append(random_num)
print(random_num)
if len(lst) == len(check_lst):
print("Finish the loop")
break
import random
lst=[0,1,2,3,4,5,6,7,8]
lstlen=len(lst)
def ListArranger():
if len(lst)!=0:
randomPick=random.choice(lst)
print(randomPick)
lst.pop(lst.index(randomPick))
ListArranger()
else:
for i in range(lstlen):
lst.append(" ")
ListArranger()
If you think of your list as a stack, you can just shuffle() once and then pop() each element off in-sequence until you are done.
Also, this is a chance to use a generator. You can turn any function into a generator simply by adding a yield <something>. Then you can use it in a for statement.
Our input list remains intact because we internally copy() it.
from random import shuffle
def chooseOneWithoutReplace(items):
data = items.copy()
shuffle(data)
while data:
yield data.pop()
# nothing more to yield
# generator ends -> outer for loop ends
daysOfWeek = [1,2,3,4,5,6,7]
for i in chooseOneWithoutReplace(daysOfWeek):
print(i)
Output
1
4
5
3
7
2
6
Use shuffle, which does just that with a given sequence.
def listArranger(a):
random.shuffle(a)
for item in a:
print(item)
Do not shadow a built-in name with a local variable: list is perhaps the most common bad variable name.
Pass your list into the function, rather than making it an assumption of the outer scope.

Using a for loop to calculate the average

Hi I'm sort of new to programming and I would really appreciate some help with this problem.
I have a list of scores and I would like to create a function which divides each individual score by the calculated average of the whole list. The function should accept a list of scores as an argument and return a list with the modified scores.
Also, it should make use of a for loop and a return statement.
Here is a brief example of the list of scores I have:
13
22
33
42
25
(there are over 500 scores)
tbh, the wording of your question was a little confusing, but here's what you would do.
def scoreAvg(scores):
scoresSum = sum(scores)
scoresSum /= len(scores)
newScores = []
for i in scores:
i /= scoresSum
newScores.append(i)
return newScores
print(scoreAvg([13,22,33,42,25]))
You said you were pretty new to python, so I'll give you a rundown of what's happening here. Input 'scores' is a list containing our set of example scores (remember to enclose the input in square brackets). We find the sum of that list with sum() and the length with len(). We then begin a for loop to loop through the elements of scores, and divide each element by the avg, then append that value to a list we created earlier to hold the new scores. Now all we have to do is return that list with return newScores !
Hope I could help.
You can try the following code.
from __future__ import division #For decimal division.
''' Function (func) '''
def func(lst):
new_list = [] #Define an empty new list.
for i in range(len(lst)):
new_list += [ lst[i]*len(lst) / sum(lst) ]
return new_list
mylist = [13, 22, 33, 42, 25] #List you wish to enter.
mod_list = func(lst = mylist) #Modified list.
print mod_list #Prints output (mod_list).
>>>[0.48148148148148145, 0.8148148148148148, 1.2222222222222223, 1.5555555555555556, 0.9259259259259259]
In the above code, each element of new_list is element of input list (lst=mylist) divided by average of input list. One can obtain average by using the following: average = sum of input list / number of elements in input list. In python, the function len() gives you the number of items of an object (e.g. list). The function sum() gives you the sum elements of an object.
I hope this was helpful. Let me know if you have any questions. =)

Find highest and lowest number from the string of numbers

I'm trying to write a function that returns the highest and lowest number in a list.
def high_and_low(numbers):
return max(numbers), min(numbers)
print(high_and_low("1 2 8 4 5"))
But I have this result:
('8', ' ')
Why do I have ' ' as a lowest number?
You are passing string to a function. In order to achieve the desired result, you need to split the string and then type-cast each element to int. Then only your min and max function will work expectedly. For example:
def high_and_low(numbers):
# split numbers based on space v
numbers = [int(x) for x in numbers.split()]
# ^ type-cast each element to `int`
return max(numbers), min(numbers)
Sample Run:
>>> high_and_low("1 2 8 4 5")
(8, 1)
Currently your code is finding the minimum and maximum value based on lexicographical order of the characters.
In order to achieve your desired result you can call split() on the string you are passing in. This essentially creates a list() of your input string—which you can call the min() and max() functions on.
def high_and_low(numbers: str):
"""
Given a string of characters, ignore and split on
the space ' ' character and return the min(), max()
:param numbers: input str of characters
:return: the minimum and maximum *character* values as a tuple
"""
return max(numbers.split(' ')), min(numbers.split(' '))
As others have pointed out you can also pass in a list of values you'd like to compare and can call the min and max functions on that directly.
def high_and_low_of_list(numbers: list):
"""
Given a list of values, return the max() and
min()
:param numbers: a list of values to be compared
:return: the min() and max() *integer* values within the list as a tuple
"""
return min(numbers), max(numbers)
Your original functions does technically work, however, it is comparing numerical values for each character and not just the integer values.
Another (faster) way using mapping:
def high_and_low(numbers: str):
#split function below will use space (' ') as separator
numbers = list(map(int,numbers.split()))
return max(numbers),min(numbers)
You can split your string by ' ' and pass it as Array
def high_and_low(numbers):
# split string by space character
numbers = numbers.split(" ")
# convert string array to int, also making list from them
numbers = list(map(int, numbers))
return max(numbers), min(numbers)
print(high_and_low("1 2 10 4 5"))
use numbers_list=[int(x) for x in numbers.split()] and use numbers_list in min() and max().
split() turns '1 23 4 5' into ['1','23','4','5']; and by using a list comprehension all the strings get converted to integers.

Python items in a list still a list?

I'm trying to create a short script where 5 random numbers from an available list are selected and then each one is displayed. The problem I'm having is that the list to which I'm appending the results returns a list as well, not integers or strings. Here's the code:
def randomStar(self):
choice = [5,4,3]
probability = [0.1, 0.2, 0.7]
star = random.choices(choice, probability)
return star
multi = []
characters = []
for x in range(5):
star = randomStar(x)
multi.append(star)
x += 1
for star in multi:
characters.append(star)
print (characters)
print (multi)
Both multi and characters lists return:
['[3]', '[3]', '[3]', '[5]', '[3]']
So when I try to iterate through "Multi" list I still get lists. How can I get the values only? Or is the way I'm appending the numbers to the list incorrect?
Thanks.
They are lists because random.choices returns "a k sized list of elements".
Since there is only one element in the list, and this is what you are trying to return, you just want to write return star[0].

Categories

Resources