Extract n first consecutive numbers from a string in python [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's consider this string :
st = 'text1text6253text'
How could I please extract the two first consecutive figures ?
Expected output :
62

You can either use regex with \d{2}and return that, or go over the string:
st = 'text1text6253text'
for i in range(len(st)-1):
if st[i].isdigit() and st[i+1].isdigit():
print(st[i]+st[i+1])
break

import re
def find_con(n, s):
result = re.search('\d{%s}'%n, s)
return result.group(0) if result else result
st = 'text1text6253text'
print(find_con(2, st))

st = 'text1text6253text'
lst = list(st)
lst2 = []
for i,v in enumerate(lst):
if lst[i].isdigit() and lst[i+1].isdigit():
lst2.append(lst[i])
lst2.append(lst[i+1])
ans = int(lst2[0] + lst2[1])
print(ans)

Thanks to your answers, I built a general function that I propose you below :
def extract_n_consecutive_numbers(st,nb):
for i in range(len(st)-nb+1):
is_numeric = True
for j in range(nb):
is_numeric = is_numeric & st[i+j].isdigit()
if is_numeric :
output = ""
for j in range(nb):
output += st[i+j]
return output
return ""
Example :
extract_n_consecutive_numbers('text1text6253text',2)
Out[1]: 62

Related

How can I do this effectively? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This problem:
Input: 123456
Result:
1+2+3+4+5+6 = 21
2+1 = 3
Return: 3
This is my code:
num = input()
print(sum(list(map(int, list(num)))))
I don't know how to do until it is 1 digit.
Try this (example in IPython):
In [1]: s = '123456'
Out[1]: '123456'
In [2]: digits = [int(j) for j in s]
Out[2]: [1, 2, 3, 4, 5, 6]
In [3]: s = str(sum(digits))
Out[3]: '21'
Repeat steps 2 and three until len(s) == 1.
One way:
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
Full code:
num = 45637
ans = num
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
print(ans)
Output for input 45637:
7
You can try this:
s = input()
while(len(s)>1):
s = str(sum(list(map(int,s))))
One way to do it using sum(), list comprehension and recursion,
def simulated_sum(input):
"""This is a recursive function
to find the simulated sum of an integer"""
if len(str(input)) == 1:
return input
else:
input_digits = [int(x) for x in str(input)]
latest_sum = sum(input_digits)
return simulated_sum(latest_sum)
input = int(input('Enter a number'))
print(simulated_sum(input))
DEMO: https://rextester.com/WCBXIL71483
Is this what you want? (instructions unclear):
def myfunction(number):
total = 0
answertotal = 0
for i in str(number):
total += int(i)
for i in str(total):
answertotal += int(i)
return answertotal
myfunction(123456)
This function returns 3

How can I print the string "aaabbbccaa" as a3b3c2a2 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am given a user entered string 'aaabbbccaa'.
I want to find the duplicates and print the string back as 'a3b3c2a2'
Maybe with this way:
from itertools import groupby
s = "aaabbbccaa"
# group by characters
groups = groupby(s)
# process result
result = "".join([label + str(len(list(group))) for label, group in groups])
print(result)
Output:
a3b3c2a2
def process_string(source):
new = ''
while source:
counter = 0
first_char = source[0]
while source and source[0] == first_char:
counter += 1
source = source[1:]
new += f'{first_char}{counter}'
return new
print(process_string('aaabbbccaa'))
'a3b3c2a2'
this kind of solution could mabye solve it, it does what you specify, however if you are able to put it into your context, no idea :)
hope it helps!
c = 0
foo = "aaabbbccaa"
bar = ""
prev = None
for counter, index in enumerate(foo):
print(c)
if prev == None:
print("first")
elif prev == index:
print("second")
elif prev != index:
c = 0
c += 1
prev = index
try:
if index in foo[counter+1]:
print("third")
else:
print("fourth")
bar += index + str(c)
except:
print("fifth")
bar += index + str(c)
print("foo is {}".format(foo)) # will output aaabbbccaa
print("bar is {}".format(bar)) # will output a3b3c2a2

For loop not carrying on till the end [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
def HydrogenCount(Compound):
HydrogenNo = 0
for i in range(0, len(Compound)):
Compound[i] == "H":
print(Compound[i+1])
Temp = Compound[i+1]
Temp = int(Temp)
HydrogenNo = HydrogenNo + Temp
return HydrogenNo
HydrogenNo = HydrogenCount(Compound)
print ("HydrogenCount = ", HydrogenNo)
for an input like CH3CH2CH3 it should output hydrogen count = 8
but instead it outputs hydrogen count = 3 as it stops at the first h
Unindent the return statement. It's currently inside of the for loop and needs to be executed after. Otherwise it will only count the first.
def HydrogenCount(Compound):
HydrogenNo = 0
for i in range(0, len(Compound)):
Compound[i] == "H":
print(Compound[i+1])
Temp = Compound[i+1]
Temp = int(Temp)
HydrogenNo += Temp
return HydrogenNo
What if the H in the molecule has more than 9 atoms, say sugar compound C12H22O11 or glucose C6H12O6?
May I suggest you revamp the code this way:
import re
regex = re.compile('H([0-9]*)')
def HydrogenCount(Compound):
try:
return sum([int(i) for i in regex.findall(Compound)])
except:
return(0)
You may run this as:
print(HydrogenCount("CH3CH2CH3"))
print(HydrogenCount("C6H12O6"))
I still see one more flaw in the question and therefore all answers, which is how about molecules like CH3COOH, where H followed by no number implies 1 atom. So, this is the revised code to handle that too:
import re
regex = re.compile('H([0-9]*)')
def HydrogenCount_v2(Compound):
try:
res = [i if i != '' else '1' for i in regex.findall(Compound)]
return sum([int(i) for i in res])
except:
return(0)
print(HydrogenCount_v2("CH3CH2CH3"))
print(HydrogenCount_v2("C6H12O6"))
print(HydrogenCount_v2("CH3COOH"))
You can refactor your code like this:
def calculate_hydrogen_count(compound):
hydrogen_count = 0
for i in range(0, len(compound) - 1):
if compound[i] == "H":
hydrogen_count += int(compound[i + 1])
return hydrogen_count
compound = "CH3CH2CH3"
hydrogen_count = calculate_hydrogen_count(compound)
print ("HydrogenCount = ", hydrogen_count)
Outputting
8

Python get range using start, end characters compatible with Excel [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How can I make this work with alpha_range(A, ZZ)?
right now it only work until Z
Code:
def alpha_range(start, stop):
""" Returns chars between start char and stop char(A,D -> A,B,C,D).
:param start: start char
:param stop: stop char
:return: list of chars
"""
return [chr(x) for x in range(ord(start), ord(stop)+1)]
You can easily make a bidirectional mapping between A-ZZ and numbers. This actually is pretty similar to a numeric system with different characters to represent the digits.
BASE = ord('Z') - ord('A') + 1
def to_number(str_input):
res = 0
for letter in str_input:
res = res * BASE + ord(letter) - ord('A') + 1
return res
def to_str(int_input):
res = ''
while int_input > 0:
int_input -= 1
res = res + chr(int_input % BASE + ord('A'))
int_input //= BASE
return res[::-1]
Now you can replace ord and chr with this functions.

is there possible to resolve this star pyramid [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Today, i have trying to resolve a small star pyramid :
Input:
5 1
Output:
*
**
***
****
Code:
x = 1
y = 0
m, e = map(int, raw_input().split())
while x < m:
print "\n" * y, "*" * e
m -= 1
e += 1
I did that but there is a better solution?? Thanks =)
I think this can be solved more easily:
stop, first = map(int, raw_input().split())
for i in range(stop - 1):
print '*' * (i + first)
just for fun >:)
class c:
def __init__(s,m,e):
s.e , s.m = sorted([e, m])
s.r = 42
def __iter__(s):
return s
def next(s):
if s.m < s.e:
t = "".join(chr(s.r) for _ in range(s.m))
s.m += 1
return t
else:
raise StopIteration
print "\n".join(c(*map(int,raw_input().split())))
n = int(raw_input())
for i in range(n): print "*"*i
This appears to do what your program intends to do, however I can't quite tell because of the issues I raised in my comment above.

Categories

Resources