I'm working on a credit project of CS50 and I have some problem with the verification of the credit card.
Here the function I create:
def main():
while True :
cardnumber = input("Please enter a credit card number: ")
if cardnumber.isdecimal() and int(cardnumber) > 0 :
break
count = len(cardnumber)
if count != 13 and count != 15 and count != 16:
print("INVALID")
else:
check(count, cardnumber)
def check(length, number):
lenght_max = 15
if length == 15 and int(number[0]) == 3 and (int(number[1]) == 4 or int(number[1]) == 7):
if validator(number):
print("AMEX")
elif length == 16 and int(number[0]) == 5 and int(number[1]) <= 5:
if validator(number):
print("MASTERCARD")
elif length == 16 or length == 13 and int(number[0]) == 4:
if validator(number):
print("VISA")
else:
print("INVALID")
return number
def validator(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
return sum
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)]
even = [int(num[i]) for i in range(0, len(num), 2)]
new_sum = sum(validator(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
return True
else:
print("INVALID")
main()
I found the way to print the evens and the odds(multiply also time 2) but now I have to sum booth and check if the remainder is 0
Here the complete instruction:
http://docs.cs50.net/problems/credit/credit.html
Write a helper function to sum your digits. You'll need to use it extensively.
def dig_sum(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
return sum
num = '378282246310005' # your credit card number
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)] # these two remain the same
even = [int(num[i]) for i in range(0, len(num), 2)]
new_sum = sum(dig_sum(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
print('Valid') #valid!
sum(dig_sum(x) for x in odd) will get the digit sum for each number in your odd list and sum(...) that finds the resultant sum.
Input:
'378282246310005'
Output:
Valid
A first problem with your function is that you do not store the even/odd digits somewhere: you construct a list with one element each time, and print that element.
Now since two times a digit, can only result in a two digit number, we can use:
def sum2(x):
return (2*x)//10 + (2*x)%10
You can construct a list of all the digits at odd index with:
odd = [int(number[i]) for i in range(1,length,2)]
The same for digits at even index:
even = [int(number[i]) for i in range(0,length,2)]
Now we can simply use the sum(..) builtin function to sum up the digits:
total = sum(sum2(oddi) for oddi in odd) + sum(even)
and check if it is a multiple of 10:
return total%10 == 0
Or putting it all together:
def validator(number, length):
odd = [int(number[i]) for i in range(1,length,2)]
even = [int(number[i]) for i in range(0,length,2)]
total = sum(sum2(oddi) for oddi in odd) + sum(even)
return total%10 == 0
Or we can use a the following one liner for experts:
from itertools import zip_longest
def validator(number,length):
numbi = iter(numbi)
return sum(x+sum2(y) for x,y in zip_longest(numbi,numbi,fillvalue=0))%10 == 0
Related
lower = int(input("Enter lower range limit:"))
upper = int(input("Enter upper b range limit:"))
Count = 0
for i in range(lower, upper+1):
if((i%3==0) & (i%5==0)):
Count += 1
print(count)
I want to print 100 values which are divisible by 3 and 5, but in count only 7 is showing, can anyone suggest what to do, it will be appreciated!
Use this
num = int(input("How many Numbers you want :"))
i=0
Count = 0
while(Count != num):
if((i%3==0) and (i%5==0)):
Count += 1
print(i)
i = i + 1
print("Count is :",Count)
Python program to print all the numbers
divisible by 3 and 5 for a given number
Result function with N
def result(N):
# iterate from 0 to N
for num in range(N):
# Short-circuit operator is used
if num % 3 == 0 and num % 5 == 0:
print(str(num) + " ", end = "")
else:
pass
Driver code
if name == "main":
# input goes here
N = 100
# Calling function
result(N)
The sum of digit is running well, but Why is the factorial section not working? Is there any mistakes that I made with the if else, or the break ?
NUM = int (input ("Enter a number "))
if NUM > 1:
for x in range (2, NUM):
if (NUM % x) == 0:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
break
else:
factorial = 1
for I in range (1, NUM + 1,1):
factorial *= I
print (factorial)
else:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
Your break statement on line 12 is outside the if statement, so the for loop will break after the first pass regardless of the value of NUM. Are you sure you didn't mean to indent the break another four spaces?
# example of factorial with prime numbers
num = int(input("Enter a number"))
factorial = 1
if num%2 == 0:
for i in range(1, num + 1):
factorial = factorial*i
print("The factorial of ",num," is",factorial)
Below code checks if the number is prime or odd number. if its prime it finds the factorial of that number and if its odd number then it sums the range of the number. Hope its what you were looking for.
NUM = int(input("Enter number here"))
if NUM > 0:
if NUM % 2 == 0:
factorial = 1
for i in range(1, NUM +1):
factorial = factorial*i
print(factorial)
else:
sum_of_NUM = 0
for x in range(NUM+1):
sum_of_NUM += x
print(sum_of_NUM)
else:
print("something you want to put")
I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime...
Any assistant will be most appreciated !
def primes():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
num = 0
i = 0
ctr = 0
for num in range(start,end+1,1):
ctr = 0
for i in range(2,num//2,1):
if num % i == 0 :
ctr = ctr + 1
break
if (ctr==0 and num != 1):
print(num)
for i in range(2,num//2,1):
Lets check this snippet of code when num = 4,it becomes
for i in range(2,2,1):
Now we see the problem.
Solution..?
for i in range(2,(num//2)+1,1):
The following methods are all possible prime checkers you might use to check within your range:
def isPrime(Number): # slow
return 2 in [Number, 2 ** Number % Number]
def isprime(n): # out of memory errors with big numbers
"""check if integer n is a prime"""
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True
def is_prime(n): # Best until now
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:
# print '\t', f
if n % f == 0:
return False
if n % (f + 2) == 0:
return False
f += 6
return True
for i in range(2,num//2,1):
Above line is wrong. You are iterating from 2 to num / 2 - 1.
You should iterate from 2 to sqrt(num). (range(2, int(math.sqrt(n)) + 1))
Alternatively you can do a special check for 2 and modify your range to range(3, int(math.sqrt(n) + 1, 2)
An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)
How can I take an integer as input, of which the output will be the Collatz sequence following that number. This sequence is computed by the following rules:
if n is even, the next number is n/2
if n is odd, the next number is 3n + 1.
e.g. when starting with 11
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
This is my code now:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n_add = [n/2]
collatz = [] + n_add
else:
n_add2 = [3*n + 1]
collatz = [] + n_add2
print collatz
if I execute this and insert a number, nothing happens.
You are never changing the number n, so it will be the same each time round. You are also only printing if the number is odd. Also, square brackets [] indicate an array - I'm not sure what your goal is with this. I would probably rewrite it like this:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n = n/2
else:
n = 3*n + 1
print n
You might want to take some time to compare and contrast what I'm doing with your instructions - it is almost literally a word-for-word translation (except for the print
It is a little unclear from your code if you want to just print them out as they come out, or if you want to collect them all, and print them out at the end.
You should be modifying n each time, this will do what you want:
n = int(raw_input('insert a random number'))
while n > 1:
n = n / 2 if not n & 1 else 3 * n + 1 # if last bit is not set to 1(number is odd)
print n
## -- End pasted text --
insert a random number11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Using your own code to just print out each n:
n = int(raw_input('insert a random number'))
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
print n
Or keep all in a list and print at the end:
all_seq = []
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
all_seq.append(n)
print(all_seq)
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = number * 3 + 1
print(number)
try:
num = int(input('Please pick any whole number to see the Collatz Sequence in action.\n'))
collatz(num)
except ValueError:
print('Please use whole numbers only.')
I've also been working on it for a while now, and here's what I came up with:
def collatz (number):
while number != 1:
if number == 0:
break
elif number == 2:
break
elif number % 2 == 0:
number = number // 2
print (number)
elif number % 2 == 1:
number = 3 * number + 1
print (number)
if number == 0:
print ("This isn't a positive integer. It doesn't count")
elif number == 2:
print ("1")
print ("Done!")
elif number == 1:
print ("1")
print ("Done!")
try:
number = int(input("Please enter your number here and watch me do my magic: "))
except (ValueError, TypeError):
print ("Please enter positive integers only")
try:
collatz(number)
except (NameError):
print ("Can't perform operation without a valid input.")
Here is my Program:
def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*number+1)
return 3*number+1
else:
print("Invalid number")
number = input("Please enter number: ")
while number != 1:
number = collatz(int(number))`
And the output of this program:
Please enter number: 12
6
3
10
5
16
8
4
2
1