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'
Related
I have a list of numbers of varying lengths stored in a file, like this...
98
132145
132324848
4435012341
1254545221
2314565447
I need a function that looks through the list and counts every number that is 10 digits in length and begins with the number 1. I have stored the list in both a .txt and a .csv with no luck. I think a big part of the problem is that the numbers are integers, not strings.
`import regex
with open(r"C:\Desktop\file.csv") as file:
data = file.read()
x = regex.findall('\d+', data)
def filterNumberOne(n):
if(len(n)==10:
for i in n:
if(i.startswith(1)):
return True
else:
return False
one = list(filter(filterNumberOne, x))
print(len(one))`
You could simply do like this :
# Get your file content as a string.
with open(r"C:\Desktop\file.csv") as f:
s = " ".join([l.rstrip("\n").strip() for l in f])
# Look for the 10 digits number starting with a one.
nb = [n for n in s.split(' ') if len(n)==10 and n[0]=='1']
In your case, the output will be:
['1254545221']
So I ended up using the following, seems to work great..
def filterNumberOne(n):
if (len(n)==10:
if str(n)[0] == '1':
return True
else:
return False
one = list(filter(filterNumberOne, x ))
print(len(one))
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
I try to extract numbers from a text file with regex. Afterward, I create the sum.
Here is the code:
import re
def main():
sum = 0
numbers = []
name = input("Enter file:")
if len(name) < 1 : name = "sample.txt"
handle = open(name)
for line in handle:
storage = line.split(" ")
for number in storage:
check = re.findall('([0-9]+)',number)
if check:
numbers.append(check)
print(numbers)
print(len(numbers))
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
if __name__ == "__main__":
main()
The problem is, if this string "http://www.py4e.com/code3/"
I gets add as [4,3] into the list and later summed up as 43.
Any idea how I can fix that?
I think you just change numbers.append(check) into numbers.extend(check)because you want to add elements to an array. You have to use extend() function.
More, you do not need to use ( ) in your regex.
I also tried to check code on python.
import re
sum = 0;
strings = [
'http://www.py4e.com/code3/',
'http://www.py1e.com/code2/'
];
numbers = [];
for string in strings:
check = re.findall('[0-9]+', string);
if check:
numbers.extend(check)
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
I am assuming instead of 43 you want to get 7
The number variable is an array of characters. So when you use join it becomes a string.
So instead of doing this you can either use a loop in to iterate through this array and covert elements of this array into int and then add to the sum.
Or
you can do this
import np
number np.array(number).astype('int').tolist()
This makes array of character into array on integers if conversion if possible for all the elements is possible.
When I add the string http://www.py4e.com/code3/" instead of calling a file which is not handled correctly in your code above fyi. The logic regex is running through two FOR loops and placing each value and it's own list[[4],[3]]. The output works when it is stepped through I think you issue is with methods of importing a file in the first statement. I replaced the file with the a string you asked about"http://www.py4e.com/code3/" you can find a running code here.
pyregx linkhttps://repl.it/join/cxercdju-shaunpritchard
I ran this method below calling a string with the number list and it worked fine?
#### Final conditional loop
``` for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(str(sum)) ```
You could also try using range or map:
for i in range(0, len(numbers)):
sum = sum + numbers
print(str(sum))
I have a array of integers which are space separated like this small example:
ar = 1000000001 1000000002 1000000003 1000000004 1000000005
I want to sum up the numbers character by character. for example the output for the small example would be:
5000000015
in fact the sum of the 1st elements from all numbers is 5, and this is the case for all elements.
to get such results I have made the following code:
def sum(ar):
for i in ar.split():
sum = 0
for j in range(len(i)):
sum += i[j]
return sum
but it does not return what I want as output. do you know how to fix it?
Try this. It should work
ar = "1000000001 1000000002 1000000003 1000000004 1000000005"
total=0
nums=ar.split(" ")
for num in nums:
total+=int(num)
print(total)
Capture all the digits first using regex, then pass it to the sum function by parsing it first.
import re
ar = "1000000001 1000000002 1000000003 1000000004 1000000005"
pattern = r'([0-9]+)'
matches = re.findall(pattern, ar)
digit_sum = sum((int(match) for match in matches))
print (digit_sum)
Outputting:
5000000015
It appears that your initial "array" is a string, so when you split the array you are still dealing with a list of strings that you can't add to your starting zero value. Also, it is not clear why you are attempting to sum "character by character" when your expected output is just the sum of all the integers. You really just need to convert each integer string to integer and then sum.
s = '1000000001 1000000002 1000000003 1000000004 1000000005'
total = sum(int(x) for x in s.split())
print(total)
# 5000000015
Trying to create an integer that starts at 0000 and increments by +1 (0001 etc) and then adds it to a string until the number reaches 9999. How could i do this?
for x in range(10000):
print(str(x).rjust(4, '0'))
You stated that you want to add them to a URL so the way to do it would be:
url = "thisisanamazingurl{0:0>4}" # insert your URL instead of thisisanamazingurl
for i in range(10000):
tempurl = url.format(i)
print(tempurl) # instead of print you should do whatever you need to do with it
This works because :0>4 fills the "input string" with leading zeros if it's shorter than 4 characters.
For example with range(10) this prints:
thisisanamazingurl0000
thisisanamazingurl0001
thisisanamazingurl0002
thisisanamazingurl0003
thisisanamazingurl0004
thisisanamazingurl0005
thisisanamazingurl0006
thisisanamazingurl0007
thisisanamazingurl0008
thisisanamazingurl0009
or if you want to store them as a list:
lst = [url.format(i) for i in range(10000)]
num = ""
for number in range(10000):
num = num + str('%04d' % number)
print num
This will iterate through every number between 0 and 9999 and append it to the num string. The '%04d' bit forces it to use 4 numeric places with the leading zeros.
(As an aside, you can change the ending number by changing the value of the number in the range function.)
Since you want to add it to a string, I am going to assume you want the type of the 4 digit number as string .
So you can do(python3.x) :
string=''
for x in range(10000):
digit= '0'*(4- len(str(x)) + str(x)
string+=digit