Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python function
#1
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?
Reply
#2
Please post the Python program and explain why it is not working as expected. Should I move this to the Homework section?
Reply
#3
This is not the solution you want.

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"?
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
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
Reply
#5
You can use default arguments, str concatenation and format-strings.

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.

greeting = "Hello"
greeting += " "
greeting += "World"
The f in front of the quotes marks the str literal as format string.

name = "all"

# name is replaced by the str content of name
greeting = f"Hello {name}"
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
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
kabeer_m likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020