text stringlengths 37 1.41M |
|---|
alphabet_lower=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
alphabet_upper=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
def cipher_array(array, key):
cipher_array=[0]*len(array)
key_count=0
... |
# Problem 4 - Using different ways to filter data
#
# ===== Description:
# There a many ways to filter data from an array. This exercise explores data filtering using list comprehension
#
# ===== Instructions:
# Complete the exercises below by completing the missing code for the python functions to accomplis... |
courses = ['History', 'Math', 'Physics', 'CompSci']
courses_2 = ['Education', 'Geography']
nums = [1, 5, 2, 4, 3]
nums_2 = [7, 10, 6, 9, 8]
print(courses[0:2]) # start at index 0 and end at index 2. ['History', 'Math']
# start is inclusive, end is exclusive.
print(courses[:2]) # slicing - ['History... |
# a = True
# b = False
#
# if(b):
# print('b is true')
# else:
# print('b is false')
#
# c = input("Enter First Number\n")
# d = input("Enter Second Number\n")
# e = int(c) + int(d)
# print(e)
# f = input("Enter the number\n")
# f = int(f)
#
# if(f % 2 == 0):
# print("The number is even")
# else:
# p... |
dictionary =[]
pra=[]
kum=[]
i=1
def menu():
global select
print("\nDictionary\n 1.add word\n 2.show word\n 3.delete word\n 4.Exit")
select = input("press select:")
def add():
dictionary.insert(0,input("add word:"))
pra.insert(0,input("type word(n. v. adj .adv):"))
kum.insert(0,input("mean:"))
... |
import sqlite3
import os
conn = sqlite3.connect(r'C:\Users\kritphol\Desktop\kraen\work\chadchalidh(Python)\student.db')
c = conn.cursor()
def menu():
global choose
print('---ระบบทะเบียนนักเรียน---\nadd info student[a]\nshow info[s]\nEdit info student[e]\ndelete info student[d]\nexti program[x]')
choose = i... |
from types import FunctionType
"""
Example call: get_func_names(module, dir(module))
We can use the module object in the analyzer.
DropDownList should get the function name list from this function
"""
def get_func_names(module_object, name_list):
func_names = []
for name in name_list:
if type... |
"""
Classic to represent basic objects like cards, bids and players.
"""
from collections import namedtuple
from enum import Enum
from itertools import cycle
from typing import Iterable, List, Union
MAX_PLAYER_HAND_SIZE = 10
class CardSuit(Enum):
Spades = 'Spades'
Clubs = 'Clubs'
Diamonds = 'Diamonds'
... |
def fibr(n):
if n==0 or n==1:
return 1
else:
return fibr(n - 1) + fibr(n - 2)
for i in range(100):
print(fibr(i)) |
from texttable import Texttable
class Puzzle:
def __init__(self):
self._board = []
self._l = 0
self._finalState = []
self._emptySpaceX = 0
self._emptySpaceY = 0
self._heuristic =0
def setBoard(self, board, final):
self._board = board
self._final... |
# used for manipulating directory paths
import os
# Scientific and vector computation for python
import numpy as np
# Plotting library
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D # needed to plot 3-D surfaces
# library written for this exercise providing additional functions for assignment... |
# 1
out_file = open("names directory.txt", "w")
name = input("What is you name? ")
print(name, file=out_file)
out_file.close()
# 2
in_file = open("names directory.txt", "r")
print("Your name is", name)
in_file.close()
# 3
out_file = open("numbers.txt", "w")
print(17, file=out_file)
print(42, file=out_file)
print(400,... |
"""
CP1404 Practical
Word occurrences
Student: Anthony Bokor
"""
phrase_to_count = {}
text = input("Text: ")
phrases = text.split()
# Finds how often a letter occurs
for phrase in phrases:
recurrence = phrase_to_count.get(phrase, 0)
phrase_to_count[phrase] = recurrence + 1
phrase = list(phrase_to_count.keys())... |
TOLERANCE = 5
def reorder_lines(lines, tol=TOLERANCE):
"""
Changes the line coordinates to be given as (top, left, bottom, right)
:param lines: list of lines coordinates
:return: reordered list of lines coordinates
"""
reordered_lines = []
for line in lines:
# we divide by tol and ... |
list_number = [2,10,44,38,50,24,16,78,65,7,11,49,33]
list_number.sort()
print(list_number)
arr_value = len(list_number)-1
print('Check if the following number exists')
number = int(input())
found = False
while (arr_value >= 0 and found == False):
if(list_number[arr_value] == number):
print('Ok')
... |
num1=float(input("Type a number: "))
num2=float(input("Type another number: "))
print(num1," / ",num2," = ",num1/num2)
|
num1=float(input("Type a number: "))
num2=float(input("Type another number: "))
print("Sum of the numbers: ",num1+num2)
|
def sum2end(list):
list2 = list.pop()
list3 = []
for i in list:
list3.append(i+list2)
return list3
# Open File "puzzle1_input.txt"
with open('puzzle1_input.txt', 'r') as reader:
# Read numbers less than 2020 into List
n = []
for line in reader.readlines():
n.append(int(lin... |
# Q13.Write a Python program to sum all the items in a dictionary.
sample={'a': 100, 'b':200, 'c':300}
sum=0
for i in sample.values():
sum=sum+i
print(sum,"is the sum of all the values in the dictionary") |
# Q17.Write a Python program to sort a dictionary by key.
#ascending order
sample={"d":17,'a': 100,"z":26,'b':200,"y":28,'c':300}
keys=list(sample.keys())
fdic={}
for k in range(len(keys)):
for i in range(len(keys)-k-1):
if keys[i]>keys[i+1]:
temp=keys[i]
keys[i]=keys[i+1]
... |
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 15
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
# in... |
print("El jugador 1 elige el numero a adivinar, y el jugador 2 trata de adivinarlo")
num_eleg = int(input("Elige tu numero: "))
num_adv = int(input("Adivina el numero: "))
while num_adv != num_eleg:
num_adv = int(input("Intentalo otra vez: "))
print("¡¡¡Ganastee!!!") |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# AUTHOR: Minzhang Li
# FILE: C:\Users\Administrator\Desktop\python数据分析\python基础语法以及配套
# 练习(持续更新)-lmz\basic\day2\calculator.py
# DATE: 2020/07/05 Sun
# TIME: 07:56:30
# DESCRIPTION: This is a simple calculator to test your acknowledgement of basic operation on integers and ... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# AUTHOR: Minzhang Li
# FILE: F:\MyGithubs\Python-Data-Analysis-notebook\python数据分析\python-data-analysis\code\day7\main.py
# DATE: 2020/07/12 Sun
# TIME: 21:22:31
# DESCRIPTION: This is main file
def main():
n = int(input('Please choose a mode with a number: 1.add\t2.... |
def find_longest_word(l):
l1=[]
for item in l:
c=0
for item2 in item:
c+=1
l1.append(c)
for i in range(len(l1)):
m=l1[i]
for j in range(i+1,len(l1)):
if m<l1[j] :
m=l1[j]
return m
print(find_longest_word(['hello','this','is','my','answer'])) |
import numpy as np
# num = int(input("请输入数字:"))
#
# isHuiwen = True
# num_list = []
# y = num
#
# while(y>0):
# temp = y % 10
# num_list.append(temp)
# y = int(y/10)
#
# print("列表:" + str(num_list))
#
# for i in range(len(num_list)):
# if num_list[i] != num_list[len(num_list)-i-1]:
# isHuiwen =... |
# -*- coding: utf-8 -*-
from random import seed, randint
class Rand(object):
def __init__(self, generator_seed):
seed(generator_seed)
def next_bool(self):
return randint(0, 1) == 1
|
#Sourced from
#http://chrisalbon.com/python/beautiful_soup_html_basics.html
#https://www.crummy.com/software/BeautifulSoup/bs4/doc/
from bs4 import BeautifulSoup
import requests
# Create a variable with the url
url = 'https://classes.usc.edu/term-20171/'
# Use requests to get the contents
r = requests.get(url)
# G... |
class RoomBuilder:
def __init__(self):
self.roomtype = None
self.doors = 0
self.windows = 0
self.traps = 0
print("-> New room created")
def setroomtype(self, roomtype):
self.roomtype = roomtype
print("-> Room type set to " + roomtype)
def adddoor(se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 27 17:47:50 2019
@author: jaime.iglesias
Purpose: To practice clustering on the wholesale customers dataset
"""
"""
This dataset is a collection of the annual spending of wholesale customers
of a company based in Portugal. The monetary uni... |
def fibonacci_func(n) :
a,b = 0,1
i = 0
while True :
if(i > n) : return
yield a
a,b = b, a+b
i += 1
fib = fibonacci_func(10)
print fib #generator
for x in fib :
print x
|
from board import Board
from player import Player
class Game:
def __init__(self,board):
self.turn = 0
self.players = []
self.board = board
def play_game(self):
'''
runs the actual code, connects all individual pieces and ties them together
'''
p... |
length=int(input("enter the length"))
bredth=int(input("enter the bredth"))
if length==bredth:
print("it is the square")
else:
print("it is rectangle")
|
#Note this is a proof of concept so I am assuming the field names and distinct field values are safe.
#An actual implementation will need to take this into account.
databaseFile = '2 - testDatabase.sqlite'
#Connect to database
import sqlite3
con = sqlite3.connect(databaseFile)
c = con.cursor()
#Specficy th... |
# python3
import sys
def compute_min_refills(distance, tank, stops,di1):
count=0
variable=0
for i in range(len(stops)-1):
if(stops[i+1]-stops[variable]>tank):
count+=1
variable=i
if(stops[i+1]-stops[i]>tank):
return -1
return count
di1=... |
# Uses python3
import sys
def gcd_naive(a, b):
if(a==0):
return b
else:
return gcd_naive(b%a,a)
if __name__ == '__main__':
a,b=input().split()
a=int(a)
b=int(b)
lcm=(a*b)//gcd_naive(a,b)
print(lcm)
|
n1,n2=input().split()
a=int(n1)
b=int(n2)
for i in range(a+1,b):
if(i%2!=0):
print(i,end=" ")
|
num=int(input())
temp=num
sum=0
while(num!=0):
r=num%10
sum=sum+(r**3)
num=num//10
if(temp==sum):
print("yes")
else:
print("no")
|
# -*- coding: utf-8 -*-
"""
Potts model, the n fold method
@author: Nina
"""
import random
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#dimenzije resetke
L = 50
N = L*L
q = 3
states = [1, 2, 3]
def decision(probability):
"""Do smth with given probability"""
return random.rando... |
import tkinter as tk # GUI package
import sqlite3 as sq # For tables and database
import tkinter.font as tkFont
import tkinter.ttk as ttk
import os
customer_window = tk.Tk()
customer_window.title("Customer Entry")
customer_window.geometry('800x600+0+0')
header = tk.Label(customer_window, text="Create New Customer", ... |
import time
import json # This is to save our JSON object in a file.
"""
Comment the print statements in this file before performing unit test in "test_app.py" file.
Uncomment the raise statements in this file before performing unit test in "test_app.py" file.
"""
dictionary = {} # This is the dictionary to store... |
def arithmetic(first_num, second_num, operator):
if operator == '+':
result = first_num + second_num
elif operator == '-':
result = first_num - second_num
elif operator == '*':
result = first_num * second_num
elif operator == '/':
result = first_num / second_num
else:... |
import copy
"""
https://docs.python.org/3/library/copy.html
copy.copy(x)
Return a shallow copy of x.
copy.deepcopy(x[, memo])
Return a deep copy of x.
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or class instances)
浅副本依赖了引用, 引... |
## TUPLES --------------
# tuples are immutable sequences like Strings
# Lists are mutable - can be changed once previously defined
t = (1,2,3)
print(t)
print(t[1])
# can also hold mixed data types.
z = ('a',True,123)
print(z)
## SETS ----------------
# sets are unordered collections of unique e... |
#!/usr/bin/python2
def backwards(word):
index = len(word)-1
while index !=-1:
letter = word[index]
print letter
index = index -1
backwards('pooperpants')
|
#!/usr/bin/python2
def find(word, letter, start_index):
### search a string for a letter and keep a counter, optional start offset
index = start_index
count = 0
while index < len(word):
if word[index] == letter:
count = count + 1
index = index + 1
print count
find('beaaxae... |
#!/usr/bin/python2
def is_palindrome(word1):
if word1 == word1[::-1]:
print 'Yes it is'
else:
print 'no it isn\'t'
is_palindrome('allen')
is_palindrome('bob')
is_palindrome('otto')
is_palindrome('redivider')
|
#!/usr/bin/python2
def avoids(word, chars):
flag = False
for l in chars:
flag = flag or l in word
return flag
#print avoids('me', 'cetwf')
prompt = "input a word. hit enter and enter all of the characters you want to check for\n"
user_input_a = raw_input(prompt)
user_input_b = raw_input('and the letters\n')
pr... |
#Caitlin J. Corbin
#Intro to Python
#Draw a Polygon
#June 15, 2020
import turtle #imports the "drawing" ability
turtle.penup() #prepares to draw
turtle.goto(40,-69.28) #goes to first coordinate
turtle.pendown() #makes first point
turtle.goto(-40,-69.28) #the foll... |
'''
Caitlin J. Corbin
2020.07.27
19.2
Intro to Python
'''
# Binary tree function
def isFullBinaryTree(self):
return CheckFullBinaryTree(self.root);
# Checks whether a binary tree is full or empty
def checkFullBinaryTree(self, root):
if root is None:
return True
if root.left is N... |
#Caitlin J. Corbin
#Intro to Python
#Draw a Clock
#June 15, 2020
import turtle
turtle.pensize(3) #minutes
turtle.forward(180)
turtle.right(180)
turtle.forward(180)
turtle.pensize(2) #seconds
turtle.right(90)
turtle.forward(200)
turtle.right(180)
turtle.forward(200)
turtle.pensize(4) #hour... |
from collections import Counter
from art import coffee_art, coffee_logo
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"c... |
import numpy as np
def function4():
#Swap columns 1 and 2 in the array arr.
arr = np.arange(9).reshape(3,3)
print(arr)
return arr[:,[0,1]] = arr[:,[1,0]] #wrtie your code here
"""
Expected Output:
array([[1, 0, 2],
[4, 3, 5],
[7, 6, 8]])
"""
pri... |
def checkRuleConform(dices, col):
"""Aufruf der Pruefungsmethoden"""
if dices == [] : return True
if col <=5 : return CheckElement(dices, col+1)
if col == 6: return CheckDreierpasch(dices)
if col == 7: return CheckViererpasch(dices)
if col == 8: return CheckFullHouse(dices)
if col == 9: ret... |
# Pop-up Quiz
import question
def main():
# Local variables
first_points = 0
second_points = 0
player = ''
# Create question list.
questions = get_questions()
for i in range(10):
if i % 2 == 0:
player = 'first'
else:
player =... |
'''
Created on 30.01.2014
@author: Marc
'''
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print("arg1: %r, args2: %r" % (arg1, arg2))
#*args is actually pointless, we can just do this
def print_two_again(arg1,arg2):
print("arg1: %r, args2: %r" % (arg1, arg... |
#calculate the sum and mean of five numbers
#say 1,2,3,4,5
a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
sum=a+b+c+d+e
mean=sum/5
print(sum)
print(mean)
|
def donuts(number):
if number >= 10:
return str('many')
else:
return str(number)
print('the no of donuts is',donuts(50))
|
def print_some_value(gender='unknown'):
if gender is 'm':
print (" prajwal is ",gender)
elif gender is 'f':
print ('tushara is ',gender)
def calculate(value):
amount = 68 * value
return amount
print_some_value()
salary_in_us=calculate(1000)
print('shylesh salary in US',salary_in_u... |
import time
import calendar
ticks =time.time()
print ("the no",ticks)
localtime=time.asctime(time.localtime(time.time()))
print (localtime)
exact=localtime.split(" ")
print(exact)
print(exact[3])
if exact[3] is '23:33:00':
print ("tushar drink water")
cal =calendar.month(2012,12)
print (cal)
|
import numpy as np
def NAND(x1, x2):
x = np.array([x1, x2]) #input
w = np.array([-0.5, -0.5]) #weight
b = 0.7 # bias
tmp = np.sum(x*w) + b
if tmp <= 0:
return 0
else:
return 1
def OR(x1, x2):
x = np.array([x1, x2]) #input
w = np.array([0.5, 0.5]) #weight
b = -0.2 # b... |
class MulLayer:
def __init__(self):
self.x = None
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
output = x*y
return output
def backward(self, dout):
#print('dout=', dout)
dx = dout * self.y #x와 y를 바꾼다
dy = dout * self.x... |
'''
programa para salas de juego y saber si es mayor de edad
si es menor de 4 años gratis, entre 4 y 18 5€, si es mayor
10€
'''
edad = input('Introduce tu edad: ')
edad = int(edad)
if edad < 4:
print('El precio es GRATUITO.')
elif edad >= 4 and edad <= 18:
print('El precio es 5€.')
else:
pr... |
#Program: camper_age_input
#Author: Terry Pope
#Last date modified: 06/03/2020
#The purpose of this program is to accept input of age and convert it to months,
#then output the results.
def convert_to_months(years):
return years*12
if __name__ == '__main__':
years = (int(input("Enter age between 1 and 5:"))... |
sdm={"cse":186,"isc":178,"eee":164,"ece":145}
def admission(entry=1,cc=0,ic=0,eec=0,ec=0):
if entry>20:
print("cse count:",cc,"isc count:",ic,"eee count:",eec,"ece count:",ec)
return
else:
dept=input("Tell us desired department: ")
cutt=int(input("Tell us cutt off: "))
if... |
# rercursive
warehouse=[0]
def details(index=0):
if index<len(warehouse):
print(warehouse[index])
index+=1;details(index)
else:
return
def update(index=0,end=len(warehouse)):
if index<end:
decide=input("Tell us what you wish to do: ")
if decide=="take":
... |
from handling.pc import laptop
class easy:
"Collection of laptop as list"
__stock=[]
def add(self,lap):
self.__stock.append(lap);print(lap.getModel(),"added")
def __str__(self):
hai=""
for each in self.__stock:
hai+=str(each)+"\n"
return hai
def __sub__(s... |
# else with loop
num=int(input("Tell us which number table you wish: "))
for left in range(1,11):
print(left,"*",num,"=",(left*num))
else:
print("requirement is over")
|
'''
boeg
boe
bo
b
'''
ser="boeg"
leng=0
for time in range(5,9):
if time==5:
leng=len(ser)
elif time==6:
leng=len(ser)-1
elif time==7:
leng=len(ser)-2
elif time==8:
leng=len(ser)-3
for one in range(leng):
print(ser[one],end="")
print()
dish="mcfe"
for cabi... |
# for in range loop
for seat in range(27,20,-1):
cutoff=float(input("Tell us Ur cuttoff: "))
if cutoff >= 78.4:
print("U got admission in SDMIT")
else:
print("Try with another college");
|
# using from
from statement import *
def add(start=0,end=10):
if start<end:
trans.append(input("Enter the entry either credit/debit: "))
start+=1;add(start,end)
else:
return
def findNPut(start=0,end=len(trans),count=0,fee=0):
if start<end:
if trans[start]=="debit":
... |
import sys
#global
num1 = 9
def isPrime ():
#def message (): ##local
#print ("This is a local function")
global num1
num1 = 3
def localFunction ():
print ("This is a local function")
##localFunction () ##local
##message() ##local
#message ("this is a function...")
... |
#### DECLARE VARIABLES #####
num1 = 0
num2 = 0
result_add = 0
result_m = 0
num1 = int ( input( "Enter number1 " ) )
num2 = int ( input( "Enter number2 " ) )
result_add = num1 + num2
result_m = num1*num2
print("this is the add: ", result_add )
print("This is the multiplication: ", result_m )
|
# TTC 39:19:06
# Need to raise exception!
import random
class BinarySearchTree(object):
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __init__(self):
self.root = None
self.size = 0
def p... |
'''
TTC: 53:24:71
Issues:
1) Need to remember how to do iter sift down
2) Need to remember to check for while len >= 0 when using 0 idx in heap
3) Sift down for HeapSort needs to take in length to sift down to (for
inplace sorting)
'''
import random
class HeapSort:
@staticmethod
def _swap(arr... |
"""a)Load the Black Friday dataset into one of the data structures (NumPy or Pandas).\n",
"b)Display header rows and description of the loaded dataset.\n",
"""
import pandas as pd
import numpy as np
df = pd.read_csv("blackfri.csv")
print("<-----Data Information----->\n")
print("Head of Dataset")
print(df.head(... |
#lists
print("********* LIST OPERATIONS ********\n")
a = [12,24,36,48,60]
print("set of values of list:",a[2:4],"\n")
print("Retrieve using negative index:",a[-2],"\n")
a[3] = "third multiple"
print("list after changing",a,"\n")
del a[3]
print("list after deleting",a,"\n")
a.insert(1,0)
print("List after insertin... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 6 16:39:57 2020
@author: VALUED CUSTOMERC
"""
import sqlite3
import assignment1
from classes import Books
def display_menu():
print("COMMAND MENU")
print("every - display everything")
print("cat - view books by category")
print("year - view books ... |
#!/usr/bin/env python3
"""
Suggest a pronoun to use for a musical artist,
by looking at their biography on Last.fm.
Usage: python artist_pronoun.py artist_name
"""
import argparse
from mylast import lastfm_network, print_it
def count_em(words, text):
"""Count how many times these words apear in the text"""
... |
#String interpolation
name = "Sean"
print(f"Hello {name}") #Hello Sean
# Are variables mutable or immutable?
# Strings are immutable because they cannot be changed, they create a new instance of the string.
# Arrays are mutable because the original changes. Arrays in Python are called Lists.
name = "Will"
name += "ie"... |
from ch3 import single_byte_xor_cipher_cracker
def single_character_xor_cipher_searcher():
"""In a given file, find the line that was single byte XOR'd
>>> x = single_character_xor_cipher_searcher()
>>> int(x[0]), x[1], x[2]
(93, 'Now that the party is jumping\\n', '35')
"""
highest_chi_2 = (0... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 2 20:12:57 2017
@author: Rafi
LEVEL MAP MODULE
"""
import random
# Level Map:
# __ __ \/ __ __
# 0 | __ | |
# 1 | | __|__ |
# 2 | |__ __ | |
# 3 |__ | __| |
# 4 |__ __| |__ __|
# 0 1 2 3 4
class LevelMa... |
#!/usr/bin/env python3
sum=0
n = int(input("Enter the number size : "))
for i in range(0,n,1):
num=int(input("Input the number: "))
sum+=num
result=sum/n
print("The average is : ",result)
|
NULL = ''
def split(string: str):
"""
Takes one argument; splits a string into a list of characters
:return: List of characters
"""
return [char for char in string]
def replace(old: str, new: str, visual = False):
"""
Takes three arguments; replaces the strings fed.
A... |
""" This function contains functions which help to link packages to
the user's root directory. It also unlinks them. Which ever you
prefer.
"""
# Standard
import os
def sym_farm(package_path):
""" This function walks through a directory, and recreates its structure
by recreating the subdirectories within the... |
import random
random.seed() #system time
compliance = {'1' : 'scissors','2' : 'paper','3' : 'rock','4' : 'lizard','5' : 'Spock', '6' : 'stop'}
win = {'scissors' : ('paper' , 'lizard'), 'paper' : ('rock', 'Spock'), 'rock' : ('scissors', 'lizard'),
'lizard' : ('Spock', 'paper'), 'Spock' : ('scissors', 'rock')}
u... |
from Queue import Queue
# suppose the problem is guaranteed to be solved only by inference
# so this is the naive version without searching
class Assignment:
def __init__(self, pos, val):
self.pos = pos
self.val = val
def __str__(self):
return "Assign " + str(self.val) + " to " + str((... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
PlusNum = 0
MinusNum = 0
ZeroNum = 0
for i in range(len(arr)):
if arr[i] == 0:
ZeroNum += 1
elif arr[i] > 0:
PlusNum += 1
... |
"""
DIAMOND PROBLEM
"""
"""
Example 1 - classical case
"""
class A:
def say(self):
print("Class A")
class B(A):
def say(self):
print("Class B")
class C(A):
def say(self):
print("Class C")
class D(C, B): # mro - first look in C, than in B, than in A and finally 'obje... |
class Animal(object):
def __init__(self, name: str, legs_number: int, is_scary: bool) -> None:
self.is_scary = is_scary
self.legs_number = legs_number
self.name = name
class Mammal(Animal):
def __init__(self, name: str, legs_number: int, is_scary: bool, walks_on_2_feet: bool = False) -> Non... |
def square_area(n : int) -> int:
res = n**2
return res
print(square_area(10))
def name(name: str) -> str:
return name.upper()
from typing import Dict, List
def trav(d: Dict[str, List[float]]):
return d
|
"""
Dynamic Programming - is an algorithmic paradigm that solves a given complex
problem by breaking it into subproblems and stores the results of subproblems
to avoid computing the same results again.
Two main properties of problems to be solved using DP:
a) overlapping subproblems
b) optimal substructure
a) overlap... |
"""
duck typing - this term comes from the saying:
“If it walks like a duck, and it quacks like a duck,
then it must be a duck.”
Duck typing is a concept related to dynamic typing, where
the type or the class of an object is less important than
the methods it defines. When you use duck typing, you do
not check types a... |
"""
For this next section, you’re going to build a program that makes use of
all three methods. This program will print numeric palindromes like before,
but with a few tweaks. Upon encountering a palindrome, your new program will
add a digit and start a search for the next one from there. You’ll also handle
exceptions ... |
# -*- coding: utf-8 -*-
"""
Pawel
2019/10/31
"""
import sys
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".... |
arrs=[]
arrs.append("abc")
arrs.append("def")
arrs.append("xyz")
arrs.append("123")
arrs.append("mno")
print "Hello World!\n"
for arr in arrs:
print(arr)
for el in arrs:
if el == "123":
index=arrs.index(el)
a=arrs.pop(index)
print(a)
print "Hello World!\n"
for arr in arrs:
print... |
import turtle
size = 1
turtle.speed(100)
turtle.color("violet")
def star(turtle, side):
for i in range(5):
turtle.forward(size)
turtle.right(144)
for i in range(80):
star(turtle, 50)
turtle.right(5)
size += 1.5
turtle.penup()
turtle.goto(-200, -100)
turtle.pendown()
turtle.color... |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
temp_map = {}
for i in range(0, 9):
if 'row' + str(i) not in temp_map:
temp_map['row' + str(i)] = []
for j in range(0, 9):... |
tion for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
start = -n + ... |
print("welcome to Evans video game quiz")
print("There are 7 questions good luck on the quiz")
def end_game(ans):
if ans == "quit":
print('Game over')
# exit
quit()
score = 0
correct_answer = True
def correct(score):
print("correct")
score = score + 1
def incorrect(sco... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.