I don't know, why isn't working that code in python. The problem is, that I can get numbers, but sometimes some numbers are uniform. And I want to do 5 different numbers between 1 and 90.
class lottery:
def __init__(self):
self.price = 50
def list(self):
numbers = []
for i in range(0,5):
numbers.append(random.randint(0,90))
for i in range(1,5):
for j in range(0,i-1):
if (numbers[i]==numbers[j]):
game.list()
return numbers
game = lottery()
game.list()
Or is there any better way to solve my problem?
Thanks!
Use random.sample:
def list(self):
return random.sample(xrange(90), 5)
This is (especially for large values of 5) much more efficient than starting over every time your randomization creates a repeat, and also avoids the possibility of overflowing the stack.
First of all you should import the random module:
import random
The problem is that you are not returning the result that you get from the recursive call, therefore you are still returning the list with repeated numbers. It should be:
def list(self):
numbers = []
for i in range(0, 5):
numbers.append(random.randint(0, 90))
for i in range(1, 5):
for j in range(0, i - 1):
if (numbers[i] == numbers[j]):
return self.list() # return
return numbers
note that self is used to access to the instance of the class that calls the method. Also, don't forget to print the results:
game = lottery()
print game.list()
Note:
Don't use list as the name of a variable or method because it will hide the built-in definition of list.
Related
The following code took me by surprise. I was hoping that I could write a function that might or might not act as a generator.
def mayGen(limit=5, asGenerator=False):
result = []
for i in range(1, limit + 1):
n = i * i
if asGenerator:
yield n
else:
result.append(n)
return result
print(mayGen(5, False))
for x in mayGen(5, True):
print(x)
But no, the output of this program is
<generator object mayGen at 0x7fa57b6ea7b0>
1
4
9
16
25
Calling mayGen with asGenerator=False is simply useless. It seems that the mere existence of a yield statement, regardless of whether it is executed, radically changes the behavior of the containing function.
So what if mayGen was actually big and complicated and I wish I could ask it to either function as a generator, or write its computed output to a file? Is there a well-traveled path here? How are people handling this sort of thing?
Just write a generator. You can always take its output and do whatever you want with it: put it in a list, write it to a file, etc. Although, if that's what you're going to be using it for a lot, you might want to write a wrapper function to do it for you, for example:
def willGen(limit=5):
for i in range(1, limit+1):
n = i * i
yield n
def willReturnList(*args, **kwargs):
return list(willGen(*args, **kwargs))
Edit: For a number of reasons mentioned in comments, this is probably not a great idea. In any event, you can write this:
def mayGen(limit=5, asGenerator=False):
def _generate(limit):
for i in range(1, limit + 1):
n = i * i
yield n
def _return(limit):
result = []
for i in range(1, limit + 1):
n = i * i
result.append(n)
return result
if asGenerator:
return _generate(limit)
return _return(limit)
Edit:
to simiplify even further, you should probably just return list(_generate(limit)) in the final line.
I have written a program that reads integers until the user enters a 0, which stores the integers and then returns the sum of integers. But its not displaying the output, what went wrong?
def readList():
n=int(input())
while n!=0:
n=int(input())
return n
def calSum(n):
n=myList
myList = readList()
sum = calSum(myList)
print(sum)
calSum was assigning myList to n, but it was INSIDE the calSum and anything OUTSIDE this def was unable to read it, as it is local variable.
Same thing about n from readList. It's local. So "n" in readList and "n" in calSum does not exist outside those functions and can not be used anywhere else.
You were able to use "n" from readList, only because you used return, which returned this value to the rest of the program. And in the very same way you have to make in in calSum to make it work.
Google for global and local variables in python for more information on topic :)
def readList():
n=int(input("Input from readList"))
while n!=0:
n=int(input("Looped input from readList"))
return n
def calSum(n):
n=myList
return n #Added return as student suggested
myList = readList()
sum = calSum(myList)
print(sum)
This should be what you're looking for
The readList function appends to a list and then returns the list, as apposed to return just the first number as it was doing previously.
The calcSum function uses Python's built-in sum function to calculate the sum of all the integers in the list.
def readList():
myList = []
n=int(input())
while n!=0:
n=int(input())
myList.append(n)
return myList
def calSum(n):
return sum(n)
myList = readList()
sum = calSum(myList)
print(sum)
I am trying to remove the minimum value from a list of randomly generated numbers without using the minimum function or the remove function.
I created a function minremo, but I am unsure of what the return value should be to make it actually work. Thus far, I have a method of removing the minimum.
def minremo(lst):
lst.sort()
lst.reverse()
lst.pop()
return n
import random
number_list = []
for count in range(10):
number = random.randint(1, 100)
number_list.append(number)
print(number_list)
print(minremo(number_list))
The algorithms to remove the minimum works at file-level scope though:
import random
number_list = []
for count in range(10):
number = random.randint(1, 100)
number_list.append(number)
print(number_list)
number_list.sort()
number_list.reverse()
number_list.pop()
print(minremo(number_list))
But it does not work within the function itself. I'm not sure what I should return within the function. What should the return be within this function?
Return the list that you just modified (lst).
def minremo(lst):
lst.sort()
lst.reverse()
lst.pop()
return lst
For example, if I want to detect all odd numbers in an array and set them to zero, I can use:
def setToZeroIfOdd(n):
if n % 2 == 0:
pass
else:
return 0
numbers = range(1,1000)
numbers = map(setToZeroIfOdd, numbers)
which works like a charm.
But when I try something like
def setToZeroIfDivisibleBy(n, divisor):
if n % divisor == 0:
return 0
else:
pass
numbers = map(setToZeroIfDivisibleBy(divisor=3), numbers)
it expects two arguments. Likewise,
numbers = map(setToZeroIfDivisibleBy, numbers, divisor=3)
does not work. How can I pass that divisor argument from within map()?
You can use functools.partial to make partial functions
from functools import partial
def setToZeroIfDivisibleBy(n, divisor):
if n % divisor == 0:
return 0
else:
pass
numbers = range(1,1000)
numbers = map(partial(setToZeroIfDivisibleBy, divisor=3), numbers)
Try using lambda function
numbers = map(lambda n: setToZeroIfDivisibleBy(n, divisor=3), numbers)
And rather than pass did you mean return n?
You make a function which returns a function:
def setToZeroIfDivisibleBy(divisor):
def callback(n):
if n % divisor == 0:
return 0
else:
pass
return callback
numbers = map(setToZeroIfDivisibleBy(3), numbers)
BTW, you can entirely omit empty branches like else: pass; it doesn't do anything. Since it results in a None, I don't think that's what you want either. You probably want return n there instead.
Another approach, instead of using partial, is to supply an infinite (or at least, long enough) sequence of 2nd arguments for the two-argument function:
from itertools import repeat
numbers = map(setToZeroIfDivisibleBy, numbers, repeat(3))
In Python 2, map will append None as necessary to the shorter of the two sequences to make them the same length. Assuming that will cause problems (either because your function cannot handle None as an input value or you end up with an infinite loop), you can either use itertools.imap, which stops after exhausting the shorter sequence:
from itertools import imap, repeat
numbers = list(imap(setToZeroIfDivisibleBy, numbers, repeat(3)))
or pass the length of numbers as a second argument to repeat so that the two sequences are the same length.
from itertools import repeat
numbers = map(setToZeroIfDivisibleBy, numbers, repeat(3, len(numbers)))
So I just finished a coding test yesterday and I'm a tad neurotic. I was asked to create a class or function to check if elements in a list were all divisible by a scalable list of elements. This is the best I could come up with and was wondering if this could be improved. Thanks! And to get in front of it, I deliberately used a partial instead of lambda. To me it is much cleaner, and allows for better code re-use. Plus, I think Guido strongly discourages the use of Lambda and advises people switch to partials.
from functools import partial
def is_divisible(mod_vals, num):
"""A partial that runs a number against the list of modulus arguments, returning a bool value"""
for mod in mod_vals:
if num%mod != 0:
return False
return True
def divisible_by_factor(*mod_vals):
"""Returns a list based off a scalable amount of modulus arguments, no range support currently"""
comparison_list = []
div_partial = partial(is_divisible, (mod_vals))
for i in range(1, 100):
if div_partial(num=i):
comparison_list.append(i)
return comparison_list
>>> def divisible_by_factor(mod_vals):
>>> return [i for i in range(1, 100) if all(i % j == 0 for j in mod_vals)]
>>> print divisible_by_factor([2, 3, 5])
[30, 60, 90]
For every i test whether it's divisible by all provided values. Keep only values that pass this test.