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
Related
I am learning Python. Having trouble at this exercise. The question is: Enter a number with up to 9 digits (less than 1 billion). Using Python, Print numbers to letters.
You can convert your int to str :
for i in str(a):
print(i)
In this function, str(a) converts the int a to a string. The in the for, you iterates over all its digits.
Another way to print the digits of an int is to use successive euclidean divisions.
Hope this helps :)
Trying to generate a certain length credit card number with a prefix given.
while len(str(cc_number)) < (len(str(length)) - 1):
digit = str(random.randrange(0, 9))
cc_number = str(cc_number) + str((digit))
return cc_number
I'm expecting to get say 16 digits long number with a variable size prefix given. How do i make this piece of code generate a right size string of numbers? This code by the way only concatenates 1 random digit to the end of the string... So i expect to get '4349578451278456', but the actual output is '41'
If length is 16, str(length) will give you the string '16' which has a len of 2. Just use length without len or str.
Beyond that, your return statement should be outside of the loop
Since you're already using the random module, I just want to offer an alternative solution:
from random import choices
from string import digits
cc_digits = choices(digits, k=16)
cc_number = "".join(cc_digits)
print(cc_number)
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)
I am trying to check whether or not a licence plate fits a certain format when the user inputs a number plate. It needs to be in the format of two numbers, three letters, and finally two more numbers. If it does not match this format then it must save it to a list.
speed_limit = []
while True :
speed = float()
distance = 50
time=float(raw_input('enter time'))
speed = distance / time
print speed
if speed > 31.2928:
#70 mph converted into meters per second
number_plate = raw_input('enter number plate')
number_plate.upper()
speed_limit.append(number_plate)
print speed_limit
else:
print 'ok'
This is my current code, I am not sure if this is possible or I am asking a too vague question but I need help!
You can do a regular expression match. The regex key that you would be needing is
(\d{2}[A-Z]{3}\d{2})
This returns 2 numbers, 3 letters and 2 numbers. You can try more regex combinations here
Try the following lines in your command prompt to check the code-
import re
m = re.match('(\d{2}[A-Z]{3}\d{2})','12MNB36')
m holds the result if the string matched the pattern or not.
Along the lines of my previous question, How do I convert unicode characters to floats in Python? , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.
For example, take the strings "1⅕" and "1 ⅕". I would like these to resolve to 1.2
I know that I can iterate through the string by character, check for unicodedata.category(x) == "No" on each character, and convert the unicode characters by unicodedata.numeric(x). I would then have to split the string and sum the values. However, this seems rather hacky and unstable. Is there a more elegant solution for this in Python?
I think this is what you want...
import unicodedata
def eval_unicode(s):
#sum all the unicode fractions
u = sum(map(unicodedata.numeric, filter(lambda x: unicodedata.category(x)=="No",s)))
#eval the regular digits (with optional dot) as a float, or default to 0
n = float("".join(filter(lambda x:x.isdigit() or x==".", s)) or 0)
return n+u
or the "comprehensive" solution, for those who prefer that style:
import unicodedata
def eval_unicode(s):
#sum all the unicode fractions
u = sum(unicodedata.numeric(i) for i in s if unicodedata.category(i)=="No")
#eval the regular digits (with optional dot) as a float, or default to 0
n = float("".join(i for i in s if i.isdigit() or i==".") or 0)
return n+u
But beware, there are many unicode values that seem to not have a numeric value assigned in python (for example ⅜⅝ don't work... or maybe is just a matter with my keyboard xD).
Another note on the implementation: it's "too robust", it will work even will malformed numbers like "123½3 ½" and will eval it to 1234.0... but it won't work if there are more than one dots.
>>> import unicodedata
>>> b = '10 ⅕'
>>> int(b[:-1]) + unicodedata.numeric(b[-1])
10.2
define convert_dubious_strings(s):
try:
return int(s)
except UnicodeEncodeError:
return int(b[:-1]) + unicodedata.numeric(b[-1])
and if it might have no integer part than another try-except sub-block needs to be added.
This might be sufficient for you, depending on the strange edge cases you want to deal with:
val = 0
for c in my_unicode_string:
if unicodedata.category(unichr(c)) == 'No':
cval = unicodedata.numeric(c)
elif c.isdigit():
cval = int(c)
else:
continue
if cval == int(cval):
val *= 10
val += cval
print val
Whole digits are assumed to be another digit in the number, fractional characters are assumed to be fractions to add to the number. Doesn't do the right thing with spaces between digits, repeated fractions, etc.
I think you'll need a regular expression, explicitly listing the characters that you want to support. Not all numerical characters are suitable for the kind of composition that you envision - for example, what should be the numerical value of
u"4\N{CIRCLED NUMBER FORTY TWO}2\N{SUPERSCRIPT SIX}"
???
Do
for i in range(65536):
if unicodedata.category(unichr(i)) == 'No':
print hex(i), unicodedata.name(unichdr(i))
and go through the list defining which ones you really want to support.