text stringlengths 5 121k |
|---|
"""
Functions for calculating various gaze/eye-tracking related statistics.
"""
import numpy as np
def cross_correlation(person1, person2, framerate=25, constrain_seconds=2):
"""
Calculate cross-correlation between two gaze signals.
This function takes 2 lists/arrays of data, each containing an individu... |
import re
import json
from pprint import pprint
import itertools
import sys
if len(sys.argv) != 3:
print("Usage: {0} <path-to-datafiles> <format>".format(sys.argv[0]))
exit(1)
datapath = sys.argv[1]
format_name = sys.argv[2]
decks = []
cards_seen = []
num_decks_card_seen_in = {}
num_decks_combo_seen_... |
class Solution(object):
def DFS(self,target, root, li):
if not root: return None
if root is target:
return li+[root]
else:
left=self.DFS(target, root.left, li+[root])
if left is None:
right=self.DFS(target, root.right, li+[root]... |
class Solution(object):
def DFS(self,root,li,sum):
"""
More clear way
if not root.left and not root.right:
if root.val==sum:
self.li.append(li+[root.val])
sum-=root.val
if root.left:self.DFS(root.left, [root.val]+li,sum)
if root.righ... |
import cv2
import numpy as np
def contour_area(input_image, save_path, calibration):
img = cv2.imread(input_image, cv2.IMREAD_UNCHANGED)
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
thresh = 100
ret,thresh_img = cv2.threshold(img_grey, thresh, 100, cv2.THRESH_BINARY)
contou... |
avar, bvar = 12.0, 2
str1 = "Hello"
str2 = "World"
int1 = 12
cvar = avar + bvar
print (str1 + " " + str2)
print (avar)
print (float(bvar))
print ("result {w1} {w2}".format(w2 = str1, w1 = str2))
ls = [12, "non", 235]
print(ls[0])
print(ls[2])
print(ls[1])
print(7 ** 2)
print(2 ** 3)
shitTon ="SHIT" * 100
print(... |
class D:
def __init__(self,lst):
self.lst=lst
def __getitem__(self, item):
return self.lst[item]
def __setitem__(self, key, value):
self.lst[key]=value
def __delitem__(self, key):
self.lst.pop(key)
d=D([11,22,"aa","cc"])
print(d[0])
d[3]... |
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
print("执行__str__方法")
return "学生的名字是%s,年龄是%s" %(self.name,self.age)
s1=Student("wdd",25)
print("学生:%s" %s1) |
str=input().strip()
n=int(input())
if n>len(str):
print(-1)
else:
for i in range(n,len(str)):
print(str[i-n:i],end=" ") |
"""
冒泡排序
"""
def bubbleSort(array):
for i in range(len(array)-1):
for j in range(0,len(array)-1-i):
if array[j]>array[j+1]:
array[j],array[j+1]=array[j+1],array[j]
array=[2,1,5,6,3,4,9,8,7]
bubbleSort(array)
print(array) |
str1=input()
str2=input()
same_str=[]
for item in str1:
if item in str2:
same_str.append(item)
sam_str=""
for item in same_str:
sam_str+=item
tmp_str1=""
tmp_str2=""
for item in str1:
if item in sam_str:
tmp_str1+=item
for item in str2:
if item in sam_str:
tmp_str2+=item
print(... |
from multiprocessing import Pipe
from multiprocessing import Process
from multiprocessing import Lock
import time
def producer(p,l):
parent, son=p
son.close()
for i in range(10):
parent.send('hello'+str(i))
parent.close()
def consumer(p,l,name):
parent, son = p
parent.close()
while... |
class A:
pass
class B(A):
pass
b=B()
print(type(b) )
print(type(b) is B)
print(isinstance(b,B))
print(isinstance(b,A))
print(issubclass(B,A))
print(issubclass(A,B)) |
n=int(input())
def fun(n):
if n==1:
return 1
if n==2:
return 2
return fun(n-2)+fun(n-1)
for i in range(n):
test_n=int(input())
print(fun(test_n)) |
def merge(seq,low,mid,height):
"""合并两个已排序好的列表,产生一个新的已排序好的列表"""
left = seq[low:mid]
right = seq[mid:height]
k = 0
j = 0
result = []
while k < len(left) and j < len(right):
if left[k] <= right[j]:
result.append(left[k])
k += 1
els... |
import math
x = (1, 2, 3, 4, 5, 6, 7, 8, 9, "maine", False, None)
y = int(input())
x += (y, )
print(x)
print(hash(x))
z = str(x)
print(type(z))
print(z)
print(x[4])
print(x[-4])
z = str(list(x))
print("aci ii o lista" + str(type(z)))
z = tuple(x)
print("Aci ii un tuple" + str(type(z)))
a =... |
from tkinter import *
master = Tk()
'''
Scale
tickinterval=5 # 刻度表
resolution=5 # 精度 == 步长
length=200 # 长度
'''
s1 = Scale(master, from_=0, to=40, tickinterval=5, length=200)
s1.pack()
s2 = Scale(master, from_=0, to=200, orient=HORIZONTAL, resolution=15, length=600)
s2.pack()
def show():
pr... |
import random
class Game:
gui = 1
fish = 10
fish_move = 1
gui_tili = 100
def __init__(self):
print("Game start......")
self.guidict = dict()
self.guidict.setdefault("gui")
self.guidict['gui'] = [random.randint(0,10), random.randint(0,10)]
sel... |
class Stack:
def __init__(self):
self.s = "fishc"
def isEmpty(self):
if self.s:
return True
else:
return False
def push(self, x):
self.s = str(x) + self.s
print(self.s)
def pops(self):
one = self.s[0]
self.s ... |
import time as t
class Time:
def __init__(self, func, number=100000):
self.begin = 0
self.end = 0
self.prompt = "未开始计时"
self.default_time = t.perf_counter
self.func = func
self.number = number
def __str__(self):
return self.... |
'''
TKinter
'''
import tkinter as tk
class App:
def __init__(self, master):
frame = tk.Frame(master)
frame.pack(side=tk.LEFT, padx=10, pady=10)
'''
tk.Button(frame, text=按钮内容, fg=前景色, bg="背景色", command=按钮被点击时做的动作)
'''
s... |
from tkinter import *
root = Tk()
w = Canvas(root, width=200, height=100)
w.pack()
rect1 = w.create_rectangle(40, 20, 160, 80, dash=(4, 4))
arc = w.create_oval(40, 20, 160, 80, fill="pink")
t = w.create_text(100, 50, text="python")
arc = w.create_oval(70, 20, 130, 80, fill="green")
root.mainloop() |
class Demo:
def __getattr__(self, name):
return "该属性不存在"
class Demo2:
'''
def __init__(self):
self.x = "king"
def __getattr__(self, name):
return super().__getattr__(name)
def __setattr__(self, name, value):
return super().__setattr__(name, value)
... |
'''
Tk PanedWinow
'''
from tkinter import *
m = PanedWindow(orient=VERTICAL)
m.pack(fill=BOTH, expand=1)
top = Label(m, text="top paned")
m.add(top)
bottom = Label(m, text="bottom pane")
m.add(bottom)
mainloop()
|
import logging
import pdb
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s - %(msg)s")
class Solution:
def pseudoPalindromicPaths (self, root):
if not root: return 0
digits = [ 0 for _ in range... |
"""
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
"""
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
total = 0
rList = list()
for i in range(len(nums)):
n = num... |
"""
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum numbe... |
def get_formatted_name(first_name, last_name, middle_name=''):
if middle_name:
full_name = first_name + " " + middle_name + " " + last_name
else:
full_name = first_name + " " + last_name
return full_name.title()
def get_formatted_name2(first_name, last_name, middle_name=''):
if middle_... |
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
motorcycles.append('haha')
print(motorcycles)
bicycles = []
bicycles.append('honda')
bicycles.append("yamaha")
bicycles.append('suzuki')
print(bicycles)
bicycles.insert(0, 'ducati')
print(bicycles)
del bicycles[0... |
from __future__ import annotations
from dataclasses import dataclass
def _calculate_bmi(weight: float, height: float) -> float:
return round(weight / (height ** 2), 1)
def _get_bmi_result(bmi: float) -> str:
if bmi < 18.5:
result = "痩せ型"
elif (bmi >= 18.5) and (bmi < 25):
result = "標... |
"""
Created on Thu Sep 22 20:15:32 2016
@author: wang_wei52
"""
import pandas as pd
from sklearn import linear_model
def get_data(filename):
data = pd.read_csv(filename)
x_parameter = []
y_parameter = []
for single_square_feet, single_price_value in zip(data['square_feet'], data['price']):
... |
n = int(input("Enter number "))
for i in range(1,n+1):
for j in range(1,n+1):
print(n+1-j,end = ' ')
print() |
for i in range(5):
print("*",end =" ") |
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
print("Welcome to the Secret Auction \n" + '''
___________
\ /
)_______(
|"""""""|_.-._,.---------.,_.-._
| ... |
import tkinter
window = tkinter.Tk()
window.title("Miles to Kilometers Converter")
window.config(padx = 50, pady=50)
input = tkinter.Entry()
input.grid(column=1, row=0)
miles_label = tkinter.Label(text = "Miles")
miles_label.grid(column = 2, row=0)
equal_label = tkinter.Label(text = "is equal to")
equal_label.grid(... |
import random
import Art
print("Let's play rock (R), paper (P), scissors (Sc), lizard (L), spock (Sp)!")
user_choice = input("What do you choose? \n")
choices = ["R", "P", "Sc", "L", "Sp"]
computer_choice = choices[random.randint(0,4)]
if user_choice == "R":
print("You chose \n" + Art.rock)
elif user_choice == "... |
s=input()
c=0
for d in range(0,len(s)):
if s[d].isnumeric() or s[d].isalpha():
c=c+1
a=len(s)-c
print(a)
|
length = int(input("how many level do you want: "))
space = 1 + (length - 1)*(2)
for h in range(length + 1):
if h == 0:
inst_level = 0
level_length = length
element = "^"
part = 1 + (inst_level)*(2)
elif h == length:
inst_level = length // 2
level_leng... |
import time
from itertools import zip_longest
def main():
print(vertical_strings(bcd(time.strftime('%H%M%S'))).replace('1', '${color4}◍${color}').replace('0', '○').replace('2', '${color2}◍${color}').replace('3', '${color7}◍${color}'))
def bcd(digits):
def bcdigit(d):
return bin(d)[2:].... |
'''Greet'='This is a variable statement'
print(Greet)'''
print('We are learning python scripting and practice the same in pycharm And Varibales ')
'''[A-Za-z _]
[AnyEnlishWords and _]'''
variable = 1000
_another = 2000
CONSDATA=3.14
a,b,c,d=10,20,30,40
print("Value of c is : ",c)
print(a,... |
class User:
def __init__(self, user_id, username):
self.id = user_id
self.username = username
self.followers = 0
self.following = 0
def follow(self, user):
user.followers += 1
self.following += 1
user_1 = User("001", "adrien")
user_... |
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if (needle=="" or haystack==needle):
return 0
substrs=dict()
strlen=len(needle)
haylen=len(haystack)
if(st... |
def palindromic(string):
letters = dict()
count = 0
for s in string:
letters[s]+=1
for key in letters:
if (letters[key]%2)==1:
count+=1
if count <=1:
return true
return false
|
class State:
def __init__(self):
pass
class StateOne(State):
def __init__(self):
self.name = 'State One'
def run(self, event):
return
def entry(self, event):
return
def exit(self, event):
return
class StateTwo(State):
def __init__(self):
self.na... |
from abc import ABC, abstractmethod
class View(ABC):
def __init__(self, game):
self.game = game
@abstractmethod
def open(self, game_controller):
pass
@abstractmethod
def show_player_turn_start(self, name):
pass
@abstractmethod
def show_player_turn_end(self, nam... |
import random
print()
def rolls():
roll1 = random.randint(25, 55)
roll2 = random.randint(25, 55)
roll3 = random.randint(25, 55)
roll4 = random.randint(25, 55)
return roll1, roll2, roll3, roll4
a, b, c, d = rolls()
if a + b >= 100:
print(f"Crystal 1: {a}%")
print(f"Crystal 2: {b}%")
... |
def dimensoes(matriz):
x = len(matriz)
for item in matriz:
y = 0
y = y + len(item)
print(str(x) + "X" + str(y))
|
'''
Closure(閉包)
- 寫法特殊請注意
- 在 A 函式中再定義一個 B 函式。
- B 函式使用了 A 函式中的變量。
- A 函式返回 B 函式名。
閉包的使用時機
- 閉包避免了全域變數的使用,並可將資料隱藏起來。
- 當你有一些變數想要定義一個類別封裝起來時,若這個類別內只有一個方法時,使用閉包更為優雅
Reference:
- https://medium.com/@zhoumax/python-%E9%96%89%E5%8C%85-closure-c98c24e52770
- https://www.pythontutorial.net/... |
'''
coroutines using yield.
Reference:
- https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb
'''
def print_name(prefix):
print('searching prefix: ', prefix)
try:
while True:
print('yield: ', (yield))
name = (yield... |
'''
使用 multiple-processing 範例
Reference:
- https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb
'''
from multiprocessing import Process
def print_country(country='Asia'):
print('The name of country is: ', country)
def not_args():
p = Process(ta... |
"""
List sorting.
- sorted: 原本的 list 則不受影響
- sort: 改變原本的 list 內容
- sorted(x, revere=True) 反向排序
- itemgetter(), attrgetter()
Reference:
- https://officeguide.cc/python-sort-sorted-tutorial-examples/
"""
from operator import itemgetter, attrgetter
scores = [
('Jane', 'B', 12),
('John', 'A', ... |
'''
downloading file 範例: (使用 multi-thread class寫法)
- 使用兩個下載任務,有使用 multi-thread,任務會放到不同的 thread 中同時啟動,總共耗費時間將會是某項最長結果。
- 請跟 use_multi-processing 範例進行比較。
- 此範例使用兩個 thread 來執行,以及各實作 class-based and function-based 方式。
- 多 thread 程式可以共享記憶體資源
Reference:
- https://github.com/jackfrued/Python-100-Days... |
crypto_list = ['george', 'peter', 'mary']
crypto_str = ', '.join(crypto_list)
print('crypto_str: ', crypto_str)
poem = '''all that doth flow we cannot liquid name Or else \
would fire and water be the same;
But that is liquid which is moist and wet
Fire that property can never get.
... |
"""
References:
- https://www.runoob.com/python/python-func-filter.html
- https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640
- https://wiki.jikexueyuan.com/project/explore-python/Advanced-Features/iterator.html
"""
import math
from collections import Iterable
def is_iterator(lst):
ret... |
"""
References
- https://docs.python.org/3.6/library/asyncio-task.html
"""
import asyncio
async def compute(x, y):
print(f"compute {x} + {y} .........")
await asyncio.sleep(3)
return x+y
async def sum(x, y):
res = await compute(x, y)
print(f"{x} + {y} = {res}")
if __name__ == '__main__':
l... |
"""
How to use classmethod in Python?
Reference:
- None
"""
import os
class InputData(object):
""" interface class. """
def read(self):
raise NotImplementedError('the read() must be overridden.')
class PathInputData(InputData):
""" concrete subclass. """
def __init__(self, path):
... |
'''
Reference:
- https://foofish.net/python-decorator.html
'''
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
''' [Example 1] This is decorator without parameters. '''
def use_logging(func):
def wrapper():
logging.debug('{} is running'.format(func.__name__))
return ... |
'''
最大工因數、最小公倍數
- 最大工因數: 找出都可以整除於兩個數,最後將這些數字相乘
- 最小公倍數: 找出都可以整除於兩個數,最後全部數相乘。
Reference:
- https://github.com/jackfrued/Python-100-Days/blob/master/Day01-15/06.%E5%87%BD%E6%95%B0%E5%92%8C%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8.md
- https://www.youtube.com/watch?v=IikEWljfL94
'''
def gcd(x,... |
'''
生成器產生偶數
- 動態產生可疊代的資料,搭配 for 迴圈使用。
- 使用 yield 語法,呼叫時回傳生成器。
Reference:
- https://www.youtube.com/watch?v=x6MNOSRY5EM&t=4s
'''
def generate_even(max):
number = 0
while number < max:
yield number
number += 2
evenGenerator = generate_even(20)
for data in evenGenerator:
print(... |
'''
Defining generic classes 定義一個 generic class
- Stack 泛型範例
- TypeVar
- Generic
首先不能使用 Any, 因為這樣無法讓函式可以除錯,return值可以式任何 type。
因此,我們就需要定義好 input/output 的 type,方便我們可以確認。但是直接定義 int, str, ...等,會讓程式變得 scale 很差。
解決的辦法就是使用 type variables:
- Type variables allow you to link several types together.
- T... |
'''
實體方法(Instance Method)
- 至少要有一個self參數
- 實體方法(Instance Method) 透過self參數可以自由的存取物件 (Object)的屬性 (Attribute)及其他方法(Method)
Reference:
- https://www.learncodewithmike.com/2020/01/python-method.html
'''
class Cars:
def drive(self):
print('Drive is instance method.')
c = Cars(... |
"""
Anonymous function. (匿名函數)
- map
- filter
- reduce
lambda程式撰寫方式:
- lambda arguments: expression
map程式撰寫方式:
- map(function, iterable(s))
- 抓取符合的元素。
filter程式撰寫方式:
- filter(function, iterable(s))
- 用來過濾序列,過濾掉不符合的元素。
reduce程式撰寫方式:
- reduce(function, sequence[, initial])
- 對序列... |
'''
http://openbookproject.net/thinkcs/python/english3e/functions.html
'''
import turtle
def draw_square(t, sz):
for i in range(8):
t.forward(sz)
t.right(45)
def draw_multiple_square(t, sz):
for i in ['red', 'purple', 'hotpink', 'blue']:
t.color(i)
t.forward(sz)
t.left... |
def square(x):
return x ** 2
def add(x):
return x + 10
def use_map(fn, lst):
return list(map(fn, lst))
if __name__ == '__main__':
arr = [1, 2, 3, 6]
res = use_map(square, arr)
print(res)
res1 = use_map(add, arr)
print(res1)
|
'''
學習如何使用 queue + threads
Reference:
- https://blog.gtwang.org/programming/python-threading-multithreaded-programming-tutorial/
'''
from threading import Thread
import time
import queue
class Worker(Thread):
def __init__(self, queue, num):
Thread.__init__(self)
self.queue = queue
se... |
'''
List comprehension
- 學習不同寫法
Reference:
- https://www.youtube.com/watch?v=SNq4C988FjU
'''
import time
fruits = ['apples', 'bananas', 'strawberries']
def list_used_direct():
for fruit in fruits:
fruit = fruit.upper()
print(fruits)
def use_new_list():
new_fruits = [... |
'''
specific method
- __str__() and __repr__()
- __repr__() magic method returns a printable representation of the object.
- The __str__() magic method returns the string
Reference:
- https://www.geeksforgeeks.org/python-__repr__-magic-method/?ref=rp
'''
class GFG:
def __init__(self, name):
... |
'''
如何破解Python private members
Reference:
- https://medium.com/citycoddee/python%E9%80%B2%E9%9A%8E%E6%8A%80%E5%B7%A7-1-private-member-on-python-fb5678b02582
'''
class Animal:
def __init__(self):
self.__alive = True
self.__age = 0
def __print_something(self):
print('call _... |
import urllib.request
import json
import matplotlib.pyplot as plt
base_url = 'https://www.quandl.com/api/v3/datasets/WWDI/UKR_NY_GDP_MKTP_CD.json?api_key=2jhCWecEKmuxzVY9ifwp'
def get_ukraine_gdp(url):
"""
Gets Ukraine's GDP from quandl in US dollars
:param url: str
:return: dict
"""
... |
import sys
from itertools import islice, count
def sequence():
"""Generate Racaman's sequence."""
seen=set()
a=0
for n in count(1):
yield a
seen.add(a)
c = a-n
if c<0 or c in seen:
c = a + n
a=c
def writeseqeunce(filename, num):
f = open(filename, mode='wt', encoding='utf-8')
f.writelines("{0}\n".f... |
from collections import defaultdict
def contains(sorted_word, sorted_candidate):
wchars = (c for c in sorted_word)
for cc in sorted_candidate:
while(True):
if wchars < cc: continue
if wchars == cc: break
return False
return True
d = defaultdict(list)
with open(r"C... |
'''
Time Complexity: O(nlogN)
- Sort O(nlogN)
- Sweep O(n)
Better choice: Use Hash Table
Not to use: Brute force (Not Accepted as the time complexity is O(n^2))
'''
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
for i in range(len(nums) - 1):
if nums[i... |
import argparse
def get_args():
parser = argparse.ArgumentParser(description='Gashlycrumb', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('letter', help='Letter(s)', metavar='letter', nargs='+', type=str)
parser.add_argument('-f','--file', help='Input file', metavar='FILE',
... |
import argparse
def get_args():
parser = argparse.ArgumentParser(description='Dictionary',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
args = parser.parse_args()
return args
def main():
args = get_args()
my_set = {1, 2, 3}
print(my_set)
my_set = {1.0, "Hello", (1, 2, 3)}
pri... |
import argparse
def get_args():
parser = argparse.ArgumentParser(description="Jump the Five",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='str', help='Input text')
return parser.parse_args()
def main():
args = get_arg... |
def triangle_type(a, b, c):
x,y,z = sorted([a,b,c])
if (x+y)<=z:
return 0
if (x*x+y*y==z*z):
return 2
if z*z > (x*x + y*y):
return 3
return 1 |
def alphabet_position(text):
s=""
for x in text:
if (ord(x) >= ord('a') and ord(x) <= ord('z')):
s+= (str(ord(x)-ord('a')+1)+" ")
if (ord(x) >= ord('A') and ord(x) <= ord('Z')):
s+= (str(ord(x)-ord('A')+1)+" ")
return s[:-1] |
def binary_search(arr, x):
return search(arr, x, 0, len(arr)-1)
def search(arr, x, low, high):
if low > high:
return -1
mid = int(low + (high-low)/2)
if arr[mid] > x:
return search(arr, x, mid+1, high)
elif arr[mid] == x:
return mid
else:
return search(arr, x, lo... |
class Emp:
empCount=0
def __init__(self, name, salary):
self.name=name
self.salary=salary
Emp.empCount += 1
def displayCount(self):
print ('Total Employees %d' % Emp.empCount)
def dispEmp(self):
print('Name:',self.name,' Salary:',self.salary)
emp1=Emp('Vjti',200... |
list1 = ['apple', 'banana', 'mango']
for word in list1:
if word == 'banana':
print(word)
for i in range(3):
print(list1[i])
for j in range(5,9, 2):
print(j) |
from tkinter import *
class MyApp(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widget()
def create_widget(self):
self.instruction_label = Label(self, text = "Only authorised person are allowed.")
self.instruction_label.grid(row=... |
x=10
y=20
print('x+y = ',x+y)
print('x-y = ',x-y)
print('x*y = ',x*y)
print('x/y = ',x/y)
|
def get_optimal_value(capacity, weights, values):
value = 0.
return value
data = list(map(int, input().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
print (n,capacity,values, weights)
|
def practica():
goleadores_2014 = {"Muller": ("Alemania", 5),
"Dempsey": ("USA", 2),
"James": ("Colombia", 6),
"Muller": ("Alemania", 5),
"Schurrle": ("Alemania", 3),
"Messi": ("Argentina", 4),
... |
def reverse(list):
if len(list) < 2:
return list
else:
print(f"list{list[1:]}, {list[0]}")
return reverse(list[1:]) + [list[0]]
teste = reverse([1, 2, 3, 4, 5])
print(teste) |
from password import Password
def main():
password = Password()
while True:
passGuess = input('Enter password: ')
password.setPassword(passGuess)
if password.isValid() is True:
print('Valid Password')
else:
print('Invalid Password\n', password... |
from tkinter import *
def ventana():
window = Tk()
window.title("Tkinter")
window.geometry('350x200')
lbl = Label(window, text="Introduce un número")
lbl.grid(column=0, row=0)
result = Label(window,text="")
txt = Entry(window,width=10)
txt.grid(column=1, row=0)
result.grid(colu... |
def fibonacci(number):
if number == 0 or number == 1:
return number*number
else:
return fibonacci(number - 1) + fibonacci(number - 2)
def product_fib_num(product):
"""
Returns a list of the two consecutive fibonacci numbers
that give the provided product and a boolean indcating if
... |
import numpy as np
import scipy as sp
from scipy import stats
import matplotlib.pyplot as mpl
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
slope,intercept,r,p,std_err = stats.linregress(x,y)
... |
number = int(input('Please enter a number that all odds and even numbers can be sumec upto: '))
odd_total = 0
even_total = 0
for n1 in range(1, (number + 1), 2):
odd_total += n1
for n2 in range(2, (number + 1), 2):
even_total += n2
print('The Sume of even Numbers upto {} is ={} and sum of even is ={}'.form... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style
style.use('ggplot')
web_stats = {'Day': [1, 2, 3, 4, 5, 6],
'Visitors': [43, 53, 34, 45, 64, 34],
'Bounce_Rate': [65, 72, 62, 64, 54, 66]}
df = pd.DataFrame(web_stats)
'''
print(df)
print(d... |
marca = input('Digite a marca da cerveja: ')
tipo = input('Digite o tipo da cerveja: ')
cervas = {}
cervas['marca'] = marca
cervas['tipo'] = tipo
cervas2 = {'marca':marca, 'tipo':tipo }
print(cervas)
print(cervas2)
|
import vindinium
client = vindinium.client()
client.setKey('your_key')
client.setParam('mode', 'training')
client.startGame()
while not client.game.finished:
client.makeMove('dir')
print(client.game.results())
client.close()
|
"""Add integer module."""
def add_integer(a, b=98):
"""
Add integer function.
@a: integer or float to be added.
@b: integer or float to be added (default set to 98).
Returns the result of the sum.
"""
if not isinstance(a, int) and not isinstance(a, float):
raise TypeError('a must... |
"""Only a sub class of module"""
def inherits_from(obj, a_class):
"""Returns True if obj is an instance of a class that inherited
from a_class; False otherwise"""
return (type(obj) is not a_class and isinstance(obj, a_class))
|
"""MyInt class Module"""
class MyInt(int):
"""Class MyInt that inherits from int"""
def __eq__(self, other):
"""Inverts == and !="""
return not super().__eq__(other)
def __ne__(self, other):
"""Inverts == and !="""
return not self.__eq__(other)
|
def letterFrequency(phrase):
string1 = ".,;:!? "
for i in string1:
phrase = phrase.replace(i,"")
phrase = phrase.lower()
phrase = [i for i in phrase]
phrase.sort()
dictionary = {}
for letter in phrase:
if letter not in dictionary:
dictionary[letter] = 1
el... |
def binaryToInt(binary_string):
binary = [character for character in binary_string]
binary.reverse()
x = 0
base_ten_number = 0
for i in binary:
base_ten_number = base_ten_number + (2 * int(i)) ** x
x = x + 1
return base_ten_number
def main():
binary_string = str(input("Input... |
def rankandSuitCount(hand):
card_rank = {}
card_suit = {}
for card in hand:
if card[0] not in card_rank:
card_rank[card[0]] = 1
else:
card_rank[card[0]] += 1
if card[1] not in card_suit:
card_suit[card[1]] = 1
else:
card_suit[ca... |
from turtle import *
import tkinter.messagebox
import tkinter
window = tkinter.Tk()
canvas = ScrolledCanvas(window,600,600,600,600)
t = RawTurtle(canvas)
screen = t.getscreen()
screen.setworldcoordinates(-500,-500,500,500)
frame = tkinter.Frame(window)
frame.pack()
window.title("What kind of farm do you have?")
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.