Snippets Collections
const myArray = ['rock', 'paper', 'scissors'];

for(item of myArray){
        const index = myArray.indexOf(item);
        console.log(index)
    
}
const repository = {
  id: 1,
  language: "javascript",
  public: true
};

for (const value of Object.values(repository)) {
  console.log(value);
}
const ages = [18, 20, 21, 30];

const agesPlusOne = ages.map(age => age + 1);
const deck = ['clubs','spades', 'hearts', 'diamonds']
for(let [index, item] of deck.entries()){
    console.log(index)
}
# numpy and matplotlib imported, seed set

# Simulate random walk 500 times
all_walks = []
for i in range(500) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        if np.random.rand() <= 0.001 :
            step = 0
        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))

# Select last row from np_aw_t: ends
ends = np_aw_t[-1, :]

# Plot histogram of ends, display plot
plt.hist(ends)
plt.show()
# Numpy is imported; seed is set

# Initialize all_walks (don't change this line)
all_walks = []

# Simulate random walk 10 times
for i in range(10):

    # Code from before
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)

        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        random_walk.append(step)

    # Append random_walk to all_walks
    all_walks.append(random_walk)

# Print all_walks
print(all_walks)


#####################################################################
# numpy and matplotlib imported, seed set

# Simulate random walk 250 times
all_walks = []
for i in range(250) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)

        # Implement clumsiness
        if np.random.rand() <= 0.001 :
            step = 0

        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()


# Numpy is imported, seed is set

# Initialization
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt

# Plot random_walk
plt.plot(random_walk)

# Show the plot
plt.show()
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

# Complete the ___
for x in range(100) :
    # Set step: last element in random_walk
   
    step = random_walk[-1]

    # Roll the dice
    dice = np.random.randint(1,7)

    # Determine next step
    if dice <= 2:
        step = step - 1
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    # append next_step to random_walk
    random_walk.append(step)

# Print random_walk
print(random_walk)

#Not Going below zero
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        # Replace below: use max to make sure step can't go below 0
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

print(random_walk)
# Numpy is imported, seed is set

# Starting step
step = 50
# Roll the dice
dice = np.random.randint(1,7)
# Finish the control construct
if dice <= 2 :
    step = step - 1
elif dice <= 5 :
    step = step + 1
else:
    step = step + np.random.randint(1,7)

# Print out dice and step
print(dice)
print(step)
# Import numpy as np
import numpy as np

# Set the seed
np.random.seed(123)

# Generate and print random float
print(np.random.rand())

#Roll The Dice
# Import numpy and set seed
import numpy as np
np.random.seed(123)

# Use randint() to simulate a dice
print(np.random.randint(1,7))
# Use randint() again
print(np.random.randint(1,7))


# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Use .apply(str.upper)


cars['COUNTRY'] = cars['country'].apply(str.upper)
print(cars)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Adapt for loop
for lab, row in cars.iterrows() :
    print(lab + ": " + str(row['cars_per_cap']))

#Something new

# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Code for loop that adds COUNTRY column
for lab, row in cars.iterrows():
    cars.loc[lab,'COUNTRY'] = row['country'].upper()


# Print cars
print(cars)
#Iterating over a Pandas DataFrame is typically done with the iterrows()
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Iterate over rows of cars
for lab,row in cars.iterrows():
    print(lab)
    print(row)
# Import numpy as np

import numpy as np
#for x in my_array : #in 1D Numpy array
#for x in np.nditer(my_array) : #for 2D Numpy array

# For loop over np_height

for x in np_height:
    print(str(x) + " inches")

# For loop over np_baseball
for x in (np.nditer(np_baseball)):
    print(x)
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
          'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
          
# Iterate over europe
for key, value in europe.items() :
    print('the capital of ' + str(key) + ' is ' + str(value))
# house list of lists
house = [["hallway", 11.25], 
         ["kitchen", 18.0], 
         ["living room", 20.0], 
         ["bedroom", 10.75], 
         ["bathroom", 9.50]]
         
# Build a for loop from scratch
for x in house :
    #x[0] to access name of room
    #x[1] to access area in sqm
    print('the ' + x[0] + " is " + str(x[1]) + " sqm")
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
/*
The tax rate is often a function of the income or in other words individuals at different income levels will pay different taxes.

Also, in some countries like the UK, individuals get to keep a certain amount of their income
that's not taxed while the remainder is taxed at the applicable rate. So for example, let's say a person makes 100K and their tax rate is 10% or 0.1 but they are allowed to keep 30K. They will end up paying 7000 or 7K in taxes because:
100K - 30K = 70K. // they keep 30K and have 70K left.
10% of 70K = 7K. // they will pay 10% tax on what's left.

Your challenge is to complete the code below to return the function that will correctly calculate taxes for a person based on the rules below.

Amount                            Tax Rate
--------------------------------------------
<= 100,000                        10% or 0.1
> 100,000 to 500,000 (inclusive)  20% or 0.2
> 500,000                         35% or 0.3
*/

// Should return a function that accepts a number that's the amount to be taxed
// and returns the tax amount after factoring in the income not taxed and the
// applicable tax rate.
function getTaxCalculator(incomeNotTaxed) {
 // your code here (approximately 10 lines)
   function calculateTax(amount){
   let taxAmount = amount - incomeNotTaxed;
    if (amount <= 100000){
        taxAmount * 0.1
    }else if((amount>100000) && (amount<= 500000)){
        taxAmount * 0.2
    }else{
        taxAmount * 0.3 
        }
}
 return calculateTax       
}

// THIS IS FOR YOUR TESTING ONLY.
const calculateTax = getTaxCalculator(30000)
console.log(calculateTax(100000)) // should print 70000
console.log(calculateTax(350000)) // should print 64000
console.log(calculateTax(600000)) // should print 171000
// This array (characters) has a length of 4 i.e characters.length is 4
// characters[0] will return ["a", "b", "c"]
// characters[0][1] will return "b"
// and so on.
const characters = [
  ["a", "b", "c"],
  ["d", "e", "f"],
  ["g", "h", " i"],
  ["x", "y", "z"],
];

function characterExist(letter) {
  // we initialize exists to false because we intend to set it to true only if /// we find the letter in the colors array
  let exist = false;

  // TODO(1): Write code to loop through the characters array, and set exist to
  // true if the value in the variable letter is found in the array.
    for(i=0; i<=characters.length; i++){
        for(j=0; j<=characters[i].length; j++){
            if(characters[i][j] === letter){
                exist = true;
        return true
            } 
        }
    }
    return exist;
}

// THIS IS FOR TESTING ONLY
console.log("a exists = " +  characterExist("a")); // prints true
console.log("p exists = " +  characterExist("p")); // prints false
 #declare two set the range
1.i = 1
2.j = 5
#use while loop for i
3.while i < 4:
#use while loop for j    
4.while j < 8:
        5.print(i, ",", j)
        6.j = j + 1
        7.i = i + 1
Output:
1 , 5
2 , 6
3 , 7                               
                                
star

Sun Apr 16 2023 22:18:18 GMT+0000 (Coordinated Universal Time)

#javascript #forof #loop #index
star

Wed Apr 05 2023 22:18:46 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-loop-through-object-in-javascript/

#javascript #loop #object
star

Wed Apr 05 2023 16:01:56 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-apply-function-to-every-array-element-in-javascript/

#javascript #array #every #loop #function
star

Sun Mar 19 2023 07:42:05 GMT+0000 (Coordinated Universal Time)

#loop #index
star

Fri Nov 26 2021 10:49:17 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop #dicegame #matplotlib #[plot #graph
star

Fri Nov 26 2021 10:42:38 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop #dicegame
star

Fri Nov 26 2021 10:06:16 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Fri Nov 26 2021 09:45:49 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 17:01:18 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:48:58 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:42:08 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:28:23 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:16:28 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 15:55:42 GMT+0000 (Coordinated Universal Time)

#numpy #booleans_in_numpy #list #forloop #for #loop
star

Wed Jun 30 2021 07:05:52 GMT+0000 (Coordinated Universal Time)

#python #comprehension #loop
star

Fri Jun 25 2021 15:12:00 GMT+0000 (Coordinated Universal Time) edconnect.com

#loop
star

Wed Jun 23 2021 13:58:24 GMT+0000 (Coordinated Universal Time) edconnect.com

#2-darrays #loop
star

Tue Apr 21 2020 06:12:11 GMT+0000 (Coordinated Universal Time) https://beginnersbook.com/2018/01/python-while-loop/

#python #python #loop #whileloop #nestedwhile loop

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension