COMP9021 Principles of Programming Lab6

1. Obtaining a sum from a subsequence of digits

Obtaining a sum from a subsequence of digits
Write a program sum_of_digits.py that prompts the user for two numbers, say available_digits and desired_sum, and outputs the number of ways of selecting digits from available_digits that
sum up to desired_sum. For 4 solutions:
--one solution is obtained by selecting 1 and both occurrences of 2 (1 + 2 + 2 = 5);
--one solution is obtained by selecting 1 and 4 (1 + 4 = 5);
--one solution is obtained by selecting the first occurrence of 2 and 3 (2 + 3 = 5);
--one solution is obtained by selecting the second occurrence of 2 and 3 (2 + 3 = 5).

#DP solution:
#available_digits = 1 2 2 3 4, sum = 5
#   1    2    3    4    5 (sum)
#1 1,1  1,1  1,1  1,1  1,1 (第一个数字是sum值,第二个数字是路径数量)
#2 1,1  2,1  3,1  3,1  3,1 
#2 1,1  2,2  3,2  4,1  5,1
#3 1,1  2,2  3,3  4,2  5,3
#4 1,1  2,2  3,3  4,3  5,4
#digits

#digits = [1, 2, 2, 3, 4]
#default: cell[0] = digits[0] * sum
##cell[i][j] = max(cell[i - 1][j], cell[i - 1][j - digits[i]] + digits[i])
##路径数量分情况讨论,如下面的代码,如果本行的digits数值与某个cell中上一行同一位置的数值相等,则本行这个cell中的路径数量等于上一行对应位置的路径数量加1
#def printcell():
#    for i in range(nrow):
#        for j in range(ncolumn):
#            print(cell[i][j], end = ' ')
#        print()


digits = input('Input a number that we will use as available digits: ')
desired_sum = int(input('Input a number that represents the desired sum: '))

digits = [int(e) for e in sorted(digits)]
nrow = len(digits)
ncolumn = desired_sum
cell = [[[0, 0] for _ in range(ncolumn)] for _ in range(nrow)]
#创建一个网格,行数等于输入的可用数字的长度,列数等于输入的总和,也就是说以1为步长构建column。网格default值为0,以及一个记录path组成方式数量的空list
for j in range(ncolumn):
    if j + 1 >= digits[0]:
        cell[0][j][0] = digits[0]
        cell[0][j][1] = 1
    else:
        cell[0][j][0] = 0
        cell[0][j][1] = 0
#创建第一行的default值,如果比某列sum值大则设置为0,否则则设置为digits第一个值
for i in range(1, nrow):
    for j in range(ncolumn):
        if digits[i] > j + 1:
            cell[i][j][0] = cell[i - 1][j][0]
            cell[i][j][1] = cell[i - 1][j][1]
        elif digits[i] == j + 1:
            cell[i][j][0] = digits[i]
            if cell[i - 1][j][0] == digits[i]:
                cell[i][j][1] = cell[i - 1][j][1] + 1          
            else:
                cell[i][j][1] = 1
        else:
            a = cell[i - 1][j][0]
            b = cell[i - 1][j - digits[i]][0] + digits[i]
            if a == b:
                cell[i][j][0] = a
                cell[i][j][1] = cell[i - 1][j][1] + cell[i - 1][j - digits[i]][1]
            else:
                if a > b:
                    cell[i][j][0] = a
                    cell[i][j][1] = cell[i - 1][j][1]
                else:
                    cell[i][j][0] = b
                    cell[i][j][1] = cell[i - 1][j - digits[i]][1]
#    printcell()

if cell[-1][-1][0] == desired_sum:
    solution = cell[-1][-1][1]
else:
    solution = 0
    
if solution == 0:
    print('There is no solution.')
elif solution == 1:
    print('There is a unique solution.')
else:
    print('There are %d solutions.' % solution)

2. Merging two strings into a third one

Say that two strings s1 and s2 can be merged into a third string s3 if s3 is obtained from s1 by inserting arbitrarily in s1 the characters in s2, respecting their order. For instance, the two strings ab and cd can be merged into abcd, or cabd, or cdab, or acbd, or acdb, ..., but not into adbc nor into cbda. Write a program merging_strings.py that prompts the user for 3 strings and displays the output as follows:
--If no string can be obtained from the other two by merging, then the program outputs that there is no solution.
--Otherwise, the program outputs which of the strings can be obtained from the other two by merging.

str1 = input('Please input the first string: ')
str2 = input('Please input the second string: ')
str3 = input('Please input the third string: ')

if len(str1) > len(str2):
    if len(str1) > len(str3):
        last = str1
        if str2 > str3:
            first, second = str3, str2
        else:
            first, second = str2, str3
    else:
        last, first, second = str3, str2, str1
else:
    if len(str2) > len(str3):
        last = str2
        if str1 > str3:
            first, second = str3, str1
        else:
            first, second = str1, str3
    else:
        last, first, second = str3, str1, str2
#按照字符串从段到长顺序分别赋给first, second, last

def merge(first, second, last):
    if not first and second == last:
        return True
    if not second and first == last:
        return True
    if not first and not second:
        return False
    if second[0] == last[0] and merge(first, second[1:], last[1:]):
        return True
    #因为second是第二长的,所以必须放在first的判断前面,以保证index不溢出
    if first[0] == last[0] and merge(first[1:], second, last[1:]):
        return True
    return False
    
if merge(first, second, last):
    if last == str1:
        output = 'first'
    elif last == str2:
        output = 'second'
    else:
        output = 'third'
    print('The %s string can be obtained by merging the other two.' % output)
else:
    print('No solution.')

3. Longest sequence of consecutive letters

Write a program longest_sequence.py that prompts the user for a string w of lowercase letters and outputs the longest sequence of consecutive letters that occur in w, but with possibly other letters in between, starting as close as possible to the beginning of w.

string = input('Please input a string of lowercase letters: ')
l = [ord(i) for i in string]
#将输入的字符串转化为对应的integer,方便后续比较,判断是否连续
l = list(set(sorted(l)))
#将integer的list排序,去重

start, longest, length, result = l[0], [l[0]], 1, [l[0]]
#初始化,设置连续integer开始的位置是第一个integer,最长的连续integer是第一个integer,最长长度是1,最长连续integer记录是第一个integer
for i in range(1, len(l)):
    if l[i] == l[i - 1] + 1:
        longest.append(l[i])
    #如果当前数字和前面数字连续,则longest记录值增加一个当前integer
    else:
        if len(longest) > length:
            result = longest
            length = len(longest)
        #如果当前数字和前面不再连续,判断longest中的最长连续数字长度是否比result中的记录长
        #如果长,则改写result和最长length
        start, longest = l[i], [l[i]]
        #重置开始的位置为当前integer,longest中只有当前integer一个元素

    if i == len(l) - 1 and len(longest) > length:
        result = longest
        length = len(longest)
    #如果是最后一个l中的元素,还要判断当前的连续数字长度是否是最长的

solution = ''
for i in result:
    solution += chr(i)
#将最长连续数字转换为对应的字母输出
print('The solution is: %s' % solution)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容

  • (二)说话篇 “良言一句三冬暖,恶语伤人六月寒,休将自己心田媚,莫把他人过时扬,莫说他人短与长,说来说去自遭殃,若...
    carlblue阅读 517评论 0 0
  • 外汇消息 特朗普最终将“黑马”优势发挥得淋漓尽致,赢下最终的胜利。70岁的唐纳德·特朗普,成功当选美国第45任总统...
    BRTFX外汇阅读 332评论 0 0