Hey guy i recently found out this how you add commas between integer values, i have been trying to find out how it works i tried looking at other sources but none of them explain how this works?
Example:
numbers = "{:,}".format(5000000)
print(numbers)
I am wondering the logic behind {:,}
def add_comma(number: int) -> str:
new_number, cnt = '', 0
for num in str(number)[::-1]:
if cnt == 3:
new_number += ','
cnt = 0
new_number += num
cnt += 1
return new_number[::-1]
add_comma(1200000)
'1,200,000'
The mechanics behind it is that after every 3 numbers counting from behind, you add a comma to it; you start counting from behind and not from the beginning. So the code above is the equivalent of what the f-string function does for you.
For example, let's say the number '14589012'. To add comma to this, we count the first 3 numbers till we reach the beginning of the number, starting counting from the last digit in the number:
210,
210,985,
210,985,41
Then reverse the string, we have 14,589,012
I hope it helps, just read the code and explanation slowly.
{:,} is used along with format().
Example:
num = "{:,}".format(1000)
print(num)
Output: 1,000
This command add commas in every thousand place.
Example:
num = "{:,}".format(100000000)
print(num)
Output: 100,000,000
Related
I'm currently learning python. There is an exercise in the book which outlines code for decoding. I followed along with this code however I keep getting back an error in the middle of the program.
Here is the code that is causing the problem:
def decode(string_for_decoding):
result = ""
for i in range(0, len(string_for_decoding)):
if string_for_decoding[i+1].isdigit():
result += string_for_decoding[i] * int(string_for_decoding[i+1])
elif string_for_decoding[i].isalpha():
result += string_for_decoding[i]
return result
string_for_decoding = input("Enter a string to decode: ")
print(decode(string_for_decoding))
Check if the index from range is larger than the number of chars in the string. It might look like this:
def decode(string_for_decoding: str):
result = ""
for i in range(0, len(string_for_decoding)):
if len(string_for_decoding) > i + 1 and string_for_decoding[i + 1].isdigit():
result += string_for_decoding[i] * int(string_for_decoding[i + 1])
elif string_for_decoding.isalpha():
result += string_for_decoding[i]
return result
print(decode(input("Enter a string to decode: ")))
You are going from 0 to len(string) and inside for loop you are trying to access index: i+1
THis is the root cause! Either:
iterate till one length less e.g. till len(string) - 1
Or use indices
inside appropriately
Moreover it is highly discouraged to use range(len(x)). You can simply iterate over any collective datatype as for i in x: If you want indices too have a look at enumerate(). And you can forget about index errors all together.
You are trying to get index i+1 which cannot be equal or greater than len(string).
Please help me understand why my Python code to solve the 13th Project Euler problem is incorrect. I believe that I understand the task correctly and I think my code is correct, but it is obviously not.
number = '5000 digit number - see in the problem decription at the provided link'
list1 = [number[i:i+100] for i in range(0, len(number), 100)]
temp = []
for i in range(0, len(list1)):
y = int(list1[i])
temp.append(y)
print sum(temp)
First, the numbers are 50 digits long, not 100. Change this:
list1 = [number[i:i+100] for i in range(0,len(number),100)]
To this:
list1 = [number[i:i+50] for i in range(0,len(number),50)]
Second, you're printing the entire sum, rather than just the first ten digits. Try:
print str(sum(temp))[:10]
Much simpler:
s = 'copied and pasted from the page'
result = sum(map(int, s.splitlines()))[:10]
Only the 11 first digits need to be summed,
somme11=sum(int(number2[i:i+11]) for i in range(100))
print(somme11)
print( 'the ten first digits are' , somme11//1000)
Because the carry can't exceed 99.
4893024188690
the ten first digits are 4893024188
An alternative is to load the numbers into a file and then just add them up, unless I too have completely misunderstood the question.
with open("sum.nums","r") as f:
data = f.readlines()
total = 0
for i in data:
total += int(i)
print "1st 10 digits ", str(total)[:10], "of total", total
1st 10 digits 5537376230 of total 5537376230390876637302048746832985971773659831892672
It's pretty simple
def e13():
f=open("100x50digits.txt")
summ=0
for line in f:
summ+=int(line[:11])
print(int(summ/1000))
f.close()
e13()
number = '''The 100 lines of 50 characters'''
numbers = number.splitlines() #Devide the string into a list of strings.
numbers = [int(i) for i in numbers] #Convert all elements into integers.
totalSum = str(sum(numbers)) #Add everything and convert to a string.
print(totalSum[:10]) #Print the first 10 digits of the result.
The correct answer is 5537376230, checked with P.E.
The real challenge here is to deal with the really long string
Use StringIO to take number as a input string and iterate trough elements by converting each one to a integer value
from io import StringIO
number = StringIO(""" # Paste one-hundred 50 numbers """)
print(str(sum(map(lambda x: int(x), number)))[:10])
>>> '5537376230'
I have been learning Python (as my first language) from "How to Think Like a Computer Scientist: Learning with Python". This open book teaches mostly through examples and I prefer to read the goal and build the program on my own, rather than actually reading the program code provided in the book.
However, I am struggling with creating a function which will search for a specific character in a given string and return how many times that character was counted.
The code I wrote is:
def find(s, x): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
else:
print count
However, when I run this code, I get the error "name 's' is not defined".
The code in the book has a slightly different goal: it searches for a specific character in a string, but instead of counting how many times the character was found, it returns the position of the character in the string.
def find(strng, ch, start=0, step=1):
index = start
while 0 <= index < len(strng):
if strng[index] == ch:
return index
index += step
return -1
I don't really understand this code, actually.
However, even when I run the code, for example, to search for 'a' in 'banana', I get the error name 'banana' is not defined.
What is wrong with my code? Could please someone explain me how the code provided in the book works?
1: There are a couple things wrong with this code. The function takes in two parameters, s and x, then immediately throws them away by overwriting those variables with user input. In your for loop, every time you encounter a character that isn't s you print the count. You should try to separate different ideas in your code into different methods so that you can reuse code more easily.
Break down your code into small, simple ideas. If the purpose of find is to count the instances of a character in a string, it shouldn't also be handling user interaction. If you take out the raw_input and printing, you can simplify this function to:
def find(s, x): #find s in x
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
return count
Now all it does it take in a character and a string and return the number of times the character appears in the string.
Now you can do your user interaction outside of the function
char = raw_input("Enter what you wish to find: ")
string = raw_input("Where to search?: )
print char + " appears " + `find(char, string)` + " times in " + string
2: The goal of this function is to find the first place where ch is found when walking through the characters strng from a starting position with a specified step. It takes in ch, strng, a position to start searching, and a step size. If the start is 0 and the step is 1, it will check every character. If the start is 2 it will check all but the first 2 characters, if the step is 2 it will check every other character, etc. This works by starting looking at the start index (index = start), then looping while the index is at least 0 and less than the length of the string. Since python is 0-indexed, the last character in the string has an index of one less than the length of the string, so this just restricts you from trying to check invalid indices. For each iteration of the loop, the code checks if the character at the current index is ch, in which case it returns the index (this is the first time it found the character). Every time it doesn't find the character at the current index, it increments the index by the step and tries again until it goes past the last character. When this happens it exits the loop and returns -1, a sentinel value which indicates that we didn't find the character in the string.
def find(strng, ch, start=0, step=1):
index = start
while 0 <= index < len(strng):
if strng[index] == ch:
return index
index += step
return -1
3: I'm guessing you passed some invalid parameters. strng should be a string, ch should be a single character, and start and step should be integers.
Try this. I took the parameters out of your function, moved the print command out of the else block and out of the for loop, and then wrote the last line to call the function.
def find(): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
print count
find()
It seems like you're taking in inputs s and x twice - once through the function arguments and once through raw input. Modify the function to do either one (say only from raw input - see below). Also, you only need to print out the count once, so you can place the print statement in the outermost indent level in the function.
def find(): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
print count
I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.
I'm sort of new to python. I'm trying to go through a specific range of numbers and have python count all the palindromes in it and return them to me (total number count, not their sum). So it would count all the integers in this range and return it to me as one number.
I keep getting an invalid syntax error and I don't know what to change. Here is what I have so far:
import math
def ispal(n):
return str(n) == str(n)[::-1]
But this is basically just what we did in class.
My range of of numbers is from 171 to 115000 and I want to go through the entire range in between and including those 2 numbers and have python tell me how many numbers are palindromes. The problem is I don't know how to fit in the for loop.
I started with:
def count_pal(n):
count = 0
for i in range(n):
if i = str(n) == str(n)[::-1]:
return:
count =+ i
else:
pass
But I don't know how to put the 2 together. I have python 3.2. Can anyone please help me out? Thank you!
def num_palindromes(start, end):
count = 0
for i in range(start, end + 1):
if str(i) == str(i)[::-1]:
count += 1
return count
Or as a one liner
def num_palindromes(start, end):
return sum(str(i) == str(i)[::-1] for i in range(start, end + 1))
You're returning inside the for loop before you have a chance to increment the counter
You also don't need that empty 'else: pass' block as it does nothing.
A correct solution will return the counter at the end of the function after the loop terminates.
Something like this will work:
count = 0
for i in range(171, 115000):
if str(i) == str(i)[::-1]:
count += 1
return count
Note a few style changes:
- 4-space indentation
- no extraneous newlines
- no unnecessary coercion of i from 'True/False' to a number (which is what you get in your code when you do i = str(i) == str(i)[::-1])
Not directly related to your question but following python conventional style will help make your code more readable and easier for others to understand and help you with.
Lastly, just as n extra tidbit, you can also accomplish this task with a list comprehension:
sum([1 for i in range(171, 115000) if str(i) == str(i)[::-1]])
I personally find it more concise/easier to understand than the loop counter variation.