Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simplifying my code
#1
Alright, I had a problem where I needed to make two random lists, then make a third list which would contain the elements that the first 2 lists shared. I did that:

import random

a = []
b = []
c = []
i = 0
while i < 13:
    y = random.randint(0, 20)
    a.append(y)
    i += 1
i = 0
while i < 14:
    y = random.randint(0, 20)
    b.append(y)
    i += 1
print("This is list a: " + str(a))
print("This is list b: " + str(b))
for x in a:
    if x in b:
        if x not in c:
            c.append(x)
print(str(c) + " are element in both a and b lists")
Now lines 7 through 15 where I make the random lists feel slightly clunky and make me feel that there is a better way to do what I did in them. Is that correct, if so how?
Secondly, there is apparently a way to solve this problem with 1 line of code. How? What is the trick for that?
Reply
#2
This is much shorter if that is what you are looking for.
import random

a = [random.randint(0,20) for num in range(13)]
b = [random.randint(0,20) for num in range(13)]

result = set(a).intersection(b)
print(result)
You could mesh that into one line, but then it would be hard to read.

A couple of things about your code:
You should never increment a counter in python while loops. That is what for loops with enumerate() is for. That alone would of shortened it.
https://python-forum.io/misc.php?action=help&hid=53

And you should use the format method (or f-strings) if you are using python3.6+
https://python-forum.io/Thread-Basic-str...xpressions
Recommended Tutorials:
Reply
#3
Basic simplification would be to use while loops instead of for loops, use sets instead of lists, add the random numbers to the sets directly instead of assigning them to a variable and then adding/appending, and union the two sets to find the elements of both.

If you create the two sets using list comprehensions, you could do it all in one line.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
(Jul-21-2019, 01:03 AM)ichabod801 Wrote: Basic simplification would be to use while loops instead of for loops
You mean this in reverse?
Recommended Tutorials:
Reply
#5
(Jul-21-2019, 01:08 AM)metulburr Wrote: You mean this in reverse?

Not only did I meant that in reverse, but it's time to go to bed.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
Another simplification could be proposed on the basis of theory of probability.
It could be shown, that probability of the event that an arbitrary random number x belonging to A = (a1, ..., a13) and B = (b1, ..., b13) simultaneously is equal 169/400 (13/20 * 13/20).

So, we can write:
result = set([random.randint(0,20) for x in range(13) if random.choice([1]*169 + [0]*(400-169))])
We can roughly verify this solution, e.g. by comparing average lengths of sets for direct solution (that uses set intersection) and the above, e.g.

res1 = list()
for k in range(100):
    res1.append(len(set([random.randint(0,20) for x in range(13) if random.choice([1]*169 + [0]*(400-169))])))

avg_len1 = sum(res1) / 100
res2 = list()
for k in range(100):
    res2.append(len(set([random.randint(0,20) for num in range(13)])& set([random.randint(0,20) for num in range(13)])))

avg_len2 = sum(res2) / 100
I got the following values:

Output:
>>> avg_len2 4.83 >>> avg_len1 4.53
Not sure, if this is simplification. Direct method based on set's intersection is clear and simpler.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help for simplifying code mmk1995 8 4,152 Sep-24-2019, 02:04 PM
Last Post: perfringo
  simplifying a stack of elifs Skaperen 8 4,087 Aug-17-2019, 04:13 AM
Last Post: Skaperen
  My program subtracts fractions, but for some reason isn't simplifying them RedSkeleton007 9 5,846 Mar-03-2018, 11:45 AM
Last Post: Gribouillis
  Simplifying multiple "or" conditions in if statement. rhubarbpieguy 8 102,079 Jul-22-2017, 12:19 PM
Last Post: rhubarbpieguy

Forum Jump:

User Panel Messages

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