Overclock.net - An Overclocking Community - Reply to Topic
Thread: What is this? Not a string.. Reply to Thread

Register Now

In order to be able to post messages on the Overclock.net - An Overclocking Community forums, you must first register.
Please enter your desired user name, your email address and other required details in the form below.
User Name:
If you do not want to register, fill this field only and the name will be used as user name for your post.
Please enter a password for your user account. Note that passwords are case-sensitive.
Confirm Password:
Email Address
Please enter a valid email address for yourself.
Email Address:


  Additional Options
Miscellaneous Options

  Topic Review (Newest First)
12-17-2018 05:04 AM
Quote: Originally Posted by PhotonFanatic View Post
Can't figure out why theirs is right, and mine is wrong. The instructions are: "Use a for loop to print out all of the elements in the list names." And here is the code they provided, and then of course you fill in your for loop.

names = ["Adam","Alex","Mariah","Martine","Columbus"]
And my answer was:

for strings in [names]:
  print names
Which printed:

['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']

But the correct answer was:

for name in names:
  print name
Which printed the exact same thing. I'm starting to wonder if I'm actually wrong, or if their site is glitching today.

What your code does is basically says, for each entry in a newly created List [ ] which contains your list of names as the first entry, return the value as strings then print the entire List assigned to names every every time. The first, and only, iteration would return the List assigned to names, and regardless of how many times you went through the loop you'd print out the same thing each time: names..

The correct code says: For each entry in the list assigned as names, return the value for use in the loop as the assignment name then call print name.. or, more shortly put: For each name / value in the names List, print it.

So you have 2 simple mistakes which changes the entire aspect of the code. Now, if you want your code to work, you would need to change the print statement, for one. The second would be creating a second for loop. For each entry in your new list return as x, then use the correct code. This is a nested loop - and in Big O it is O( n^2 ) or exponential growth in terms of cost. A normal loop is O( n ). No loops or simple constant logic such as a = 1, b = 2, etc.. = O( 1 ).. Big O looks into determining a way of determining COST of executing code. Evaluating how well it works. I have a lot of issues with Big O, but it isn't bad for getting a generalized overview - I'd suggest looking into it.

Quote: Originally Posted by PhotonFanatic View Post
for strings in [names]:
  print names
Which printed:

['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']

But the correct answer was:

for name in names:
  print name
Which printed the exact same thing. I'm starting to wonder if I'm actually wrong, or if their site is glitching today.
yours printed ['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus'] once because there was 1 entry in the List you supplied [ names ] which is a reference to the names List. If there were more elements such as the same amount as the names list ie [names, '', '', '', ''] or you just used the names list: names then it would've printed:
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']

Theirs would print:

-- The difference is they print each value from the List, and you print the entire list, completely ignoring the table you're supposed to be processing because you don't use the variable assigned ( the first for x in list: where x is each element returned from list. Since yours was list inside of list, you never accessed the list of names, you access the reference to the list, but never each name... ).. You used for strings in [names]: meaning you would've had to print strings instead of names. names is the reference to the List. strings would be each entry in the list as it is processed by the for each loop. Since you added [ ] you would've needed to run this:

## What yours actually did:
print( 'Looping through every element in names - Note: By not using the name assignment, the value of each entry in the for-each loop which it provides for you, the loop essentially becomes a loop which runs 5 times instead of a for-each loop...' );
for name in names:
    print( names );
print( 'Finished printing the names list ' + str( len( names ) ) + ' times....' );

## Another way to describe the above:
print( 'Looping ' + str( len( names ) ) + ' times - printing the names list for each iteration of the loop - will end up with ' + str( len( names ) ) + ' copies of the list after this is completed!' )
for i in range( 0, len( names ) ):
	print( names );
print( 'Finished outputting the names list ' + str( len( names ) ) + ' times!' );

# How to fix yours
print( 'Looping through every element in names, and printing every name in the list...' )
for name in names:
    print( name );
print( 'Finished printing the ' + str( len( names ) ) + ' names in the names list...' );

## How to fix yours IF you keep [ names ]...
print( 'Looping through the list containing the names list... It will output once Processing List: ..., then ' + str( len( names ) ) + ' names, then Finished...' )
for strings in [names]:
    print( 'Processing List: ' + str( names ) );
    for name in strings:
        print( name );

print( 'Finished...' );
Needless to say, this nested loop doesn't serve any purpose since it is hard-coded. But it would output your intended results. I hope this example clarifies some things.

Second, I would highly recommend taking : Philosophy: Symbolic Logic. It will greatly help in setting up logical statements, inverting them, and more. It is an absolute must if you are looking to becoming a developer ( hardware or software ).

In Python there are double meanings.:L

( ) can be used to organize math operations, boolean statements, etc.. to be bound to your order if you're unsure of the mathematical order ( ie * is done before + - ). However, ( ) is also used to create a Tuple, which is similar to a List ( which is created using [ ]s ) however Tuples can not be changed in size where-as a List size can change.

{ } is used to create a dictionary. Lists / Tuples are essentially identical - they require the key / index to be a number. A Dictionary can use strings as the key / number. Dictionaries are useful for creating maps - ie say you create ENUMs so BLAH_DEFAULT = 0, BLAH_BLEH = 1, BLAH_BLEECH = 2, and so on.. You can use a dictionary to convert a string to those. An example of where you may do this is: Lets say you have a networking system and your enumerators ( enums are used to give meaning to a variable name in code, the value is irrelevant as long as they are different from the other enums in the same grouping - you can re-use values for different groups, ie networking vs photo editing ) are set. But lets say you want to create a map to convert your ENUMs to a word - so some could be NET_CLIENT, NET_SERVER, NET_SHARED and values 0, 1, 2... Then you take a list and set list[ NET_CLIENT ] = 'client', list[ NET_SERVER ] = 'server', etc... Then your Dictionary you can take it in the opposite direction and take server = 1, client = 0, shared = 2.

I could give you a few functions I wrote, along with a long-winded explanation of how useful enums are, maps, and so on. I'll link a dropbox tut to that so I can stay on topic... In short, ENUMs are used to ensure the WORD has a meaning in the code. the value doesn't mean anything as long as it is unique from other enums in the same set. ENUMs can be used very simply to very complexly.. ie they can be used as a simple switch.. If NET_CLIENT or NET_SHARED then ... end if NET_SERVER or NET_SHARED then ... end ...

They can be used for translating languages in your GUI by replacement so you leave a replaceable word such as $HELP_MENU, or $REGISTER_OPTION and it will look up from your list of languages from a user friendly 'en' to a number 1, lets say, which can then be used to look up your words database so MAP_WORDS[ MAP_LANG.get( 'en', 'default' ) ].get( 'HELP_MENU', 'L: "$1" NOT MAPPED!' )... In short... as I said... first MAP_LANG is a Dictionary which converts string language names to their enum ids ( you don't need to store it like this, you could use Dictionaries for all but it may be faster to use numerical keying ) so that returns 1 as we said. Then MAP_WORDS is a Tuple ( we don't need to change the size of a completed language db for an app ) of Dictionaries... Language ENUM ID mapped to their respective Word / Phrase Dictionary... So: MAP_WORDS[ 1 ] returns the dictionary for the English Language. Then MAP_WORDS[ 1 ].get( 'HELP_MENU', 'L: "$1" NOT MAPPED ) returns the Word or Phrase stored under the key "HELP_MENU". If it isn't mapped, then return L: "$1" NOT MAPPED, and the $1 can be replaced with the word missing so you get a nice debugging statement.

Some things may seem complicated in any programming language, but it doesn't need to be. What I do is if I ever repeat code, I turn it into a helper function so I create a repo of building blocks. For instance the math formula: math.Round( _snap / _current ) * _current; is very useful. It lets you Snap to the nearest division... So lets say you use that for Angles... If you want to return an angle snapped every 45 degrees, you put the current angle in for p / y / r, then 45 for the snap to value... And no matter where you are from -180 to 180 it will snap to the nearest 45 degree to your current point. If you had to put that every single place you want to use it, it may be confusing what it is. But, you create a function saying math.SnapTo( _current, _snap ) with that, then you create an Angle.SnapTo( _component, _snap ) - and you put in p / y / r and where you want to snap it, and it'll take the current straight from the object and snap it. It makes things easier to read and it gives you building blocks.

Using building blocks, you can simplify everything to the point your solution reads very easily...

I create building blocks, as said, any time I repeat code - this is as simple as math I use frequently, to gui or text effects.. Say I want to create a Bordered Rounded Rectangle and I'm not given that in the api, but I can make a rounded rectangle. I can easily create a function and call 2 of them, 1 being larger ( the bordered one ) starting at 0, 0.. The small one, which is the color of the rectangle is offset by +border on x and y. And the size w / h is -border * 2 to ensure the rectangle has the border all the way around ( although you can easily change that to have a border along 1 side, 2, 3, 4.. simply by changing the size and / or offset of the center rectangle ).. Instead of calling 2 rounded rectangles each time, I call a single line and if I made a mistake or need to change it, I change it in one place to affect all areas...

I digress...

I say that logic is universal. As you start learning more and more languages you'll start to see patterns emerge. These will greatly help you in learning more, porting / transcribing code between languages, and more. I know several dozen languages already and learning new ones doesn't take long simply because there are always so many similarities it isn't like learning a new language - only learning a new way to write what I already know.

Here's the ENUM function and helpers: https://www.dropbox.com/s/dq5e84cbwh..._usage.py?dl=0 -- There is a LOT of text here... I'd recommend waiting a bit until you are a bit more advanced so you don't feel overwhelmed. But I'm including it here because the function is helpful for efficiency when you start creating programs thousands or tens of thousands of lines long - it can save you thousands of lines of setting up enums, maps, and so on..

Here is a simple intro to classes / objects with inheritance - shapes: https://www.dropbox.com/s/qlvt8023qf...shapes.py?dl=0

Here is a very simple AccessorFunc System - Creates some functions, doesn't create the properties - May have some issues with some objects especially if more complex because of creating them late..
Simple: https://www.dropbox.com/s/3uc55emxmr..._class.py?dl=0
Extended: https://www.dropbox.com/s/h1k8esv3mc..._class.py?dl=0

This is similar to my current AccessorFunc System - although outdated... This is really ugly.. It was an extension of one I previously made, similar to the Alien one except much larger, except this one adds in properties... The object which uses the AccessorFunc system to add functions to it is: AccessorFuncDemoClass - This adds ( I think by one count was over 100 functions / properties, etc.. using 8 lines of code [ the __key = ...( ... ); lines of code ] - the rest is for debugging, output, etc... You'll see a ton of output if you compile this )..

But with 8 lines of code over 100+ functions are created... The nice thing is you can use self.x = 123.. or self.SetX( 123 ), etc.. and they do the same thing.

This is the old version of the AccessorFunc System. I went to add more of the current stuff but it has changed so much that it won't work.

Here's the latest version. Basically AcecoolLib.py copied directly into it, I have only left the example / demo class remain, and added the line to run all the examples. So with all the examples uncommented you'll see everything from my library - almost. I still have more examples to run... This will show you a lot of working code and I have written a lot of comments - some are missing. But it may help you learn. This may not be the only way to complete a task - and it may not be the best way. It is a way. There is an almost endless number of ways you can write code to solve a problem.

Note: I haven't completed recoding the current wiki database / helper. So some of the functions will not work for displaying the functions which have been created. Functionality wise, everything works other than the debugging function to display the function list. However, there is the AccessorFuncDB - Right now you do get a complete list of the function names, it is in JSON format so you can beautify it using an online beautifier or in Sublime Text using an addon. Eventually, this will be linked together in the parent object using a simple function to list everything in a very nice looking concise output showing all of the functions added, all of the aliases, etc.. Right now, it won't look great but it will work ( Just because it works, doesn't make it right. -Josh 'Acecool' Moser )

I hope some of this helps. If you are interested in learning, I do tutor ( for free / donations ) - Add me on Steam: http://www.steamcommunity.com/id/Acecool

I usually tutor Lua ( I have over 500 GLua tutorials I wrote, most of which are simply working code from really simple to incredibly advanced with comments explaining everything ), but I have been working with Python a lot lately to create a utility in order to make me more efficient at coding by mapping my files and creating an output ( Sublime Text - AcecoolCodeMappingSystem - Version 1.0.0 will have threading and a redesign of the entry system along with more updates / upgrades to make it better - it works with Python, GLua, Lua and a lot of other languages, and the default uses Symbols so it should work with any language which has a syntax file )...

Let me know.
12-13-2018 05:48 AM
PhotonFanatic Can't figure out why theirs is right, and mine is wrong. The instructions are: "Use a for loop to print out all of the elements in the list names." And here is the code they provided, and then of course you fill in your for loop.

names = ["Adam","Alex","Mariah","Martine","Columbus"]
And my answer was:

for strings in [names]:
  print names
Which printed:

['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']

But the correct answer was:

for name in names:
  print name
Which printed the exact same thing. I'm starting to wonder if I'm actually wrong, or if their site is glitching today.
12-09-2018 02:18 AM
Quote: Originally Posted by deepor View Post
You are appending to start_list by mistake. You have to append to square_list.

The sorting you should do after the for loop, not inside it (but it won't change the end result, it will just prevent a bunch of extra calls to that .sort() method).
And a call is just python checking something, correct? You'd want it to not have to go back and check a bunch of times because that would slow things down and use up computing power unnecessarily.
12-08-2018 04:34 AM
deepor You are appending to start_list by mistake. You have to append to square_list.

The sorting you should do after the for loop, not inside it (but it won't change the end result, it will just prevent a bunch of extra calls to that .sort() method).
12-08-2018 02:34 AM
PhotonFanatic Oh nice. I always thought it would throw an error if the slightest thing were out of place.

But now I'd like to ask you to take a look at this code. The exorcise appears broken on their site. It either never tells you if you got it wrong, (just does nothing) or marks it wrong with no error message. And it always gives you the python error, along with some words from them with a little help about where you went wrong.

The instructions are: Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list. Then sort square_list!

So I wrote:

start_list = [5, 3, 1, 2, 4]
square_list = []

for the_numbers in start_list:
  start_list.append(the_numbers ** 2)
print square_list
12-06-2018 04:13 AM
deepor The person just made a tiny mistake. There's other languages where you put a semicolon after every statement, so this could have just been a sort of muscle memory for the person who typed this.

If you've never seen it, in Python you can use a semicolon to write stuff on a single line instead of with line-breaks:

>>> print "hello"; print "hi"
That's why the ";" wasn't an actual mistake. Python won't complain about it being there.
12-06-2018 12:58 AM
PhotonFanatic I recently restarted that lesson to help memorize the rules. As I frequently do. And on the very first exorcise, I see something I've never seen before. Didn't notice it the first time. Why is there a semicolon after the list? Its outside the end bracket on the list. What purpose does this serve? Seems like it wouldn't really be needed. You could've started the if statement without that, couldn't you? And all would've been well.

zoo_animals = ["pangolin", "cassowary", "sloth", "bat"];
# One animal is missing!

if len(zoo_animals) > 3:
  print "The first animal at the zoo is the " + zoo_animals[0]
  print "The second animal at the zoo is the " + zoo_animals[1]
  print "The third animal at the zoo is the " + zoo_animals[2]
  print "The fourth animal at the zoo is the " + zoo_animals[3]
12-04-2018 04:17 AM
PhotonFanatic Yep makes sense now lol. That is one that I think I already knew, but it looks confusing for some reason. Kind of like telling a variable to do something new with itself. Like updating a variable or something.
12-04-2018 03:01 AM
deepor There's a "+=" shortcut that you can use:

inventory['gold'] += 50
About why you need to write "x = x + 50" instead of just "x + 50", I don't know how to explain best. Perhaps what's confusing you is that those "=" and "+" symbols are not really the ones you know from equations in math. In math you are describing how things relate with those symbols, but in (most) programming languages those symbols are not descriptions of how things relate, they are instead commands for the machine.

"a + b" <-- read two values and return the result of adding them

"left = right" <-- read the value on the right side and write it into the target on the left side
12-04-2018 12:06 AM
PhotonFanatic Well I'll just continue to pick your brain forever I guess. Why is it necessary to basically say the same thing twice in order to add 50 gold to the inventory? So in order to add 50 gold, I have to say:

inventory['gold'] = inventory['gold'] + 50
It seems to me that: inventory['gold'] + 50 would be sufficient.

here is the whole thing in case its needed.

inventory = {
  'gold' : 500,
  'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
  'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'

# Your code here
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['gold'] = inventory['gold'] + 50
This thread has more than 10 replies. Click here to review the whole thread.

Posting Rules  
You may post new threads
You may post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off