Jan-12-2022, 05:32 PM
Hi guys,
This actually is not my homework assignment. It's someone else's that I thought to try and see if I could get it running.
I've coded it to the best of my abilities however, I know that there is a more pythonic way of coding it.
When executing the code, I noticed that according to the indentation of the print statement it either runs continuously or doesn't run at all.
The assignment is:
1. Given two strings (strings s and f): one of English lowercase letters and the other of favorite English lower case letters.
2. perform an operation to change the first letter in string to the previous or next letter alphabetically then loop back until it is == to that of string f:
for example if s = j and f = a loop would be ran until 'j' eventually becomes 'a'.
3. The output is text format Case #x: y operations. x representing incremented case number and y representing the total amount of operations undergone to transform the letter.
Here's what I have:
Cheers,
This actually is not my homework assignment. It's someone else's that I thought to try and see if I could get it running.
I've coded it to the best of my abilities however, I know that there is a more pythonic way of coding it.
When executing the code, I noticed that according to the indentation of the print statement it either runs continuously or doesn't run at all.
The assignment is:
1. Given two strings (strings s and f): one of English lowercase letters and the other of favorite English lower case letters.
2. perform an operation to change the first letter in string to the previous or next letter alphabetically then loop back until it is == to that of string f:
for example if s = j and f = a loop would be ran until 'j' eventually becomes 'a'.
3. The output is text format Case #x: y operations. x representing incremented case number and y representing the total amount of operations undergone to transform the letter.
Here's what I have:
import random import string def randomLowerAlpha(): # generates random letters of the alphabet in the range of 6 return str("".join(random.choice(string.ascii_lowercase) for _ in range(6))) def match_string(str_1, str_2): index = 0 case = 0 op_count = 0 for char in str_1: curr_pos = index valS = ord(str_1[curr_pos]) valF = ord(str_2[curr_pos]) while valS > valF: op_count += 1 if valS > valF: for i in range(valS, valF, -1): prev_letter = i new_str = str_1.replace(str_1[curr_pos], chr(prev_letter)) if valS == valF: break else: while valS < valF: op_count += 2 if valS < valF: for i in range(valS, valF, +1): next_letter = i new_str = str_1.replace(str_1[curr_pos], chr(next_letter)) if valS == valF: break case += 1 print(f"Case #{case}: {op_count} operations.") break s = randomLowerAlpha() f = 'aeiouy' match_string(s,f)Thank you in advance.
Cheers,