text
stringlengths
37
1.41M
class Wine: """ This class represents a Wine. """ def __init__(self, appellation, name, vintage, price, global_score, color): self.appellation = appellation self.name = name self.vintage = vintage self.price = price self.global_score = global_score self.c...
# This is a comment print ('Hello world') # this prints hello world '''Assigning variables''' location = "lung'aho" name = 'Venus' age = 21 height = 163 print('My name is',name,'My height is ',height) print('My age is' , age) print ('My location is ', location) my_list = ['Venus','Mike','Inno','Trinna',7,8.9] my_tu...
#!/usr/bin/python # coding: latin-1 import math class Vector2(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __str__(self): return "(%s, %s)"%(self.x, self.y) def _get_length(self): x, y = self.x, self.y return sqrt(x*x + y*y...
def is_even(preset_num, ttl_even, ttl_not_even): if preset_num == 0: print(f'A number {preset_num} is made up of {ttl_even + ttl_not_even} ' f'numbers and has {ttl_even} even and {ttl_not_even} odd numbers.') else: tmp = preset_num % 10 if tmp % 2 == 0: ttl_even...
try: user_data = int(input('Please enter the year in YYYY format: ')) if user_data % 4 == 0: if user_data % 100 == 0: if user_data % 400 == 0: print('Leap year.') else: print('Not leap year.') else: print('Leap year.') ...
""" Не понял ремарку задания "объясните результат", Прикладываю псевдотаблицы с логическими операциями. +-and-+ +--or--+ +-xor-+ |--+--| |--+---| |--+--| |00| 0| |00| 0 | |00| 0| |01| 0| |01| 1 | |01| 1| |10| 0| |10| 1 | |10| 1| |11| 1| |11| 1 | |11| 0| +-----+ +------+ +-----+ 5 и 6 по битам 0101 и 0110 соот...
""" Address: https://leetcode-cn.com/problems/add-two-numbers/ Thinking: 1.链表形式表达没想明白。 猜测本题的关键点可能在满10进1上。涉及到链表的操作(访问和修改) remark.看完题目解析,明白ListNode即是结点,通过next 访问下一结点。重要的是,我们一开始并不需要知道所有元素,只要头结点就可以代表整条链表,同时双链表相加要考虑链表长度问题。 想到递归生成,有两种方式,一种是已经想到的,ListNode(,ListNode) 构造结构时候,这个用while,同时要反序输出,借助cur。 另一种是 ...
a = [1, 2, 3, 4, 5, 6] b = a[1:3:2] print(b) lenguajes = [ " Python " , " Java " , " Kotlin " , " Python2 " , " Python3 " , " python -dev " , " Ruby " , " C " , " python " , " php " , "Perl " " PyThoN " , " pytHON " , " pYTHON " , " Pyth@n " ] resultado = filter ( lambd...
class Stack(object): def __init__(self): self.data = [] def isEmpty(self): return self.data ==[] def push(self,newElem): self.data.append(newElem) def pop(self): if self.isEmpty(): raise Exception("Your Stack is Empty!") else: return s...
import sys # 최고값을 구하는 함수작성 : my_max() def my_max(number): max = sys.float_info.min for value in number: if max < value : max = value return max number =[ ] while True: n = int(input('숫자를 입력하세요:')) if n ==0: break number.append(n) print("최대값...
# Print binary reps # def binary(num): #O(log n) # val = '' # while num: # val = str(num&1)+ val # num = num>>1 # print(val) # def binary(num): # print(bin(13)) # binary(13) #--------Check even/odd------------# # def checkEvenOdd(num): # if num & 1: # print('Odd') # else:...
# https://www.youtube.com/watch?v=IEEhzQoKtQU&pbjreload=10 # Threading is different from multi-processing. Threading can speed up our script when it's IO bound, while # multiprocessing can speed up when its CPU bound. Even threading can slow down our processing speed because it has # an extra overhead of creating and d...
# To fix imbalance we perform rotations. # T1, T2 and T3 are subtrees of the tree rooted with y # (on left side) or x (on right side) # y x # / \ Right Rotation / \ # x T3 – – – – – – – > T1 y # / \ ...
__author__ = 'noomatik' from datetime import datetime YEAR = datetime.now().year name = input("What is your name? ") birth = input("What is your year of birth? ") age = YEAR - int(birth) print("Hello %s! You are about %s years old." % (name, str(age)))
''' Graphs module: 1. Graph calculator 2. By : Sina Honarvar ''' from collections import deque from matrix import Matrix #_________________________________________________ ''' def is_simple_graph(adj_matrix): 'Returns True if the given matrix can b...
#integer n1=5 print(str(n1) + " is type of " + str(type(n1))) #float n2=5.5 print(str(n2) + " is type of " + str(type(n2))) #lists mixed=[] print(type(mixed)) mixed=[2,5.5,'a','b',"uber"] print(type(mixed)) print(mixed) print(mixed[0]) print("length of list is" + str(len(mixed))) #tuple nochang...
#lists mixed=[2,4,8,"kalyani",88.88,1,43,"venky",'l'] print(mixed[4]) print(id(mixed)) #:operator print(mixed[3:8]) #Sclice from 3rd index position to (8-1)th position newslice=mixed[3:8] print(type(newslice)) #slice from negative direction backslice=mixed[-4:-1] print(backslice) backslice1=mixed[-5:] ba...
'''for loops''' vowel="aeiou" for v in vowel: print(v) numbers=[1,2,3,4,5,6,7,8,9,0] total=0 for n in numbers: #total =total+n print("sum of all list from 1 to 10 ", total) #using from loop with range for n in range(1,5): print(n,end=" ") print() for n in range(1,10,2): print(n, ...
""" This module is used to read the configurations from the various configurations files and generates the flat dictionaries for the same """ from Modules.file_type_mappings import FILE_TYPE_MAPPINGS class ReadModule: def read_file(self,file_name): """ Used to read the configuration file p...
import random # importing random to generate random numbers later ques = {} # a dictionary to hold questions (key: an integer, value: question) ans = {} # a dictionary to hold answers (key: an integer, value: answer) def loadQuiz(): """ This function loads the quiz's data (i.e, questions and answers) f...
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # 这是原始Python代码,看不懂js版本的可以参考 import tkinter as tk # 导入 Tkinter 库 import math import random class Pair(): # 数据组 def __init__(self, x, y): self.x = x self.y = y def __lt__(self, b): if isinstance(b, Pair): return self.x...
def column_to_list(df, col_name): return [x[col_name] for x in df.select(col_name).collect()] def two_columns_to_dictionary(df, key_col_name, value_col_name): k, v = key_col_name, value_col_name return {x[k]: x[v] for x in df.select(k, v).collect()} def to_list_of_dictionaries(df): return list(map(lam...
import numpy as np def find_closest_centroids(X, centroids): """ Computes the centroid memberships for every example. Parameters ---------- X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. centroids ...
import numpy as np def select_threshold(y_val, p_val): """ Find the best threshold (epsilon) to use for selecting outliers. Parameters ---------- y_val : ndarray, shape (n_samples,) Labels from validation set, where n_samples is the number of samples and n_features is the number of featur...
import numpy as np def feature_normalize(X): """ Normalizes the features in X. Parameters ---------- X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_norm : ndarray, shape ...
import numpy as np import matplotlib.pyplot as plt from poly_features import poly_features from feature_normalize import feature_normalize def plot_fit(min_x, max_x, mu, sigma, theta, p): """ Plots a learned polynomial regression fit over an existing figure. Parameters ---------- min_x : float ...
import matplotlib.pyplot as plt from plot_data_points import plot_data_points from draw_line import draw_line def plot_progress_k_means(X, history_centroids, idx, K, i): """ Helper function that displays the progress of k-Means as it is running. It is intended for use only with 2D data. Parameters -...
import numpy as np def pca(X): """ Run principal component analysis on the dataset X. Parameters ---------- X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. Returns ------- U : ndarray, shap...
#!/usr/bin/env python3 imie = input("Podaj imie ") nazwisko = input("Podaj nazwisko? ") wiek = input("Podaj wiek? ") print("Imie "+imie) print("Nazwisko "+nazwisko) print("wiek " + wiek)
#! /usr/bin/env python ''' A program which takes in an input file of json log entries and counts the number of unique occurances of each extension type. By: Robin Verleun ''' import sys import argparse import json import re from collections import defaultdict from validator import Validator def get_cli_i...
import collections # 从序列中随机抽取一个元素 from random import choice # namedtuple是继承自tuple的子类。 # namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。 # 这对象更像带有数据属性的类,不过数据属性是只读的 # 创建card类型,带属性rank,suit Card = collections.namedtuple('Card', ['rank', 'suit']) class FrenchDeck: ranks = [str(n) for n in range(2, 11)] + list('JQKA') #pr...
""" Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you. Take this opportunity to practice using functions, described below. """ from math impor...
""" Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. Extras: 1. Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. 2....
import vector import boid import numpy as np import matplotlib.pyplot as plt # This is the main program for running a flocking simulation in python # It uses two objects: a 3D Cartesian vector, and a boid (a birdlike object) # Look inside boid.py and vector.py to see the objects and their methods # Boids follow sever...
def number(): n = int(input()) sum="" for i in range(1,n+1): sum=sum+str(i) print(int(sum))
# small program to create a simple enigma machine #by Riya Philip alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' class Rotor(): #when all the variables are set to starting position position = 'A' def __init__(self, configuration): self.initial_config = configuration self.connections = configurat...
from fractions import Fraction x1 = Fraction(150,42) print(x1) print(type(x1), x1.numerator, x1.denominator) x2 = Fraction(264, 64) print(x1+x2)
from pip.backwardcompat import raw_input __author__ = 'Fotty' """ Write a program that prompts a user for their name (first name and family name separately) and then welcomes them. This time, the program should always welcome so that both the first name and the last name begin with a capital letter and the rest of th...
def budget(number_of_people): room = 100 food = 15 min_budget = room + food * (number_of_people - not_sure_if_attending_guests) max_budget = room + (number_of_people * food) return "Minimum budget is: " + str(min_budget) + " EUR" + "\n" + "Maximum budget is: " + str(max_budget) + " EUR" attending_...
''' Created on Jun 25, 2018 Author: @G_Sansigolo ''' from statistics import mean import numpy as np import matplotlib.pyplot as plt xs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64) ys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64) def best_fit_slope(xs,ys): m = ( ((mean(xs) * mean(ys)) - mean(xs*ys)) / ((mean(...
tw = pd.read_csv('../data/topwords_test.csv', index_col=0) tw.columns = ['word','freq_rej','freq_app'] def minFreq(df,myMin): return df[(df['freq_rej']>myMin) & (df['freq_app']>myMin)] tw = minFreq(tw,0) def distinctiveWords(df,myMin): df2 = minFreq(df,myMin) df2['ratio_rej'] = df2.freq_rej/df2.freq_app...
#!/usr/bin/env python from Tkinter import Frame, Label, OptionMenu, Button, Entry, SUNKEN, LEFT, RIGHT, StringVar, N, W, E, END from ListPane import ListPane from SpellingDatabase import SpellingDatabase import random class CreateView(Frame): """A class describing the list creation page of the UI""" def __in...
def makeParen(k=0, left=0, right=0, str=""): if left + right == k: print str return else: if left < k/2: makeParen(k, left + 1, right, str + "(") if right < left: makeParen(k, left, right + 1, str + ")") def paren(value): return makeParen(value*2, ...
# move 0s to end of array, either in place or out of place def moveZeros(a): indx = 0 for i in xrange(len(a)): if a[i] != 0: a[indx] = a[i] indx += 1 while indx < len(a): a[indx] = 0 indx += 1 return a a = [5, 0, 3, 1, 0, 0, 3, 4, 5, 6] print moveZeros(a...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def addHelper(self, root, v, d, curr_d): if root == None: return if curr_d == d - 1: ...
# Hackerrank Language Proficiency Module: Python # Title: Shape and Reshape # Directory: Python > Numpy > Shape and Reshape import math import os import random import re import sys import numpy as np if __name__ == "__main__": arr = np.array(list(map(int, input().split()))) arr.shape = (3, 3) print(arr) ...
# Hackerrank Language Proficiency Module: Python # Title: Finding the percentage # Directory: Python > Basic Data Types > Finding the percentage import math import os import random import re import sys if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line =...
__version__ = '1.0' if __name__ == '__main__': while 1: user_number = input("Choose a number: \n") if user_number.isdigit(): user_number = int(user_number) break else: print("{} is not a valid number".format(user_number)) if user_number > 100: ...
# Hackerrank Language Proficiency Module: Python # Title: Print Function # Directory: Python > Introduction > Print Function import math import os import random import re import sys if __name__ == '__main__': n = int(input()) answer_string = '' for i in range(1, n+1): answer_string += str(i) p...
# -*- coding: utf-8 -*- """ Created on Sat Sep 18 18:04:30 2021 @author: Gabe Butler """ import random, turtle turtle.colormode(255) # setting up the panel panel = turtle.Screen() w = 1200 h = 400 panel.setup(width=w, height=h) sky = ((random.randint(100,135)), random.randint(180,206), random.randin...
#!/usr/bin/env python """Example using transition system dynamics. This example illustrates the use of TuLiP to synthesize a reactive controller for system whose dynamics are described by a discrete transition system. """ # RMM, 20 Jul 2013 # # Note: This code is commented to allow components to be extracted into # th...
# school类 import pickle import os from . import Course from . import Group from . import Student from . import Teacher class School(object): def __init__(self): self.sname = '' self.saddress = '' self.teacherlist = [] self.courselist = [] self.grouplist = [] self.st...
import random print ("Hello warrior. Enter your name and face death standing proud") name = input(str) secretNumber= random.randint(1,99) print ("HAHAHA," + name + ", i am hiding somewhere between 1 and 99! TRY AND FIND ME BEFORE I KILL YOUR ENTIRE VILAGE") for guessesTaken in range(1, 20): print ("Roll the D20 until...
import tkinter as tk from tkinter import N, S, E, W, END, Button class EditView(tk.Toplevel): def __init__(self, master): tk.Toplevel.__init__(self, master) self.master = master self.protocol('WM_DELETE_WINDOW', self.withdraw) self.title('Input data') self.__text_area = ...
# In this challenge, you are tasked with creating a Python script for analysing # the financial records of your company. You will give a set of financial data called # budget_data.csv. The dataset is composed of two columns: Date and Profit/Losses. # (Thankfully, your company has rather lax standards for accounting so...
#!/usr/bin/python3 import unittest def factor(number): fac = number // 8 rem = number % 8 print (number," = 8 *",fac, " + ", rem) return fac class Test2(unittest.TestCase): def test_factor1(self): self.assertEquals(factor(1), 0) def test_factor2(self): ...
def french_rap(csv): try: list_read = {} f = open(csv, 'r') str = f.read() arr = str.splitlines() for x in arr: divide = x.index(',') list_read.setdefault(x[divide + 1:], []).append(x[:divide]) f.close() return list_read except File...
__author__ = 'Scott' #pyChallenge 6 #url: http://www.pythonchallenge.com/pc/def/channel.html #HINT: now there are pairs #HINT: zip # pants.html #HINT: amazing. zoom in #url: http://www.pythonchallenge.com/pc/def/channel.zip -> downloads a zip file #IN ZIP #welcome to my zipped list. #hint1: start from 90052 #hint2:...
""" <Program Name> upper_dot_lower.py <Started> March, 2017 <Author> Lukas Puehringer <lukas.puehringer@nyu.edu> <Purpose> Provides functions to encode and decode to and from dot-lower encoding. Dot-lower encoding replaces all upper case letters in a string with a dot followed by the lower case represent...
file = open('month.txt', 'r') list = [] for line in file: list.append(line.strip()) list.sort() for line in list: print(line) outFile = open('sorted_month.txt','w') for line in list: outFile.write(line + '\n') file.close() outFile.close()
# -*- coding: utf-8 -*- """ Created on Sun Sep 18 08:25:23 2016 @author: Meng Wang """ #question 1 def is_palindrome(string): ''' This function is a palindrome recogniser that read a string and return TRUE if it's a palindrome or FLASE if else. Parameter: A string ...
""" An implementation of a Binary Tree based on the description given in Computer Science by Bob Reeves (Hodder Eduction, 2015). This is not a terribly good implementation as it doesn't take advantage of OOP to create node objects to build the tree. Instead it uses three arrays (lists), node[], left[] and right[] to...
def show_list_contents(l): if len(l) > 0: # Spacing and row headings output = [""] * 5 output[0] = " " output[1] = " Index: " output[2] = " " output[3] = "Contents: " output[4] = " " # For each item in the list, print ou...
class TuringMachine: def __init__(self): self.__tape = [] self.__head_pos = 0 self.__start_state = self.__s1 self.__current_state = "" self.__halt_reached = False def load(self, s): self.__tape = list(s) def show(self): print("CURRENT STATE: " + se...
class btNode: __data = None __left = None __right = None def __init__(self, d): self.__data = d def getData(self): return self.__data def getLeft(self): return self.__left def getRight(self): return self.__right def addChild(self, d): if d < s...
class HashTable: __table = [] def __init__(self, size = 10): self.__table = [None] * size def getHashValue(self,key): hashValue = 0 for digit in key: hashValue = hashValue + ord(digit) hashValue = hashValue % len(self.__table) return hashValue def ...
text_to_compress = input("Enter some text to compress: ") text_to_compress += " " previous_character = "" same_character_count = 1 output = "" # Look at each letter for letter in text_to_compress: # If the letter is the same and the previous letter if letter == previous_character: # Count consecutive...
__author__ = 'Kyle Rouse' def d(data1, data2): value = 0 for i in range(len(data1)): value += (data1[i] - data2[i])**2 return value**.5 def traversal_first_traversal(data, k): point = data[0] centers = [] centers.append(point) data.remove(point) while len(centers) < k: ...
__author__ = 'kyle' <<<<<<< HEAD def longest_path_setup(text): file_in = open(text) lines_list = file_in.read().split("\n") dimensions = lines_list[0].split(" ") m1, m2 = get_matrices(lines_list[1:len(lines_list)]) n = int(dimensions[0]) m = int(dimensions[1]) return longest_path(n, m, m...
__author__ = 'kyle' <<<<<<< HEAD def coins(text): in_file = open(text) lines = in_file.read().split("\n") total = int(lines[0]) tmp = lines[1].split(",") coins_available = list() for i in tmp: coins_available.append(int(i)) coins_available.sort() coin_bag = list() for i i...
def palindromesubsequence(x,y): m = len(x) n = len(y) L = [[0]* (n+1)]*(m+1) for i in range(n+1): for j in range(n+1): if (i==0 or j==0): L[i][j]=0; elif (x[i-1] == y[j-1]): L[i][j] = L [i-1][j-1]+1; else: ...
def addition(l1): for i in l1: sum1=sum(l1) return sum1 def multiplication(l1): mull=1 for i in l1: mull = mull*i return mull
class Level: def __init__(self, current_level=1, current_xp=0, level_up_base=200, level_up_factor=150): self.current_level = current_level self.current_xp = current_xp self.level_up_base = level_up_base self.level_up_factor = level_up_factor # Calcula a experiencia neces...
roomies=[] print('Enter the name of all the roomies:') while True: name=input() if name=='': break roomies=roomies+[name] print('The name of the roomies are') for i in roomies: print(' '+ i)
import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset=pd.read_csv("logistic.csv") x=dataset.iloc[:,:-1].values y=dataset.iloc[:,-1].values from sklearn.preprocessing import * #en=LabelEncoder() #x[:,1]=en.fit_transform(x[:,1]) m=MinMaxScaler() x=m.fit_transform(x) def sigmoid(theta,x): ...
from collections import Counter import pandas as pd import seaborn as sns from matplotlib.colors import ListedColormap from palettable.colorbrewer import diverging, qualitative, sequential def is_data_homogenous(data_container): """ Checks that all of the data in the container are of the same Python data ...
#!/usr/bin/python import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as anim def plot_cont(fun,xmax): y = [] fig = plt.figure() ax = fig.add_subplot(1,1,1) def update(i): yi = fun() y.append(yi) x = range(len(y)) ax.clear() ax.plot(x...
from collections import deque data = {} data['a'] = 1 data['b'] = 2 data['c'] = 3 def print_test(data): for i in data: print(i, data[i]) #print_test(data) class Node: # Creates single double facing nodes def __init__(self, val, prev=None, nxt=None): self.val = val self.prev = prev self.nxt = nxt class L...
#!/usr/bin/env python3 def main(): with open('input.txt', "r") as f: number = int(f.readline()) for i in range(2,int(number**0.5)+1): if number/i == int(number/i): print('false') break else: print('true') if __name__ == '__main__': main()
#!/usr/bin/python3 ################################################################# # Simple Python3 script to generate random passwords # # Made for educational purposes, feel free to use if you'd like # # Created by Kris Rostkowski # ####################################...
current_wickipidia = int(input("current_wickipidia count")) if current_wickipidia >= 1000: print("buy10") elif current_wickipidia <= 1000: print("holding")
#!/usr/bin/env python3 # -*- coding: utf8 -*- #------------------------------------------------------------------------------- # created on: 11-12-2018 # filename: makewordplot.py # author: brendan # last modified: 12-11-2018 21:26 #------------------------------------------------------------------------------- """ Par...
#1 import datetime import calendar Name=input("Give me your Name") DOB =input("Give me your DOB") Date=datetime.datetime.strptime(DB,'%d %m %Y') Day=D.replace(year = Date.year+100) print("Hello " +Name+ ", You will turn 100 years old in the year" ,Day.year) N=Day.weekday() Day_Name= ['Monday', 'Tuesday', 'We...
# Big-O # 1. Constant----------------- O(1) # 2. Logarithmic-------------- O(Log N) # log (base) N = exponent # log 8 = 3 # linear---------------------- 0(N) animals = ['duck', 'cat', 'dog', 'bear'] def print_animals(animal_list): for i in range(len(animal_list)): print(animal_list[i]) cou...
# this program issues a serach for youtube videos , given a particular search import json import urllib.parse import urllib.request GOOGLE_API_KEY = "AIzaSyAdpz4y7NlVi6diJnNUm61FxgV7qTxPFY0" BASE_YOUTUBE_URL = 'https://www.googleapis.com/youtube/v3' def build_search_url(search_query:str, max_results: int) ->str...
#gridlayout from tkinter import * root = Tk() label1 = Label(root, text = "Label 1 ") label2 = Label(root, text = "Label 2 ") label3 = Label(root, text = "Label 3 ") label1.grid(row = 0 , column = 0 ) label2.grid(row = 0, column = 1) label3.grid(row = 1 , column = 0) root.mainloop()
from tkinter import * import Othello import math class OthelloApplication: def __init__(self, gameState: Othello.Othello, winner :str): # creates a game board self._state = gameState self._state._new_game_board() self._root_window =Tk() self._root_window.configure(bg =...
''' Project 5 Othello GUI ''' import tkinter import Othello import math ##class OthelloGame: ## ## def __init__(self, game: Othello.Othello, winner :str): ## ''' ## ## Initializes the game board, and prepares the menu to the user ## , update the score of the board ## ## ''' ## ##...
# bhaskar directions=[[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]] def print_board(temp_board): for i in range(0,len(temp_board)): for j in range(0,len(temp_board[0])): print(temp_board[i][j], end=' ') print("") def get_opposite_of(color): if color == "B": return "W" else: return "B" def ge...
from collections import namedtuple Bedroom = namedtuple('Bedroom', 'room_num ') Reservation = namedtuple('Reservation', 'room_num checkinDate checkoutDate lastName firstName') def stage3(): list_of_bedrooms = [] list_of_reservations = [] reservation_dict = {} bb = open ('stage3.txt', 'r') lines = ...
# Shambhu Thapa 10677794 #Project 3: Ride Across The River import mymap import generator def user_interface(): ''' interact betweeen different modules and produce the output ''' try: locations = get_locations() data = mymap.get_result(mymap.build_search_url(lo...
### If you want to run the code, you should comment out the problems you haven't ### done yet so you can't see the answers for them. ### Hints for each problem are at the bottom of this file ## ### 1. What's the output of the following code? ##try: ## try: ## a = 5 ## b = 7 ## ...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1+class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_clas...
def main(): out = "" while True: try: string = input().strip() except EOFError: break; out = out + string print(out, end='') main()
# -*- coding: utf-8 -*- """ Data Incubator milestone project: stock chart """ from datetime import datetime, timedelta #from pandas import DataFrame import yfinance as yf from math import pi from calendar import monthrange import streamlit as st from pandas_datareader import data as pdr import plotly.graph_objects as ...
""" This little program shows the use of the enumerate() - operator """ def enuming(): t = [6, 7, 8, 19, 42] for p in enumerate(t) print(p) def enuming2(): x = [192, 135, 643, 346] for i, v in enumerate(x): print("i = {}, v = {}".format(i,v)) """ range() isn't used widely in python!: >>> list(range(0,10,...
''' Exercise 3 Note: This exercise should be done using only the statements and other features we have learned so far. Write a function that draws a grid like the following: + - - - - + - - - - + | | | | | | | | | | | ...
def knapsack(items, i, size): """items: sequence of weights, i: item you're considering; i==len(items)->done size: size of knapsack""" memo = {0: [0]} for i in range(len(items)): memo[i+1] = [] for weights in memo[i]: memo[i+1].append(weights) if weights + it...
class Node: # node for linked list def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def push(self, key): # push to the front of the linked list new_head = Node(key) new_head.next = self...
import time # cheap way to do squares squares = dict([(c, int(c)**2) for c in "0123456789"]) # list of numbers in the never-ending sequence bad_nums = sorted([4, 16, 37, 58, 89, 145, 42, 20]) def midpoint(low, high): ''' gets the midpoint of two ints. If the ints sum to an odd number, we round using Python's...