Wikipedia:Reference desk/Archives/Computing/2020 October 3

Computing desk
< October 2 << Sep | October | Nov >> October 4 >
Welcome to the Wikipedia Computing Reference Desk Archives
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages.


October 3

edit

Clarification on what a part of a code does?

edit

For this problem:

https://www.codewars.com/kata/582b0d73c190130d550000c6/python

I saw this specific solution by Basementality:

https://www.codewars.com/kata/582b0d73c190130d550000c6/solutions

   def factors(n):
       sq = [a for a in range(2, n+1) if not n % (a**2)]
       cb = [b for b in range(2, n+1) if not n % (b**3)]
       return [sq, cb]

Basically, I just want to acquire greater clarity in regards to what the last part here--specifically the "if not n % (a**2)" and the "if not n % (b**3)" actually does. Futurist110 (talk) 00:21, 3 October 2020 (UTC)[reply]

Futurist110, Assuming you know list comprehension, it's essentially saying in English, add a to the list if the remainder of n divided by a2 is 0. The syntax ** raises the variable to the power, and % (modulo) returns the remainder of the division, if the remainder is 0, then the number is a factor of n. Since 0 would evaluate to false, the not operator reverses the boolean to true. Dylsss (talk) 00:44, 3 October 2020 (UTC)[reply]
I think that I got it; thank you! Futurist110 (talk) 02:33, 3 October 2020 (UTC)[reply]

How does one do a for loop iteration across a Python dictionary where one wants to loop through every item in the dictionary other than a specific single item?

edit

How does one do a for loop iteration across a Python dictionary where one wants to loop through every item in the dictionary other than a specific single item? Futurist110 (talk) 02:33, 3 October 2020 (UTC)[reply]

Futurist110, It sounds like you just want something like this
colors = {1:"RED", 2:"BLUE", 3:"GREEN"} 
for item in colors.values(): 
   print(item)
This will iterate through the values in the dictionary, e.g. "RED", "BLUE", "GREEN". Just use the values() function. Hope that helps. Dylsss (talk) 13:40, 3 October 2020 (UTC)[reply]
But I want to exclude one of the dictionary values from my iteration here. How do I do that? Futurist110 (talk) 21:19, 3 October 2020 (UTC)[reply]
for item in colors.values(): 
   if not item == "RED":
      print(item)
...or do I miss something? --Stephan Schulz (talk) 21:32, 3 October 2020 (UTC)[reply]
That might actually work; thank you! Futurist110 (talk) 03:35, 4 October 2020 (UTC)[reply]

Style point: it's just a convention and not part of the language, but "item" in a python dictionary usually refers to the key and the value. For just the value, you'd use "value" instead of "item". 2602:24A:DE47:BB20:50DE:F402:42A6:A17D (talk) 21:14, 5 October 2020 (UTC)[reply]