Write a program that find the largest integer in a string - python

Write a program that find the largest integer in a string. 'abcd51kkk3kk19ghi' would output 51.
I am having a hard time putting two digit integers into the list.
s = input('Enter a sequence of strings: ')
lst = []
for i in range(0, len(s)):
if s[i].isdigit() == True:
lst.append(s[i])
print(lst)

This problem is a good fit for regular expressions:
In [8]: max(map(int, re.findall(r'\d+', s)))
Out[8]: 51
Here, r'\d+' matches a sequence of one or more decimal digits. The matching strings are then converted to integers, and the maximum is taken.
A slightly more verbose way to write the same thing is
In [9]: max(int(digits) for digits in re.findall(r'\d+', s))
Out[9]: 51

Here's another solution, if you don't want to use regex:
s = input("Enter a sequence of strings: ")
current_num = "" # A string containing the current number that is being read
current_max = 0 # The maximum number found so far
for ch in s: # Iterate on the string, character by character
if ch.isdigit():
current_num += ch # append the digit ch to the current number
elif current_num: # if we just finished reading a number
current_max = max(int(current_num), current_max)
current_num = ""
if current_num: # in case there is no character after the last number
current_max = max(int(current_num), current_max)
print(current_max)

You can use itertools.groupby and a comprehension:
max(int(''.join(v)) for k, v in groupby(s, str.isdigit) if k)

Related

How to generate a list of numbers from a list of numeric and alphanumeric string ranges?

Given a list
n = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
From the list above, I want to match the string with hyphens and increase the numeric or alphanumeric value to a given range. So far I could only match the value using re:
p = re.compile('([\d]|[A-Z\d]{1,})[\-]')
Expected output:
['4276', '4277', '4278', '4279', 'I69', 'I70', 'I71', 'V104', 'V105', 'V106', 'V107', 'V108', 'V109', 'V110', 'V111', 'V112', '11528']
You can process each element in your list, seeing if it matches the pattern
^([A-Z]*)(\d+)-\1(\d+)$
i.e. an optional letter, some digits, a hyphen (-), the letter repeated if it was present and finally some more digits.
If it does, you can generate a range from the 2nd and 3rd groups, and prepend the first group to each value generated from that range:
import re
lst = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
new = []
for l in lst:
m = re.match(r'^([A-Z]*)(\d+)-\1(\d+)$', l)
if m:
new += [m.group(1) + str(i) for i in range(int(m.group(2)), int(m.group(3))+1)]
else:
new += [l]
print(new)
Output:
['4276', '4277', '4278', '4279', 'I69', 'I70', 'I71', 'V104', 'V105', 'V106', 'V107', 'V108', 'V109', 'V110', 'V111', 'V112', '11528']
import re
n = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
big_list=[]
for item in n:
print(item)
if '-' in item:
part1,part2=item.split("-")
if part1.isnumeric() and part2.isnumeric():
big_list.extend([x for x in range(int(part1),int(part2))])
continue
if part1.isalnum() and part2.isalnum():
list1=re.findall(r"[^\W\d_]+|\d+", part1)
list2=re.findall(r"[^\W\d_]+|\d+", part2)
print(list1,list2)
temp_list=[]
for i in range(int(list1[1]),int(list2[1])):
temp_list.append(list1[0]+str(i))
big_list.extend(temp_list)
else:
if item.isnumeric():
big_list.append(int(item))
else:
big_list.extend(item)
print(big_list)
This code worked for me for your input.
Please try and tell me if it works.

find the longest word and the largest number in a text file

So im learning python right now and i really need your help.
For example you do have random text file with words and numbers inside.
You need to find the longest word and maximum number in this file.
I managed to do the first half, i found the longest word:
def longest_word(word):
with open(word, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print (("the longest word is :"), longest_word ('text.txt'))
can you help me with the second part? how to find maximum number in a file?
You can implement error handling and try to parse the str as int: "2" --> 2
def longest_integer(word):
max_int = 0
with open(word, 'r') as infile:
words = infile.read().split()
for word in words:
try:
int_val = int(word)
if int_val > max_int:
max_int = int_val
except:
pass
return max_int
print (("the longest integer is :"), longest_integer ('text.txt'))
You're almost there! You can check each word to see if it's actually an integer, and then check if that value is greater than the previous max. This assumes the goal is to find the largest integer
for word in words:
try:
if int(word) > MAX_INT:
MAX_INT = word
except:
pass
with open(word, 'r') as infile:
data = infile.read()
nums = [int(num) for num in re.findall('\d+', data)
max_num = max(nums)
As numbers are integers you might get them using str's method isdigit, consider following example:
words = ['abc', '123', 'xyz', '1', '999']
numbers = [i for i in words if i.isdigit()]
print(numbers) # ['123', '1', '999']
then you might provide max with int as key following way:
print(max(numbers, key=int)) # 999
remember to NOT compare strs representing numbers as it might give surprising results, for example:
print(max(['9000','999'])) # 999
note that ValueError will occur if original list (words) do not contain any number.
Edit: I forget to note that above works solely for non-negative integers, to allow also negative one, you might write function for checking that as follow:
def represent_int(x):
if not x: # empty str
return False
if x[0] == '-': # leading - that is negative integer
return x[1:].isdigit()
return x.isdigit()
and use it as follows:
numbers = [i for i in words if represent_int(i)]
note that I assume represent_int will be feeded solely with strs.

multiplying letter of string by digits of number

I want to multiply letter of string by digits of number. For example for a word "number" and number "123"
output would be "nuummmbeerrr". How do I create a function that does this? My code is not usefull, because it doesn't work.
I have only this
def new_word(s):
b=""
for i in range(len(s)):
if i % 2 == 0:
b = b + s[i] * int(s[i+1])
return b
for new_word('a3n5z1') output is aaannnnnz .
Using list comprehension and without itertools:
number = 123
word = "number"
new_word = "".join([character*n for (n, character) in zip(([int(c) for c in str(number)]*len(str(number)))[0:len(word)], word)])
print(new_word)
# > 'nuummmbeerrr'
What it does (with more details) is the following:
number = 123
word = "number"
# the first trick is to link each character in the word to the number that we want
# for this, we multiply the number as a string and split it so that we get a list...
# ... with length equal to the length of the word
numbers_to_characters = ([int(c) for c in str(number)]*len(str(number)))[0:len(word)]
print(numbers_to_characters)
# > [1, 2, 3, 1, 2, 3]
# then, we initialize an empty list to contain the repeated characters of the new word
repeated_characters_as_list = []
# we loop over each number in numbers_to_letters and each character in the word
for (n, character) in zip(numbers_to_characters, word):
repeated_characters_as_list.append(character*n)
print(repeated_characters_as_list)
# > ['n', 'uu', 'mmm', 'b', 'ee', 'rrr']
new_word = "".join(repeated_characters_as_list)
print(new_word)
# > 'nuummmbeerrr'
This will solve your issue, feel free to modify it to fit your needs.
from itertools import cycle
numbers = cycle("123")
word = "number"
output = []
for letter in word:
output += [letter for _ in range(int(next(numbers)))]
string_output = ''.join(output)
EDIT:
Since you're a beginner This will be easier to understand for you, even though I suggest reading up on the itertools module since its the right tool for this kind of stuff.
number = "123"
word = "number"
output = []
i = 0
for letter in word:
if(i == len(number)):
i = 0
output += [letter for _ in range(int(number[i]))]
i += 1
string_output = ''.join(output)
print(string_output)
you can use zip to match each digit to its respective char in the word (using itertools.cycle for the case the word is longer), then just multiply the char by that digit, and finally join to a single string.
try this:
from itertools import cycle
word = "number"
number = 123
number_digits = [int(d) for d in str(number)]
result = "".join(letter*num for letter,num in zip(word,cycle(number_digits)))
print(result)
Output:
nuummmbeerrr

Convert an integer into a string of its ascii values

Given a number number such that its digits are grouped into parts of length n (default value of n is 3) where each group represents some ascii value, I want to convert number into a string of those ascii characters. For example:
n number Output
==================================
3 70 F
3 65066066065 ABBA
4 65006600660065 ABBA
Note that there is no leading 0 in number, so the first ascii value will not necessarily be represented with n digits.
My current code looks like this:
def number_to_string(number, n=3):
number = str(number)
segment = []
while number:
segment.append(number[:n])
number = number[n:]
return str(''.join('{:0>{}}'.format(chr(segment), n) for segment in number))
Expected outputs:
number_to_string(70)
'F'
number_to_string(65066066065)
'ABBA'
number_to_string(65006600660065, n=4)
'ABBA'
My current code however returns an empty string. For example, instead of 'F' it returns ' '. Any reason why this is? Thank you!
P.S.:
I'm wanting to reverse the process of this question, i.e. turn an integer into a string based on the ascii values of each character (number) in the string. But reading that question is not a requirement to answer this one.
Try this:
import re
def number_to_string(num, n=3):
num_str = str(num)
if len(num_str) < n:
num_str = '0' * (n-len(num_str)) + num_str
elif len(num_str) % n != 0:
num_str = '0'*(n-len(num_str)%n) + num_str
print(num_str)
chars = re.findall('.'*n, num_str)
l = [chr(int(i)) for i in chars]
return ''.join(l)
First pad the given number (converted into string) with required number of zeros, so that it can be evenly split into equal number of characters each. Then using re split the string into segments of size n. Finally convert each chunk into character using chr, and then join them using join.
def numToStr(inp):
"""Take a number and make a sequence of bytes in a string"""
out=""
while inp!=0:
out=chr(inp & 255)+out
inp=inp>>8
print "num2string:", out
return out
does this help?
Is this what you want?
def num_to_string(num, leng):
string = ""
for i in range(0,len(str(num)),leng):
n = str(num)[i:i+2]
string += chr(int(n))
print string
Output:
>>> ================================ RESTART ================================
>>>
>>> num_to_string(650065006600,4)
AAB
>>> num_to_string(650650660,3)
AAB
>>> num_to_string(656566,2)
AAB
>>>
You can just append \x to number as this prints 'p':
print '\x70'

python - ordinal value - list indices must be integers not str

what i want to do is take a string and for each character make the ordinal value 1 more from the value it has.
myinput=input("Message : ")
mylist =list(myinput) #convert to list in order to take each character
for character in mylist:
mylist[character]+=ord(mylist[character])+1
print(character)
The problem is with the "ord(mylist[character])+1"
Thank you!
Probably you are looking for the next:
>>> m = raw_input('Message:')
Message:asdf
>>> ''.join(chr(ord(c) + 1) for c in m)
'bteg'
Notes:
use raw_input when you need to get string input from a user;
ord convert character to integer, chr - vise versa;
... for c in m syntax is a generator expression. It is also used for list comprehension.
Three problems here. First, you're mixing up list indices and list elements. Second, you didn't convert back to a character (I'm assuming you want characters, not numbers). Third, you're adding to the existing value.
One way:
for i range(len(mylist)):
mylist[i] = chr(ord(mylist[i])+1)
Another way:
for i, character in enumerate(mylist):
mylist[i] = chr(ord(character)+1)
Instead of
for character in mylist:
mylist[character]+=ord(mylist[character])+1
(where character is a list index and therefore invalid), you probably want:
mylist = [ord(character) + 1 for character in mylist]
Or a Counter.
You can do like this
def ordsum(astring, tablesize):
sum = 0
for num in range(len(astring)):
sum = sum + ord(astring[num])
return sum
myinput = input() # use raw_input() in Python 2
myinput = map(lambda ch: chr(ord(ch) + 1), myinput)
# or list comp.
myinput = [chr(ord(ch) + 1) for ch in myinput]
You can iterate directly over a string, you do not have to make it a list first. If your end goal is to have a new string, you can do this:
myinput=input("Message : ")
result = []
for character in myinput:
result.append( chr( ord( character ) + 1 )
mynewstring = ' '.join(result)

Categories

Resources