Posts: 5
Threads: 4
Joined: Mar 2022
Hello!
I need to create a function with 3 numbers, let's say def f(x,y,z). If I have something like (2,3,2), I want it to return A2B3C2 but if I have (1,3,2) I want it to return AB3C2.
I can't seem to achieve this. Any help?
Posts: 4,803
Threads: 77
Joined: Jan 2018
Mar-10-2022, 10:44 AM
(This post was last modified: Mar-10-2022, 10:45 AM by Gribouillis.)
Please post the Python program and explain why it is not working as expected. Should I move this to the Homework section?
Posts: 2,128
Threads: 11
Joined: May 2017
This is not the solution you want.
1 2 3 4 5 |
def function(a, b, c):
if (a, b, c) = = ( 1 , 3 , 2 ):
return "AB3C2"
else :
return f "A{a}B{b}C{c}"
|
What defines the different output?
Why "AB3C2"?
Posts: 5
Threads: 4
Joined: Mar 2022
Mar-10-2022, 12:25 PM
(This post was last modified: Mar-10-2022, 02:29 PM by Yoriz.
Edit Reason: removed unnecessary quote of previous post
)
AB3C2 was just an example. It could be any numbers, so that's why if loop won't work here. It actually has to do with chemical substances. x is the number of carbon atoms, y the number of hydrogen and z the number of oxygen. I want my function to return the molecular type of the substance.
If the function is f(6,12,6) I want it to return C6H12O6.
But if an atom is present only once, I don't want it to type 1. So if the function is (2,6,1) I want it to return C2H6O
Posts: 2,128
Threads: 11
Joined: May 2017
You can use default arguments, str concatenation and format-strings.
1 2 3 4 5 6 7 8 9 |
def hydrocarbon(carbon, hydrogen = None , oxygen = None ):
result = f "C{carbon}"
if hydrogen:
result + = f "H{hydrogen}"
if oxygen:
result + = f "O{oxygen}"
return result
|
This does only generate the str and does not check, if anything is valid.
In the function specification, you can see that hydrogen and oxygen are assigned to None .
Checking a None of truthiness returns False .
So if you don't set hydrogen or oxygen, those branches are not executed, because they are None .
The += is an inline addition. This works also with str .
1 2 3 |
greeting = "Hello"
greeting + = " "
greeting + = "World"
|
The f in front of the quotes marks the str literal as format string.
1 2 3 4 |
name = "all"
greeting = f "Hello {name}"
|
Posts: 6,818
Threads: 20
Joined: Feb 2020
Mar-11-2022, 07:16 PM
(This post was last modified: Mar-12-2022, 02:05 PM by deanhystad.)
1 2 3 4 5 6 7 |
def merge(counts, symbols = ( "CHO" )):
return " ".join(" " if c==0 else s if c==1 else f" {s}{c}" for s, c in zip (symbols, counts))
print (merge(( 0 , 2 , 1 )))
print (merge(( 2 , 6 , 1 )))
print (merge(( 2 , 1 , 4 ), ( "HSO" )))
print (merge(( 2 , 1 , 4 ), ( "Na" , "S" , "O" )))
|
Output: H2O
C2H6O
H2SO4
Na2SO4
|