With my code, I want to get the last two digits of an integer. But when I make x a positive number, it will take the first x digits, if it is a negative number, it will remove the first x digits.
Code:
number_of_numbers = 1
num = 9
while number_of_numbers <= 100:
done = False
num = num*10
num = num+1
while done == False:
num_last = int(repr(num)[x])
if num_last%14 == 0:
number_of_numbers = number_of_numbers + 1
done = True
else:
num = num + 1
print(num)
Why don't you extract the absolute value of the number modulus 100? That is, use
abs(num) % 100
to extract the last two digits?
In terms of performance and clarity, this method is hard to beat.
To get the last 2 digits of num I would use a 1 line simple hack:
str(num)[-2:]
This would give a string.
To get an int, just wrap with int:
int(str(num)[-2:])
Simpler way to extract last two digits of the number (less efficient) is to convert the number to str and slice the last two digits of the number. For example:
# sample function
def get_last_digits(num, last_digits_count=2):
return int(str(num)[-last_digits_count:])
# ^ convert the number back to `int`
OR, you may achieve it via using modulo % operator (more efficient), (to know more, check How does % work in Python?) as:
def get_last_digits(num, last_digits_count=2):
return abs(num) % (10**last_digits_count)
# ^ perform `%` on absolute value to cover `-`ive numbers
Sample run:
>>> get_last_digits(95432)
32
>>> get_last_digits(2)
2
>>> get_last_digits(34644, last_digits_count=4)
4644
to get the last 2 digits of an integer.
a = int(input())
print(a % 100)
You can try this:
float(str(num)[-2:])
Related
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:
This question already has answers here:
How to take the nth digit of a number in python
(7 answers)
Closed 4 years ago.
How can I get the nth digit of a number when the first digit is on the right-most of the number? I'm doing this on python.
You could convert the number to a string and then use a negative index to access a specific digit from the end:
>>> num = 123456
>>> n = 3
>>> str(num)[-n]
'4'
If your numbers are integers, you can compute it with integer division and modulo:
def nth_digit(number, digit):
return abs(number) // (10**(digit-1)) % 10
nth_digit(4321, 1)
# 1
nth_digit(4321, 2)
# 2
If we go further left, the digit should be 0:
nth_digit(4321, 10)
# 0
Here's one way, assuming you are talking about integers and the decimal system:
def extract_digit(n, number):
number = abs(number)
for x in range(n-1):
number = number // 10 #integer division, removes the last digit
return number % 10
Convert to a string, reverse the string, and then take the index of the string and convert the string back into an integer. This works:
def nth_digit(digit, n):
digit = str(digit)
return int(digit[::-1][n])
Let me know if this works for you!
Convert to a string, reverse the string, and then take the index of the string and convert the string back into an integer. This works:
def nth_digit(digit, n):
digit = str(digit)
return int(digit[::-1][n])
Let me know if this works for you!
I am trying to count the number of digits of an input. However, whenever I input 10 or 11 or any two digit number, the output is 325. Why doesn't it work?
inputnumber = int(input())
countnumber = inputnumber
digitcount = 0
while countnumber > 0:
digitcount += 1
countnumber = countnumber/10
print(digitcount)
# result is 325 when input is 10 or 11
Your error mainly happened here:
countnumber=countnumber/10
Note that you are intending to do integer division. Single-slash division in Python 3 is always "float" or "real" division, which yields a float value and a decimal part if necessary.
Replace it with double-slash division, which is integer division: countnumber = countnumber // 10. Each time integer division is performed in this case, the rightmost digit is cut.
You also have to watch out if your input is 0. The number 0 is considered to be one digit, not zero.
I would not convert that beautiful input to int to be honest.
print(len(input())
would be sufficient.
An easily understandable one liner that no one can complain about.
But of course, if negative sign bothers you like wisty said,
len(str(abs(int (v))))
will be safer for sure.
Again, if you are worried about the non numeric inputs like mulliganaceous said, you better cover that case.
str = input()
if str.isnumeric():
print(len(str(abs(v))))
else:
print("bad input")
The reason is that in python 3 the division of two integers yields a floating point number. It can be fixed using the // operator:
number = int(input())
digits_count = 0
while number > 0:
digits_count += 1
number = number // 10
You must be using Python3, logically your function is right. You just have to change
countnumber = countnumber // 10
because Python3, // is floor division, meanwhile / is true division.
>>>print(1 / 10)
0.1
>>>print(1 // 10)
0
Btw, as #chrisz said above, you can just simply using the len() function to get the number of digits of the input
>>>print(len(input())
num = int(input())
count = 0
while num > 0:
count += 1
num = num // 10
print(count)
def digits(number):
number = str(number)
lenght = len(number)
return lenght
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
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")
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 !