Python: Detect duplicate and consecutive numbers - python

Instructions:
"Create a python program to detect if a number of 10 digits is valid. The number should have 10 digits, it can't contain the number "0" and can't contain duplicate consecutive numbers."
...I am using the append to request the 10 numbers and validating that they are different of 0, but I still dont know how to see if the numbers are consecutive.
This is what I have so far:
list=[]
for num in range (1,10): #Request 10 numbers (it can't be zero)
num=int (input("Add 10 digits:"))
list.append (num)
while num != 0:
print ("The number is valid.")

Hints:
Convert the number to a string using the str() function
Use the len() function to validate the length
Use the in-operator to see validate whether the number contains zero
Use zip(s, s[1:]) as a simple way to bring consecutive characters together

use while because for will end you loop before finished if there duplicate digit
mylist=[]
while len(mylist) < 10: #Request 10 numbers (it can't be zero)
mylistLength = str(len(mylist))
num=int(input("Add 10 digits [" + mylistLength +"]: "))
if num not in mylist:
mylist.append(num)
else:
num=int(input("Digit exist, try other: "))
if len(mylist) == 10:
print("The number is valid.")
print(mylist)

Related

Python: Credit Card digits verification

I need to implement a function called “verify” that takes a single parameter called “number” and then checks the following rules:
The first digit must be a 4.
The fourth digit must be one greater than the fifth digit; keep in mind that these are separated by a dash since the format is ####-####-####.
The sum of all digits must be evenly divisible by 4.
4 If you treat the first two digits as a two-digit number, and the seventh and eighth digits as a two-digit number, their sum must be 100
This is what I have come up with so far:
def verify(number) : # do not change this line!
# write your code here so that it verifies the card number
number_string = number.replace("-","")
cardnumber = [int(n) for n in number_string]
if cardnumber[0] != 4:
return 1
elif cardnumber[3] != cardnumber[4] + 1:
return 2
elif sum(map(int, cardnumber)) % 4 != 0:
return 3
elif cardnumber[0:2] + cardnumber[6:8] != 100:
return 4
return True
# be sure to indent your code!
input = "4002-1001-0000" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output of the function
# do not remove this line!
You seem to have forgotten that you already converted cardnumber to a list of integers. It's not a string any more, so you don't need to use int each and every time. To compute your sums, you just need cardnumber[0]*10+cardnumber[1] and cardnumber[7]*10+cardnumber[8].
cardnumber is a list. A list can not be converted to an integer. To do so, you first need to convert the list to a string and to integer or directly to an integer using some logic.
using string to integer logic
elif int(''.join(cardnum[0:2])) + int(''.join(cardnum[7:9])) != 100:

How to include a lot of decision making loops for checking a number within a range in a correct way?

I am trying to solve a question to generate a list of numbers from a given range by making each number passed through a set of rules to get that number added in the list. Also to find the maximum element from the list.
This is the actual question:
Write a python program which finds the maximum number from num1 to num2 (num2 inclusive) based on the following rules.
Always num1 should be less than num2
Consider each number from num1 to num2 (num2 inclusive). Populate the number
into a list, if the below conditions are satisfied
a)Sum of the digits of the number is a multiple of 3
b)Number has only two digits
c)Number is a multiple of 5
Display the maximum element from the list
In case of any invalid data or if the list is empty, display -1.
First of all, I am new to Python and not familiar to solve these type of complex problems. So I think I made a lot of silly mistakes.
def find_max(num1, num2):
max_num=-1
num_list=[] #list declared
if(num1<num2): #to check num1 < num2 as said in the question
for numbers in range(int(num1),int(num2)+1): #for numbers from the range
tot=0
count=0
while(numbers>0):
digit=numbers%10
tot=tot+digit #to generate sum of digits
numbers=numbers//10
count=count+1 #to count the number of digits
if(tot%3==0 and count==2 and numbers%5==0):
num_list.append(numbers) #to generate the list
else:
print(-1)
else:
print(-1)
max_num = max(num_list) #to find the maximum value in the list
return max_num
#Provide different values for num1 and num2 and test your program.
max_num=find_max(10,15)
print(max_num)
Results I am getting :
-1
-1
-1........
The mistake in your code is that in your 'while' loop, you're modifying the value which is being checked for the conditions. (lulian has explained this well.)
Actually, your code can be rewritten more simply. You have these requirements. (a) Sum of the digits of the number is a multiple of 3. (b) Number has only two digits (c) Number is a multiple of 5.
Requirements (a) and (c) can be combined into a single requirement: if you know middle school mathematics, (a) basically means that the number itself is divisible by 3, and (c) means that it is divisible by 5. Together, they mean that the number should be divisible by 3 times 5, i.e. 15. We can exploit this property.
Let us revisit the problem. Observe that each time invalid data is detected, I use a return statement.
def find_max(num1, num2):
# check for invalid data: 'num1' and 'num2' should be integers
if type(num1) != int or type(num2) != int:
return -1
# check if 'num1' is greater than 'num2'
if num1 > num2:
return -1
# initialize empty list
num_list = []
# find the nearest multiple of 15 to 'num1'
if num1 % 15 == 0:
nearest_multiple = num1
else:
nearest_multiple = num1 + 15 - num1 % 15
# scan through possible numbers from 'nearest_multiple' to 'num2'
for numbers in range(nearest_multiple, num2 + 1, 15):
if 10 <= numbers <= 99 or -99 <= numbers <= -10:
num_list.append(numbers)
# if no valid number was detected, the list will remain empty
if num_list == []:
return -1
return max(num_list)
Explanation:
First, locate the nearest multiple of 15 greater than or equal to num1. So, if num1 is 15, then nearest_multiple is also 15. But if num1 were 21, then nearest_multiple would be 30. (The formula used is pure math.)
Then, we iterate from nearest_multiple to num2 in jumps of 15. That way, we encounter only numbers which satisfy both (a) and (c). Then we check the number we encounter for condition (b).
Your function is not working like you want because you are using numbers for checking condition, but you're changing it in your code when you are making computations.
numbers = numbers // 10
So when you'll use it in if block, numbers will have a different value not the initial one.
For example with numbers = 15 at the start it will become:
numbers -> 15 -> 1 -> 0
Thus when you check numbers % 5 == 0 it will never pass and the if conditional will fail. Use a copy of the number and every thing will work fine.
Revisited code:
def function_name(num1,num2):
num_list=[] #list declared
if(num1<num2): #to check num1 < num2 as said in the question
for numbers in range(int(num1),int(num2)+1): #for numbers from the range
tot=0
count=0
copy = numbers
while(copy>0):
digit=copy%10
tot=tot+digit #to generate sum of digits
copy = copy//10
count = count+1 #to count the number of digits
if(tot%3==0 and count==2 and numbers%5==0):
num_list.append(numbers) #to generate the list
else:
print(-1)
else:
print(-1)
if num_list:#if the list is populates with some numbers
return max(num_list)
else: return "what you think is needed in case there aren't numbers" #None is a good choice equivalent to null in other programming languages
print(function_name(10,15))
My idea to implement your function
Not the best, but its shorter and more readable.
def function_name(num1,num2):
num_list=[] #list declared
if(num1<num2): #to check num1 < num2 as said in the question
for number in range(int(num1),int(num2)+1): #for numbers from the range
# for every char return its int and group all in a list
# [int(digit) for digit in str(number)]
tot = sum( [int(digit) for digit in str(number)])
#count how many char are that is like saying how many digits
count= len(str(number))
if(tot%3==0 and count==2 and number%5==0):
num_list.append(number) #to generate the list
else:
print(-1)
else:
print(-1)
if num_list:#if the list is populates with some numbers
return max(num_list)
else:
return "what you think is needed in case there aren't numbers" #None is a good choice equivalent to null in other programming languages
print("Max", function_name(10,15))
def find_max(num1, num2):
if (num1<num2):
max_num=-1
for i in range(num1,num2 + 1,1):
if (10 <= i <= 99 or -99 <= i <= -10):
j = i/10
k= i%10
if ((j+k)%3==0 and i%5 == 0):
max_num = i
# Write your logic here
return max_num
else:
return -1
#Provide different values for num1 and num2 and test your program.
max_num=find_max(-100,500)
print(max_num)
def find_max(num1, num2):
max_num=-1
num_list=[]
if(num1<num2):
for numbers in range(int(num1),int(num2)+1):
tot=0
count=0
while(numbers>0):
digit=numbers%10
tot=tot+digit
numbers=numbers//10
count=count+1
if(tot%3==0 and count==2 and numbers%5==0):
num_list.append(numbers)
else:
print(-1)
else:
print(-1)
max_num = max(num_list)
return max_num
max_num=find_max(10,15)
print(max_num)

to allow the user to input a 3-digit number, and then output the individual digits in the number

how would i allow a user to input a 3-digit number, and then output the individual digits in the number in python
e.g. If the user enters 465, the output should be “The digits are 4 6 5”
sorry if this sounds basic
You use for your number num:
num % 10 to extract the last digit.
num = num // 10 to remove the final digit (this exploits floored division).
Finally, you want to get out the leading digit first. Therefore you adopt a recursive function to perform the above (which calls itself prior to printing the digit).
The solution using str.isdigit and re.sub functions:
import re
num = input('Enter number:')
if num.isdigit():
num_sequense = re.sub(r'(\d)(?=\d)', r'\1 ', num)
print("The digits are:", num_sequense)
else:
print("There should be only digits", num)
The output for the input 123:
The digits are: 1 2 3
The output for the input a1s2d3:
There should be only digits a1s2d3
Hard to make in one line, anyway this should do exactly what you want:
inp = list(input())
print("The digits are ", end ='')
for i in inp:
print(i, end=' ')
If you don't care for formatting, one-liner is possible:
print("The digits are ",list(input()))

How to pick one number of an Integer

How can I pick one of the digits from an Integer like: 97723
and choose (for example) the number 2 from that number and check if its an odd or an even number?
Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)
Thanks in advance
2 is the 4th digit.
You can get the digits of a number using this construct.
digits = [int(_) for _ in str(97723)]
This expression will be true if the 4th digit is even.
digits[3] % 2 == 0
# choose a digit (by index)
integer = 97723
digit_3 = str(integer)[3]
print(digit_3)
# check if even:
if int(digit_3) % 2 == 0:
print(digit_3, "is even")
# get all odd numbers directly
odd_digits = [digit for digit in str(integer) if int(digit) % 2 == 1]
print(odd_digits)
even = lambda integer: int("".join([num for num in str(integer) if int(num) % 2 == 0]))
or
def even(integer):
result = ""
integer = str(integer)
for num in integer:
if int(num) % 2 == 0:
result += num
result = int(result)
return(result)
If you want to "parse" a number the easiest way to do this is to convert it to string. You can convert an int to string like this s = string(500). Then use string index to get character that you want. For example if you want first character (number) then use this string_name[0], for second character (number) use string_name[1] . To get length of your string (number) use len(string). And to check if number is odd or even mod it with 2.
# Converting int to string
int_to_sting = str(97723)
# Getting number of characters in your string (in this case number)
n_of_numbers = len(int_to_sting)
# Example usage of string index
print("First number in your number is: ",int_to_sting[0])
print("Second number in your number is: ",int_to_sting[1])
# We need to check for every number, and since the first number is int_to_sting[0] and len(int_to_sting) returns actual length of string we need to reduce it by 1
for i in range(n_of_numbers-1):
if int_to_sting[i]%2==0:
print(int_to_sting[i]," is even")
else:
print(int_to_sting[i]," is odd")

Python: How to use a Variable Integer to Call a Specific Part of a String

Ok, so I've got a couple issues with a program (for school again) that I'm using to add up all the digits of a number. I've got some of the program down, except 2 things. First, how to use a variable (thelength below) in replacement of a number to call a specific digit of the input (I'm not sure if this is even possible, but it would be helpful). And second, how to add up different numbers in a string. Any ideas?
Here's what I have so far:
number = str(int(input("Please type a number to add up: ")))
length = len(number)
thelength = 0
total = 0
thenumbers = []
while thelength < length:
#The issue is me trying to use thelength in the next two lines, and the fact that number is now a string
total += number[thelength]
thenumbers.append(number[thelength])
thelength += 1
for num in thenumbers:
print(num[0])
print("+")
print("___")
print(total)
Thanks for any help I can get!
I don't know what "call a specific digit of the input" means, but the error in your code is here:
total += number[thelength]
total is an int, and you're trying to add a string to it, convert the digit to an integer first.
total += int(number[thelength])
Result:
1
2
3
+
___
6
import re
import sys
INPUT_VALIDATOR = re.compile("^[0-9]+$")
input_str = input("Please type a natural number to add up: ")
if INPUT_VALIDATOR.match(input_str) is None:
print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
print ("This displeases me, goodbye puny human.")
sys.exit(1)
total = 0
for digit_str in input_str:
print(digit_str)
total += int(digit_str)
print("+")
print("___")
print(total)
If you don't need to print the digits as you go, it's even easier:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))
number = int(input("Please type a number to add up: "))
total = 0
while number > 0:
total += number % 10
total /= 10
print(total)
num % 10 pretty much gets the last digit of a number
then we divide it by 10 to truncate the number by its last digit
we can loop through the number as long as it's above 0 and take the digital sum by using the method outlined above
Every thing that you need is convert the digits to int and sum them :
>>> s='1247'
>>> sum(map(int,s))
14
But as you get the number from input it could cause a ValueErorr , for refuse that you can use a try-except :
try :
print sum(map(int,s))
except ValueErorr :
print 'please write a valin number :'
Also if you are using python 2 use raw_input for get the number or if you are using python 3 just use input because the result of both is string !

Categories

Resources