C2W3 assignment 1

I see some people report completing assignment1 and I am very humbled…
Nevertheless, I have a question which seems like a fundamental issue. We have this expression in original Python2.7 code:
indices_to_remove = set([int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)])
This set expression randomizes indices_to_remove very differently from python3. And seems that fundamentally this order cannot be reproduced… Any hint I appreciate! Spent a lot of time on this code and even wasted 20 bucks on OpenAI. :frowning:

The numpy random seed is ensuring that that sequence is the same, dont change that part numpy.random.seed(seed), if I am understanding right your question!

numpy.random is same. It is set operation on array:
set([int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)])
that randomizes in python2.7 but not in python3… In python2.7 it comes out as random according to some hash function while in python3 it comes out in sorted order. So I get two sets indices_to_remove in different sequence and do not know how to reproduce randomness of python2.7. So actual numbers of sets “indices_to_remove” are same but seems that python2.7 sequence cannot be reproduced…

what I mean is this:
# indices_to_remove = set([int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)])
array=[int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)]
print “Indices to array:”, array
indices_to_remove = set(array)
print “Indices to remove:”, indices_to_remove

– here in code I replace one line by two lines (separate set operation and random on list operation) and do some printing for debug.
This is the output:
(python27) jovyan@8b8b94334109:~/work/assignment_part_1$ python magic_summation_python27.py 22 5
Indices to array: [20, 5, 21, 11, 14]
Indices to remove: set([11, 20, 5, 14, 21])

You can see that array 20, 5, 21, 11, 14 is randomized to 11, 20, 5, 14, 21

I do not know how to replicate such randomization in python3. May be I am looking in a wrong way? Hope someone can hint me.
Thanks

Keep numpy.random.seed(seed) and in python 3 the indices to remove is the same as in python 2.7, no need to change anything there!

Hi Gent:
What I want to say is that the random numbers 20, 5, 21, 11, 14 agree between python3 and python2.7, but their sequence in python2.7 is random in a way that I cannot reproduce in python3, because set() in set([int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)]) randomizes then in a way that I do not know how python3 can reproduce. And then the complex loop that follows goes in a different iterator sequence in python3 which yields to different magic_summation result. I really do not know how to solve it. Moreover, after I zeroed in on a problem via numerous prints and discussed it with ChatGPT 4o and o1, both of them told me the problem is fundamental. Something big I am missing :frowning:

I mean this line in python2.7 code:
indices_to_remove = set([int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)])
array=[int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)]

if indices_to_remove=[int(numpy.random.random() * n) + 1 for _ in range(int(numpy.random.random() * n) + 1)]

(without set()) in python2.7 code, I could easily reproduce result. But really have no clue what to do about set() because it further randomizes the list and no clue how python3 can replicate it!

I dont you need to have them in sorted order, as long as the set includes the right items no need to have them in sorted order!

I’m having the same issue, no matter what I try it does not work and when I add 1 to the indices by default, it works for the unittests.py file but not when I submit it

I tried running:

import sys
import numpy

def magic_summation(n, seed=None):
### DO NOT REMOVE OR CHANGE THE COMMAND BELOW
### AS IT WON’T BE POSSIBLE TO CORRECTLY GRADE YOUR SOLUTION
numpy.random.seed(seed)

if n <= 2:
    raise ValueError('n cannot be less than or equal to 2')
elif not isinstance(n, int):
    raise TypeError("n must be an integer")

magic_list = list(range(1, n + 1))  # Convert range to a list
indices_to_remove = set([int(numpy.random.random() * n) for _ in range(int(numpy.random.random() * n) + 1)])

if len(indices_to_remove) == len(magic_list):
    print("Magic summation is equal to 0.")
    return 0

def iterator():
    for idx in sorted(indices_to_remove):  # Sort indices to prevent index errors
        if idx < len(magic_list):
            del magic_list[idx]
    for i in range(len(magic_list)):
        if i < len(magic_list) - 1:
            magic_list[i] = magic_list[i + 1] / magic_list[i]
    for el in magic_list:
        yield el

it = iterator()
magic_summation = 0

while True:
    try:
        magic_summation += next(it)  # Use next() function
    except StopIteration:
        break
        
# Round the result before printing
rounded_summation = round(magic_summation)
print("Magic summation is equal to: {0}.".format(rounded_summation))
return rounded_summation

#######################################
####### DO NOT EDIT THIS PART #########
#######################################

if name == “main”:
if len(sys.argv) > 3:
raise ValueError(“You must pass at most two arguments, the value for n”)

elif len(sys.argv) == 1:
    raise ValueError("You must pass at most two arguments, the value for n")

elif len(sys.argv) == 3:
    n = int(sys.argv[1])
    seed = int(sys.argv[2])
else:
    n = int(sys.argv[1])
    seed = None

magic_summation(n, seed=seed). 

But still there are some issues with different numbers (well this is the final code I thought would work after numerous iterations)

Any help would be appreciated!

integer division is required instead of float division

Yeah but my code seems to deviate from the expected output

yes that’s the issue almost everyone is facing, it is giving answers other than the ones required

I am not saying that I have numbers in sorted order in one case (python3) and in non-sorted order in another case (python2.7). What I am saying is that doing set(array of random numbers) in python2.7 makes those numbers indices_to_remove in a certain random order because of set operation. And this order cannot be reproduced in python3; at least cannot figure out how to reproduce it. So in python3 I get the SAME random numbers in a different order. And this makes magic_summation output different. The issue is not numpy.random; the issue is set() rearranging number sequence and that rearrangement cannot be copied in python3.

You say:
I dont you need to have them in sorted order, as long as the set includes the right items no need to have them in sorted order!
– yes, you don’t need them in sorted order, but you need them in the same order when you do python2.7 or python3; this is my understanding

1 Like

Hope they change the code to something that won’t be as much of a headache, I can’t figure out how to do it, I’ve tried chat gpt, gemini and deepseek coder but nothing worked, I’ve given at least 50 prompts till now but idk how to resolve it.

This assignment was just updated. Please refresh your notebook before you proceed.

2 Likes

Hi Tom:
Yeah, updated assignment has a solution. I am done (after 3 days :hot_face:)
I wonder how did some other learners manage to pass the assignment before this update? There are people who posted that they were done before this was updated…

1 Like

I’m glad the issues are being resolved.

1 Like