[英]Switch indexes, create the next highest number using the same exact 9 digits presented
因此,我收到了一個挑戰,陳述如下:“設計一個程序,輸入一個9位數字,其中沒有數字出現兩次,並輸出對應於下一個最高數字的相同9位數字作為輸出。如果不存在這樣的數字, ,算法應該指出這一點。因此,例如,如果輸入為781623954,則輸出將為781624359。”
因此,我想到了翻轉索引的想法,因此請在檢查前一個索引之前檢查一下哪個索引更大,然后進行比較,然后在必要時翻轉,但由於某些原因我的代碼無法正常工作。 我只是檢查最后兩位數字而不是全部數字,因此,如果您可以幫助我並為我檢查一下,並且您對解決此問題有更好的想法,請分享。
input = raw_input("Enter 9 Digits: ")
x = 9
while x>0:
x-=1
if input[8] > input[7]:
temp = input[8]
input[8] == input[7]
input[7] == temp
print input
break
這是使用14世紀印度數學家Narayana Pandita的算法的一種更有效的方法,該算法可以在Wikipedia上有關置換的文章中找到。 這種古老的算法仍然是已知的按順序生成置換的最快方法之一,並且它非常健壯,因為它可以正確處理包含重復元素的置換。
下面的代碼包括一個簡單的test()
函數,該函數生成有序數字字符串的所有排列。
#! /usr/bin/env python
''' Find the next permutation in lexicographic order after a given permutation
This algorithm, due to Narayana Pandita, is from
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists,
the permutation is the last permutation.
2. Find the largest index k greater than j such that a[j] < a[k].
3. Swap the value of a[j] with that of a[k].
4. Reverse the sequence from a[j + 1] up to and including the final element a[n].
Implemented in Python by PM 2Ring 2015.07.28
'''
import sys
def next_perm(a):
''' Advance permutation a to the next one in lexicographic order '''
n = len(a) - 1
#1. Find the largest index j such that a[j] < a[j + 1]
for j in range(n-1, -1, -1):
if a[j] < a[j + 1]:
break
else:
#This must be the last permutation
return False
#2. Find the largest index k greater than j such that a[j] < a[k]
v = a[j]
for k in range(n, j, -1):
if v < a[k]:
break
#3. Swap the value of a[j] with that of a[k].
a[j], a[k] = a[k], a[j]
#4. Reverse the tail of the sequence
a[j+1:] = a[j+1:][::-1]
return True
def test(n):
''' Print all permutations of an ordered numeric string (1-based) '''
a = [str(i) for i in range(1, n+1)]
i = 0
while True:
print('%2d: %s' % (i, ''.join(a)))
i += 1
if not next_perm(a):
break
def main():
s = sys.argv[1] if len(sys.argv) > 1 else '781623954'
a = list(s)
next_perm(a)
print('%s -> %s' % (s, ''.join(a)))
if __name__ == '__main__':
#test(4)
main()
我不相信您會用數字翻轉的方法來保證找到下一個最高的數字(至少在沒有進一步檢查的情況下)
這是一個簡單的解決方案:只需增加輸入數字並檢查是否滿足條件或找不到數字。
set()
可用於獲取數字中唯一的一組數字。
input_num = '781623954'
next_num = int(input_num) + 1
input_digits = set(input_num)
found = False
while not found:
next_num += 1
next_digits = set(str(next_num))
found = len(next_digits) == 9 and input_digits == next_digits
if next_num > 987654321:
break
if found:
print(next_num)
else:
print("No number was found.")
input[8] == input[7]
input[7] == temp
你可能的意思是:
input[8] = input[7]
input[7] = temp
是不是
如注釋中所述,它不能直接在字符串上工作,因為它在Python中是不可變的。 因此,作為第一步,您可以列出該字符串中的字符:
input = list(input)
最后,從修改后的列表中返回一個字符串:
input = ''.join(input)
順便說一句,您可能想從Python元組解壓縮中受益,它允許您交換兩個變量而不必引入第三個變量:
input[7], input[8] = input[8], input[7]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.