text
stringlengths
37
1.41M
""" MERGE SORT [algorithm] (recursive) 1. Divide given array 2. Sort each divided array 3. Merge sorted array [order] O(nlogn) """ def sort(A, l, r, compare): """ [arguments] A -- Given array l -- Left boundary r -- Right boundary compare -- lambda function for comparison of two values (ascend or descend...
names = ["Judith", "Abel", "Tyson", "Martha", "Beverley", "David", "Anabel"] estimated_insurance_costs = [1000.0, 2000.0, 3000.0, 4000.0, 5000.0, 6000.0, 7000.0] actual_insurance_costs = [1100.0, 2200.0, 3300.0, 4400.0, 5500.0, 6600.0, 7700.0] # Add your code here # Create a variable total_cost and initialize it to 0 ...
class Home: # Attributes price = district = rooms = baths = size = floor = url = type = parking = None # Constructor def __init__(self, url, district): self.district = district self.url = url def toString(self): print('Precio:', self.price) print('Distrit...
""" It makes one liners functions Author: Bruno Lerner """ def space_triple(message): ''' it multiplies each char of the message into 3 of itself :param message: :return: ''' return " ".join([3*x for x in message.split()]) if __name__ == "__main__": print(space_triple('hello world'))
import random modes = ["rock", "paper", "scissors"] def comp_turn(): """The choice made by the computer""" comp = random.choice(modes) return comp def calc_win(comp, move): """Determining the winner""" print("The computer chose {0}.".format(comp)) win = None tie = False if move == ...
# -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals import tensorflow as tf from time import time # Download the dataset from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) def weight_variable(shape): in...
""" This file solves the copaste exercise, where we need to basically copy file from a directory to another Author: Bruno Lerner """ def copaste(file_path, folder): """ It receives the full file path and parses it to get just the name of the file, and saves it to the new full path, which is folder + filen...
""" It generates a happy birthday song without any for and while loops, only using magic functions Author: Bruno Lerner """ import functools HAPPY = "Happy Birthday " DEAR = "dear %s" TO_YOU = "to you" def generate_song(a, b, name): """ It mounts the verse in the song accordingly to the number on range(4) ...
""" Advent of Code 2020 Day 16 """ def get_data(fname: str) -> tuple: """ Read the data file. """ with open(fname) as f: texts = f.read().split('\n\n') # Get the fields and all their valid values. Not space efficient, # but there aren't that many of them. fields = {} for field...
""" Advent of Code 2020 Day 15 """ def play(data: list, turns: int): """ Play the game. """ # Start the game. previous = {} # No comp so speak exists. for turn, speak in enumerate(data, 1): previous[speak] = turn # Take 4th turn. A bit annoying. spoke = 0 turn += 1 # ...
# Correlation Coefficient (r), also known as the Pearson Product-moment Coefficient, and the Coefficient of Determination (r-squared) import scipy.stats import numpy as np # Replace the lists below with your own data. a = np.random.randn(100) b = np.random.randn(100) num_values = len(a) sqr_a = a ** 2 sqr_b = b ** ...
def fibonacci(num): a,b=1,2 c=1 while c<=num: if c%2==0: yield a a,b,c=b,a+b,c+1 return n=int(input("Enter number of Test Cases:\n")) for i in range(n): t=int(input("Enter Case:\n")) print(sum(list(fibonacci(t))))
import sqlite3 class Database(object): def __init__(self): self.connection = self.create_connection() self.create_table(self.connection) def create_connection(self): """ create a database connection to a SQLite database """ try: conn = sqlite3.connect("/home/szczoc...
def check(): password = input("Please enter your password: ") if password == "autonomous": print("password accepted!") return else: print("Sorry, that is the wrong password") check() check()
hours_worked = int(input("How many hours worked for? ")) print("Hours worked is:\n",hours_worked) hourly_pay_rate = int(input("What is hourly pay rate? ")) print("Hourly pay rate is:\n", hourly_pay_rate) gross_pay = hours_worked * hourly_pay_rate ##assert(gross_pay == "") print("The gross pay is:\n", "$", gross_pay) ...
"""Base model classes.""" import abc from collections import namedtuple import warnings import tensorflow as tf from garage.misc.tensor_utils import flatten_tensors, unflatten_tensors class BaseModel(abc.ABC): """Interface-only abstract class for models. A Model contains the structure/configuration of a se...
import random import math grade = 'D' for i in xrange(0,10): random_num = int(math.floor(41*random.random() + 60)) if random_num < 70 and random_num >= 60: grade = 'D' elif random_num < 80: grade = 'C' elif random_num < 90: grade = 'B' elif random_num <=100: grade = 'A' print 'Score: ' + str(random_num) +...
class Bike(object): """docstring for bike""" def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print 'Price: {}, Max Speed: {}, Miles: {}'.format(self.price, self.max_speed, self.miles) return self def ride(self): print 'Riding...' ...
def max_heapify(A, i, heap_size): l = 1; r = 2; if (i != 0): l = 2 * i + 1 r = 2 * i largest = i if l < heap_size and A[l] > A[largest]: largest = l if r < heap_size and A[r] > A[largest]: largest = r if largest != i: A[i], A[largest] = A[largest], A[i...
#-*- coding:utf-8 -*- #Ejercicio 2.7. Escribir un programa que imprima por pantalla todas las fichas de dominó, de una por línea y sin repetir. for i in range (1,7,1): for j in range (1,7,1): print(i,j)
# -*- encoding:utf-8 -*- # Ejercicio 5.4. # Utilizando la función randrange del módulo random, escribir un programa que obtenga un número aleatorio # secreto, y luego permita al usuario ingresar números y le indique sin son menores o mayores que el número a adivinar, # hasta que el usuario ingrese el número correcto...
# -*- encoding:utf-8 -*- #Ejercicio 5.8. # Escribir un programa que le pida al usuario que ingrese una sucesión de números naturales.\ # (primero uno, luego otro, y así hasta que el usuario ingrese ’-1’ como condición de salida). # Al final, el programa debe imprimir cuántos números fueron ingresados, la suma total de...
# -*- coding: utf-8 -*- """ Created on Thu Sep 22 11:06:17 2016 A scientific calculator that accepts inputs of +-*/^% as well as (). Also accepts trigonometric inputs (sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), sqrt(x), root(x,n), log(x), ln(x), fact(x) and abs(x) functions. Accepts exponential notation in the...
width = int(input("enter the width: ")) length = int(input("enter the length: ")) print("The area is", width/length)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 27 14:25:35 2019 @author: sinsakuokazaki """ #my answer def permutation(st1, st2): #I forgot this sentence if len(st1) != len(st2): return False permutationHelper(st1, "") for perm in permList: if perm == st2: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 20 15:05:24 2019 @author: sinsakuokazaki """ from linkedList import LinkedList def sumList(ll_1, ll_2): n1, n2 = ll_1.head, ll_2.head ll_result = LinkedList() carry = 0 while n1 or n2: result = carry if n1: ...
def itemremover(*items): ''' itemgetterの削除版 https://docs.python.org/ja/3/library/operator.html#operator.itemgetter ''' def g(obj): if hasattr(obj, 'keys'): return tuple(obj[key] for key in obj.keys() if key not in items) if len(items) == 1: if isinstance(obj, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 26 00:14:44 2018 @author: rishabh """ """ Program to check if the given two lists have intersection or not """ class Node: def __init__(self,data): self.data = data self.next = None class Solution: def ge...
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 11:56:16 2018 @author: Rishabh Sharma """ #Palindrome Permutation ''' Given a string we need to return true if the string has a permutation that is also a palindrome else we will return False. ''' """ The idea is that in a palidrome we will have even oc...
def anagram_checker(str1, str2): """ Check if the input strings are anagrams of each other Args: str1(string), str2(string): Strings to be checked Returns: bool: Indicates whether strings are anagrams """ clean_str1 = str1.replace(" ", "").lower() clean_str2 = str2.replace(...
"""simulation to answer https://www.youtube.com/watch?v=dDrhWQVLdL8""" from random import randint import timeit def ant_cube_first_attempt(): """runs an ant_cube simulation, returns true on collision, false otherwise""" cube = [] for x in range(0, 8): x = ("000" + bin(x)[2:])[-3:] cube.ap...
def unitsOfRing(n): units = 0 for u in range(n): for v in range(n): if (u * v) % n == 1: units += 1 break return units def main(): mappings = [] for i in range(2, 50): units = unitsOfRing(i) mappings.append( (i, units) ) mappings.sort(key=lambda x: x[1]/x[0]) for n, units in mappings: ...
"""solves this problem through brute force https://www.youtube.com/watch?v=vhp3d9XXDcQ """ from random import randint import timeit def get_num_rolls(): #create counter for number of rolls counter = 0 #loop until break condition while True: #get a roll roll = randint(1, 6) ...
import socket import logging import re # All the HTTP header types that should be converted to integers NUMBER_TYPES = ["content-length"] # The size of the byte buffers used to recv BUFSIZE = 4096 RE_REQLINE = re.compile("(.+?)(?: )(.+?)(?: )(.+?)(?:\r\n)") RE_HEADERS = re.compile("(.+?)(?::\s*)(.+?)(?:\r\n)") clas...
#listas #es una coleccion de elementos que poedemos almacenar en una variable nombres= ["Elda","Rebeca","William","Griselio","William José"] print(nombres) #conocer el largo de la linea print(len(nombres)) #acceder a un elemento print(nombres[0]) #navegacion inversa print(nombres[-1]) print(nombres[-5])
# -*- coding: utf-8 -*- """ Every Logger object will log to global.log in addition to other handlers. Usage: _ = Logger(__name__) \ .add_file_handler("logfile.txt", "info") \ .create() The logger object is identical to the Python's built-in Logger object. """ import os import logging from loggi...
while 1<2: fac =int(input("Enter a number: ")) ans = 1 if fac == -1: break else: for i in range(1,fac+1): ans *= i print(str(fac) + "! = " + str(ans))
def factorial(k): if k == 0: return 1 return k*factorial(k-1) n = int(input('Enter n:')) m = int(input('Enter m:')) while ((n>0) and (m>=0)): def Combi(n,m): if m == 0: return 1 if n == m: return 1 else: return Combi(n-1,m) + Combi(n-1,m-...
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.cardgame = CardGame("CardGame") def test_card_is_ace(self): self.card1 = Card("Hearts", 1) self.assertEqual(True, self.cardgame.check_for_ace(self.c...
n=int(input()) for i in range(n+1): if(i%3==0 or i%7==0): print(i)
# This alogorithm is used to predict continues data. # To solve this algorithm we will try and minimise our cost function using the technique called Gradient Descent. import numpy as np class LinearRegression: def __init__(self, lr=0.01, n_iters=1000): self.lr = lr self.n_iters = n_iters self.weigths =...
def selectionsort(list,length): for i in range(length): minindex=i for j in range(i+1,length): if list[j]<list[minindex]: minindex=j list[i],list[minindex]=list[minindex],list[i] list=[9,4,7,2,910,1] selectionsort(list,len(list)) print(list)
# File: major.py # Author: Kent Phan # Date: 5/26/2018 # Lab Section: ? # UMBC email: kphan1@umbc.edu # Description: This program shows the proper layout of code in a Python file, # and greets the user with the name of the programmer. def main(): usersMajor = input("Please enter yo...
import random import hangman_words from hangman_art import stages,logo print(logo) word_list = hangman_words.word_list chosen_word = random.choice(word_list) end_of_game = False lives = 6 display = ["_"]*len(chosen_word) while not end_of_game: guess = input("Guess a letter: ").lower() if guess in displ...
logo = """ ________ ___________.__ _______ ___. / _____/ __ __ ______ ____ ____ \__ ___/| |__ ____ \ \ __ __ _____\_ |__ ___________ / \ ___| | \/ ___// __ \_/ __ \ | | | | \_/ __ \ / | \| | \/ ...
class Solution: def longestcommonprefix(self, strs): if not strs: return '' if len(strs) == 1: return strs[0] strs.sort() shortest = strs[0] prefix = '' for i in range(len(shortest)): if strs[len(strs) - 1][i] == shortest[i]: ...
''' Uses heap data structure to build a MST based on Prim's algorithm. The algorithm runs until there is a node not added to the graph and later removes the K - 1 edges to form K of clusters. @author: Damares Resende @contact: damaresresende@usp.br @since: May 25, 2019 @organization: University of Sao Paulo (USP) ...
''' Created on Sep 8, 2018 Universidade de Sao Paulo - USP São Carlos Instituto de Ciencias Matematicas e de Computacao SCC5809: Redes Neurais Tests - Exercise 2: Neural networks with backpropagation - Enconding @author: Damares Resende ''' import unittest import numpy as np from SCC5809.ex2v2 import encoding as ec...
num1,num2=eval(input("enter two numbers sperated in a comma(,) :-")) if num2!=0: print("divded",num1/num2) else: print("you can't use 0 to divid") print("multiple",num1*num2) exit=input("press enter to exit")
# @thecoder777 || Python """ Formatted Strings in Python [PEP 498]""" name = "Bob" # with '.format()': print("Hello, my name is {}!".format(name)) # with f-strings: 'Literal String Interpolation' print(f"Hello, my name is {name}!") """ Output: Hello, my name is Bob! Hello, my name is Bob! """ # In my opinion, ...
# All 4 values are displayed when the print function executes # because data is the entire list of values. data = [2.71, 3.14, 1.41, 1.62] print(data) # Notice that printing the element at index 1 displays the second # element in the list because the first element in the list has index 0. data = [2.71, 3....
# FIRST OPEN importedstaffclass.py FILE AND LOOK THROUGH IT # Instantiating a Child Object # Now that we have coded our child classes, let us create a separate .py file to # make use of these classes. import importedstaffclass peter = importedstaffclass.BasicStaff('Peter', 0) john = importedstaffclass.Manag...
''' Exercise : Maximum Integer This exercise examines the process of identifying the maximum value in a collection of integers. Each of the integers will be randomly selected from the numbers between 1 and 100. The collection of integers may contain duplicate values, and some of the integers between 1 and 100 ma...
################# START WITH OPENING importclass.py - read through it # Other way to do it comment out below # from importclass import SomeClass, SomeOtherClass import importclass #In the code above, we instantiated the objects by prefixing the class name with #the file name, such as myclass.SomeClass() ...
''' Our box-drawing function prints characters on the screen. While it takes arguments that specify how the box will be drawn, the function does not compute a result that needs to be stored in a variable and used later in the program. But many functions do compute such a value. For example, the sqrt function in the...
import math y = 14 z = math.sqrt(y) print(z) x = 12 y = -2.75 z = "Andrew" name = z numCookies = x print("%.2f" % x) print("%s ate %d cookies!" % (name, numCookies))
user_list = input('Введите элементы через пробел - ').split() for i in range(0, len(user_list), 2): user_list.insert(i + 2, user_list[i]) user_list.pop(i) print(user_list)
number = input('Введите целое число n - ') print(f'Сумма чисел n + nn + nnn = {int(number) + int(number + number) + int(number + number + number)}')
import turtle def test_drive(): turtle.forward(100) turtle.left(87) turtle.setheading(127) turtle.up() turtle.down() turtle.goto(50, 50) turtle.home() turtle.circle(25) def turtle_state(): v2=turtle.isdown() v3=turtle.heading() vx=turtle.xcor() vy=turtle.ycor() print...
import example def test_echo(): result = example.echo('message') assert isinstance(result, str) assert 'message' == result def test_vector_int2str(): data = example.vector_int2str([1, 2, 3]) assert isinstance(data, tuple) assert ('1', '2', '3') == data def test_reverse_map(): str2int =...
class Cart: def __init__(self, x, y, direction): self.x = x self.y = y self.direction = direction self.next_intersection = 'L' self.active = True def update_next_intersection(self): if self.next_intersection == 'L': self.next_intersection = 'S' ...
# ---- GUIA 2. Parte 2 FIGURITAS ---- # Punto 2 # el metodo random.randint(_,_) en la funcion comprar_una_figu me devuelve un numero aleatorio # dentro de un rango entre el primer y segundo argumento import random import numpy as np import matplotlib.pyplot as plt # importo para graficar def comprar_una_figu(figus...
def readFileIntoList(): try: fp = open('input.txt', 'r') line = fp.read().strip() return list(line) finally: fp.close() def getRidOfReaction(theList): foundSomething = True while foundSomething: foundSomething = False for x in range(len(theList)-1): if (theList[x].swapcase() == theList[x+1]): d...
#A set is a collection which is unordered,changable and unindexed. In Python sets are written with curly brackets. thisset = {"apple", "banana", "cherry"} print(thisset) thisset = set(("apple", "banana", "cherry")) print(thisset) thisset.remove("banana") print(thisset) print(len(thisset))
#A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. thistuple = ("apple", "banana", "cherry") print(thistuple) print(thistuple[1]) #thistuple[1] = "blackcurrant" # Unchangeble #print(thistuple) thistuple = tuple(("Yugant", "Satish", "Geeta")) print(len(thist...
# list=[2,7,1,4,6,9,0] # print(list) # print(sorted(list)) # list.append("chaumau") # print(list) # list.insert(0,33) # print(list) # list.remove(33) # print(list) # list.pop(0) # print(list) # print(id(list)) #The id is the object's memory address, and will be different for each time you run the program # a=[1,2,3,4,5...
from collections import Counter # initialising dictionaries ini_dictionary1 = Counter({'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}) ini_dictionary2 = Counter({'akash': 7, 'akshat': 5, 'm': 15}) # printing initial dictionaries print("initial 1st dictionar...
# The goal of this script is to check whether two rolls of a dice either sum upto 7 or 11. import random min = 1 max = 6 roll_again = "yes" die1 = random.randint(1,6) die2 = random.randint(1,6) print("The dice rolled: {}, {}".format(die1, die2)) print("The sum of dice rolled values is {}".format(die1 + die2))...
""" Given two strings. Return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Examples: Input: s = "ab#c", t = "ad#c" Output: True # Both s and t become "ac". Input: s = "a##c", t = ...
""" Given a Tic-Tac-Toe 3x3 board (can be unfinished). Write a function that checks if the are some winners. If there is "x" winner, function should return "x wins!" If there is "o" winner, function should return "o wins!" If there is a draw, function should return "draw!" If board is unfinished, function should return...
# -*- coding: utf-8 -*- """ Created on Wed May 16 09:44:05 2018 @author: Kyunghan @vehicle simulation model """ from math import pi, sin, cos import numpy as np from scipy.spatial import distance as dist_calc import scipy.io as io import matplotlib.pyplot as plt # Simulation configuration Ts = 0.01 #%% 0. local functi...
class Auto: modelo = '' agencia = '' precio = 0 transmision = '' def __init__(self, modelo, agencia, precio, transmision): self.modelo = modelo self.agencia = agencia self.precio = precio self.transmision = transmision def TraerModeloYAgencia(self): retu...
def pedir_operacion_dato_producto(mensaje): operacion=input(mensaje) while len(operacion)==0: operacion=input(mensaje) return operacion def pedir_unidades(mensaje): unidad=input(mensaje) while len(unidad)==0 or not unidad.isdigit(): unidad=input(mensaje) return int(uni...
# Import cv2 module import cv2 from dataPath import DATA_PATH # Path to the image we are going to read # This can be an absolute or relative path # Here we are using a relative path imageName = DATA_PATH+"images/boy.jpg" # Load the image image = cv2.imread(imageName, cv2.IMREAD_COLOR) # Draw an ellipse # Note: Ellip...
# Ask Question from data Dictionary (hash) data = {"Q": "Is it an aquatic animal"} # A simple Y/N validation function # q_text = Question text # Get question from data q_txt = ' ' def get_answer (q_text): return True # Ask question and define result if get_answer(q_txt): print('YES') else: print('No')
#!/usr/bin/env python3 # Created by: Andrei Chirilov # Created on: December 2019 # This program get's random numbers and finds the minumum/lowest number import random def min_num(input_list): # Process current_min = input_list[0] for counter in input_list: if counter < current_min: c...
# -*- coding: utf-8 -*- """ Created on Thu May 23 15:12:47 2019 @author: 376020 """ import csv class Customer: ''' To come up with program which reads the file and builds a set of unique profession list and given input profession of client – system tells whether client is eligible to be approache...
##Tuple are similar to list but are immutable ##A tuple is a read only data structure in which size and value of the items can't be modified ##Tuples are enclosed in paranthesis tup = ("Hi","python",2) print(type(tup)) print(tup) print(tup*3) print(tup[2]) print(tup[0:1]) print(tup[1:]) print([tup + tup]) ...
list = [1,2,3,4,5,6,7,8,9,10] n = 5 for i in list: T = n*i print(T)
list = [2,3,2,45,35,3,5] sum = 0 for i in list: sum = sum+i print(sum)
# Yatin Batra | yatinbatra31@gmail.com | Aka Developer Yatin # Multiple Linear Regression on the '50_Startups' Dataset # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = d...
def invert_dictionary(d): ''' (dict of str:str)-> dict of str:list of str Takes a dictionary as a parameter and Returns an inverted dictionary. To make sure no items are missed, maps values of the dictionary paramter to a list of keys. >>>d = {'watermelon': 'green', 'pomegranate': 'red', ...
class Solution: def reverseList(self, head: ListNode) -> ListNode: new_head = None i = head while i is not None: temp = i.next i.next = new_head new_head = i i = temp return new_head
"""Code for splitting up the Hamiltonian into blocks""" from qutip import Qobj, qdiags import numpy as np import scipy.sparse def split_AB(m, block_info, n, as_qobj=False): """Split a sparse matrix into two block-diagonal matrices Args: m (scipy.sparse.spmatrix or qutip.Qobj): The sparse matrix to op...
balance=5000 annualInterest=0.02 monthlyInterestRate=annualInterest/12.0 lower_bound=balance/12 upper_bound=(balance*(1+monthlyInterestRate)**12)/12.0 monthlyPayment=(lower_bound+upper_bound)/2 newbalance=balance month=0 while newbalance>0: newbalance=balance for month in range(1,13): newbalance -= monthlyPayment...
# Author: Michael Le # Date: 11/03/2019 # Description: Function that takes a list of numbers, and returns the median value def find_median(input_array): """ :param input_array: this is a input list of values :return: the return value is a median number of the values within the list from input_array ...
cents = int(input("Please enter an amount in cents less than a dollar.\n")) quarters=cents//25 leftover=cents leftover=(cents%25) dimes = leftover//10 leftover=(leftover%10) nickels = leftover//5 leftover = (leftover%5) pennies = leftover print("Your change will be:") print("Q: "+str(quarters)) print("D: "+s...
# Author: Michael Le # Date: 10/4/2019 # Description: A program that converts Celsius temperatures to Fahrenheit temperatures. C = float(input("Please enter a Celsius temperature.\n")) F = (9/5)*C + 32 print("The equivalent Fahrenheit temperature is:") print(F) #End of Program
# coding=utf-8 calc = lambda a: 1 if a <= 2 else (calc(a - 1) + calc(a - 2)) def cycling(times): r = [1, 1] while times > 2: times -= 1 r.append(r[-1] + r[-2]) return r if __name__ == '__main__': print("递归法\n", [calc(i) for i in range(1, 20)]) print("循环法\n", cycling(20))
def bubble_sort_swaps(nums): #n = 4 count = 0 swapped = True indexOfLastSorted = len(nums) while swapped: swapped = False for i in range(indexOfLastSorted): count+=1 if i+1 < len(nums): if nums[i] > nums[i+1]: nums[i],nums[i+1] = nums[i+1],nums[i] #swaps both values ...
# -*- coding: utf-8 -*- """ Can you get the loop ? Instructions Output You are given a node that is the beginning of a linked list. This list always contains a tail and a loop. Your objective is to determine the length of the loop. For example in the following picture the tail's size is 3 and the loop size is 11. I...
city = "narva" estonianPopulation = [ ["tallinn", 441000], ["tartu", 94000], ["narva", 58000], ["parnu", 41000] ] for p in estonianPopulation: if p[0] == city: print("Population of " + p[0].capitalize() + ": " + str(p[1])) break
#To-do App priority_dic = {"H":"high","L":"low","M":"medium"} task_ls = [] task = str() print("\n\nLet's create a TODO list!\n") while ((task != 'q') and (task != 'Q')): task = input("\nPress 1 to add task\n" "Press 2 to delete task\n" "Press 3 to view all tasks\n" "Press q to quit\n" ...
# KEEPING YOURSELF ORGANIZED # Define global functions and variables first at the top of your program # Define classes netx and any unique methods inside of them # Then define your while loop if you need the user to keep doing tasks until a certain condition is met (remember, your condition needs to be global, # and ne...
"""basic Flask app - demo of using a variable in a route""" from flask import Flask, render_template app = Flask(__name__) import csv def convert_to_dict(filename): """ Convert a CSV file to a list of Python dictionaries """ # open a CSV file - note - must have column headings in top row datafile ...
import os ''' This function finds a file or multiple files in the path specified. File(s) can be located in nested directories. If you need to find files with common prefixes, enter the common part as the name input. Outputs a python list. ''' def locate_file(name, path): result = [] for root, dirs, files in ...
import argparse import fileinput from data_board import Data_Board from display_board import Display_Board ''' Product requirements: * Square board of size N * Number of mines M * Mines randomly distributed * If you choose a mine, game over * If you choose a space next to a mine, space becomes the number of mines nex...
import multiprocessing from multiprocessing import Manager, Pool import time input_list = list(range(1,10)) manager = Manager() shared_list = manager.list() def do_stuff(element): global shared_list shared_list.append([element]) print(shared_list) #def do_stuff1(element): # not_shared_list = list() #...
import argparse from glob import glob parser = argparse.ArgumentParser() parser.add_argument('--file_set', help='Takes a file name as a string.') parser.add_argument('--min_chars', help='all seqs under this number will be excluded. ') args = parser.parse_args() infile_name ...
''' @author: Tyler Weirick @date: 2013-09-24 This program will remove sequence and name matches from one file that match another. ''' import argparse parser = argparse.ArgumentParser() parser.add_argument('--file_name1', help='A set of fastas, fastas will be removed from this file.') parser.add_argument('--f...