When my program is done printing 10 random numbers, it should print something like this. (These numbers 3, 7, and 10 are just used as example.)
List had 3 evens and 7 odds
The 3rd element in sorted nums is 10
For some reason this isn't happening for me.
This is the code I have so far:
import random
nums =[]
for i in range (1,11):
x = random.randint(1,50)
nums.append(x)
print(nums)
nums.sort()
print(nums)
start = nums[0:5]
print(start)
finish = nums[7:10]
print(finish)
def evenOdd(num):
odd = 0
even = 0
for x in num:
if (x % 2 == 0):
even += 1
else:
odd += 1
print('List had', even, 'evens and', odd, 'odds')
print('The 3rd element in sorted nums is', num[2])
When I run it, this is what the program displays:
Traceback (most recent call last):
[7, 21, 6, 14, 22, 8, 24, 20, 26, 27]
line 35, in <module>
[6, 7, 8, 14, 20, 21, 22, 24, 26, 27]
print('List had', even, 'evens and', odd, 'odds')
[6, 7, 8, 14, 20]
NameError: name 'even' is not defined
[24, 26, 27]
Process finished with exit code 1
You have a number of problems in your code. You aren't actually calling your evenOdd function, if you did call it, you have provided no way to get its results, and you have some variable name mismatches. Also, your evenOdd() function wasn't doing the right thing because the else clause needed to be indented to be within the for loop. The way it is in your version, odd will always be 1:
Here's code that fixes all of these issues:
import random
nums =[]
for i in range (1,11):
x = random.randint(1,50)
nums.append(x)
print(nums)
nums.sort()
print(nums)
start = nums[0:5]
print(start)
finish = nums[7:10]
print(finish)
def evenOdd(num):
odd = 0
even = 0
for x in num:
if (x % 2 == 0):
even += 1
else:
odd += 1
return even, odd
even, odd = evenOdd(nums)
print('List had', even, 'evens and', odd, 'odds')
print('The 3rd element in sorted nums is', nums[2])
The main thing here is that the evenOdd function returns a "tuple" that contains the resulting counts of odd and even numbers so that you can use them outside the function.
Sample result:
[2, 36, 20, 32, 6, 40, 39, 27, 24, 47]
[2, 6, 20, 24, 27, 32, 36, 39, 40, 47]
[2, 6, 20, 24, 27]
[39, 40, 47]
('List had', 7, 'evens and', 3, 'odds')
('The 3rd element in sorted nums is', 20)
I am assuming the last print statements ought to be in your evenOdd function, in which case your code isn't properly indented. It should be like this:
def evenOdd(num):
odd = 0
even = 0
for x in num:
if (x % 2 == 0):
even += 1
else:
odd += 1
print('List had', even, 'evens and', odd, 'odds')
print('The 3rd element in sorted nums is', num[2])
After that, you can call the function thus:
evenOdd(nums)
Define the variables even and odd globally - they're only available inside the function.
even = 0
odd = 0
# ...
def evenOdd(num):
global even
global odd
even = 0
odd = 0
# ...
you can use this also, :-
import random
nums =[random.randint(1,51,) for var in range(1,11)] # creating nums list by short method
nums.sort()
print(nums)
def evenOdd(num):
odd = 0
even = 0
for x in num:
if (x % 2 == 0):
even += 1
else:
odd += 1
return even,odd
even,odd = evenOdd(nums)
print('List had', even, 'evens and', odd, 'odds')
print('The 3rd element in sorted nums is', nums[2])
I hope you learn something new.
Related
I have to replace in a list the multiples of 5 by the number + x. For example, if I have the list [1,3,5,7,9,9,11,13,15,17,19,21,23,25,27,29], the result has to be [1,3,5x,7,9,11,13,15x,17,19,21,23,25x,27,29]. I have tried to develop the script but it doesn't work, can anyone help me?
numbers = list (range(1,31))
odds = [number for number in numbers if number % 2 == 1]
print(odds)
for index, value in enumerate(odds):
if value%5==0:
odds[index] = '5x'
print(odds)
We can solve your problem by using the value variable, which stores the current number. We just need to reference this variable when setting the current element to add to "x", like this:
odds[index] = str(value) + "x"
Notice the need to cast value as a string, as we cannot concatinate an integer and a string without creating a touple.
You can make your code much simpler:
numbers = range(1, 31, 2)
res = [str(i) + 'x' if i%5 == 0 else i for i in numbers]
print(res)
Result:
[1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]
Explanation:
numbers = range(1, 31, 2)
This creates an iterable with odd numbers from 1 to 29 without having to do:
numbers = list(range(1,31))
odds = [number for number in numbers if number % 2 == 1]
which is redundant. The syntax for the range function is range(start, stop, step), so for odd numbers from 1 to 30, it'll be range(1, 31, 2) which will give 1, 3, 5, 7, and so on.
res = [str(i) + 'x' if i%5 == 0 else i for i in numbers]
I'm assuming you know how to use list comprehensions since you've used it in your code. The above line of code simply searches for a value that is divisible by 5 and adds an x to this value, else it simply adds i to the list.
You can also use f-strings instead of str(i) + x (as Stuart suggests under Jensen's answer):
res = [f'{i}x' if i%5 == 0 else i for i in numbers]
I want to make a program as an exercise which prints all prime numbers in range of given limit(parameter). Thanks.
#prime numbers
prime = list()
for x in range(1, 100):
for a in range(2, x):
if x % a == 0:
break
else:
prime.append(x)
print(prime)
You can use this list comprehension to find prime numbers in given range;
def prime_generator(number):
return [x for x in range(2, number) if not any(x % y == 0 for y in range(2, int(x/2)+1))]
In: prime_generator(30)
Out: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
i have a task:
got a range on input
[x;y]
then i should check every number from that range and check every numeral in number. if its odd, i should print it
for example: 3, 20
i should print 4,6,8,20
def check(num):
if int(num) % 2 == 0:
return True
x, y = int(input()), int(input())
numbers = []
if x <= y:
while x != y:
for i in str(x):
if check(i):
numbers.append(x)
x += 1
else:
while y != x:
for i in str(y):
i = int(i)
if check(i):
numbers.append(y)
y += 1
if y == x:
for i in str(x):
if check(i):
numbers.append(x)
print(numbers)
it prints
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29]
instead of 2,4,6,8,20,22,24,26,28
You are checking and approving based on a single digit for each number. You should check all of them before appending the entire number. That's why you get 22 twice: once for the first 2 and once for the second. You get 10, because even though 1 is odd, 0 is even and so you append it to your list.
Move the check for the entire number into the function check and have it return True only if all digits are even. This shortens your code. Also note that you can trivially swap x and y if the user entered them in the wrong order.
The function check immediately returns False as soon as it finds a digit i is odd, and you can see it can only return True if the loop ended and all digits were even.
def check(num):
for i in str(num):
if int(i) % 2 != 0:
return False
return True
x, y = int(input()), int(input())
if x > y:
x,y = y,x
numbers = []
while x <= y:
if check(x):
numbers.append(x)
x += 1
print (numbers)
Result, with 3 and 20 entered (but 20 and 3 would also work):
[4, 6, 8, 20]
Given the list:
n = [3, 6, 12, 24, 36, 48, 60]
I need to turn a random number divisible by 3, after by 6, after by 12, after by 24, after by 36, after by 48 and after by 60. One at each time, not the divisible for the seven numbers simultaneously.
But, to make the number divisible, I need to sum another number to reach the number divisible by 3, 6, 12, 24, 36, 48 or 60.
I don't know the random number neither the number to add to this random number in order to turn it divisible by 3, 6, 12, 24, 36, 48 or 60.
Can someone help me, please?
Using the map function list comprehension:
import random
n = [3, 6, 12, 24, 36, 48, 60]
a = random.randint(start, stop)
result = [a + x - a % x if a % x else a for x in n]
addition = [x - a for x in result]
print(a)
print(result)
print(addition)
start and stop are the limits for your random number.
Output for a = 311:
311
[312, 312, 312, 312, 324, 336, 360]
[1, 1, 1, 1, 13, 25, 49]
Begin of the old answer to the rather unclear question before the first edit by the author.
The following post answers the question: Which is the next number after a, which is a multiple of all numbers of the list n, if it is not a?
First the least common multiple lcm of the numbers from the list must be determined. For this purpose, the method least_common_multiple is executed for the complete list. The modulo operation then checks whether a is not already a multiple of the numbers. If this is the case, a is output. Otherwise, the next multiple of lcm is output.
from math import gcd
from functools import reduce
n = [3, 6, 12, 24, 36, 48, 60]
a = 311
def least_common_multiple(x, y):
return abs(x * y) // gcd(x, y)
lcm = reduce(least_common_multiple, n)
result = a if a > 0 else 1 # can be change if necessary, see edit
mod = result % lcm
if mod:
result += (lcm - mod)
print('Current number: ' + str(a))
print('The next number divisible by any number from the given list: ' + str(result))
print('Necessary addition: ' + str(result - a))
Output:
Current number: 311
The next number divisible by any number from the given list: 720
Necessary addition: 409
Edit: Changed the code so that 0 is no longer a valid result for a non-positive a.
However, if it is valid, you can change the code at the commented part with: result = a.
New answer for the clarified question:
import math
def f(x, a):
return math.ceil(a / x) * x - a
n = [3, 6, 12, 24, 36, 48, 60]
a = 311
result = [f(x, a) for x in n]
print(result)
Old answer:
I think you're looking for the LCM (lowest common multiple) of all numbers in n. We can get the LCM for two numbers using the GCD (greatest common divisor). We can then use reduce to get the LCM for the whole list. Assuming x can be negative, simply subtract a from the LCM to get your answer. The code could look like this:
import math
from functools import reduce
def lcm(a, b): # lowest common multiple
return a * b // math.gcd(a, b)
n = [3, 6, 12, 24, 36, 48, 60]
smallest_divisible_by_all = reduce(lcm, n)
a = 311
x = smallest_divisible_by_all - a
print(x)
which outputs
409
If speed is not important, you could also do a brute force solution like this:
ns = [3, 6, 12, 24, 36, 48, 60]
a = 311
x = 0
while not all([(a + x) % n == 0 for n in ns]):
x += 1
(assuming that x >= 0)
So I can think of 2 solutions:
First if you want a list which show how much you have to add for the random number to get to a divisible number:
def divisible(numbers,random):
l = []
for number in numbers:
if random % number != 0:
l += [number - (random % number)]
else:
l += [0]
return l
a = 311
n = [3, 6, 12, 24, 36, 48, 60]
print(divisible(n,a))
Output:
[1, 1, 1, 1, 13, 25, 49]
Or if you want to know how far is the smallest number from the random number that everyone shares as divisible. For this take a look how you calculate lcm.
from math import gcd
def divisible_all(numbers, random):
lcm = numbers[0]
for i in numbers[1:]:
lcm = lcm*i//gcd(lcm, i)
tempLcm = lcm
while lcm < random: # in case the lcm is smaller than the random number add lcm until it is bigger (I assume you only allow positive numbers)
lcm += tempLcm
return lcm-random
print(divisible_all(n,a))
Output:
409
You can do:
import math
n = [3, 6, 12, 24, 36, 48, 60]
div_n={el: False for el in n}
a=311
a0=math.ceil(a/max(n)) * max(n)
while not all(div_n.values()):
div_n={el: False for el in n}
# print(a0)
for el in n:
if(a0 % el > 0):
a0=math.ceil(a0/el) * el
break
else:
div_n[el]=True
print(a0-a)
Output:
409
I'm given with an array with numbers.
I'm trying to build a program that identifies if the number is an even or odd number.
Here's what I've done.
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
i=0
while i <= len(a):
if a[i] % 2 == 0:
print(a[i], " is an even number")
i = i + 1
else:
print(a[i], " is an odd number")
I was thinking since a[0], a[1] represents 1, 4, I thought that I can use a[i] where i increases until the length of a.
But this code gives me an infinite loop.
This is the only way I figured to use individual numbers in array.
I tried using
if a%2==0:
print(a, " is an even number")
But that gave me an error.
Thanks in advance
You can achieve that simply with a for loop like below:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for n in a:
if n % 2:
print(n, "is an odd number")
else:
print(n, "is an even number")
For your above code issues, you are not incrementing i inside else block and your condition should be < len(a) instead of <= len(a)
Put your i = i+1 outside of the if/else and replace <= with a < otherwise it goes over the array length.
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
i=0
while i < len(a):
if a[i] % 2 == 0:
print(a[i], " is an even number")
else:
print(a[i], " is an odd number")
i = i + 1
your problem is that the following:
instead of using <= use <.
Add your i = i + 1 in both if and else.
Because if you hit an even number it will add 1 to i, but also if you hit a odd number it will add 1 too.
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
i=0
while i < len(a):
if a[i] % 2 == 0:
print(a[i], " is an even number")
i = i + 1
else:
print(a[i], " is an odd number")
i = i + 1
Then if you use this code:
if a%2==0:
print(a, " is an even number")
What happens here is that the variable "a" is a list and to loop through it you need to break up the list into single components as you did "a[i]". What you are doing here is taking the list as a single component and not breaking up the list to get each value of the list.
Hope you get it.