Taking away from nearest 10 - python

Okay, i have made my code so that a user can input 7 numbers and times them by 1 for the odd index numbers and 3 for the even:
num = str(input("Please enter 7 numbers")
length = len(num)
while length < 7 or length ? 7:
num = input("Only enter 7 numbers")
string = ''
for t in range(1,8):
if t % 2 == 0:
string += str(t * 3)
else:
string += str(t) + ' '
print(string)
This works fine, but now i need to add all the numbers up and take it away from the highest 10 so for example, all the numbers add up to 53 i need to take that away from 60 which leaves me 7, that will be my eight number, then after i have got that number i print it out, how do i get it to add the numbers up and the take it away from the highest 10 and output the difference of the two into the numbers i already have?
Thanks
Brad

If you have a number, x, which is equal to 53, then going up should be math.ceil(x) except that math.ceil() rounds for 1. To account for that, we divide by 10, use math.ceil(), and then multiply by 10 again:
import math
rounded_up = math.ceil(x / 10) * 10
result = rounded_up - x

Brad could you clarify your question? Also your above code does not work.
Missing a bracket on the first line and this isn't valid while length < 7 or length ? 7:

I believe this is what you're looking for:
def take_away_from_nearest(number, nearest):
return nearest - (number % nearest)
Usage:
>>> take_away_from_nearest(53, 10)
7
edit:
If I understand you correctly, this would be the entire code:
while True:
# this is just an easy way to keep asking until the input is correct
num = input("Please enter 7 numbers: ")
if len(num) == 7:
break
weird_sum = 0 #here's where we're gonna sum up the numbers; the "eighth number"
for index, character in enumerate(num):
if index % 2 == 0: # index is odd, so count the character thrice
print(3 * int(character))
weird_sum += 3 * int(character)
else: # index is even
print(int(character))
weird_sum += int(character)
print(10 - (weird_sum % 10)) # 10 minus (weird_sum modulo 10)
# and finally, adding them all up and checking whether it ends with 0:
print((10-(weird_sum % 10) + weird_sum) % 10 == 0) # prints True

Related

How to create list of 15-digit numbers with condition?

I want to create list of random 20 15-digit numbers and each of this 15-digit numbers must follow 1 rule.
The rule is that I want this 15-digit number to be made out of 5 3-digit numbers in which first digit + second digit = third digit or if sum of first two digits is greater than 10 then third digit must be, equal to second digit of sum of first two digits. for example if first digit is 5 and second is 8, third digit must be 3 since 5 + 8 = 13.
I've written code that fills list with 15-digit numbers with the same rule, but it only works for first three digits.
import random as rd
def numchoose(start, end):
arr=[]
num=0
while num<20:
a=(rd.randint(start, end))
if int(str(a)[0]) + int(str(a)[1]) == int(str(a)[2]):
arr.append(a)
num+=1
elif int(str(a)[0]) + int(str(a)[1]) > 10 and int(str(a)[2]) == int(str(int(str(a)[0]) +
int(str(a)[1]))[1]) :
arr.append(a)
num+=1
else: continue
print(numchoose(100000000000000, 999999999999999))
How do I write this code so that entire 15-digit number is made out of 3-digit numbers that follow the stated rule and first three digits are not the only ones that follow rule?
This seems to work, but i replaced the big number with how long you want the number to be.
import random as rd
def numchoose(len):
number = ""
for i in range(int(len/3)):
a = rd.randint(0, 9)
while i == 0 and a == 0:
a = rd.randint(0, 9)
b = rd.randint(0, 9)
c = a + b
if c >= 10:
c -= 10
number += str(a) + str(b) + str(c)
return int(number)
print(numchoose(15))
Bit more compact then #eav28 but credit goes to them for answering first:
import random
def NumberGen(Length):
Number = ""
for X in range(int(Length // 3)):
A = random.randint(0, 9)
## To drop leading zero's:
## if X == 0 and A == 0:
## A = random.randint(1, 9)
B = random.randint(0, 9)
C = A + B
if C > 9:
C -= 10
Number += str(A) + str(B) + str(C)
return Number
print(NumberGen(15))
I hope this answers your question

Validate Credit Card Number Using Luhn Algorithm Python

I am trying to implement Luhn algorithm in Python. Here is my code
def validate(n):
if len(str(n)) > 16:
return False
else:
if len(str(n)) % 2 == 0:
for i in str(n[0::2]):
digit = int(str(n[i])) * 2
while digit > 9:
digit = sum(map(int, str(digit)))
dig_sum = sum(map(int, str(n)))
return True if dig_sum % 10 == 0 else False
elif len(str(n)) % 2 != 0:
for i in str(n[1::2]):
digit = int(str(n[i])) * 2
while digit > 9:
digit = sum(map(int, str(digit)))
dig_sum = sum(map(int, str(n)))
return True if dig_sum % 10 == 0 else False
I keep getting the error
TypeError: 'int' object has no attribute '__getitem__
Following is python implementation of Lunh Algorith to detect a valid credit card number. Function takes a number as string and return whether its valid credit card or not.
Its based on the steps mentioned in the following link: https://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm
Step 1 - Starting with the check digit double the value of every other digit (right to left every 2nd digit)  
Step 2 - If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.
Step 3 - Now add the un-doubled digits to the odd places
Step 4 - Add up all the digits in this number
If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid. 
def luhn(ccn):
c = [int(x) for x in ccn[::-2]]
u2 = [(2*int(y))//10+(2*int(y))%10 for y in ccn[-2::-2]]
return sum(c+u2)%10 == 0
#Test
print(luhn("49927398716"))
It is hard to tell without the complete error message, but it is likely because you confused in some places where you put the indexing and where you put the string conversion, for example: for i in str(**n[1::2]**) and digit = int(str(**n[i]**)) * 2
A good way to handle it is to just create a temporary variable n_str = str(n), and use it instead of str(n) over and over again.

python addition 2 digit number

I'm studying algorithms. The exercise consist in put a number of 2 digits (between 10 and 99) and then do the addition of the two digits. I made it in python and it works, but my teacher said that there's another way to do it without the conversions that i'm using. Can you help me? Is there a better way? Thanks.
for i in range(5):
add = 0
num = input("Number: ")
num = int(num)
if num > 9 and num < 100:
num = str(num)
add = int(num[0]) + int(num[1])
print("The addition of the two digits is: " + str(add))
else:
print("It is not a two digit number.")
I think he meant:
(num // 10) + (num % 10)
With num // 10 you perform an integer division with 10. But this is the first digit. With num % 10 you get the remainder of the division, which is the second digit. For example:
>>> 67 // 10
6
>>> 67 % 10
7
The most succinct way must be:
sum(divmod(num, 10))
because divmod performs the integer division with 10 and finding the remainder at the same time. So with sum we get the sum of those two numbers. For example:
>>> divmod(67, 10)
(6, 7)
>>> sum(divmod(67, 10))
13
rem = num%10
quotient = int(num/10)
sum = rem+quotient
print sum
I guess this should suffice.

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Recursion function for counting the number of digits in a number?

So I know that this is something simple that can be done without a recursion function but I need to know the backside to this as I can't seem to figure out how to write this using recursion. im using this so far
n = int(raw_input("What is n? "))
def digit(n):
if n< 10:
return 1
else:
new = n/10
print 1 + digit(new/10)
return 1 + digit(new/10)
digit(n)
Now if I type in a number such as 33 then it outputs 2 but if I do a longer number then it doesn't print it properly and I was unsure as to what exactly it wrong with it.
The problem is,
new = n/10
return 1 + digit(new/10)
You are already dividing the number by 10, in new = n / 10, which reduces the last digit and you are again dividing it by 10 before calling digit. So, you are ignoring 1 digit in every recursive call.
Instead, you can simply do
return 1 + digit(n / 10)
or
new = n / 10
return 1 + digit(new)
#!/usr/bin/python
n = int(raw_input("What is n? "))
def digit(n):
if n < 10:
return 1
else:
return 1 + digit(n/10)
print digit(n)
You can do like this too.
def counter(number):
if(number == 0):
return 0
return counter(int(number/10)) + 1
number = 1998
print(counter(number)) // it will print 4

Categories

Resources