How do I change this recursive approach to iterative approach?
This is a game function from pygame. If user press left (pygame.KEYDOWN.K_LEFT), angle -= 1. Else if user press right (pygame.KEYDOWN.K_RIGHT), angle += 1. 'Event.type' is the detection of which key the user pressed. angle can be negative.
Question: is this a recursive approach? if yes, how to change it to be iterative, or faster efficiency?
angle = 0
if event.type == pygame.KEYDOWN.K_LEFT:
angle -= 1
elif event.type == pygame.KEYDOWN.K_RIGHT:
angle += 1
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
MIPS Assembly - how to calculate squre of n recursively
I want to write a program that calculates the square of
n
using recursively based on the equationn^2 = (n - 1)^2 + 2(n - 1) + 1
But I don't know how to write thenonbasecase
part. Can anyone help?A python program would be
def square(n) { if (n==0): return 0 else: return square(n-1) + 2*(n-1) + 1 }
Here is what I got so far.
start: li $a0, 0x0003 #$a0 contains the number to be squared jal square # recursive call square: subi $sp, $sp, 8 # decrement the stack pointer $sp sw $ra, 4($sp) # push the return address register $ra sw $a0, 0($sp) # push argument register $a0 li $t0, 0x0001 # load $t0 with 1 as part of test for base case bne $a0, $t0, nonbasecase # branch if not the base case li $v0, 0x0001 # return base result in $v0 addi $sp, $sp 8 # recover stack space jr $ra # jump to return address in $ra nonbasecase: #not sure how to write when it is not the base case jr $ra # jump to contents of return address register $ra
-
Nested list in C# with layers
I am not an expert coder and I have just started learning about Generic data types. What I am trying to code is a List inside of a list inside of a list .
For example- at the first level - I want numbers each inside of a list
Layer 1 list1=[1,2,3,4,5,6,7,8,9,10......1000] ,
At the 2nd layer I'd like list from 1st layer added as an element to a parent list 2 when layer 1 meets certain condition- ex layer 1 reaches max=10
List2=[List1[0:10],List1[10:20],List1[20:30], .....] ,
At layer 3, i'd like to repeat the process, all elements of layer 2 get added as an element to a new parent list 3 when layer 2 meets a max condition. list3[0]=[list2[0:10],list2[10:20],list2[20:30]..... and so on.
Only the first layer would have integer values, the successive layer would be a wrapping of it's the previous layer. How can I code this in C#?
Thanks!
-
Why println is being executed in this recursive piece of code?
In this code arrLength starts with four and then keeps being decremented until it reaches zero. At the moment it reaches zero it should not execute what is inside the if block anymore. But what is happening is that when it reaches zero it still executes the println line. Not understanding how that println line is being executed since that line is inside the if block and nothing inside the if block should execute when arrLength gets to zero. At the end it prints 5, 6, 2, 1 while in my understanding it should print nothing never executing the println line.
class ArrayElements{ public void printElements(int arr[], int arrLength){ if(arrLength != 0){ arrLength--; printElements(arr, arrLength); System.out.println(arr[arrLength]); } } } public class Main { public static void main(String[] args) { int arr[] = {5,6,2,1}; int arrLength = arr.length; ArrayElements mv = new ArrayElements(); mv.printElements(arr, arrLength ); } }
-
Why does my player disappears when pressed jump? All indentations wrong or right?
https://github.com/Aditya13114/pygame-error2
So, I am a beginner to Py game and i was creating an Infinite Runner Game. Turns out it is not working at all and when i asked the Youtube creator what was happening he said the indentations were wrong. Spent 8 hours looking for them still cant figure out. So basically what is happening, i created the Game state called game_active and set it to True by default. And all of my blit functions, i stored them inside if game_active: then pasted all my code. In the output window i press Space key and it disappears then stops. It stops because i added the code if snail_rect.colliderect(player_rect): game_active = False. I dont know why is it not working. Pls help
-
How to start a music at the exact runtime the last one stopped?
i'm just starting with Python and creating games with pygame, and i try to do something specific with the background music :
- The game start with the "background music"
- when pressing a key, the player activ a cheat that slow time for ennemies
- the current background music stops
- a slow-mo version of this background music then starts at the exact moment where the last time stopped
- when the player releases the Key, the "background 1" music continue from were the slo-mo one stopped
here what i've coded:
pygame.mixer.music.load("music.wav") pygame.mixer.music.play(-1, 0.0) timeSet = 0 timePos = pygame.mixer.music.set_pos(timeSet) if event.type == KEYDOWN: if event.key == K_q: slowCheat = True timeSet = pygame.mixer.music.get_pos() pygame.mixer.music.stop() pygame.mixer.music.unload() pygame.mixer.music.load("slowmusic.wav") pygame.mixer.music.play(-1, 0.0) timePos if event.type == KEYUP: if event.key == K_q: slowCheat = False timeSet = pygame.mixer.music.get_pos() pygame.mixer.music.stop() pygame.mixer.music.unload() pygame.mixer.music.load("music.wav") pygame.mixer.music.play(-1, 0.0) timePos
i get this error message when lauching the program :
pygame.error: set_pos unsupported for this codec
I search online to find a solution but nothing. I've pygame 2.1.2 and Python 3.10.4, so the version shouldn't be the problem I've also read something about dividing "pygame.mixer.music.set_pos(timeSet)" result by 1000.0 ?
-
Is it possible to proportionally scale an image in Pygame so that it scales from the middle?
I’m currently trying to make an interactive button that grows when you hover over it with the mouse. As of right now, all that happens is that the width and height increase by 100, but this causes the image to be out of proportion and also grow toward the right because the anchor point is at the top left like with all Pygame sprites. How could I make it so the image grows proportionally to itself from the middle?
Here is what I have currently (width and height is 490x44 and they are passed as parameters)
self.image = pygame.transform.smoothscale(self.image,((self.width + 100), (self.height + 100)))
-
pivot_wider does not keep all the variables
I would like to keep the variable
cat
(category) in the output of my function. However, I am not able to keep it. The idea is to apply a similar function tom <- 1 - (1 - se * p2)^df$n
based on the category. But in order to perform that step, I need to keep the variable category.Here's the code:
#script3 suppressPackageStartupMessages({ library(mc2d) library(tidyverse) }) sim_one <- function() { df<-data.frame(id=c(1:30),cat=c(rep("a",12),rep("b",18)),month=c(1:6,1,6,4,1,5,2,3,2,5,4,6,3:6,4:6,1:5,5),n=rpois(30,5)) nr <- nrow(df) df$n[df$n == "0"] <- 3 se <- rbeta(nr, 96, 6) epi.a <- rpert(nr, min = 1.5, mode = 2, max = 3) p <- 0.2 p2 <- epi.a*p m <- 1 - (1 - se * p2)^df$n results <- data.frame(month = df$month, m, df$cat) results %>% arrange(month) %>% group_by(month) %>% mutate(n = row_number(), .groups = "drop") %>% pivot_wider( id_cols = n, names_from = month, names_glue = "m_{.name}", values_from =m ) } set.seed(99) iters <- 1000 sim_list <- replicate(iters, sim_one(), simplify = FALSE) sim_list[[1]] #> # A tibble: 7 x 7 #> n m_1 m_2 m_3 m_4 m_5 m_6 #> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 1 0.970 0.623 0.905 0.998 0.929 0.980 #> 2 2 0.912 0.892 0.736 0.830 0.890 0.862 #> 3 3 0.795 0.932 0.553 0.958 0.931 0.798 #> 4 4 0.950 0.892 0.732 0.649 0.777 0.743 #> 5 5 NA NA NA 0.657 0.980 0.945 #> 6 6 NA NA NA 0.976 0.836 NA #> 7 7 NA NA NA NA 0.740 NA
Created on 2022-05-07 by the reprex package (v2.0.1)
-
No of Passes in a Bubble Sort
For the list of items in an array i.e. {23 , 12, 8, 15, 21}; the number of passes I could see is only 3 contrary to (n-1) passes for n elements. I also see that the (n-1) passes for n elements is also the worst case where all the elements are in descending order. So I have got 2 conclusions and I request you to let me know if my understanding is right wrt the conclusions.
Conclusion 1 (n-1) passes for n elements can occur in the following scenarios:
- all elements in the array are in descending order which is the worst case
- when it is not the best case(no of passes is 1 for a sorted array)
Conclusion 2 (n-1) passes for n elements is more like a theoretical concept and may not hold true in all cases as in this example {23 , 12, 8, 15, 21}. Here the number of passes are (n-2).