Multiples of 10 in a list - python

I am currently doing an assignment in my intro level CS class and just need a smidge of help.
They are asking me to write a program that reads a list of integers and determines if it has;
multiples of 10
no multiples of 10
mixed values.
It currently correctly outputs everything but mixed values. This is what I have:
n = int(input())
my_list =[]
for i in range(n):
num = int(input())
my_list.append(num)
def is_list_mult10(my_list):
mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 0:
mult10 = False
return mult10
def is_list_no_mult10(my_list):
no_mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 1:
no_mult10 = False
return no_mult10
if is_list_no_mult10(my_list) == True:
print("no multiples of 10")
elif is_list_mult10(my_list) == True:
print("all multiples of 10")
else:
print("mixed values")

def check_multiplier(my_list):
is_10_multiplier = []
for i in my_list:
if i % 10 == 0:
is_10_multiplier.append(True)
else:
is_10_multiplier.append(False)
if sum(is_10_multiplier) == len(my_list):
print("all multiples of 10")
elif sum(is_10_multiplier) == 0:
print("no multiples of 10")
else: print("mixed values")
# tests
mixed = [1, 20, 34, -10]
check_multiplier(mixed)
no_10 = [13, 22, 101, -5]
check_multiplier(no_10)
only_10 = [20, 140, 30, -50]
check_multiplier(only_10)
Function check_multiplier indexing all elements from my_list and saves booleans into is_10_multiplier. Then checks the sum of is_10_multiplier, if all items are True then sum is equal length of passed list, if all are False then sum is 0.

As mentioned in the comments, you have a couple of errors in your code (the return statements are inside the for loop).
Also, the logic seems a little too complicated :) No need to have 2 separate functions, you can try:
n = int(input('How many numbers?: '))
my_list =[]
for i in range(n):
num = int(input(f'Insert element {i}: '))
my_list.append(num)
def how_may_mult10(my_list):
# counting how many multiples of 10 you have in your list
number_of_m10 = 0
for num in my_list:
if num % 10 == 0:
number_of_m10 += 1
return number_of_m10
number_of_m10 = how_may_mult10(my_list)
if number_of_m10 == len(my_list):
print('All multiples of 10')
elif number_of_m10 == 0:
print('No multiples of 10')
else:
print('Mixed values')

I see you have done some logical as well as syntactic error, as mentioned in the comments also.
Below is your modified code :
n = int(input())
my_list =[]
for i in range(n):
num = int(input())
my_list.append(num)
def is_list_mult10(my_list):
mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 0:
mult10 = False
return mult10 #changed here
def is_list_no_mult10(my_list):
no_mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 == 0: #changed here
no_mult10 = False
return no_mult10 #changed here
if is_list_no_mult10(my_list) == True:
print("no multiples of 10")
elif is_list_mult10(my_list) == True:
print("all multiples of 10")
else:
print("mixed values")
It successfully prints the correct statement. However I'll suggest you to try to optimise e your program.

Related

Why am I not getting four unique numbers returned?

I am trying to create a function that returns a 4 digit string which consists of 4 unique values.
I currently have the following code:
def generateNum():
ValidNum = False
while ValidNum == False:
RanNumber = random.randint(1000, 9999)
RanNumber = str(RanNumber)
for number in RanNumber:
if RanNumber.count(number) > 1:
ValidNum = False
else:
ValidNum = True
return RanNumber
print(generateNum())
Can someone explain what is wrong with this piece of code and what I can potentially do to fix it?
Thank you.
Following your logic, this is what would have worked:
def generateNum():
ValidNum = False
while True:
RanNumber = random.randint(1000, 9999)
RanNumber = str(RanNumber)
for number in RanNumber:
if RanNumber.count(number) == 1:
ValidNum = True
continue
else:
ValidNum = False
break
if not ValidNum:
continue
break
return RanNumber
import random
def generate_random():
num = ''
while len(num) < 4:
random_int = random.randint(0,9)
if str(random_int) in num:
pass
else:
num += str(random_int)
return num
print(generate_random())
This should work fine

How to solve Luhn algoritm

there is a lot of information about how to write Luhn algortim. I'm trying it too and I think that I'am very close to succes but I have some mistake in my code and dont know where. The test card is VALID card but my algorithm says otherwise. Don't you know why? Thx for help
test = "5573497266530355"
kazde_druhe = []
ostatni = []
for i in test:
if int(i) % 2 == 0:
double_digit = int(i) * 2
if double_digit > 9:
p = double_digit - 9
kazde_druhe.append(p)
else:
kazde_druhe.append(double_digit)
else:
ostatni.append(int(i))
o = sum(ostatni)
k = sum(kazde_druhe)
total = o+k
if total % 10 == 0:
print(f"Your card is valid ")
else:
print(f"Your card is invalid ")
Finally! Thank you all for your help. Now it is working :-)
test = "5573497266530355" kazde_druhe = [] ostatni = []
for index, digit in enumerate(test):
if index % 2 == 0:
double_digit = int(digit) * 2
print(double_digit)
if double_digit > 9:
double_digit = double_digit - 9
kazde_druhe.append(double_digit)
else:
kazde_druhe.append(double_digit)
else:
ostatni.append(int(digit))
o = sum(ostatni)
k = sum(kazde_druhe)
total = o+k if total % 10 == 0:
print(f"Your card is valid ")
else:
print(f"Your card is invalid ")
From this description
2. With the payload, start from the rightmost digit. Moving left, double the value of every second digit (including the rightmost digit).
You have to check the digit position, not the number itself.
Change to this:
for i in range(len(test)):
if i % 2 == 0:
This code works. :)
I fixed you code as much as i could.
test = "5573497266530355"
#test = "3379513561108795"
nums = []
for i in range(len(test)):
if (i % 2) == 0:
num = int(test[i]) * 2
if num > 9:
num -= 9
nums.append(num)
else:
nums.append(int(test[i]))
print(nums)
print((sum(nums) % 10) == 0)
I found where your code went wrong.
On the line:
for i in test:
if int(i) % 2 == 0:
It should be:
for i in range(len(test)):
if i % 2 == 0:
You should not be using the element of the string you should be using the index of the element.

Python - function returns true when a given number is a prime number or else false

Hi I'm a beginner and I'm stuck on this question that wants me to use only while loop to solve. The question wants me to write a function that returns True when the given number is a prime number and it returns False if the given number is not a prime number.
My code so far:
def is_prime(n):
i = 2
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
The problem I have is I think my code displays the correct output for numbers 4 and above and it returns 'None' for 1, 2, and 3. I've debugged it and I think the problem is the while loop condition. But I don't know how to fix it. I would appreciate it if any of you pros can help me out!
edit:
I changed the while condition but 1 still returns None.. and 2 returns False when it's supposed to return True
def is_prime(n):
i = 2
while i <= n:
if n%i != 0:
return True
else:
return False
i+=1
import math;
def is_prime(n):
i = 2
while i < max(math.sqrt(n),2):
if n%i != 0:
return True
else:
return False
if i == 2:
i+=1
else
i+=2
You could hard-code these 3 cases, in case you dont want to use sqrt:
def is_prime(n):
i = 2
if n in (1,3):
return True
elif n == 2:
return False
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
for x in range(1, 5):
print(x, '=', is_prime(x))
Output:
(1, '=', True)
(2, '=', False)
(3, '=', True)
(4, '=', False)
Want to get really fancy? Make a Sieve of Eratosthenes:
def is_prime(n):
a = list()
# Assume all are prime
a[0:n+1] = (n+1)*[1]
# Start with removing even numbers
i = 2
while i*i <= n:
print ("I: ", i)
# Set all divisible by i to 0
a[0:n+1:i] = len(a[0:n+1:i])*[0]
# If a[n] is zero, return False
if a[n] == 0:
return False
# Increment i until we have a prime number
while a[i] == 0:
i+=1
if a[n] == 0:
return False
else:
return True
If you want to impress your lesson teacher you can show him a fast probabilistic prime number isprime for numbers larger than 2**50. I haven't found any errors in it after weeks of cpu time stress testing it on a 6 core AMD:
import random
import math
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def fast_probabilistic_isprime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if lars_last_modulus_powers_of_two(hm+hm) != 2:
return False
if pow(2, hm-1, hm) == 1:
return True
else:
return False
def fast_probabilistic_next_prime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if hm % 2 == 0:
hm = hm + 1
hm += 2
while fast_probabilistic_isprime(hm) == False:
hm += 2
return hm
""" hm here is bitlength, which must be larger than 50.
usage is create_probabilistic_prime(1000)
"""
def create_probabilistic_prime(hm):
if 2**hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
num = random.randint(2**hm,2**(hm+1))
return fast_probabilistic_next_prime(num)

How do i check if the number is semi prime

def is_prime(num):
if num > 1:
for i in range(2,num):
return False if (num % i) == 0:
if (num % i) == 0:
return False
return True if prime
else:
return True
return False if not prime
else:
return False
def is_semiprime():
n = int(input("Enter a number to find out if its semiprime or not\n>>> "))
for d1 in range(2, int(n**.5)):
if n % d1 == 0:
d2 = int(n / d1)
is_prime(d1) and is_prime(d2) go through and don't tell me there true or false they just send blank lines.
return is_prime(d1) and is_prime(d2)
return False
is_semiprime()
when it Returns is_prime(d1) and is_prime(d2) if they are both True then return True
A semi-prime number is a number that's the product of two prime numbers. So the algorithm is simple:
Find one divisor of the number, call it d1.
Divide the number by d1 to get a second divisor, d2.
Test whether both d1 and d2 are prime. If they are, then the original number is semi-prime.
Code:
def is_semiprime(n):
for d1 in range(2, int(n**.5)+1):
if n % d1 == 0:
d2 = n / d1
return is_prime(d1) and is_prime(d2)
return False
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
def ask_semiprime():
num = int(input("What number would you like to check?"))
if is_semiprime(num):
print(num, " is semiprime")
else:
print(num, " is not semiprime")
ask_semiprime()
I copied the is_prime function from isPrime Function for Python Language
number=int(input())
s=number
x=[]
for i in range(2,number+1):
if s%i==0:
x.append(i)
s=s//I
if s==i or (i>s and s!=1):
x.append(s)
if len(x)==2:
print(f"{number} is a semiprime number because it is the product of Tow primes: ",end="")
else:
print(f"{number} is not a semiprime number because it is the product of {len(x)} primes: ",end="")
for i in x:
if i==x[-1]:
print(i)
else:
print(str(i)+"*",end="")
def check_prime(n): #for checking wheather prime or not
if n > 1:
if n == 2: return True
for i in range(2,n):
if n % i == 0:
return False
break
return True
return False
def primeproduct(m): #for checking wheather prime product or not
if m >= 0:
for i in range(1,m):
if m%i == 0 and check_prime(i) and check_prime(m//i):
return True
break
return False
this may help

How do I display the max function i created in python

I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum

Categories

Resources