Sum of parts of a string in Python - python

I'm learning to program using the book "Introduction to computation and programming using Python" by John V. Guttag. There is an exercise on it that says the following:
'Finger exercise: Let s be a string that contains a sequence of
decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write
a program that prints the sum of the numbers in s.'
My try was:
#Finger exercise [MIT] PAGE 42 12:50 | 11.10.2015
s = ','+raw_input('Enter a string that contains a sequence of decimal numbers separated by commas, e.g. 1.23,2.4,3.123): ')+','
total = 0
for l in range(0,len(s)):
if s[l] == ',':
c = l + 1
while s[c] != ',':
c = c + 1
if s[c] == ',':
total = total + int(s[int(l),int(c)])
print total
but it keeps showing this error
TypeError: string indices must be integers, not tuple
I've tried to seek solutions online but only found solutions that work but not with the content I already now.
Any help?

You are creating a tuple when accessing your string item here:
s[int(l),int(c)]
Commas generally create tuples.
Instead, you want to use a slice here using a colon:
s[int(l):int(c)]
Note that both variables are already integers, so you don't actually need to convert them:
s[l:c]
Also note that you are summing integer values although you accept floats as the input. So instead of adding int(s[l:c]) you want to add float(s[l:c]).

First of all, there is no processing of anything before the first comma.
Next, you should comment each part of it at least initially to you are clear what each line is doing.
You shouldn't need to check for a ',' in multiple places, keep a variable.

A solution I found, hope its useful:
s = "1.23, 2.4, 3.123"
news = s.split(",")
total = 0
for string in range(len(news)):
total += float(news[string])
print(total)

Related

Why am I getting a different output when the multiplication of the digit is above 10?

#card number
card = input('Number: ')
j = int(card[::2]) # this will jump character by 1
# multiplying each other number by 2
j *= 2
print(j)
So whenever I run this code and input e.g. 1230404
The output would be correct which is 2688
But when I input for example 1230909 the output is 2798, I expected 261818
Let's look at what your code is doing.
You slice every second character from your input string, so '1230909' becomes '1399'.
You convert that to a single int, 1399.
You multiply that number by 2, producing 2798. I assure you that the computer did the math correctly.
It appears what you expected was for each digit to be doubled individually. To do that, you need to convert each digit, double it, and combine them back. Python has great facilities for this, I'd suggest a generator expression inside a join call.

How do I print numbers from 1 to n in python in a single line without spaces?

print(*range(1, int(input())+1), sep='')
This was the code I found in a discussion on hacker rank. But I did not understand it.
Can anyone please explain this?
So, from what I can tell, this is how it works:
int(input())
This takes input from the user.
Next;
range(1,...+1)
This creates a range from 1 to our number we inputted earlier. The +1 means that it will include the max number.
And then:
print(*...,sep='')
The * sign, from what I can tell, just effectively returns each value in our range one to be printed.
The sep='' just means each value is separated by '' or nothing.
Hope this is useful to you.
[EDIT]
More on star and double star expressions in this post:
What does the star and doublestar operator mean in a function call?
Ok so we have print function. Inside we have this strange *range(1, int(input())+1) this is range function which return value from 1 to n (n is typed in input) in a form of a range object. * unpack this object to form like: 1 2 3 4 ... with spaces, so we have this sep='', keyword argument that makes separation from space to '' (no separate between).
Also you can do it like that:
n = input("Type integer value: ")
try:
[print(x+1,end="") for x in range(int(n))]
except ValueError:
exit("Typed string not number")

Take out numbers from String without list

I have to make a (def) program using Python language where user inserts a string ( up to 8 digits numbers (0-9) and letters (a-z) together), program has to find out how many numbers are there in a string. Program will calculate the sum and average of those numbers.
Approach 1 : Pure implementation by string, without using list at all.
def sum_and_average(string):
COUNT = 0
SUM = 0
for value in string:
if value.isdigit():
SUM += int(value)
COUNT +=1
print('Sum :',SUM)
print('Average :',SUM/COUNT)
Approach 2 : Using List Comprehensions and Ascii values
def sum_and_average2(s):
L = [int(var) for var in s if 48<=ord(var)<=57]
print('Sum :', sum(L))
print('Average :', sum(L)/len(L))
Approach 3 : Using Regex, Already Mentioned However Regex will also store values as list object so in your case approach 1 would be best but approach 3 will be fastest in case of long string input.
you can use regular expression to parse the spring to get your numbers and letters separately and then perform the required operation on the numbers.
Example
import re
def spring_program(spring):
regex = re.compile("([0-9]+)([a-z]+)")
numbers = regex.match(spring).group(1)
letters = regex.match(spring).group(2)
print(numbers)
print(letters)
#you can now do any manipulation to the numbers

How to increment a numeric string in Python

I've spent the last two days trying to figure out how to increment a numeric string in Python. I am trying to increment a sequence number when a record is created. I spent all day yesterday trying to do this as an Integer, and it works fine, but I could never get database to store leading zeros. I did extensive research on this topic in StackOverflow, and while there are several examples of how to do this as an Integer and store leading zeros, none of the examples worked for me. Many of the examples were from 2014, so perhaps the methodology has changed. I then switched over to a String and changed my attribute to a CharField, and can get the function to work with leading zeros, but now I can't seem to get it to increment. Again, the examples that I found on SO were from 2014, so maybe things have changed a bit. Here is the function that works, but every time I call it, it doesn't increment. It just returns 00000001. I'm sure it's something simple I'm not doing, but I'm out of ideas. Thanks in advance for your help. Here is the function that works but doesn't increment.
def getNextSeqNo(self):
x = str(int(self.request_number) + 1)
self.request_number = str(x).zfill(8)
return self.request_number
Here is the field as it's defined:
request_number = models.CharField(editable=True,null=True,max_length=254,default="00000")
I added a default of "00000" as the system is giving me the following error if it is not present:
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
I realize the code I have is basically incrementing my default by 1, which is why I'm always getting 00000001 as my sequence number. Can't seem to figure out how to get the current number and then increment by 1. Any help is appreciated.
A times ago I made something similar
You have to convert your string to int and then you must to get its length and then you have to calculate the number of zeros that you need
code = "00000"
code = str(int(code) + 1 )
code_length = len(code)
if code_length < 5: # number five is the max length of your code
code = "0" * (5 - code_length) + code
print(code)
Can this be done? Yes. But don't do it.
Make it an integer.
Incrementing is then trivial - automatic if you make this the primary key. For searching, you convert the string to an integer and search the integer - that way you don't have to worry how many leading zeros were actually included as they will all be ignored. Otherwise you will have a problem if you use 6 digits and the user can't remember and puts in 6 0's + the number and then doesn't get a match.
For those who want to just increase the last number in a string.
Import re
a1 = 'name 1'
num0_m = re.search(r'\d+', str(a1))
if num0_m:
rx = r'(?<!\d){}(?!\d)'.format(num0_m.group())
print(re.sub(rx, lambda x: str(int(x.group()) + 1), a1))
number = int('00000150')
('0'*7 + str(number+1))[-8:]
This takes any number, adds 1, concatenates/joins it to a string of several (at least 7 in your case) zeros, and then slices to return the last 8 characters.
IMHO simpler and more elegant than measuring length and working out how many zeros to add.

Count up and down from a given letter

I need to write a function "alphabet" that takes a string (n), and counts up and then down in the alphabet. I tried to solve it, but I could only write the code where it counts down and then up in integers. Somehow, these integers are supposed to represent a letter. I know that I should use char() and ord(), but I don't know how. Here is what I've done so far:
letter= ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z']
numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24']
index=0
def alphabet('n')
while index < len(letter):
print(count[index], end=' ')
for n in range(0,count[index]):
print(line[index]-numbers,end='')
print()
index = index + 1
for n in range(0,count[index]):
print(line[index]+1,end='')
print()
index = index + numbers
I am aware that this is wrong, but a little guidance would be nice :)
I think ord() gives back the ascii code in consecutive order, for instance ord('a') gives 97 and ord('b') 98 and so on, i would work on converting one from another and adding +1 in each loop

Categories

Resources