+ 2

Replacing repeated numbers with zero

So the idea of the code is to replace 0 in the blist if the same number occurs in mlist. I know how to solve the problem if the list if of the same length. But because the first list length is smaller than the second list. I don’t know how to code it. https://code.sololearn.com/cC4noTfg97zJ/?ref=app

26th Apr 2018, 12:18 AM
Andrews Essilfie
7 Réponses
+ 11
You could cycle through both lists with 2 nested fors. This code will check each item in blist 4 times, using each item in mlist: for i in range(0, len(mlist)): #Cycles through each item in mlist for j in range(0, len(blist)): #Cycles through each item in blist #Check the current item in blist against the current item in mlist #Replace if same
26th Apr 2018, 12:37 AM
Tamra
Tamra - avatar
+ 10
Sorry! Here's the full code: for i in range(0, len(mlist)): for j in range(0, len(blist)): if mlist[i] == blist[j]: blist[j] = 0
26th Apr 2018, 2:34 AM
Tamra
Tamra - avatar
+ 6
I...don't mean to confuse but this works: print( [x if x not in mlist else 0 for x in blist ] ) I'm happy to break that down (or let someone else take a shot; it's potentially a good learning tool to break it down)
26th Apr 2018, 12:46 AM
Kirk Schafer
Kirk Schafer - avatar
+ 4
Ah, I'm using some things ahead of where you are in the Python lessons I think: * Lists (and using "in") are covered in section 2, just after "while" * List comprehensions [ x for x in list ] are in section 5 (More Types) * The construct: "true value" if condition "false value" is the very last section (Pythonicness...) When you're ready for those sections, this explanation may help. # iterates every item in blist, returning a new list: [x for x in blist] # Normal "if" statement if x in mlist: useValue = 0 else: useValue = x ... Shorter way in Python (called ternary in other languages) "use this value if true" if test_condition else "use this value if false" useValue = x if x in mlist else 0 So pretending that useValue contains the above test, it looks like this to Python: [useValue for x in mlist] Hope that helps you / visitors.
26th Apr 2018, 3:09 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
@ Kirk. I ran the code and it works. Thanks. I was taught using while loops. So this is a new one to me. But thanks tho
26th Apr 2018, 2:16 AM
Andrews Essilfie
+ 2
Thanks. I’ve read everything and it make sense. Really appreciate it
26th Apr 2018, 4:31 AM
Andrews Essilfie
+ 1
@Tamra. Am confused. What goes in the for loops. Thanks.
26th Apr 2018, 2:14 AM
Andrews Essilfie