E.g. in a given input the fourth digit must be one greater than the fifth digit
input = "5000-0000-0000"
if input[3] != input[5] + 1
return false
If you think about what input[3] and input[5] are, you will pretty quickly realize they are characters and not numbers that can be added or compared with mathematical operations (think about what would happen if you wrote input = "Andrew Francis").
You can see this by using print(type(input[3])).
Fortunately, if you have a string that contains only characters that make up a valid number, you can convert it to (for instance) an integer using the int() function. So, try print(type(int(input[3]))) and see what you get.
Related
So here is a simple problem input:
The first line contains an integer, N, the number of students.
The 2N subsequent lines describe each student over lines.
The first line contains a student's name.
The second line contains their grade.
and code:
l = []
second_lowest_names = []
scores = set()
for _ in range(int(input())):
name = input()
score = float(input())
l.append([name, score])
scores.add(score)
second_lowest = sorted(scores)[1]
for name, score in l:
if score == second_lowest:
second_lowest_names.append(name)
for name in sorted(second_lowest_names):
print(name, end='\n')
I'm just a bit confused of how the float() function only takes the numbers but not the names as input
here's a sample input
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
In your loop, you call input() twice. Each time you get a single line of the input, so the two values corresponding to the student are both read in a single pass of the loop:
for _ in range(int(input())):
name = input() # get the name
score = float(input()) # get the score, and convert it to a number
Only the second input line, which represents the student's score, gets passed to float. If you passed the student's name (from the previous line) to float, you'd get an exception unless the student had a very unconventional name (like 'Nan' or 'Inf').
Do you know what float does? It's an abbreviation for floating point number, which is a way of representing numbers in computers that can have fractional portions after the decimal point. Whenever you call input(), python always receives what you typed as a string, which means a sequence of characters.
Strings have no direct numeric meaning in the computer in the way that floats do. The string "41" to the computer is not the meaningful number that you or I would immediately interpret it as. To the computer, it is just two characters in order, the first of which happens to be the "4" character and the second of which happens to be the "1" character - nothing more, nothing less. The quotes in python indicate strings. If you were to evaluate "41"+"1" you would get "411". You could even evaluate "41" + "hello" to get "41hello". These are all just strings.
Calling float("41") takes the string and tries to evaluate it into an floating point number which the computer interprets as an actual number and not simply a sequence of characters. The sum of two floating point values such as 41.0 + 1.0 evaluates to 42.0 as you would expect.
Since a student's name is not meant to represent a number, you should not try to call float() on it as it doesn't make any sense to do so. Float will most likely fail to produce a numeric interpretation unless the name was one of a few special strings like "nan" (not a number) or "inf" (infinity). If the name did happen to be one of these strings, you wouldn't want this translation anyways.
This is why float is called on the numeric entities and not on the names in the code.
Another similar thing besides float() is int(), which is an abbreviation of integer. Both floats and ints are actual numeric representations. The difference essentially is that integers are restricted to be whole numbers (positive, negative, or zero), whereas floating point values can have fractional numbers after the decimal point. They are different ways of expressing numbers within a computer, each suited to different situations.
The output value is not including the 0's in the beginning, can someone help me fix the problem?
def bitwiseOR(P, Q):
return bin(P | Q)
bitwiseOR(0b01010111, 0b00111000)
OUTPUT: '0b1111111'
The leading zeroes are just for representation, so you can utilize Format Specification Mini-Language to display them as you wish:
Format string:
# Includes 0b prefix
0{length} Pad leading zeroes so total length is length
def bitwiseOR(P, Q, length=10):
return format(P | Q, f'#0{length}b')
x = bitwiseOR(0b01010111, 0b00111000)
# 0b01111111
print(x)
Leading zeros are a property of the string you produce, not the number. So, for example, if you're looking for a way to make the following two calls produce different results, that's not possible:1
bitwiseOR(0b01010111, 0b00111000)
bitwiseOR( 0b1010111, 0b111000)
However, if you can provide the number of digits separately, then you can do this using the format() function. It accepts a second argument which lets you customize how the number is printed out using the format spec. Based on that spec, you can print a number padded with zeros to a given width like this:
>>> format(127, '#010b')
'0b01111111'
Here the code consists of four pieces:
# means apply the 0b prefix at the beginning
0 means pad with leading zeros
10 means the total length of the resulting string should be at least 10 characters
b means to print the number in binary
You can tweak the format code to produce your desired string length, or even take the length from a variable.
1Well... technically there is a way to make Python re-read its own source code and possibly produce different results that way, but that's not useful in any real program, it's only useful if you want to learn something about how the Python interpreter works.
Say I have 2 hex values that were taken in from keyboard input.
E.g. val1 = 0x000000 and val2 = 0xFF0000
and I do,
print(hex(val1))
print(hex(val2))
I get the right output for val2 but val1 is just 0x0, how do I get it to print the whole value?
By whole value, I mean, if the inputted value is 0x000000, I want to output the value as 0x000000 and not 0x0.
Use the format() built-in function to show the hex representation to the expected level of precision:
>>> format(53, '08x')
'00000035'
>>> format(1234567, '08x')
'0012d687'
The format code 08x means "eight lowercase hex digits padded with leading zeros".
You can pad the hex value to the specified number of digits by using the ljust method.
Whenever the string is less than the specified width, it'll append the specified filler character to extend it.
In your example example, hex(0x0).ljust(8, '0') == "0x000000".
Strings that are already long enough are preserved so that 0xFF0000 will still work.
print(hex(0x000000).ljust(8, '0')) # Prints 0x000000
print(hex(0xFF0000).ljust(8, '0')) # Prints 0xFF0000
A couple of important things to note that have bitten me in the past:
Make sure your width includes the length of the leading "0x"
This is because the ljust function operator operates on raw text and doesn't realize it's a hex string
If you give a width value shorter than you need, the strings won't be filled up enough and will have different lengths.
In other words len(hex(0xFF0000).ljust(4, '0')) != len(hex(0xFF0000).ljust(4, '0')) because you need a length of 8 characters to fit both cases
You say the user typed this input in on the keyboard. That means you already started with the strings you want, but you parsed integers out of the input and threw away the strings.
Don't do that. Keep the strings. Parse integers too if you need to do math, but keep the strings. Then you can just do
print(original_input)
without having to go through a reconstruction process and guess at how many leading zeros were originally input.
I have several float values that have necessary zeros at the ends.
One number that I have is 0.0013790.
When finding the length of this, I get 8 when I should be getting 9, since the zero at the end is dropped. I can not use .format(), since some numbers are shorter than others and there is no concrete length that I want them set to. If I had a float that was seven digits long after the decimal and set the format to 8, I would get an extra zero which should NOT belong there.
I can not afford to have my program adding zeros through format when they are not always necessary, since some numbers will be shorter than others. How do I find the actual length of these numbers when a zero is at the end?
I can not make an if statement that checks if the number .endswith 0, because it never does. The zero is always dropped! I am already checking the length of the string of the float and still the zero is dropped! Many numbers will not end with zero, so I can not simply add one to the length found. Please help!
Numbers to test:
When inputting _, you should get _. If you can get the below to work along with some other numbers, please give me the solution. I've been racking at my brain for hours!! Thanks.
WANTED RESULTS: 0.12345 -> 7, 0.123450 -> 8, 0.1234500 -> 9.
UPDATE:
Thank you for your solutions, but the numbers are not inputs. I have them set to the eval() function, since I have roughly 1000 variables that need to be accessed dynamically from a websocket. Values are retrieved just fine, but if I am not mistaken, eval() defaults to float. Switching it from float to string has not done me much good, since I am guessing that eval() is always a float. Any solutions??
You need to store your values as strings if you want to track length independent of the value of the float.
Floating point values have no length, and trailing 0s do not affect the value so they produce identical floats. This means after it gets defined, there is no way to determine whether 0.12345 was defined using 0.12345 or 0.12345000000.
0.12345 is 0.123450 # True
0.12345 is 0.1234500 # True
len(0.12345) # TypeError: object of type 'float' has no len()
Everything works fine for the string representation of those floats:
"0.12345" is "0.123450" # False
"0.12345" is "0.1234500" # False
len("0.12345") # 7
Thus you should store these values as strings, and convert them to float when necessary.
If you first convert the input to a number, and then to a string, you'll lose any insignificant digits.
If you are asking the user to enter the value:
>>> foo = input('Enter the number here: ')
Enter the number here: 0.0013790
>>> len(foo)
9
If you are using Python 2, make sure you use raw_input and not input
As long as you don't cast the value to a float, you should get correct values for len().
Then we have to store the float as a string value. Following lines may be answer to the question where it is a default behaviour.
mynum = input('Enter your number: ')
print('Hello', mynum)
print(len(mynum))
First of all, I have only recently started to learn Python on codeacademy.com and this is probably a very basic question, so thank you for the help and please forgive my lack of knowledge.
The function below takes positive integers as input and returns the sum of all that numbers' digits. What I don't understand, is why I have to change the type of the input into str first, and then back into integer, in order to add the numbers' digits to each other. Could someone help me out with an explanation please? The code works fine for the exercise, but I feel I am missing the big picture here.
def digit_sum(n):
num = 0
for i in str(n):
num += int(i)
return num
Integers are not sequences of digits. They are just (whole) numbers, so they can't be iterated over.
By turning the integer into a string, you created a sequence of digits (characters), and a string can be iterated over. It is no longer a number, it is now text.
See it as a representation; you could also have turned the same number into hexadecimal text, or octal text, or binary text. It would still be the same numerical value, just written down differently in text.
Iteration over a string works, and gives you single characters, which for a number means that each character is also a digit. The code takes that character and turns it back into a number with int(i).
You don't have to use that trick. You could also use maths:
def digit_sum(n):
total = 0
while n:
n, digit = divmod(n, 10)
num += digit
return num
This uses a while loop, and repeatedly divides the input number by ten (keeping the remainder) until 0 is reached. The remainders are summed, giving you the digit sum. So 1234 is turned into 123 and 4, then 12 and 3, etc.
Let's say the number 12345
So I would need 1,2,3,4,5 from the given number and then sum it up.
So how to get individuals number. One mathematical way was how #Martijn Pieters showed.
Another is to convert it into a string , and make it iterable.
This is one of the many ways to do it.
>>> sum(map(int, list(str(12345))))
15
The list() function break a string into individual letters. SO I needed a string. Once I have all numbers as individual letters, I can convert them into integers and add them up .