Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
New in programming and need to find out what will be the following function in python3?
void expand (char s1 [], char s2[])
{
char c;
int i,j;
i=j=0;
while ((c=s1[i++]) != '\0')
if (s1[i] =='-' && s1[i+1] >=c {
i++;
while (c<s1 [i])
s2 [j++] = c++;
}
else
s2 [j++] =c;
s2 [j] = '\0';
}
The direct translation, working on byte objects only, would be:
def expand(s1):
i = 0
s2 = bytearray()
while i < len(s1):
c = s1[i]
i += 1
if (i + 1) < len(s1) and s1[i] == ord(b'-') and s1[i + 1] >= c:
i += 1
while c < s1[i]:
s2.append(c)
c += 1
else:
s2.append(c)
return bytes(s2)
This appears to expand ranges in the form of a-f into abcdef:
>>> expand(b'a-f')
b'abcdef'
You can use regular expressions to do the same:
import re
_range = re.compile(rb'(.)-(.)')
def _range_expand(match):
start, stop = match.group(1)[0], match.group(2)[0] + 1
if start < stop:
return bytes(range(start, stop))
return match.group(0)
def expand(s1):
return _range.sub(_range_expand, s1)
or, for unicode strings (type str) instead:
import re
_range = re.compile(r'(.)-(.)')
def _range_expand(match):
start, stop = ord(match.group(1)), ord(match.group(2)) + 1
if start < stop:
return ''.join([chr(i) for i in range(start, stop)])
return match.group(0)
def expand(s1):
return _range.sub(_range_expand, s1)
Related
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 5 months ago.
Improve this question
Input:
D
3
Output:
G
Explanation:
3rd element from D is G in alphabets
And how do you code if the input is x and 4 and I should get the output as b.
Help!!!
You could consider utilizing the modulo operator (%), string.ascii_lowercase, str.islower(), str.isalpha(), str.upper(), and ord():
from string import ascii_lowercase
def shift_letter(c: str, n: int) -> str:
if len(c) != 1:
raise ValueError('c must be a single letter.')
if not c.isalpha():
raise ValueError('c must be a letter.')
current_index = ord(c.lower()) - ord('a')
new_index = (current_index + n) % 26
new_c = ascii_lowercase[new_index]
return new_c if c.islower() else new_c.upper()
def main() -> None:
print(f"shift_letter('D', 3) = {shift_letter('D', 3)}")
print(f"shift_letter('x', 4) = {shift_letter('x', 4)}")
if __name__ == '__main__':
main()
Output:
shift_letter('D', 3) = G
shift_letter('x', 4) = b
You already have ascii_lowercase and ascii_uppercase in string module to use. Using the indexes from these strings and % operator you can shift the character:
from string import ascii_lowercase, ascii_uppercase
def shift_char(char: str, n):
if char.isupper():
idx = ascii_uppercase.index(char)
return ascii_uppercase[(idx + n) % len(ascii_uppercase)]
else:
idx = ascii_lowercase.index(char)
return ascii_lowercase[(idx + n) % len(ascii_lowercase)]
print(shift_char("D", 3))
print(shift_char("x", 4))
output:
G
b
ord and chr string methods are really useful for this problem.
ord gives you the Unicode code for a character:
>>> ord('a')
97
>>> ord('b')
98
>>> ord('A')
65
>>> ord('B')
66
Given the code, chr, will give you the Unicode character
>>> chr(65)
'A'
So to get the 3rd character from 'D', you could do
>>> code = ord('D') + 3
>>> char = chr(code)
>>> print(char)
G
or, as a one-liner
>>> print(chr(ord('D')+3))
G
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
I'm trying to solve this problem. I have seen other solutions that involve lists and using recursion but I'm interested in learning how to solve this with loops and I can't seem to get the right output.
(i.e. no regular expressions, no tuples, no methods of string, etc.)
input: caaabbbaacdddd
expected output:empty string
input:abbabd
expected output:bd
below is my code i have found other methods to solve this problem im just looking for the most basic solution for this.
answer = input("enter a string: ")
new_answer = ""
#while answer != new_answer:
if answer == "":
print("goodBye!")
#break
p = ""
for c in answer:
if p != c:
new_answer += p
p = c
else:
p = c
print(new_answer)
the commented out part is to make the whole program loop through to verify thier is no more duplicates.
The simplest loop-based solution would be:
result = ""
for i in answer:
if result == "" or result[-1] != i:
result += i
You could also use itertools.groupby which does what you're looking for:
print("".join([i for i in map(lambda x: x[0], itertools.groupby(answer))])
Try this! Only issue in your logic is that you are not removibg the character which is being repeated once its added tk the new_answer.
count = 0
for c in answer:
if p != c:
new_answer += p
p = c
else:
new_answer = new_answer.replace(c,””,count)
p = c
count += 1
print(new_answer)
Simplifying it even more without replace function:
count = 0
for c in answer:
if p != c:
new_answer += p
p = c
else:
if count == 0:
new_answer =“”
else:
new_answer=new_answer[:count-1]
count -=1
p = c
count += 1
print(new_answer)
I would do like this with javascript ( i know it's not python, but same logic):
let answer = 'acacbascsacasceoidfewfje';
for(i=0;i<answer.length;i++){
if(obj[answer.substr(i,1)] === undefined){
obj[answer.substr(i,1)] = 1
}else{
obj[answer.substr(i,1)]++;
}
}
JSON.stringify(obj)
Results:
"{"a":4,"c":4,"b":1,"s":2,"e":2,"o":1,"i":1,"d":1,"f":1,"w":1,"j":1}"
It seems you are just comparing the current character with the immediate previous character. You can use the in operator:
if char in String
for all 26 characters
You could also make a dictionary for all 26 characters if you can use that (since you are only using loops)
public class RemoveAdjacentDuplicates {
public static void main(String[] args) {
System.out.println(removeDuplicates("abbabd"));
}
public static String removeDuplicates(String S) {
char[] stack = new char[S.length()];
int i = 0;
for(int j = 0 ; j < S.length() ; j++) {
char currentChar = S.charAt(j);
if(i > 0 && stack[i-1] == currentChar) {
i--;
}else {
stack[i] = currentChar;
i++;
}
}
return new String(stack , 0 , i);
}
}
Results of the program are :
input: caaabbbaacdddd
output:empty string
input:abbabd
output:bd
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.
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 7 years ago.
Improve this question
I am trying to extract what's between parenthesis (including parenthesis) recursively.
This is my solution:
def paren(txt):
if txt[1] == ")":
return ''
if txt[0] == "(":
if len(txt) > 2:
return txt[1] + paren(txt[:1] + txt[2:])
return txt[1]
if len(txt) > 2:
return paren(txt[1:])
return ""
But it doesn't include any parenthesis. How can I fix it?
Example:
print paren("h(ello)o")
Output: (ello)
print paren("(hello)")
Output: (hello)
If you have a single pair of parenthesis, I would recommend to go with Halcyon Abraham Ramirez's answer. Otherwise, try this method:
def paren(text):
pstack = 0
start = 0
end = len(text)
for i, c in enumerate(text):
if c == '(':
if pstack == 0:
start = i
pstack += 1
elif c == ')':
pstack -= 1
if pstack == 0:
end = i
break
return text[start:end]
And here is an example:
>>> paren("h(ello)")
'(ello)'
If you do not need the root parenthesis, you can modify the return statement like this:
return text[start+1:end-1]
And again:
>>> paren("h(ello)")
'ello'
use index
word = "hehlllllllll(ooooo)jejejeje"
def extract(word):
return word[word.index("("):word.index(")") + 1]
output:
(ooooo)
taking it further.
if there are multiple parenthesis:
a = "h((el(l))o"
def extract_multiple_parenthesis(word):
closing_parenthesis = word[::-1].index(")")
last_parenthesis_index = (len(word) - closing_parenthesis)
return word[word.index("("):last_parenthesis_index]
output:
((el(l))