text stringlengths 37 1.41M |
|---|
# This class creates and displays graphs to illustrate solutions
import matplotlib.pyplot as plt
# Used to show the positions of the locations on the grid
def ShowPositions(locations):
locationsx = []
locationsy = []
for x in range(len(locations)):
locationsx.append(locations[x][0])
locat... |
"""
What was the max amount of snow per date?
"""
from mrjob.job import MRJob
import mrjob
class Snow_days(MRJob):
INPUT_PROTOCOL = mrjob.protocol.RawProtocol
def mapper(self, key, line):
all_data = line.split(",")
yield "key",key
if all_data[4] and float(all_data[4]) > 0:
... |
word = input()
length = 0
for i in range(len(word)):
for i2 in range(len(word)):
if i2 >= i:
newword = word[i:i2+1]
if newword == newword[::-1]:
if i2+1-i > length:
length = i2+1-i
print(length)
|
quarters = int(input())
machine = 1
m1 = int(input())
m2 = int(input())
m3 = int(input())
counts = 0
while quarters > 0:
quarters -= 1
if machine == 1:
m1 += 1
if m1%35 == 0:
quarters += 30
machine = 2
elif machine == 2:
m2 += 1
if m2%100 == 0:
... |
#Generalize the above implementation of csv parser to support any delimiter and comments.
import csv
def parse_csv():
with open('sample.csv', newline='') as f:
reader = csv.reader(f, delimiter=' ', quotechar='|')
for row in reader:
print(','.join(row))
parse_csv()
|
import numpy as np
np.random.seed(25)
def sigmoid(x,deriv=False):
if deriv==True:
return x*(1-x)
return 1/(1+np.exp(-x))
X = np.array([[0,1,1],[1,0,1],[0,0,1],[1,1,0]])
Y = np.array([[1,1,0,0]]).T
weight1 = 2*np.random.random((3,4))-1
weight2 = 2*np.random.random((4,1))-1
for j in range(... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# !@Time :2019/7/19 10:17
# !@Author :will
import threading
class MyThread(threading.Thread):
def __init__(self, func, args):
threading.Thread.__init__(self)
self.func = func
self.args = args
self.result = None
def run(self):
... |
def brute(g,p,y) :
i=2
sol = pow(g,i,p)
if sol == y :
return 2;
if(y==g) :
return 1
if(y==1) :
return p-1
for i in range(3,p-1) :
sol = pow(g,i,p)
if sol == y :
return i
if __name__ == "__main__" :
g,p,y = map(int,raw_input().split(' '))
... |
#write a program to delete double space in a string
st = "This is a string with double spaces"
doubleSpaces = st.find(" ")
print(doubleSpaces) |
list_1 = ["apple", "banana", "orange", "peru"]
print(list_1) #['apple', 'banana', 'orange', 'peru']
print(list_1[0]) #apple
|
i_want_drink = False
i_want_food = False
# if i_want_drink :
# print ("Lets go to restaurant!")
# else :print ("I'm good")
# if i_want_drink :
# print ("Lets go to restaurant!")
# elif i_want_food :print ("I'm good")
# else :print ("nope")
if not i_want_drink :print ("Lets go to restaurant!")
|
# Evan Wiederspan
# Advanced Python Lab 7: Producer and Consumer threads
# 2-24-2017
from random import randrange
from time import sleep
from queue import Queue, Empty
from myThread import MyThread
NITEMS = 5
NREADERS = 3
WRITEDELAY = 2
finishedWriting = False
def writeQ(queue, item):
print('producing obje... |
import re
message = 'Call me on 415-555-1234 tommorow or on 415-555-9999 today'
phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phone_num_regex.findall(message)
print(mo)
""""
def is_phone_number(text):
if len(text) != 12:
return False
for i in range(0, 3):
if ... |
from math import *
from sys import stdin,stdout
def cross(v1, v2):
#return the cross product of two vectors
return (v1[0] * v2[1]) - (v1[1] * v2[0])
def angle_cmp(pivot):
''' receive a coord as the pivot and return a
function for comparing angles formed by another
two coords around the pivot
... |
def mod_pow(x,y,p):
res = 1
x = x % p
while(y > 0):
if((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x*x)%p
return res
n = int(input("Enter n : "))
c = int(input("Enter cipher text to decrypt : "))
m = int(input("Enter message to encrypt : "))
... |
# Second version of the exercise 'firstRepInList', which works for numbers
# repeated more than two times.
def firstRep(numList):
# Define counters
c1 = 0
c2 = 0
# Variables used to compare the index for each of the two iterations done.
indRep = 0
guardRep = None
for i in numList:
... |
import urllib.request,urllib.parse,urllib.error
# Request for the given url using urllib
fhand = urllib.request.urlopen('http://data.pr4e.org')
# Prepare to count the overall number of characters
char = 0
for line in fhand:
if len(line) < 1:
print('No more info to show\n')
break
# Even ... |
import numpy as np
def normalization(data):
# data is a numpy multidim array
minval=np.amin(data,axis=0) # axis=0 returns an array containing the smallest element for each column
maxval=np.amax(data,axis=0)
# Iterate over each column (feature) and compute the normalized value of ea... |
import string
ENCODING = 'UTF-8'
def remove_punctuation(in_str):
for p in string.punctuation:
in_str.replace(p, '')
return in_str
def get_words(in_str):
return remove_punctuation(in_str).split()
def find_count_words(file_name, word):
sum_w = 0
with open(file_name, 'r', encoding=ENCODI... |
# for num in range(0,100):
# if num % 15 == 0:
# print("FizzBuzz")
# elif num % 3 == 0:
# print("Fizz")
# elif num % 5 == 0:
# print("Buzz")
# else:
# print(num)
str = "create a list of first letter of every word"
lst = list()
lst = ([word[0] for word in str.split()])
pr... |
#Lists
#1:simple difference
friends = ['joe','moe','poe']
for i in range(len(friends)):
friend = friends[i]
print('Happy New Year: ',friend)
for friend in friends:
print('Happy New Year: ',friend)
#2: cal average
numlist = list()
while True:
inp = input("enter a number:")
if inp == "done" : break... |
a = {"a": 1, "b": 2}
print(a)
a.update([("c", 3)])
print(a)
a.update(dict(zip(['one', 'two'], [11, 22])))
print(a)
|
# -*- coding: utf-8 -*-
# Copyright @ 2018 HuiXin Zhao
from math import hypot
class Vector:
"""
一个简单的二维向量类
different between __repr__ and __str__:
__repr__ goal is to be unambiguous
__str__ goal is to be readable
Container’s __str__ uses contained objects’ __repr__
__bool__:
... |
"""
所有的映射类型在处理找不到的键的时候,都会牵扯到 __missing__方法。这也是这个方法称作
“missing”的原因。虽然基类 dict 并没有定义这个方法,但是 dict 是知道有这么个东西存在的。也
就是说,如果有一个类继承了 dict,然后这个继承类提供了 __missing__ 方法,那么在 __getitem__
碰到找不到的键的时候,Python 就会自动调用它,而不是抛出一个 KeyError 异常。
__missing__ 方法只会被 __getitem__ 调用(比如在表达式 d[k] 中)。提供 __missing__
方法对 get 或者__contains__(in 运算符会用到... |
# -*- coding=utf-8 -*-
#
# Copyright @ 2018 HuiXin Zhao
import bisect
# eg1:
def grade(score, breakpoints=(60, 70, 80, 90), grades='FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i]
if __name__ == '__main__':
res1 = [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
print(res1)
... |
# -*- coding: utf-8 -*-
# Copyright @ 2018 HuiXin Zhao
# 黑桃:S-Spade
# 红桃:H-Heart
# 方块:D-Diamond
# 梅花:C-Club
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
"""
通过实现 __len__和 __getitem__ 这两个特殊方法,FrenchDeck 就跟一个 Python 自
有的序列数据类型一样.同时这个类还可以用于标准库中诸如random.ch... |
# Write a function that generates ten scores between 60 and 100. Each time a score is generated,
# your function should display what the grade is for a particular score.
import random
def student_grade():
print "enter the score"
score= random.randint(1, 100)
print score
if (score<100 and score>9... |
#Write a program that prints a 'checkerboard' pattern to the console
def my_checkerboard():
list_one = ["*"," ","*"," ","*"," "]
list_two = [" ","*"," ","*"," ","*"]
for i in range(6):
print " ".join(list_one)
print " ".join(list_two)
print my_checkerboard()
|
class Animal(object):
def __init__(self,name,health):
self.name = name
self.health = health
def walking(self):
self.health -= 1
return self
def running(self):
self.health -= 5
return self
def display_health(self):
print sel... |
class MathDojo(object):
def __init__(self):
self.result = 0
def add(self,*args):
for i in args:
if type(i) == list or type(i) == tuple:
for k in i:
self.result += k
else:
self.result += i... |
import numpy as np
'''
Input Population, Distance, and Flow Arrays, compute fitness scores
from distance array and flow array. The flow is given by the indices
at the corresponding coordinates from the chromosomes. The scores
from all chromosomes are added, later to be normalized.
'''
def get_fitness_scores(population... |
# Create your first MLP in Keras
# importing libs
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import pandas as pd
# In[3]:
# fix random seed for reproducibility
seed = 7
np.random.seed(seed)
# In[3]:
# load pima indians dataset
dataset = np.loadtxt("data/pima-indians-diabetes.... |
def same (list1, list2):
list_same = [i for i in list1 + list2 if i in list1 and i in list2]
list_same = list(dict.fromkeys(list_same))
return list_same
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print ("List first: " + str(a))
print ("List second: " + str(b))
z ... |
from typing import List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
data = []
for list in lists:
while list:
data.append(list.val)
... |
# Definition for singly-linked list.
import collections
from typing import Deque
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def isPalindrome(self, head):
res = []
while head:
res.append(head.... |
class Solution(object):
def reverseString(self, s):
for i in range(int(len(s)/2)):
temp = s[i]
s[i] = s[-(i+1)]
s[-(i+1)] = temp
lst = ["h","e","l","l","o"]
app = Solution()
print(lst)
app.reverseString(lst)
print(lst)
|
def solution(msg):
answer =[]
dic = []
for i in range(26):
dic.append(chr(ord("A")+i))
start = 0
i = 1
while i<=len(msg):
if msg[start:i] in dic :
i+=1
continue
else:
dic.append(msg[start:i])
answer.append(dic.index(msg[star... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
def reverse_List(head: ListNode) -> ListNode:
curr = head
prev = next = None
w... |
from Restaurant import Restaurant
class Combo(Restaurant):
def __init__(self, name, price, comboProducts):
super().__init__(name, price)
self.comboProducts = comboProducts
#REVIEW
def showInformation(self):
print(f"\nNombre del combo: {self.name} \nPrecio: {self.price}")
... |
from simulation import BaseObject
class Warehouse(BaseObject):
def __init__(self, initial_goods=None, *args, **kwargs):
super().__init__()
if initial_goods is not None:
self.contains = initial_goods
else:
self.contains = {}
def add_good(self, good, count):
... |
age = 18
if age>18:
print('大于18岁')
elif age<18:
print('小于18岁')
else:
print('等于18岁') |
# i = 0;
# while i < 5:
# str = '*' * (i+1)
# print(str)
# i+=1
row = 1
while row<=5:
i = 1
while i<=row:
print('*',end="")
i+=1
print('') # 换行
row+=1 |
# try:
# num = int(input('输入一个整数'))
# except Exception as e:
# print(e)
def demo1():
return int(input('输入一个整数'))
def demo2():
return demo1()
try:
print(demo2())
except Exception as e:
print(e) |
import tkinter
from tkinter import ttk
# 创建主窗口
win = tkinter.Tk()
# 设置标题
win.title('title-hjl')
# 设置大小和位置
win.geometry("600x400+200+50")
# 表格
tree = ttk.Treeview(win)
tree.pack()
# 定义列
tree['columns'] = ('姓名','年龄','身高','体重')
# 设置列,不显示
tree.column('姓名',width=100)
tree.column('年龄',width=100)
tree.column('身高',width=10... |
row=1
while row<=9:
col=1
while col<=row:
ji = col * row
print("%d * %d = %d\t"%(col,row,ji),end='')
col+=1
print()
row+=1
|
import tkinter
# 创建主窗口
win = tkinter.Tk()
# 设置标题
win.title('title-hjl')
# 设置大小和位置
win.geometry("400x400+200+50")
lbv = tkinter.StringVar()
# 与BORWSE相似,但是不支持鼠标选中位置
lb = tkinter.Listbox(win,selectmode=tkinter.SINGLE,
listvariable=lbv)
lb.pack()
for item in ['good','nice','handsome','word','haha']:
# 按顺序添加
lb.ins... |
class Person:
def __init__(self,name,weight):
self.name = name
self.weight = weight
def __str__(self):
return "我的名字shi%s体重是%.2f公斤"%(self.name,self.weight)
def eat(self):
print('吃饭')
self.weight +=1
def run(self):
print('跑步')
self.weight -=0.5
wo = Person('小明',55)
wo.eat()
wo.run()
print(wo)... |
import threading
import time
def run(num):
print("子线程%s启动"%(threading.current_thread().name))
print("打印%d"%num)
time.sleep(2)
print("子线程%s结束"%(threading.current_thread().name))
if __name__ == "__main__":
# 任何进程默认会启动一个线程,称为主线程,主线程可以启动新的子线程
# current_thread() 返回当前线程的实力
print("主线程启动--%s" %(threading.cu... |
import tkinter
# 创建主窗口
win = tkinter.Tk()
# 设置标题
win.title('title-hjl')
# 设置大小和位置
win.geometry("400x400+200+50")
# <Enter> 鼠标光标进入控件时候触发
# <Leave> 鼠标光标离开控件时候触发
label = tkinter.Label(win,text='he jiao long is a good man',bg='yellow')
label.pack()
def func(event):
print(event.x)
label.bind('<Leave>',func)
# 进入消息循环... |
#These are the items in our shoping list
shopping_list = ["pants", "skateboards"]
#dictionary called "stock"
stock = {
"hoodie": 5,
"pants": 5,
"skateboards": 30,
"Wheels": 10
}
#dictionary called "prices"
prices = {
"hoodie": 1,
"pants": 15,
"skateboards": 35,
"Wheels": 5
}
#fucntio... |
# imports
import time
# calculation function
def calculate():
for i in range(0,10000):
pass
# function that calculates how long the calculation function takes
def timeFunc():
startTime = time.time()
calculate()
endTime = time.time()
print(endTime-startTime)
timeFunc() |
"""Common algorithm interviewed on that I wanted to try"""
def main():
# creating an empty list
array = []
# number of elemetns as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input("Enter element: "))
array.ap... |
from tkinter import *
from tkinter import messagebox
'''
def keyEvent(event):
messagebox.showinfo("키보드 이벤트","눌린 키 : "+chr(event.keycode))
print(event.keycode)
'''
def keyEvent(event):
if event.keycode==37:
messagebox.showinfo("키보드 이벤트","눌린 키 : shift + 아래쪽 화살표")
elif event.keycode==38:
messagebox.showinfo("키보드 이... |
import turtle
turtle.speed(4)
turtle.pensize(5)
turtle.color('black', 'pink')
turtle.begin_fill()
for i in range(4): #사각형
turtle.forward(200)
turtle.left(90)
turtle.end_fill()
turtle.penup()
turtle.goto(0, -100)
turtle.write("speed는 4, pensize 5, color는 black&pink")
turtle.forward(200)
turtle.reset() #다시 시작, 전부... |
"""
board.py
author: Colin Clement and Samuel Kachuck
date: 2016-01-15
Representation of a Bananagrams board, an unbounded square lattice
"""
from collections import defaultdict
class Board(object):
""" Representation of a Bananagram board """
def __init__(self):
self.reset()
def reset(self):... |
#This is Python. The file extension is .py
#It is used mainly as it is a general language, and can be used for lots of things
import time #This is a framework, used for adding functionality to the program
numVariable = 5 # This is a variable decleration, setting numVariable as 5
stringVariable = "Hello" # This is a ... |
timein = int(input("Введите время в секундах: "))
hour = timein // 3600
minut = timein % 3600 // 60
second = timein % 3600 % 60
if hour < 10:
hour = str(0) + str(hour)
if minut < 10:
minut = str(0) + str(minut)
if second < 10:
second = str(0) + str(second)
print(f"{hour}:{minut}:{second}") |
# Let's generalize a mutex so that multiple threads can run in the critical section at the same time.
# But we set an upper limit on the number of concurrent rheads.
import threading
multiplex = threading.Semaphore(3)
# 3 threads, we do 3 for the semaphore!
count = 0
def fun1():
global count
multiplex.acqu... |
import unittest
from myproj.array import Array
class TestArray(unittest.TestCase):
"""
Create class instance
"""
def setUp(self):
self.array = Array('1 2 3 4 10 11')
"""
Test that the result sum of all numbers
"""
def test_sum(self):
result = self.array.sum(6)
... |
import numpy as np
import matplotlib.pyplot as plt
#data
x = np.arange(0,6,0.1)
y1 = np.sin(x)
y2 = np.cos(x)
#draw graph
plt.plot(x,y1,label="sin")
plt.plot(x,y2,linestyle="--",label="cos")
plt.xlabel("x") #x축 이름
plt.ylabel("y") #y축 이름
plt.title('sin & cos') #title
plt.legend()
plt.show()
|
# -*- coding: utf-8 -*-
import numpy as np
def AND(x1,x2):
x = np.array([x1,x2])
w = np.array([0.5,0.5])
b = -0.7
# 편향 : 뉴런이 얼마나 쉽게 활성화 하느냐를 조정하는 매개변수 (theta의 이항 값)
tmp = np.sum(w*x) + b
if tmp <=0 :
return 0
else:
return 1
print AND(0,0)
print AND(1,0)
print AND(0,1)
print ... |
name = input("Please enter your name:")
bday = input("Please enter your numerical birthday (month/day):")
bdayParts = bday.split("/")
month = int(bdayParts[0])
day = int(bdayParts[1])
if (( month == 3 and day >= 21 ) or (month == 4 and day <=20)):
zodiac = "Aries"
elif((month == 4 and day >= 21) or (month == 5 and ... |
"""2D random walk simulation in pygame."""
import pygame
import random
rows = 100
w = 1200
sizeBtwn = w // rows
start_pos = (480,480)
curr_pos = start_pos
mov_opts = ((0,sizeBtwn),(0,-sizeBtwn),(sizeBtwn,0),(-sizeBtwn,0))
line_to_draw = [start_pos]
# Intializing widnow
pygame.init()
win = pygame.disp... |
a = int(input('输入年份'))
if(a%4 == 0 and a%100 != 0) or (a%400 == 0):
print("闰年")
else:
print("平年")
|
list = []
for i in range(3):
d = {}
name = input("请输入名字")
d["name"] = name
age = int(input("请输入年龄"))
d["age"] = age
sex = input("请输入性别")
d["sex"] = sex
list.append(d)
print(list)
for i in list:
for k,v in items():
print(k,v)
|
list = []
def print_menu():
print("欢迎进入点菜系统".center(30," "))
while True:
print("1:上菜")
print("2:查菜")
print("3:换菜")
print("4:撤菜")
print("5:打印菜单")
print("6:退出")
input_info()
def input_info(): # 选择
num = input("请选择功能")
if isNum(num):
num = int(num)
else:
print("输入有误")
if num == 1:
add()
elif n... |
for i in range(1,5):
for a in range(1,5):
for c in range(1,5):
if i != a and a != c and c != i:
print(i,a,c)
|
i = 1
a = 0
while i < 11:
a = 1
while a <= 2:
a+=1
a+=i
print("共花%.00%f")
|
list = [1,2,4,65,7,8,6,64,86]
for i in range(0,len(list)-1):
for j in range(i+1,len(list)):
if list[i] > list[j]:
list[i],list[j] = list[j],list[i]
print(list)
|
FOR LOOP
In [60]: for i in range(len(nba_teams)):
...: each_team = nba_teams[i]
...: print(nba_teams[i])
Lakers
Nuggets
Celtics
Clippers
In [59]: for i in range(len(nba_teams)):
...: each_team = nba_teams[i]
...: print(i)
...:
0
1
2
3
-----------------------------------------------... |
import time
timer = int(input("타이머를 입력해주세요(초 단위) : "))
for i in range(timer):
print(timer)
timer -= 1
time.sleep(1)
print("끝")
#한글 |
# Input: s = "III"
# Output: 3
# Input: s = "LVIII"
# Output: 58
# Explanation: L = 50, V= 5, III = 3
# Input: s = "MCMXCIV"
# Output: 1994
# Explanation: M = 1000, CM = 900, XC = 90 and IV = 4
# Roman numerals are usually written largest to smallest from left to right.
# However, the numeral for four is not IIII. I... |
''' Test board for Game Evaluation '''
from typing import List
# constants
ROWS = 5
COLS = 8
BOARD_H = ROWS + 2
BOARD_W = COLS + 2
# 1d array board representation
board =[9,9,9,9,9,9,9,9,9,9,
9,1,0,0,0,0,0,0,0,9,
9,0,0,0,2,2,2,0,0,9,
9,1,0,0,0,0,0,0,0,9,
9,0,0,0,0,0,0,0,0,9,
... |
# 1. Make a Class that processes Employee Details (3 employees will do)
# 2. Make a function that creates instances of that class from a Dictionary
# 3. Use the function to display the new Details
# 4* Make a new dictionary with the new values?
employees = {"Dr Pi":49000, "Bob Marshall" : 22000, "Tommy Vance" :33000}... |
class Solution:
def countOdds(self, low: int, high: int) -> int:
if high%2==0 and low%2==0:
return ((high-low)//2)
if high%2!=0 and low%2!=0:
return ((high-low)//2)+1
if high%2!=0 and low%2==0:
return (((high+1)-low)//2)
... |
num = int(input("maraton de peliculas"))
pelicula =[]
for i in range(num):
print(i+1,"duraccion de pelicula")
lista =input().split()
nombre = lista[0]
hora =int (lista[1])
minuto= int(lista[2])
pelicula.append([nombre,hora,minuto])
pass
print()
for x in range(num):
print(pelicula[x])... |
print 'hello, global..!'
x = 2
y = 0
if x != y :
print 'in if'
else :
print 'in else'
names = {'mahi', 'manu', 'siva', 'sri', 'sharu', 'kd'}
for char in names :
print char
|
"""
# Simple Thresholding -
Thresholding is a technique in OpenCV, which is the assignment of pixel values in relation to the threshold value provided. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maxi... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Savin Ilya Python Homework N9
# 6 Problem
# The sum of the squares of the first ten natural numbers is,
# The square of the sum of the first ten natural numbers is,
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Savin Ilya Python Homework N5
# -------
# Встроенная функция input позволяет ожидать и возвращать данные из стандартного
# ввода ввиде строки (весь введенный пользователем текст до нажатия им enter).
# Используя данную функцию, напишите программу, которая:
# 1. После запус... |
from tkinter import *
from functools import partial # To prevent unwanted windows
import random
class Quiz:
def __init__(self):
# Formatting variables...
self.quiz_results_list = [4, 6]
# In actual program this is blank and is populated with user calculation
self.round_results_l... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:FCQ
# datetime:2018/4/9 13:48
# software: PyCharm
#本模块包换购物车主体函数、购物记录查询函数
def shoppingcart(username,salary):
' 购物车主体函数 '
# salary = input("请输入工资:")
product_list = [
('Iphone',5800),
('mac',9800),
('bike',800),
... |
#Palindrome
def is_palindrome():
str1 = input("enter a input:")
if str1 == str1[::-1]:
print("yes palindrome")
else:
print("No palindrome")
is_palindrome() |
#if statement to determine whether a variable holding a year is a leap year.
def is_prime(year):
if year % 4 == 0 and year % 100 != 0:
print("leap2 year")
elif year % 100 == 0:
print("Not leap year")
elif year % 400 == 0:
print("leap year")
else:
print("Not lea... |
#filters out strings an returns the array filled with numbers
#First attempt
import unittest
def filter_list(l):
new_l = []
for value in l:
if isinstance(value, int):
new_l.append(int(value))
return new_l
print(filter_list([10,2,50,77,'abd','ccd',89,100]))
print(filter_list([1,2,'a','b... |
"""Short Rules
1 Arrange your ships on Grid according to FLEET table
2 Take turns firsing a salvo at your enemy, calling out squares
as "A3,B3", etc
Salvo = number of your ships you have left (use count)/1 shot(easy)
3 Mark salvos fired on "Enemy Ships" grid
"/" marks water,
"X" marks hit
4 Sink 'em al... |
# Importing the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# The table loaded is the births data
births = pd.read_csv('https://raw.githubusercontent.com/jakevdp/data-CDCbirths/master/births.csv')
# Code Below is trying to acheive something
# Please explain w... |
cases = int(input())
def SolveCase(case):
lst = [int(x) for x in input()]
string = ''
nestLevel = 0
for el in lst:
if nestLevel == el:
pass
elif nestLevel > el:
while nestLevel > el:
string += ')'
nestLevel -= 1
elif nest... |
m = float(input("Enter the month"))
d = float(input("Enter the day"))
y = float(input("Enter the year"))
y0 = y - (14 - m) // 12
x = y0 + y0//4 - y0//100+ y0//400
m0 = m + 12 * ((14 - m) // 12) - 2
d0= (d + x + (31*m0)//12) % 7
print ("The day of the week is:", d0)
|
def merge_sort(start, end, nums):
if start > end:
return
if start == end:
return nums[start]
mid = (start + end) / 2
merge_sort(start, mid, nums)
merge_sort(mid+1, end, nums)
merge(start, end, mid, nums)
def merge(start, end, mid, nums):
temp = [0] * (end-start+1)
index1 = start
index2 = mid+1
list1_siz... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def find_mid(self, head):
if not head:
return None
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next... |
class Solution(object):
def change(self, amount, coins, level):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
level += "-"
ways = 0
if amount == 0:
return 1
if amount < 0:
return 0
for c in coins:... |
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
slow, fast = head, head.next
while fast and fast.next:
if slow == fast:
break
slow ... |
def permutation(numstr):
rst = []
level = []
dfs(rst, level, numstr)
return rst
def dfs(rst, level, numstr):
if len(level) == len(numstr):
rst.append(level[:])
for s in numstr:
if s.lower() in level or s.upper() in level:
continue
level.append(s.lower())
... |
#I am creating an array signifyig the board.
class board():
def __init__(self):
self.board=[[0 for l in range(32)] for j in range(30)]
#returns 1 if the block can occupy else 0.
def checkpiecepos(self,x,y,array):
for i in range(x,x+4):
for j in range(y,y+4):
if(ar... |
#Sawyer Paeth
#Due Dec. 7th
#CS 325 Portfolio Project - Sudoku Solver
def checkRow(board, row):
seenArr = [] #Creates empty array to track non empty squares
for i in range(0, 9):
if board[row][i] in seenArr: #return false if repeat is found
return False
if... |
#!/usr/bin/env python
import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6,7]
x1 = [8,9,10,11]
y = [0,1,2,3,5,6,7,8]
y1 = [9,10,11,12]
x2 = [2,23,45,68]
def main():
plt.plot(x, y, 'go-', label = 'Test1', antialiased = False)
lines = plt.plot(x1,y1, 'b*-', label = 'Test2')
plt.setp(lines)
plt.xlabel('Testx')
plt.y... |
#!/usr/bin/env python3
import random
board = []
board_ends = []
player_pos = []
monster_type = ''
x = 0
y = 0
#print menu at beginning
def menu():
print('> Welcome to the game!')
choose_board()
choose_monster()
def choose_board():
choose_dim = input('> Default board dimensions is 3x3. Press Y for default or... |
#!/usr/bin/env python3
from queue import Queue
class BinaryTree:
def __init__(self, value):
self.value = value
self.left_node = None
self.right_node = None
def insert_left(self, value):
if self.left_node == None:
self.left_node = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.lef... |
def dp_make_weight(egg_weights, target_weight, memo = {}):
new_eggs = egg_weights
if target_weight in memo:
return memo[target_weight]
elif len(new_eggs) == 1:
result = target_weight
elif new_eggs[-1] > target_weight:
result = dp_make_weight(new_eggs[:-1], target... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.