Course Module Three python programming problem to explain (on)

@

    Next we introduce some of the topics I am learning solution python course, if you have any better solution, please private letter to me. Here only display the title and code.

1. Happy Digital

   Description: write an algorithm to determine whether a number is "happy." Happy figure is determined as follows: starting from a positive integer, with each square of which number and the number of substituents, and repeat the process until the final digital convergence or equal to 1 and equal to 1 has been, or will cycle endlessly and ultimately will not go convergence equal to 1. 1 can equal the number of final convergence is a happy number. For example:

19 is a happy number , is calculated as follows:


1^2 + 9^2 = 82

8^2 + 2^2 = 68

6^2 + 8^2 = 100

1^2 + 0^2 + 0^2 = 1


When the input digital happy, output True, otherwise output False.

   Author Code: recursion can be.

a = input('')
def num(a):
    sum = 0
    for i in list(a):
        sum += int(i)**2
    try:
        if sum != 1:
            num(str(sum))
        else:
            print('True')
    except:
        print('False')


result = num(a)


2. Caesar cipher I

   Description: The Caesar cipher is the Roman Julius Caesar used to be military intelligence encryption algorithm, which uses an alternative method for each English character cycle information with a third character behind the character alphabet sequence, namely correspondence between the alphabet as follows:

原文: ABCDEFGHIJKLMNOPQRSTU VWXYZ
文: DEFGHIJKLMNOPQRSTUVWX YZABC

For the original character P, the character ciphertext C which satisfy the following conditions: C = (P + 3) mod 26

The above is Caesar cipher encryption method, decryption method and vice versa, i.e.: P = (C-3) mod 26

   Assume that the user may use the input contains only a ~ z lowercase letters and spaces, write a program, the input string Caesar cipher encryption, a direct output, where the space is not encrypted. Using input () to get input.

Author    Code: judged according to different criteria.

my_str = input("")
result = ""
for i in my_str:
    if i != my_str[-1] and i not in ['x','y','z']:
        result += chr(int(ord(i)) + 3 % 26)
    elif i == my_str[-1]:
        result += chr(int(ord(i)) + 3 % 26)
    elif i in ['x','y','z']:
        result += chr(int(ord(i)) - 23)
print(result.replace('#',' '))


3. Caesar cipher II

   Description: Caesar cipher Caesar the Roman military intelligence of the algorithm for encryption and decryption, which uses an alternative method for each cycle of the English character information with a third alphabet characters after the character sequence, That is, a correspondence relationship alphabet as follows:

原文: ABCDEFGHIJKLMNOPQRSTU VWXYZ

密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B C‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

For the original character P, the character ciphertext C which satisfy the following conditions: C = (P + 3) mod 26

The above is Caesar cipher encryption method, decryption method and vice versa, i.e.: P = (C-3) mod 26

   Assume that the user may use the input contains only the Letter, i.e., the English lowercase letters a ~ zA ~ Z and special characters, write a program, the input string Caesar cipher encryption, a direct output, wherein the special characters are not encrypted deal with.

Author    Code: depending on whether the judgment can be within the ASCII range.

my_str = input("")
result = ""
for i in my_str:
    if i != my_str[-1] and i not in ['x','y','z','X','Y','Z'] and (65 <= int(ord(i)) <= 90 or 97 <= int(ord(i)) <= 122):
        result += chr(int(ord(i)) + 3 % 26)
    elif i == my_str[-1] and (65 <= int(ord(i)) <= 90 or 97 <= int(ord(i)) <= 122):
        result += chr(int(ord(i)) + 3 % 26)
    elif i in ['x','y','z','X','Y','Z']:
        result += chr(int(ord(i)) - 23)
    else:
        result += i
print(result.replace('#',' '))


4. A bracket detector pairs

   Description: The user inputs his string, which may include the parentheses (), check whether the parentheses are correctly paired, pairing success outputs:

The pairing is successful, unsuccessful pairing

Wherein paired parentheses to consider matching sequence, i.e., () indicates pairing) (not paired, pairing only consider parentheses.

Note that this is a topic OJ, get input using input ( "").


Author    Code: C language can be used in the stack, where you can not use a simpler method

# 把每一个的右括号的值的位置放进去
def everyRight(right,a):
    # 找到该右括号左边的最近左括号的序列号
    for j in a:
        if j - right < 0:
            m = j
    return m


my_str = input("")
my_list = list(my_str)
a = [];b = []
for i in range(0,len(my_list)):
    if '(' == my_list[i]:
        a.append(i)
    elif ')' == my_list[i]:
        b.append(i)

s1 = [];s2 = []
i = 0
try:
    while 1:
        # 递归,首先,先找到第一个右括号和第一个左括号,找到后,就去除,然后递归
        left = everyRight(b[i],a)
        right = b[i]
        s1.append(left)
        s2.append(right)
        # 删除上一次左括号对应的序号,并将下一次的右括号和左括号调用函数
        a.pop(left)
        everyRight(b[i+1],a)
        i = i+1
except:
    pass

try:
    if len(s1) == len(s2) and len(s1) !=0 and len(a) != 1:
        print('配对成功')
    else:
        print('配对不成功')
except:
        print('配对不成功')

However, this method has a problem, such as during the following output:

Why does this happen? We look at the following output:

   This time is a mistake is when encountered have not met the right parenthesis left parenthesis will stop, we value our list to delete removed, when to the last stop, and then judged according to the number of left and right parentheses.
code show as below:

# 把每一个的右括号的值的位置放进去
def everyRight(right,a):
    # 找到该右括号左边的最近左括号的序列号
    for j in a:
        if j - right < 0:
            m = j
    return m


my_str = input("")
my_list = list(my_str)
a = [];b = []
for i in range(0,len(my_list)):
    if '(' == my_list[i]:
        a.append(i)
    elif ')' == my_list[i]:
        b.append(i)

s1 = [];s2 = []
i = 0
try:
    while 1:
        # 递归,首先,先找到第一个右括号和第一个左括号,找到后,就去除,然后递归
        left = everyRight(b[i],a)
        right = b[i]
        s1.append(left)
        s2.append(right)
        print('right{0}'.format(right))
        # 删除上一次左括号对应的序号,并将下一次的右括号和左括号调用函数
        a.pop(left)
        # 删除列表对应的值
        my_list.remove(my_list[left])
        my_list.remove(my_list[right])
        everyRight(b[i+1],a)
        i = i+1
except:
    pass

# print(s1)
# print(s2)
# print(a)
# print(len(a))
# print(my_list)

a1 = my_list.index(')')
a2 = my_list.index('(')

try:
    if len(s1) == len(s2) and len(s1) !=0 and a2 < a1:
        print('配对成功')
    else:
        print('配对不成功')
except:
        print('配对不成功')

But still there is an error:

But we are close to the correct answer, the complete code for improved next blog I will explain.

Guess you like

Origin www.cnblogs.com/ITXiaoAng/p/11600978.html