Credit Card Number Validator Function [Python 3] - python

I am a Starter in Python programming , and I took the challenge I found in the internet ( Credit Card Number Validator {Luhn Algorithm} ) and i wrote this Function :
def CheckNumber(CreditCardNumber) :
CheckNumberBool = False
CreditCardNumber = list(map(int, CreditCardNumber))
x = 1
y = 0
WorkingList = list()
#--------------------------------------------------#
while x <= 15 :
WorkingList[x].append(CreditCardNumber[x] * 2)
x += 2
#--------------------------------------------------#
while y <= 15 :
WorkingList[y].append(CreditCardNumber[y])
y += 2
#--------------------------------------------------#
WorkingListStr = str(sum(WorkingList))
#--------------------------------------------------#
while y <= 15 :
if WorkingList[y] >= 10 :
for x in WorkingListStr :
WorkingList.append(int(x))
y += 1
#--------------------------------------------------#
if sum(WorkingList) % 10 == 0 :
CheckNumberBool = True
print("This is a Valid Credit Card Number")
else :
CheckNumberBool = False
print("This isn't a Valid Credit Card Number")
But the problem is that when i run it in my Terminal Command Line (python3 myfile.py) , I get this error :
File "Credit_Card_Algorithm.py", line 13, in CheckNumber
WorkingList[x].append(CreditCardNumber[x] * 2)
IndexError: list index out of range
Thanks to all of your very helpful suggestions and sorry if i made a mistake , this is my first time writing to the huge StackOverflow Community ;-D

Related

Finding number with specified collatz sequence length

I need to make a program that finds a number with specified collatz sequence length. However, there is always a problem that the program is too slow. For example my current best score that i could get was number with collatz sequence length of 1200 (I need to be able to get number with collatz sequence length of 1800).
I tried a lot of diffrent methods, but the best one so far was trying to recreate collatz number tree.Here is an example from wiki. As I said before i need to be able to get a number with collatz sequence length of 1800 but I cant get more than 1200.
That's my current solution (I know it's complicated but other methods I tried so far were able to get collatz sequence length up to 500 only):
A = int(input())
limit = 1000000000000000000
def runCollaz(ciag):
steps = 0
while ciag != 1:
if (ciag % 2 == 0):
ciag /= 2
else:
ciag *= 3
ciag += 1
steps+=1
return steps
def makeChainLess(number):
if (number % 2 == 0):
return number / 2
else:
return ((number * 3) + 1)
collatzTree = [[1, 1]]
finallAns = "None"
def getAns(collatzTree, what):
awnser = "None"
if (collatzTree[0][0] < limit and collatzTree[0][1] == A):
awnser = collatzTree[0][0]
while (len(collatzTree) > 250):
currentHigh = collatzTree[0][0]
highIndex = 0
index = 0
for x in collatzTree:
if (x[0] > currentHigh):
currentHigh = x[0]
highIndex = index
index += 1
collatzTree.pop(highIndex)
if (collatzTree[0][0] > 4):
if (collatzTree[0][0] - 1) % 3 == 0:
if (collatzTree[0][0] - 1) % 2 != 0:
collatzTree += [[(collatzTree[0][0] - 1) / 3, int(collatzTree[0][1]) + 1]]
collatzTree += [[collatzTree[0][0] * 2, int(collatzTree[0][1]) + 1]]
collatzTree.pop(0)
else:
collatzTree += [[collatzTree[0][0] * 2, int(collatzTree[0][1]) + 1]]
collatzTree.pop(0)
else:
collatzTree += [[collatzTree[0][0] * 2, int(collatzTree[0][1]) + 1]]
collatzTree.pop(0)
if (what == "C"):
return collatzTree
else:
return awnser
while finallAns == "None":
finallAns = getAns(collatzTree, "A")
collatzTree = getAns(collatzTree, "C")
print(int(finallAns))
If anyone could help i would really appricate it.
Here is a simple code that takes only a few minutes to run for 10 million. It just needs more computing power, which is kind of the story on Collatz.
'''
This code finds numbers that have the specified Collatz sequence length
(by brute force)
'''
import time
start = time.time() #start code timer
n = 1 #set low end of range
for number in range (10000000, n-1, -1): #work down from max range
num = number
trial = 0
while number > 1: #set up looping until 1 is reached
if number % 2 == 0: #set up normal Collatz sequence comp.
number = number // 2
else:
number = (number * 3) + 1
trial = trial+1 #update counter for each loop
if number == 1 and trial == 500 or trial == 600: #set target numbers
#print all numbers where specified target occured:
print("Number with sequence "
"length of {0}: {1}".format(trial, num))
if number == n:
print("end of range") #tells user that code has ended
end = time.time()
print("elapsed time: ",end - start)

Is there a way I can compare the same variable and choose the higher one and print it?

The value of y is changing every time the while loops continues, I tried the watchpoints modules but I need a way to find out the highest y has ever been and print it, I'll print the code that I'm trying to get to work.
import random
from watchpoints import watch
def alg(I):
print(I)
x = 1
while i > 1:
if (i % 2) == 0:
i = int(i / 2)
x = x + 1
else:
i = int(3 * i + 1)
x = x + 1
print(I)
y = 1
if i in range(1, 9):
y = 1
if i in range(10, 99):
y = 2
if i in range(100, 999):
y = 3
if i in range(1000, 9999):
y = 4
watch(a)#I want to know when y reachest the highest
print(y, "is the max number of caracters")#then print it
print("numero passaggi = ", str(x))
print("1: choice")
print("2: random")
type = int(input(" 1 or 2: "))
if type == 1:
i = input("Enter a number: ")
alg(int(I))
elif type == 2:
i = random.randint(1, 100) # 10^9
alg(I)
else:
print("Enter 1 or 2")
I want to know when y reaches the highest and print it below.
There are many ways to do this, but since you seem interested in "watching" the values of y as they change, one good option might be to make your alg function a generator that yields the values of y. The caller can then do whatever it wants with those values, including taking the max of them.
Note that instead of doing this kind of thing to figure out how many digits a number has:
if i in range(1, 9):
y = 1
if i in range(10, 99):
y = 2
if i in range(100, 999):
y = 3
if i in range(1000, 9999):
y = 4
you can just do:
y = len(str(i))
i.e. turn it into a string and then count the characters.
def alg(i: int):
x = 1
while i > 1:
if i % 2 == 0:
i = i // 2
x += 1
else:
i = 3 * i + 1
x = x + 1
print(f"i: {i}")
yield len(str(i))
print(f"numero passaggi = {x}")
print(f"Max number of digits: {max(alg(50))}")
i: 25
i: 76
i: 38
i: 19
i: 58
i: 29
i: 88
i: 44
i: 22
i: 11
i: 34
i: 17
i: 52
i: 26
i: 13
i: 40
i: 20
i: 10
i: 5
i: 16
i: 8
i: 4
i: 2
i: 1
numero passaggi = 25
Max number of digits: 2
The simplest method would be to create another variable to store the highest value that y has achieved and run a check each loop to see if the new y value is larger than the previous max.
Here is an example:
def exampleFunc():
i = 0
y = yMax = 0
while i < 20:
y = random.randint(1, 100)
if y > yMax:
yMax = y
i += 1
print(yMax)
The easiest way to approach something like this is to transform your function into one that returns all intermediate values, and then aggregate those (in this case, using the builtin max()).
from math import log10
def collatz_seq(n):
yield n
while n > 1:
if n % 2:
n = 3 * n + 1
else:
n //= 2
yield n
def print_stats(n):
seq = collatz_seq(n)
idx, val = max(enumerate(seq), key=lambda x: x[1])
digits = int(log10(val)) + 1
print(f"{digits} is the max number digits")
print(f"{idx} is the iteration number")
Here I use enumerate() to give me the index of each value, and I use math.log10() to obtain the number of digits in the number (minus one).

Error: '>=' not supported between instances of 'type' and 'int'

My code is in file Test.py
name = input("enter your name :")
id = int(input("enter your id :")
score = [int]*3
MyLib.calculate(score)
MyLib.result(name, id, score)
And this the code in MyLib.py
def calculate (x) :
n = 0
for n in x :
nilai = int(input("Input Your Score : "))
def result (a,b,c) :
n = 0
sum = 0
for n in c :
if n >= 80 and n <= 100 :
i = 4
x = "A"
elif n < 80 and n >= 70 :
i = 3
x = "B"
elif n < 70 and n >= 60 :
i = 2
x = "C"
elif n < 60 and n >= 50 :
i = 1
x = "D"
elif n < 50 and n >= 0 :
i = 0
x = "E"
sum += i
print("Your Name :",a)
print("Your ID :", b)
print("Your score number is ",n," and your score alphabet is ",x)
print("Your avg score is", sum)
But after i input the score (ex. 80, 70, 60) the result is TypeError: '>=' not supported between instances of 'type' and 'int'.
The line
score = [int]*3
produces the list
[int, int, int]
When you pass score to MyLib.calculate, you iterate over each element (i.e., each int) and create the local variable nilai which holds the value entered by the user.
However, nilai is reassigned to each new input meaning that you lose the previous value. Furthermore, you never return any of these values which mean that they are lost forever.
score then gets passed to result. It is then iterated over. In each iteration, n is equal to int since that's the only element in the list.
You compare int to 80 in the line
if n >= 80 and n <= 100:
int is an object of type type. It makes no sense to compare a type object to 80 which is an integer.
Try replacing MyLib.calculate with the following.
def calculate(length):
scores = []
for _ in range(length):
nilai = int(input("Input Your Score : "))
scores.append(nilai)
return scores
You can then call
scores = MyLib.calculate(3)

boolean string not counted in while/if statement in python[3.8]

I'm a beginner programmer and chose python[3.8] as my choice to learn. I don't even know what to ask or how to search this site. My program counts 30 to 40 and prints 'Go' for multiples of 3 and strings of 3 and remainders of 3. It counts Go's. Output should be 10 but it's 3. It's not counting the strings. There is no error msgs.
`enter code here`
s = '3'
x = 40
y = 30
num = 0
while y < x :
y=y+1
if y % 3 == 0 or y % 10 == 3 or s in 'y' :
print('Go',y)
num = num + 1
print(num, 'Go\'s')
I think the problem here is to understand how python works.
When you write s in 'y' it will always return false because y here is a character that composes the string which value is ythe character.
So what you'll need to do is use the function str(param) to convert your integer to a string with the same value.
This is a code that works the way you want to.
s = '3'
x = 40
y = 30
num = 0
while y < x :
if y % 3 == 0 or y % 10 == 3 or s in str(y) :
print('Go',y)
num = num + 1
y=y+1
print(num, 'Go\'s')

How to multiply through repeated addition using python?

I can't display the needed output for my homework. Where do I need to change my code?
The question is:
Multiplication through repeated addition
Example: 5 x 6 = 5+5+5+5+5+5
I am a second year engineering student and a beginner at programming. I lack the skills and background on how to code. I have been doing this for days and still can't discover the problem. Our university professor does not teach us this lesson yet so I am still not familiar with programming.
#4bit by 4bit multiplication through repeated addition.
#Example: 5 x 6 = 5+5+5+5+5+5
def multiply(x,y):
#Any number multiplied by 0 will result to 0.
if(y == 0):
return 0
#This will repeatedly add ‘x’, ‘y’ times.
if(y > 0 ):
return (x + multiply(x, y - 1))
#When 'y' is negative...
if(y < 0 ):
return -multiply(x, -y)
def add(x, y):
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ""
carry = 0
for i in range(max_len - 1, -1, -1):
r = carry
r += 1 if x[i] == "1" else 0
r += 1 if y[i] == "1" else 0
result = ("1" if r % 2 == 1 else "0") + result
carry = 0 if r < 2 else 1
if carry != 0: result = "1" + result
return result.zfill(max_len)
#This will convert the binary number to an integer.
def conv(binary):
exponent = 0
total = 0
for digit in reversed(binary):
if digit == "1":
total += 2 ** exponent
exponent += 1
return total
#The user will input numbers here:
c = int(input("Enter the multiplicand: "))
d = int(input("Enter the multiplier: "))
result1=c
a=(bin(c)[2:])
b=(bin(d)[2:])
result=a
print("The binary value of the multiplicand is ",a)
print("The binary value of the multiplier is ",b)
for i in range(conv(b) - 1):
print("{} + {}".format(result, a), end="")
result = add(result, a)
print("= {}".format(result))
This is the output:
Enter the multiplicand: 5
Enter the multiplier: 6
The binary value of the multiplicand is 101
The binary value of the multiplier is 110
101 + 101= 1010
1010 + 101= 1111
1111 + 101= 10100
10100 + 101= 11001
11001 + 101= 11110
The product of 5 and 6 is 30
The product in binary is: 101 x 110 = 11110
5 + 5Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module> start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start exec(open(mainpyfile).read(), _main_.__dict__)
File "<string>", line 68, in <module>
File "<string>", line 20, in add
TypeError: object of type 'int' has no len()
[Program finished]
Based on the amount of code here, it seems that this question is more complex than the shared info. To just have the effect of multiplying user-input integers, I'd do this:
x = int(input("Enter the multiplicand: "))
y = int(input("Enter the multiplier: "))
result = 0 #this will be the ultimate answer
if y < 0: #figure out if y is negative
count = -y #establish a counter
else:
count = y
while count > 0: #set the condition for your loop. If count == 0, it will loop 0 times. result is already set to 0.
if x == 0:
count = 0 #this will exit the loop. Other options include "break"
result += x #this will only execute if x doesn't equal 0.
count -= 1 # when this value equals 0, loop ends, and the result is set.
print result

Categories