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

Thursday, August 18, 2022

[FIXED] How to get a different output?

 August 18, 2022     list, output, python     No comments   

Issue

I am new to python programming. I was trying to write a program to find how many 9s are present in the list.enter image description here

seq = [1, 2, 3, 4, 9, 6, 8, 13, 9, 12, 19]
n = 0
t = []
y = len(seq)
for x in range (0, y-1):
    if seq[x] == 9:
        n += 1
        t.append(x+1) 
    else: continue
print (n, "numbers of 9s are present at", t, "position" )'

output: 2 numbers of 9s are present at [5, 9] position

How i have write the program to get the output as "2 numbers of 9s are present at 5 and 9 position".


Solution

You can use the list comprehension. enumerate return the element (num) of list and the index of element (idx) and if the element (num) is equal to 9 then the positions list will contain the idx as a string. The indexing starts from 1 (not 0) (start=1). You can get the number of 9s with len(positions) and you can join the element with " and ".join(positions).

Code:

seq = [1, 2, 3, 4, 9, 6, 8, 13, 9, 12, 19]
positions = [str(idx) for idx, num in enumerate(seq, start=1) if num == 9]
print("{} numbers of 9s are present at {} positions".format(len(positions), " and ".join(positions)))

Output:

>>> python3 test.py 
2 numbers of 9s are present at 5 and 9 positions

I guess it is the most elegant way to solve your issue.



Answered By - milanbalazs
Answer Checked By - Katrina (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