TRENDING NEWS

POPULAR NEWS

How To Check For 2 Equal Tuples In Python

Tuple and list in Python?

A tuple is like constant, it cannot be modified, hence it is termed immutable.
A list is variable, it can be modified, hence it is termed mutable.

You can have a tuple in a list, something like the following will work, you can modify the content of alist like line 3, but you just cannot modify btup.
alist = [1,2,3]
btup = (alist,5,6)
alist[0] = 4
print btup

The vice versa (i.e. tuple in a list) will work as well, just note that, where the tuple is in the list, you can reassign with something else (list, number, etc.) but you just cannot modify the tuple.

Fractions in Python using tuples?

My professor says fractions can be represented in Python with two integers as a tuple in the format: (numerator, denominator). So I guess (7,10) would equal 7/10. The problem I was assigned was to make a function that will add two fractions (given as two arguments like (7,10),(8/10)). The thing is, we haven't gone into classes yet and are not supposed to utilize the .Fraction module, because that would just make it too easy... But from the way I see it, you CAN'T make a function that adds two tuple fractions without using the .Fraction module.

For example,
add_fract((7,10),(3,4)) should yield (29,20).
So we have to make the definition add the two arguments (which are fractions in the form of tuples) and output them in the most reduced form, in the same format: a tuple with (numerator, denominator).
I was thinking of indexing at [0] and [1] because that would place the numerator over the denominator, but it doesn't seem to be working.

def add_fract(frac1, frac2):
....frac1 = int(frac1)
....frac2 = int(frac2)
....tupleFrac1 = frac1[0]/frac1[1]
....tupleFrac2 = frac2[0]/frac2[1]
....return tupleFrac1 / tupleFrac2

This doesn't work, and even if it did what I wanted it do, I would still need to convert the value to a tuple in the (numerator, denominator) format, and that's not possible either because Python will just return a decimal value instead of the whole fraction.

How would you go about making an add fraction function that recognizes the tuple statement as a fraction and return the sum of the fractions in the same tuple format and in reduced form?

What is the Pythonic way to check for an empty set?

Guido, the father of Python, specifically points out the preferred way to check for empty lists, sets, strings, tuples, or dictionaries in PEP8:http://www.python.org/dev/peps/p...- For sequences, (strings, lists, tuples),
use the fact that empty sequences are false.
Yes: if not seq:
if seq:

No: if len(seq)
if not len(seq)

How do you search a list of tuples in Python?

If you just want to search for the index of a value in the tuple, you can iterate through the list like so:# list of tuples
tups = [("a", 1), ("b", 2), ("a", 1), ("c", 3)]

# create an index counter to avoid problems with identical values
c = 0

# loop through the list
for t in tups:
... if "a" in t:
... print(c)
... c += 1

0
2
>>>

Fractions in Python using tuples?

I'm not going to write the code for you, but here's a description of one way to do this.

If the denominators of the two argument fractions are the same then it's easy: the numerator of the result is the sum of the numerators of the arguments, and the denominator of the result is the same as the denominator of the arguments. And then you reduce that result to get the final answer.

If the denominators of the arguments are not the same then you must generate an new pair of fractions whose values are the same as the original arguments *and* whose denominators are the same. To do that, create one new fraction by multiplying both the numerator and denominator of the first argument by the denominator of the second argument, and create the other new fraction by multiplying both the numerator and denominator of the second argument by the denominator of the first argument. For example, your ( 7, 10 ) + ( 3, 4 ) would become ( 28, 40 ) + ( 30, 40 ). Now that the denominators are the same you can add the numerators. And then you reduce that result to get the a final answer. (If you're feeling lazy you can do this cross-multiplication even if the original denominators are equal. That will make the computation slightly less efficient when the denominators happen to be the same, but will save you from the stress of having to write an if/else block that tests whether the denominators are the same.)

To reduce the result, start by writing a function that takes two numbers as arguments and returns the greatest common factor of those two numbers. (Visit the Wikipedia page for the "Euclidean Algorithm" for a discussion of one way to find the GCF.) Use that function to find the GCF of the fraction's numerator and denominator, then get your final answer by dividing both the numerator and the denominator by that GCF. In your example the intermediate result would be (58, 40), the GCF of those numbers is 2, so the final answer is (29, 20).

Watch out for the numerator being 0 after the addition. If the numerator of the intermediate result is zero (as would happen with, say, (1, 2) + (-1, 2)) then obviously you must skip the GCF step.

What is a tuple in python programming? Do I need it?

A tuple is just a collection of multiple objects.For example, if your mouse pointer has a distance from the left side of the screen and a distance from the top of the screen.You can look at them as two individual values, or as a single tuple of two values.It’s useful because it allows you to use multiple objects (bundled up into one) in all the places where only a single object is acceptable, and it’s a standard, uniform, well-known way of doing it.So if you use a tuple, rather than creating your own class to handle that stuff, everyone reading your code will immediately say “ah, that’s a tuple” without having to read the code of your class.One of the differences to a list is that a list is usually thought to be a collection of similar objects of dynamic length, while a tuple is more idiomatic with a collection (of possibly very different objects) of static length.For example with your mouse pointer coordinates, you wouldn’t use a list because the number of values is static (in fact, equal to two).

When returning multiple values from a function, why does Python use a tuple instead of a list?

What are Immutable Objects?In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. [...] Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.Source: Wikipedia (http://en.wikipedia.org/wiki/Imm...)What does security mean in this context? Here you go:>>> tup = (1,2,3,4)
>>> tup[2]
3
>>> tup[2] = 2
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
Why do I care?Because mutable objects are not hashable in Python. An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.Source: Glossary - Python 2.7.8 documentationI still don't care. Should I?You don't need to most of the time. Unless you have something like this in your code:def many_values(a=3,b=2,c=1):
return a, b, c
...
...
my_fancy_dictionary[many_values()] = something
print("I don't care.")
You would now care, because that print function isn't getting called.

I have written a function in Python that returns multiple values one after another. How do I store these values in a list?

It's unclear exactly what you mean. One interpretation of that your function is a generator (using the yield) or otherwise returns an iterable. That is, your interface isa = f()
first_value = next(a)
second_value = next(b)In this case you can just use the list constructor:l = list(f())You might also mean that the function f returns different values when you call f multiple times, and you want a list of these values. In that case it's probably easiest to write a loop. Exactly how this will look will depend on what your stopping condition is, but it might look something like this:l = []
while True:
a = f()
if a is None:
break
else:
l.append(a)

In the Python dictionary, can 1 key hold more than 1 value?

In python, a dictionary can only hold a single value for a given key. However, if you use a relevant data type for that value, you should be able to save multiple values for a single key.Option 1: Use a tuple to represent the value of the key.var my_dict = {
"my_key": (value_1, value_2, value_3)
};
print (my_dict["my_key"][0]) // This will print value_1
print (my_dict["my_key"][1]) // This will print value_2
Option 2: Use a list (array) to represent the value of the key.var my_dict = {
"my_key": [value_1, value_2, value_3]
};
print (my_dict["my_key"][0]) // This will print value_1
print (my_dict["my_key"][1]) // This will print value_2
Option 3: Use another dictionary to represent the value of the key.var my_dict = {
"my_key": {
"key_1": value_1,
"key_2": value_2
}
};
print (my_dict["my_key"]["key_1"]) // This will print value_1
print (my_dict["my_key"]["key_2"]) // This will print value_2
Hope this helps !!

TRENDING NEWS