PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How can I modify my program to return the same output if a single number is inputted?

 July 20, 2022     function, integer, list, python     No comments   

Issue

So I'm trying to create a program to find all the permutations of every number within 1 to n

So for instance if n = 5, so basically we must find the permutations for [1, 2, 3, 4, 5] and for instance if n = 3, we must find the permutations for [1, 2, 3]. The output must be returned as a tuple.

So now I have this code that returns the permutations if the input is a list only and it works.. but how can I modify it to return all permutations when n: int is the input...

def permutation(lst):
    if len(lst) == 0:
        return []
    if len(lst) == 1:
        return [lst]
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remLst = lst[:i] + lst[i + 1:]
        for p in permutation(remLst):
            l.append([m] + p)
    return l

What changes should I make for my code to work?


Solution

You can use the range built-in function:

def permutation(lst):
    if isinstance(lst, int):
        lst = list(range(1, lst + 1))
    if len(lst) == 0:
        return []
    if len(lst) == 1:
        return [lst]
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remLst = lst[:i] + lst[i + 1:]
        for p in permutation(remLst):
            l.append(tuple([m] + list(p)))
    return tuple(l)

Now both integer and list arguments should work:

print(permutation(3))

or

print(permutation([1, 3, 5]))


Answered By - Selcuk
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing