Home > OS >  Limiting number of parameters to a number inputed by the user
Limiting number of parameters to a number inputed by the user

Time:04-12

I am trying to limit the number of parameters defined by the user to the number of inputs first defined by the user in the first input line. nexon = input('Number of exons')

(i.e If the user inputs 2, I want the user to then input values for 2 parameters, ex1 and ex2 if they input 3, I want them to input values for 3 parameters,ex1,ex2,ex3 and so on.) After inputting the parameter values, I'd like to follow the mathematical summation shown below.

Here is the code. I am struggling with why python does not request inputs for ex1, ex2, and so on when it is in an if statement. Is there a way to optimize this using a for loop?

This code only considers the possibility of 4 inputs, ideally I would like it to be able to consider any number of inputs.

The mathematical formula I am trying to incorporate is this one

nexon = input('Number of exons:')

if nexon == 1:
  ex1 = input("Exon 1 lenght:")
if nexon == 2:
  ex1 = input("Exon 1 lenght:")
  ex2 = input("Exon 2 lenght:")
if nexon == 3:
  ex1 = input("Exon 1 lenght:")
  ex2 = input("Exon 2 lenght:")
  ex3 = input("Exon 3 lenght:")
if nexon == 4:
  ex1 = input("Exon 1 lenght:")
  ex2 = input("Exon 2 lenght:")
  ex3 = input("Exon 3 lenght:")
  ex4 = input("Exon 3 lenght:")

EL1 = int(ex1)
EL2 = int(ex2)
EL3 = int(ex3)
EL4 = int(ex4)

IP1 = (EL1%3)
IP2 = (EL1 EL2)%3
IP3 = (EL1 EL2 EL3)%3
IP4 = (EL1 EL2 EL3 EL4)%3

print('exon 1 phase IP1',IP1)
print('exon 2 phase IP2',IP2)
print('exon 3 phase IP3',IP3)
print('exon 3 phase IP4',IP4)```

CodePudding user response:

You can use a loop to ask for user input repeteadly.

Regarding the modulo calculation, for efficiency you can use numpy:

nexon = int(input('Number of exons:'))

lengths = []
for i in range(nexon):
    lengths.append(int(input(f"Exon {i 1} lenght:")))

import numpy as np

IPs = (np.array(lengths).cumsum()%3).tolist()
    
for i, ip in enumerate(IPs, start=1):
    print(f'exon {i} phase IP{i} {ip}')

example:

Number of exons:4
Exon 1 lenght:1
Exon 2 lenght:3
Exon 3 lenght:5
Exon 4 lenght:8
exon 1 phase IP1 1
exon 2 phase IP2 1
exon 3 phase IP3 0
exon 4 phase IP4 2

python only version:

nexon = int(input('Number of exons:'))

cum_lengths = []
v = 0
for i in range(nexon):
    cum_lengths.append(v int(input(f"Exon {i 1} lenght:")))
    v = cum_lengths[-1]

IPs = [v%3 for v in cum_lengths]
    
for i, ip in enumerate(IPs, start=1):
    print(f'exon {i} phase IP{i} {ip}')

CodePudding user response:

1. Why the current code doesn't work properly

The reason Python does not request inputs for the exons is because you are comparing a str to an int.

Python 3's input() function always returns a str even if a number is inputted by the user, but you compare it to an int. Instead, you first need to convert the str to an int using int(nexon). However, if the user enters something other than an integer, this will give an error, and it is better to check before trying to convert, and ask the user again if they do not enter a number, to avoid an error.

This can be done using:

nexon = input("Enter the number of exons: ")
while not nexon.isdigit():
    nexon = input("Number of exons must be a nonnegative integer. Please try again: ")
nexon = int(nexon)

2. How to use a for loop

You can use a for loop to input all of the lengths and add them to a list, before outputting them all modulo 3.

Here is how you would do this:

exon_lengths = []
for i in range(nexon):
    exon_length = input(f"Enter the length of exon {i   1}: ")
    while True:
        try:
            exon_lengths.append(float(exon_length))
            break
        except ValueError:
            exon_length = input("Exon length must be a number. Please try again: ")

3. Full code

nexon = input("Enter the number of exons: ")
while not nexon.isdigit():
    nexon = input("Number of exons must be a nonnegative integer. Please try again: ")
nexon = int(nexon)

exon_lengths = []
for i in range(nexon):
    exon_length = input(f"Enter the length of exon {i   1}: ")
    while True:
        try:
            exon_lengths.append(float(exon_length))
            break
        except ValueError:
            exon_length = input("Exon length must be a number. Please try again: ")

for i, l in enumerate(exon_lengths, start=1):
    print(f"Exon {i} phase IP{i}: {l}")

CodePudding user response:

You can do

nexon = int(input('Number of exons: '))

# stores key:value pairs where e.g. key = 'ex1' and value an int
d = {}
# stores key:value pairs where e.g. key = 'ip1' and value an int
e = {}
for i in range(nexon):
  d[f"ex{i   1}"] = int(input(f"Exon {i   1} length: "))
  e[f"ip{i   1}"] = sum(d[key] for idx, key in enumerate(d) if idx < i   1) % 3

print()
for i in range(nexon):
  print(f"Exon {i   1} phase IP{i   1}", e[f"ip{i   1}"])

print(f"\nd: {d}\ne: {e}")

Sample session:

Number of exons: 3
Exon 1 length: 5
Exon 2 length: 2
Exon 3 length: 1

Exon 1 phase IP1 2
Exon 2 phase IP2 1
Exon 3 phase IP3 2

d: {'ex1': 5, 'ex2': 2, 'ex3': 1}
e: {'ip1': 2, 'ip2': 1, 'ip3': 2}
  • Related