Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have started learning Python and was wondering how to make a loop, I cant find a website that has it so if you knew it would be great!
I assume you mean a for loop. You do it like so:
for i in range(10):
print i
This is the simplest way. You can use xrange rather than range for very long loops to help with memory management.
Also there are ways to iterate through iterable objects (like lists, arrays, strings etc.):
a=[1,2,3]
for something in a:
print something
You could also use comprehension to make the code shorter, but that's a bit more advanced and you probably don't need it just yet. Should you so wish to learn what it's about this looks OK for a start.
There are many ways.
while True:
That loops until you put break on a line.
The two Aleksander Lidtke mentioned.
for x in range(10): #Loops through the following code 10 times
And:
x = [1,2,3,4]
for items in x: #the variable items is assigned to
#each variable as it iterates through
To learn more about python, read this book.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I am making a Go game and I've stumbled across a problem with my list.append() method.
Every time a player makes a move I want to append the board (2d list) to my ex_boards list. With every iteration of my for loop, instead of appending the current board to my list, it appends it and changes every past board to the current one in the list, something like ex_boards[every index possible in the list] = current_board. So instead of having every state of the game in my list, I have n (len of the list) times the last updated board.
What don't I understand about classes? Also, my list is right below Class Go.
Try using
ex_boards.append(copy.deepcopy(board))
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
name=str(input("enter the string:"))
count=0
for x in name:
if x.isupper():
count=count+1
print("The number of capital letters found in the string is:",count)
How can I rewrite this code without a for loop that gets the same function?
Since this seems like a homework problem, it's probably not appropriate to just post an answer. To give you some hints:
you could re-write the for loop as a while loop that uses a counter
you could re-write the for loop as a while loop that pops characters off of name one-at-a-time, and terminates when name is empty
you could use a list comprehension with a filter to get just the upper-case characters, and report the length of the resulting string
you could write a recursive function
you could use filter the same way you would use a list comprehension
you could use sum, as suggested in comments above
you could use functools.reduce (or just reduce if you're using a geriatric python interpreter)
if you're feeling really perverse, you could use regular expressions
Along with probably a dozen other ways that I'm not thinking of now...
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Does syntax change Big O? Or perhaps change the speed of how a program is processed? I am going to use python as an example.
If I had the list comprehension code:
new_list = [expression(i) for i in old_list if filter(i)]
Would it run any differently than:
new_list = []
for i in old_list:
if filter(i):
new_list.append(expressions(i))
Do these pieces of code have anything different in them? Would one be considered faster than the other? Why or why not?
Big-O says nothing about syntax choice in a programming language. It is only useful as a tool to compare algorithms.
Syntax choices can change the fixed cost of each iteration. Your specific sample has different fixed execution cost per iteration and so the speed of execution will differ.
In Python you could use the timeit module to compare execution speed of two ways to implement the same algorithm, and you could use the dis module to analyse what bytecode will be executed for each alternative 'spelling', informing you how much work the Python interpreter will do for each iteration.
For the specific example, the list comprehension will be faster because it does less work in bytecode; the extra lookups of the .append() method in the second example as well as invoking it is what slows it down.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
On many websites I often see comments that code isn't Pythonic, or that there is a more Pythonic way to achieve the same goal.
What does Pythonic mean in this context? For example, why is
while i < someValue:
do_something(list[i])
i += 1
not Pythonic while
for x in list:
doSomething(x)
is Pythonic?
Exploiting the features of the Python language to produce code that is clear, concise and maintainable.
Pythonic means code that doesn't just get the syntax right, but that follows the conventions of the Python community and uses the language in the way it is intended to be used.
This is maybe easiest to explain by negative example, as in the linked article from the other answers. Examples of un-Pythonic code often come from users of other languages, who instead of learning a Python programming patterns such as list comprehensions or generator expressions, attempt to crowbar in patterns more commonly used in C or Java. Loops are particularly common examples of this.
For example, in Java I might use
for (int index = 0; index < items.length; index++) {
items[index].performAction();
}
In Python we can try and replicate this using while loops, but it would be cleaner to use:
for item in items:
item.perform_action()
Or, even a generator expression
(item.some_attribute for item in items)
So essentially when someone says something is un-Pythonic, they are saying that the code could be rewritten in a way that is a better fit for Python's coding style.
Typing import this at the command line gives a summary of Python principles. Less well known is that the source code for import this is decidedly, and by design, un-Pythonic! Take a look at it for an example of what not to do.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on script which is going to run loop over a input file and extract and/or change some words in the text file. Depending on parameter from console values of all variables from nested loops will be modified accordingly.
My question is: what would be the best way of storing values of variables for all valid parameters? I was considering using dictionary, however I am unsure if I will be able to store more than one string per one key? Essentially I would like to be able to retrieve set of strings and assign their values to the set of variables - based on key value. Some sort of 'nested' dictionary, equivalent of two dimensional array in Java.
Please help me find a suitable (the best and fastest) solution.
Thank you.
Hope this one could help
Use tuple or list for the multiple string
I recommend use tuple, because I assume that the sentences will never change.
my_dict = {
1:("Hello", "World"),
2:("Stackoverflow", "is", "Great")
}
Maybe you can try to store the file in json format.
In order to meet the requirement of retrieving and assignment in a fast way, (k, v) and (v, k) should be store in the json value,eg.something like inverted-table. Code example,
json format(DataStructure):
{k1:[v1,v2], k2:[v1], v1:[k1,k2], v2:[k1]}
Two operations can be made in O(1) time.