text
stringlengths
37
1.41M
#!/usr/bin/python3 """Lists all cities from a database""" if __name__ == "__main__": from sys import argv import MySQLdb if len(argv) == 4: db = MySQLdb.connect(user=argv[1], passwd=argv[2], db=argv[3], host="...
#!/usr/bin/python3 def remove_char_at(str, n): newstr = str[:n] + str[n + 1:] for i in str: j = j + 1 if j != n: return i
#!/usr/bin/python3 from sys import argv if __name__ == "__main__": num = 0 if len(argv) > 1: for i in argv[1:]: num = num + int(i) print("{:d}".format(num))
""" pymysql库使用代码示例 """ import pymysql # 连接数据库 def db_connect(): conn = pymysql.connect(host='localhost', user='root', password='Zpj12345', port=3306, db='test') return conn # 创建一个数据库表 def create_table(c): c.execute( "CREATE TABLE IF Not Exists person(id INT AUTO_INCREMENT PRIMARY KEY,name VARCH...
"""Input gathering functions""" import readline from typing import List, Union import completions def get_project() -> str: """Take user input and return project""" readline.set_completer(completions.project_complete) project = input("project: ") if project == "": project = None return pro...
import sys; def convert(c): return { 'A' : "100000", 'B' : "110000", 'C' : "100100", 'D' : "100110", 'E' : "100010", 'F' : "110100", 'G' : "110110", 'H' : "110010", 'I' : "010100", 'J' : "010110", 'K' : "101000", 'L' : "...
class Solution: def threeSum(self,nums): ''' :type nums:List[int] :rtype:List[List[int]] ''' result = [] nums.sort() for i in range(len(nums)-2): if i>0 and nums[i] == nums[i-1]: continue l,r = i+1,len(nums)-1 ...
class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self,root): if not root: return [] stack,out = [],[] while True: while root: stack.append(root) ...
# day 23 # This solution is super ugly cup_labels = [3, 6, 4, 2, 9, 7, 5, 8, 1] print(f"original cup labels {cup_labels}") current_cup = cup_labels[0] picked_up_cup_indices = [] picked_up_cups = [] destination_cup = "" move = 0 while move < 101: #designate current cup print(f"cup labels {cup_labels}") pri...
import csv class Bike: def __init__(self,name,color,status): self.name = name self.color = color self.status = status def readBikes(): bikes=[] print("Opna bikes.txt") with open('bikes.txt', 'r', newline='', encoding='utf-8')as file: reader = ...
import functools import math import operator __author__ = 'Skurmedel' import problem as pm import itertools def sieve(n): candidates = list(range(2, n)) c = 2 end = False while not end: for i in range(2, n): m = c * i if m >= n: break candi...
#Exercise 5.1.1 print("\n Exercise 5.1.1*** \n") import time def t(): epoch=time.time() print(epoch,"epoch \n ") return epoch t() def t1(): e_date = t() #e_date=epoch total_days = e_date // 3600 // 24 print(total_days,"days since epoch") c_date = total_days * 24 * 360...
import pandas as pd #merging two df by key/keys.(may be used in database) #simple example left=pd.DataFrame({'key':['K0','K1','K2','K3'],'A':['A0','A1','A2','A3'],'B':['B0','B1','B2','B3']}) right=pd.DataFrame({'key':['K0','K1','K2','K3'],'C':['C0','C1','C2','C3'],'D':['D0','D1','D2','D3']}) print(left) print(right) r...
""" Recursive sorting module """ def merge(arr_a, arr_b): """ Merge Sort helper function """ merged_arr = [] while len(arr_a) > 0 and len(arr_b) > 0: if arr_a[0] > arr_b[0]: merged_arr.append(arr_b[0]) arr_b.pop(0) else: merged_arr.append(arr_a[...
""" This simple animation example shows how to move an item with the keyboard. If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.move_keyboard """ import arcade #making the arcade library accessable for this code SCREEN_WIDTH = 640 #setting the width o...
#count the number in a list my_dict={"a":[1,2,3],"b":[3,4,5],"c":[8,3,4]} # count=0 # for x in my_dict: # if isinstance(my_dict[x],list): # # count += len(my_dict[x]) # print(count) ctr=sum(map(len ,my_dict.values())) print(ctr)
from matplotlib import pyplot as plt from matplotlib import style a=[1,2,3] y=[5,6,7] plt.plot(a,y,'g',label='data') plt.legend() plt.xlabel("x axis") plt.ylabel("y axis") plt.show()
#program to reverse a tuple tuple=(1,2,3,4,5) print("original:",tuple) tup=tuple[::-1] #by slicing technique print("reverse:",tup)
#program to count occurance of substring in a string str= input("enter the element in string") print(str) substring=input("enter the substring which u want to count") print(str.count(substring))
from array import * class occurance_specified_element(): def occurance(self): arr=array('i',[]) arr_length = int(input("Enter the Length of the array:")) for x in range(arr_length): element=int(input("Enter the element: ")) arr.append(element) print("Original ...
import time def sum(a): start_time=time.time() s=0 for i in range(1,a+1): s=s+i end_time=time.time() return s,end_time-start_time print(sum(5))
def clone(): list=[] m=[] length=int(input("enter the length of a list")) for value in range(length): number=int(input("enter the element in the list")) list.append(number) print("old list",list) m=list.copy() print("new list",m) clone()
# Curso Intensivo de Python # 12/06/2021 - UFOP - Eng. da Computação - Victor Ivan Piloto Santos # Apresentação de metodo para tornar as letras em maiusculas e minusculas ex = "victor ivan" # O metodo .title() atua emcima da variavel 'ex', exibindo cada palavra com uma letra maiuscula no inicio. print(ex.title()) ex...
# Curso Intensivo de Python # 23/06/2021 - UFOP - Eng. da Computação - Victor Ivan Piloto Santos print('1º Parte - Conceitos Iniciais') # Lista é uma coleção de itens em uma ordem em particular. #Ex: [a,b,c,d,e,f] ou [0,1,2,3,4,5,6,7,8,9] # Não precisam estar relacionados de nenhum modo em particular. bicycles = ['...
import turtle vertices = [[-200, -100], [0, 200], [200, -100]] yes = {'yes', 'ye', 'y'} no = {'no', 'n'} # function to have the turtle draw a triangle, the basic unit of our fractal def draw_triangle(vertices, ChaosTriangle): ChaosTriangle.up() ChaosTriangle.goto(vertices[0][0], vertices[0][1]) ChaosTria...
#!/usr/bin/python3 def print_last_digit(number): if (number > 0): lastnumber = number % 10 else: tmp = number * -1 lastnumber = tmp % 10 print("{:d}".format(lastnumber), end="") return lastnumber
#!/usr/bin/python3 """Function to print a text. If it finds a specific letter it will print two newlines. This fucntion provides a .txt file to test""" def text_indentation(text): """Text Arguments: text {[str]} -- [text] """ if type(text) != str: raise TypeError("text must be a strin...
#!/usr/bin/python3 """Module which creates an inherited class of list""" class MyList(list): """Class to Initialize the class Arguments: list {[list]} -- [list] """ def print_sorted(self): """Prints lists sorted""" lista = self.copy() lista.sort() print(lista)
#!/usr/bin/python3 """Counts the number of lines in a file""" def number_of_lines(filename=""): """function to count number of lines Keyword Arguments: filename {str} -- [Filename] (default: {""}) Returns: [int] -- [number of lines] """ lines = 0 with open(filename) as f: ...
#!/usr/bin/python3 def multiply_by_2(a_dictionary): new_dict = a_dictionary.copy() for i, j in a_dictionary.items(): new_dict[i] = j*2 return (new_dict)
#!/usr/bin/python3 """Module which contain a function to find a Peak in a list""" def find_peak(list_of_integers): """function to find a Peak in a lis Args: list_of_integers ([list]): [List to evaluate] """ lista = sorted(list_of_integers) try: return(lista[-1]) except: ...
#!/usr/bin/python3 """Module to create a class for an object and modify private attribute size. There are also two method to get the area fo size and print the square""" class Square: """Class of the object""" def __init__(self, size=0): self.__size = size @property def size(self): ""...
# Import the matplotlib.pyplot and numpy libraries. import matplotlib.pyplot as plt import numpy as np # Import the confusion_matrix method from scikit-learn. from sklearn.metrics import confusion_matrix """ Visualize a confusion matrix with labels. """ # Tested results from an experiment y_test = ["cat", "cat", "ca...
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns raddf = pd.read_csv("data/santacruz/airborne/santa_cruz_rad.csv", index_col="fid", encoding="utf-8") magdf = pd.read_csv("data/santacruz/airborne/santa_cruz_mag.csv", index_col="fid", encoding="utf-8") # K-Nearest neighbors c...
import csv import os import pandas as pd """ Usage: "python dataskills.py" Use a scaffolding on competencies through various domains of data management. This is based on existing research in data management skills. """ # Check which directory we are in. If we're not in the main journalism # directory, then cd to it. ...
"""Functions for scraping IMDB""" from bs4 import BeautifulSoup as bs import requests import re ROOT = "http://imdb.com" def get_html(link): return bs(requests.get(link).text) def get_a(html, find=''): """Finds all the 'a' tags with find in their href""" links = [] for a in html.find_all('a'): ...
import six from tabulate import tabulate __all__ = ["dict_to_string", "merge_as_list", "ask_to_proceed_with_overwrite", "create_table"] def create_table(small_dict): """ Create a small table using the keys of small_dict as headers. This is only suitable for small dictionaries. Args: ...
import pandas as pd import numpy as np import acquire as a import os def clean_sales_data(): ''' Requires no inputs and returns cleaned sales data df ''' df = a.combined_df() # call acquire function to get all data from API df = df.drop(columns=['item', 'store']) # drop redundant columns df.sal...
###列表(可变) py_type = ["string","number","list","tuple","dictionary"] print(py_type); human = ["body","head"]; human.append("leg"); ##列表末尾增加 human.insert(1,"arm"); ##在第0个后面增加 print(human) del human[0] ##删除第0个元素 print(human) poped_human = human.pop(); ##删除最后一个元素并使用它(括号内可添加元素对应的序号值) print(poped_human) human.remove("arm"); ...
def laceStrings(s1, s2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ count1 = 0 count2 = 0 newString = '' while count1 != l...
""" Illustration return a without elements present in both a and b """ def array_diff(a, b): for i in b: if i in a: for j in range(a.count(i)): a.remove(i) return a print(array_diff([1,2,2], [1]))
class Node: def __init__(self, key, data=None): self.key = key self.data = data self.children = {} self.word_count = 0 class Trie: def __init__(self): self.head = Node(None) def insert(self, string): node = self.head for char in string: ...
# Lab 4: List, Tuple, Dictionary # Exercise 1: The List Data Type myFruitList = ["apple", "banana", "cherry"] print(myFruitList) print(type(myFruitList)) print(myFruitList[0]) print(myFruitList[1]) print(myFruitList[2]) myFruitList[2] = "orange" print(myFruitList) # Exercise 2: The Tuple Data Type myFinalAnswerTu...
from Tiles import * from random import shuffle ## @file Bag.py # @author The Trifecta # @brief This method implements the back end model of the bag for the Scrabble game. # @date Feb.15,2020 class Bag: ## @brief initializes the bag model by calling the initBag() method, which adds the default 100 tiles to the ...
## @file Board.py # @author The Trifecta # @brief This method implements the back end model of the board for the Scrabble game. # @date Apr.06,2020 class Board: ## @brief initializes the board object. def __init__(self): self.backBoard = [["0" for col in range(0, 15)] for row in range(0, 15)] ## @brie...
import pandas as pd import matplotlib.pyplot as plt import numpy as np #pre_processing dataset=pd.read_csv('Position_Salaries.csv') X=dataset.iloc[:,1:2].values #level itself decides Y=dataset.iloc[:,2].values #no need of splitting as X contain only 1 col '''from sklearn.cross_validation import train_test...
z=int(input("")) sum=0 rem=0 k=z while k>0: rem=k%10 sum=sum*10+rem k=k//10 if(sum==z): print("yes") else: print("no")
""" Face Detection using Face_recognition and HOG FACE DETECTOR """ import cv2 import dlib import face_recognition from matplotlib import pyplot as plt def show_image_with_matplotlib(color_image,title,pos): """Shows an image using matplotlib capabilities""" img_RGB=color_image[:,:,::-1] ax=plt.subplot(1...
# Python naming convention. # 1- Modules (filenames) all-lowercase names, contains underscores "_" # 2- Packages ( directories) all-lowercase without underscore. # More info in: https://stackoverflow.com/questions/48721582/how-to-choose-proper-variable-names-for-long-names-in-python/48721872#48721872 # Python variable...
#!/usr/bin/env python3 import time class Task: """ Class describing a Task for use in the TaskManager Args: run_at: when should the task run, use "now" for a immediate task recurrence_time: after how many seconds should the task re-occur recurrence_count: how often should the task re...
import div import add import mult import sub def main(): while True: try: var_a = input('Введите первое число: ') if var_a == "exit": print ('Выход') exit() else: var_a = float(var_a) pass v...
def encode_to_morse(text): '''функция для кодировки текста азбукой Морзе''' itog = [] for i in text.lower(): itog.append(MorseCode[i]) return ' '.join(itog) def decode_from_morse(code): '''функция для декодировки текста из азбуки Морзе''' itog = [] tmp = code.replace(' ', '*') ...
N = int(input()) lista = [6,2,5,5,4,5,6,3,7,6] for i in range(N): soma = 0 V = input() for x in V: soma += lista[int(x)] print("{} ".format(soma))
""" This problem was asked by Twitter. You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API: record(order_id): adds the order_id to the log get_last(i): gets the ith last element from the log. i is guaranteed to be small...
""" This problem was asked by Jane Street. cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return f(a, b) r...
#Input #Assignment Statement r = input("What is the radius: ") r = int(r) #Casting is the process of changing type #Strings - collections of characters #int - integers #float - numbers with decimals h = input("What is the height: ") h = int(h) #Process sa = (2 * (3.14) * r * h) + (2 * (3.14) * (r * r)) #Output pr...
#f = open("data.txt","w") f = open("data.txt","a") #a = appended to file, it gets added along #with the the other/previous results #f.write("Line 1\n") #f.write("Line 2\n") name = input("What is your name: ") age = input("What is your age: ") f.write(name + "\n") f.write(age + "\n") f.close()
#!/usr/bin/env python3 """ This is the db-connect file. This file contains all the functions that the tool need. """ import psycopg2 DBNAME = "news" def execute_query(query): """ execute_query returns the results of an SQL query. execute_query takes an SQL query as a parameter, executes the query...
# -*- coding: utf-8 -*- #----------------------------------------------------------------------- # # FRC Game Field Mapper # # This class maps out an FRC game field including all fixed obstacles, # loading stations, and scoring locations. The game field itself is # divided into M x N squares. An extra square is inc...
print('\nWelcome the Avgerage Test Caculaator') stop = int (1) #Program Loop while stop != 2: zerocheck = int(0) # Zero Check Var #Checking for Zero while zerocheck == 0: total = input('\nHow many tests did you take? : ') total = int(total) zerocheck = total totalcount = total...
print('\nWelcome the Avgerage Test Calculator') stop = int (1) #1st Start #1 for go, 2 for Stop Program Loop while stop != 2: zerocheck = int(0) # Zero Check Var #Checking for Zero while zerocheck == 0: # Int only while True: try: print('\n\nRemember 0 is not a ...
from tkinter import * master = Tk() listbox = Listbox(master) scrollbar = Scrollbar(listbox) scrollbar.pack(side=LEFT, fill=Y) listbox.pack() listbox.insert(END, "a list entry") listy = "hello my name is joseph and I really like to type into lists like these because I can type a lot of words" listy = listy.split()...
""" Program: test_assign_average.py Author: Michael Skyberg, mskyberg@dmacc.edu Last date modified: June 2020 Purpose: test a switch style statement """ import unittest import unittest.mock as mock from more_fun_with_collections import assign_average as aa class MyTestCase(unittest.TestCase): def test_case_A(se...
# a) number_list = [i for i in range(100)] print(number_list) # b) total = 0 for number in number_list: if number % 3 == 0 or number % 10 == 0: total += number print(total) # c) for i in range(0, len(number_list) - 1, 2): number_list[i], number_list[i + 1] = number_list[i + 1], number_list[i] print...
def c2f(): c = int(input("Temperatur i celsuis: ")) print(c, "grader celsius er", round((c * 9 / 5) + 32, 1), "grader Fahrenheit.") def f2c(): f = int(input("Temperatur i Fahrenheit: ")) print(f, "grader fahrenheit er", round((f - 32) * 5 / 9, 1), "grader celsius") def main(): c2f() f2c() ...
while True: print('Hei, jeg er THE DOORMAN!') navn = input('Hva heter du? ') alder = int(input('Okey ' + navn + ', hvor gammel er du? ')) if alder < 18: print('Du er for ung,', navn) else: print('Du er gammel nok') full = input('Men er du for full? ') if full == 'ja'...
facebook = [["Mark", "Zuckerberg", 32, "Male", "Married"], ["Therese", "Johaug", 28, "Female", "Complicated"], ["Mark", "Wahlberg", 45, "Male", "Married"], ["Siv", "Jensen", 47, "Female", "Single"]] # a) def add_data(user): list = user.split() list[2] = int(list[2]) ret...
# Deloppgave a) print("Oppgave a)") def is_leap_year(year): if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True def weekday_newyear(year): weekdays = ['man', 'tir', 'ons', 'tor', 'fre', 'lor', 'son'] day = 0 for i in rang...
from time import sleep def show_display(content): print() if len(content) == 6 and len(content[0]) == 30: print("####################################") print("# #") for row in content: print('# ' + row.upper() + " #") print("# ...
def power(a, n, pow): while n > 0: pow *= a n -= 1 while n < 0: pow /= a n += 1 return(pow) a = float(input()) n = int(input()) pow = 1 print(power(a, n, pow))
str = input() str = str.replace("h", "H") pos1 = str.find("H") pos2 = str.rfind("H") str1 = str[0:pos1] + "h" + str[pos1 + 1:pos2] + "h" + str[pos2 + 1:len(str)] print(str1)
from math import sqrt a = float(input()) b = float(input()) c = float(input()) if a == 0: if b == 0: if c == 0: print("3") else: print("0") else: print("1", c*(-1)/b) else: d = b ** 2 - 4 * a * c if d > 0: x1 = (b * (-1) - sqrt(d)) / (2 * a) ...
import math a = int(input()) summ = 0 sqs = 0 n = 0 while a != 0: summ += a sqs += a**2 n += 1 a = int(input()) s = summ / n ans = (sqs - 2*summ*s + n*s*s) / (n-1) print(math.sqrt(ans))
a = int(input()) aprev = a a = int(input()) count = 0 while a != 0: if a > aprev: count += 1 aprev = a a = int(input()) print(count)
maxm = int(input()) maxm2 = int(input()) if maxm2 > maxm: temp = maxm maxm = maxm2 maxm2 = temp a = int(input()) while a != 0: if a > maxm: maxm2 = maxm maxm = a elif a > maxm2: maxm2 = a a = int(input()) print(maxm2)
str = input() pos1 = str.find("h") pos2 = str.rfind("h") str1 = str[0:pos1] + str[pos2 + 1:len(str)] print(str1)
a = int(input()) count = 1 maxcount = 1 sign = 0 numb = 1 while a != 0: if numb == 1: pass elif numb == 2 and a != aprev: count += 1 elif sign == -1 and a < aprev: count += 1 elif sign == 1 and a > aprev: count += 1 elif a == aprev: count = 1 else: ...
a = int(input()) b = int(input()) c = int(input()) if a >= b: if a >= c: print (a) else: print (c) elif b >= c: print (b) else: print (c)
a1 = 1 a0 = 1 a = int(input()) i = 3 if a == 0: print(0) else: while a0 <= a: temp = a0 a0 += a1 a1 = temp i += 1 if a == a1: print(i-2) else: print("-1")
menu = {'burger':3.5 , 'chips':2.5 , 'drink':1.75} # Establishing dictionary salads = ['cucumber' , 'lettuce' , 'tomato'] # Establishing list sauces = ['mustard', 'bbq', 'tomato'] # Establishing list price = 0 # Initialising value of price outside of function total_price = 0 # Initialising value of total_price outside...
#coding:utf-8 x = int(input()) ans = 'Christmas' for i in range(25-x): ans+=' Eve' print (ans)
#coding:utf-8 K = int(input()) odd = int((K+1)/2) even = int(K/2) print (odd*even)
#coding:utf-8 y = int(input()) if ((y%4==0 and y%100!=0) or y%400==0): print ("YES") else: print ("NO")
N = int(input()) N%=10 if N==3: print('bon') elif N in (0,1,6,8): print('pon') else: print('hon')
#coding:utf-8 S = input().split() d = {"Left":"<", "Right":">", "AtCoder":"A"} S = [d[s] for s in S] print (" ".join(S))
import datetime import json_file import sys class database: def __init__(self): self.json = json_file.return_base_json() def appendToDatabase(self, string): with open("database.csv", "a") as myfile: myfile.write(string) def addToDatabase(self, foodNames): now = datetim...
# Question: Given an unsorted array, find 2 elements that sum to 15. arr1 = [4, 12, 21, 1, 5] arr2 = [12, 7, 2, 1, 10, 3] def two_element_sum(arr): arr.sort() print("Sorted Array: " + str(arr)) for num, next_num in zip(arr[::], arr[1::]): if num + next_num == 15: return num, next_num ...
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements i = 0 j = 0 k = 0 while i < len(arrA) and j < len(arrB): if arrA[i] < arrB[j]: merged_arr[k] = arrA[i] i ...
# Python Program for implementing DFS on a Directed Graph using Adjacency List method (Recursive Method # Riddhesh Bonde - 202170002 visitedNodes = set() # Empty Set from storing visited nodes graph = {} # Empty Dictionary for storing the adjacency List nodes = [] temp_list = [] def nodesInput(): try: while...
print("answer these!!") name = input("what is your name? ") quest = input("enter your company:") color = input("what is your favorite sport:") print(name, quest,color) age = input("what is your age:") print(age)
#!/usr/bin/env python import sys count = 0 word = str(sys.argv[1]) with open('DATA/alice.txt') as alice_in: for raw_line in alice_in: if word in raw_line: count += 1 print(f"There are {count} lines with the word '{word}' in them")
#!/usr/bin/env python movie_star = "Tommy Trotter" print(movie_star) print(movie_star.upper()) print(movie_star.count('t')) print(movie_star.count('Tom')) print(len(movie_star)) print(type(movie_star)) print(movie_star.count('T') + movie_star.count('t')) print(movie_star.lower().count('t')) print(movie_star.startswi...
#!/usr/bin/env python def add(arg1, arg2): val = float(arg1) + float(arg2) return val def subtract(arg1, arg2): val = float(arg1) - float(arg2) return val def divide(arg1, arg2): if float(arg2) == 0: print("Cannot Divide by Zero") return else: val = float(arg1) / float...
#!/usr/bin/env python a_list = [] b_list = [] with open('DATA/alt.txt') as alt_in: for raw_line in alt_in: line = raw_line.strip() if line[0] == 'a': a_list.append(raw_line) elif line[0] == 'b': b_list.append(raw_line) else: print(raw_line.rsp...
import tensorflow as tf ''' tf.get_default_graph() -->是默认计算图。在Tensorflow程序中,系统会自动维护一个默认的计算图。 a.graph -->获取张量的计算图。a为计算图上面的一个节点 因为a、b张量没有特意指定计算图,所以他们都属于默认计算图上面的节点。所以张量计算图等于默认计算图 每一次运行程序默认计算图tf.get_default_graph()的值都会变化。但是不管怎么变张量计算图等于默认计算图 不同python脚本的默认计算图的值是不一样的。但是同一个脚本获取的值都是一样的 ''' def tensor(): a = tf.constant([1....
def play_the_game(players_num, last_marble_score): winning_score = 0 current_marble = 1 game = [0, 1] current_player = 1 current_marble_index = 1 players_score = [] for i in range(0, players_num): players_score.append(0) while current_marble != last_marble_score: curren...
class Worker: worker_id = 0 working_on = '' time_left = -1 def __init__(self, wid): self.worker_id = wid def can_step_be_performed(reqs, done): for req in reqs: if not done.__contains__(req): return False return True def get_instruction_time(instr): # return...
def count_number_of_recipes_until_input_occurrence(n): n = [int(i) for i in n] scores = [3, 7] elves_positions = [0, 1] last_scores = scores[:] position = 0 while True: # Check if we got input if last_scores == n: break # Check if we got input if la...
people = ['Nathaniel', 'Ngethe'] print() for name in people: print(name) index = 0 while index < len(people): print(people[index]) index = index + 1 print()
"""That data.strip().split(',') line looks a little weird. Can you explain what’s going on? A: That’s called method chaining. The first method, strip(), is applied to the line in data, which removes any unwanted whitespace from the string. Then, the results of the stripping are processed by the second method, split(',...