← coderbyte_practice

using yield

0de0700e17bd8bd5f3cbdc711c7548608cc25fde · ovidiucs · May 22, 2015 00:20

+32 · 1 file changed

  • medium/16-PermutationStep.py +32 −0
diff --git a/medium/16-PermutationStep.py b/medium/16-PermutationStep.py
new file mode 100644
index 0000000..a177f08
--- /dev/null
+++ b/medium/16-PermutationStep.py
@@ -0,0 +1,32 @@
+__author__ = 'ovidiucs'
+import itertools
+"""
+Using the Python language, have the function PermutationStep(num) take the num
+parameter being passed and return the next number greater than num using the
+same digits. For example: if num is 123 return 132, if it's 12453 return 12534.
+ If a number has no greater permutations, return -1 (ie. 999).
+"""
+# Input = 11121Output = 11211
+# Input = 41352Output = 41523
+def PermutationStep(num):
+
+    nn = list(num)
+
+    if len(nn) <=1:
+        yield nn
+    else:
+        for n in PermutationStep(nn[1:]):
+            for x in range(len(nn)):
+                yield n[:x] + nn[0:1] + n[x:]
+
+
+
+# code from
+# http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python
+# using yield Yield is a keyword that is used like return, except the function will return a generator.
+#
+# keep this function call here
+# to see how to enter arguments in Python scroll down
+print [x for x in PermutationStep("123")]
+#print PermutationStep("41523")
+#print PermutationStep("11211")
\ No newline at end of file