text stringlengths 37 1.41M |
|---|
#echo function
def echo(self, args):
out = ''
for word in args:
out += word+' '
print(out)
#function reference, min args, max args, help info, case sensitive?, function name
func_alias = 'echo'
func_info = (echo,
0,
-1,
'Prints all arguments back to the user.'... |
#!/usr/bin/env python
import auth
import argparse
def get_playlist(playlist_name, spotify_client, username):
for playlist in spotify_client.spotify.user_playlists(username)['items']:
if playlist['name'] == playlist_name:
print "Playlist gia esistente"
return playlist
#Playlist not present, so create it
pri... |
# 7. Create a list of tuples of first name, last name, and age for your friends
# and colleagues. If you don't know the age, put in None. Calculate the
# average age, skipping over any None values. Print out each name,
# followed by old or young if they are above or below the average age.
list_=[]
tuple_1=('sita ','Dah... |
# 2. Write an if statement to determine whether a variable holding a year is
# a leap year.
a=int (input("enter input:"))
if a%4==0 and a%100 !=0:
print(a," is leap year")
elif a%100==0:
print(a,'is not leap year')
elif a%4==0:
print(a,"is leap year")
else:
print("given year is not leap year") |
# coding=utf-8
from decimal import Decimal
INFINITY = float('Infinity')
class Node:
def __init__(self, label):
self.label = label
class Edge:
def __init__(self, to_node, length):
self.to_node = to_node
self.length = length
class Graph:
def __init__(self):
self.nodes = ... |
import unicodedata
def remove_accented_chars(text):
text = unicodedata.normalize('NFKD',text).encode('ascii','ignore')\
.decode('utf-8','ignore')
return text
#The normal form KD (NFKD) will apply the compatibility decomposition, i.e. \
# replace all compatibility characters with their equivalents.
ac... |
def is_isogram(string):
string = string.lower()
ns = "".join(c for c in string if c.isalpha())
return len(ns) == len(set(ns))
|
# Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and
# 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
# Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, left, right):
self.val = x
self.left = left
self.right = right
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
print root.val, ": ", self.va... |
"""
use Counter
88 ms
"""
from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
return [pair[0] for pair in Counter(nums).most_common(k)]
if __name__ == '__main__':
s = Solution()
print s.topKFrequent([1, 1... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
def recurse(nums):
if not nums:
return None
... |
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
i = 1
j = n
... |
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
next_board = [[cell for cell in row] for row in board]
m = len(board)
n = len(board[0])
for i in range(m):
for j in range(n):
cell = ... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# iterative
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None: return None
if head.next == None: return head
prev = Non... |
class DoublyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def push(self, node):
"""
push to the end of list
"""
if self.tail != None:
self.tail.next = node
node.prev = self.tail
self.tail = node
... |
'''
Brute Force + Memoize
Time: O(n)
Space: O(n)
'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
self.d = dict()
return self.climb(0, n)
def climb(self, i, n):
if i in self.d:
return self.d[i]
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
return "N({})".format(self.val)
def traverse_inorder(self):
if self == None:
return
traverse_inorder(self.left)
print self.val
traverse_inorder(self.right)
def addNode(root, treeno... |
class Vector2D(object):
def __init__(self, vec2d):
"""
Initialize your data structure here.
:type vec2d: List[List[int]]
"""
# self.size = sum([sum([1 for x in row]) for row in vec2d])
assert(len(vec2d) != 0)
self.m = vec2d
self.i = 0
self.j =... |
# Definition for a binary tree node.
class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def __init__(self, x, left, right):
self.val = x
self.left = left
self.right = right
def __str__(self):
return "N({})".format(self.val)
class Stack(obje... |
from heapq import heapify, heappop
class Task:
def __init__(self, s, e, order):
self.s = int(s)
self.e = int(e)
self.order = order
self.assignee = None
def __lt__(self, other):
if self.s != other.s:
return self.s < other.s
return self.e < other.e
... |
# -*- coding: utf-8 -*-
from com.salesianostriana.sge.cifrado_cesar.utiles_cifrado import *
opcion = -1
texto = ""
while(opcion != 0):
opcion = int(input("\nOPCIONES"
"\n--------"
"\n1. Encriptar texto"
"\n2. Desencriptar texto"
... |
import Weapon
from Weapon import weapon_list
class Character:
#создает игрока и дает ему базовые функции
def __init__(self):
self.health = 100
self.armor = 0
self.money = 6000
self.height = 1
self.speed = 2
self.noise = 1
self.ammunition = 0... |
#要求三:演算法 找出至少包含兩筆整數的列表 (Python) 或陣列 (JavaScript) 中,兩兩數字相乘後的最大值。
#由大到小排序,找出最大值跟第二大值的數,再讓它們相乘。
def maxProduct(nums):
re_nums = sorted(nums, reverse = True)
result = re_nums[0] * re_nums[1]
print("兩兩相乘的最大值為: ", result)
# 請用你的程式補完這個函式的區塊
maxProduct([5, 20, 2, 6]) # 得到 120 因為 20 和 6 相乘得到最大值
maxProduct([10, -20, 0... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 1 13:31:44 2019
@author: ashutosh.k
{ 25 Projects } Fashion MNIST
Fashion MNIST Classification using Keras
"""
from __future__ import print_function
import keras
from keras.datasets import fashion_mnist
from keras.models import Sequential
from... |
with open("newfile.txt") as f:
print(f.read())
"""
file = open("newfile.txt","r")
print(file.read())
file.close()
"""
"""
An alternative way of doing this is using with statements.
This creates a temporary variable (often called f),
which is only accessible in the indented block of the with statement.
with open(... |
from typing import Iterable, List, Any
__all__ = ['Language']
class Language(object):
"""
Represents a programming language that is supported by boggart.
"""
@staticmethod
def from_dict(d: dict) -> 'Language':
assert 'name' in d
assert 'file-endings' in d
assert isinstance... |
import math
class Matrix:
def __init__(self, matrix, name):
self.name = name
self.setmatrix(matrix)
self.len = [len(self.matrix), len(self.matrix)]
def copy(self):
matrix = []
for row in self.matrix:
r = []
for item in row:
r.appen... |
#!/usr/bin/env python
# coding: utf-8
# The excel file used is found at:
# http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/tvds/frames/frame.html
#
# According to the website description, a random sample of male/female assitant professor pairs was taken from 22 U.S. univers... |
#!/usr/bin/env python3
import argparse
import os
from PIL import Image
def main() -> None:
parser = argparse.ArgumentParser(
description="""\
\"Compress\" an image for the boot-splash.
The boot-splash is a two-color image."""
)
parser.add_argument("image", help="Boot-splash image")
parser.add... |
import sys_display
import color
# font enumeration
FONT8 = 0
FONT12 = 1
FONT16 = 2
FONT20 = 3
FONT24 = 4
class Display:
"""
The display class provides methods to allow the lcd display
in card10 to be used in a safe way. All draw methods return
the display object so that it is possible to chain calls.... |
"""
Text Reader Script
=================
This script will list and display text files
"""
import buttons
import color
import display
import os
import utime
STATE_LIST = "List"
STATE_SHOW = "Show"
SPECIAL_NO_FILES = "# no txt files"
SPECIAL_EXIT = "[ exit ]"
SPECIAL_EMPTY = "# empty file"
BUTTON_TIMER_POPPED = -1
def... |
def mergeSkyline(left, right):
# 2D array of x-coordinate, height sorted by x
# traverse through each element and its next
# print(left, right)
if left is None:
return right
elif right is None:
return left
res = []
h1, h2 = 0, 0
i, j = 0, 0
while i < len(left) and j <... |
import re
import sys
user_regex = r'(?:/user/show/)(\d+-[a-zA-Z0-9-]+)'
def parse(data):
users = re.findall(user_regex, data)
return set(users)
def main():
if len(sys.argv) < 3:
print("[+] Usage: user_parser.py INPUT_FILE OUTPUT_FILE")
exit()
users = parse(open(sys.argv[1], 'r', enc... |
import RPi.GPIO as GPIO
import time
from threading import Timer
class LED():
def __init__(self, channel, input_output):
"""
Control an LED given a GPIO channel
"""
self.channel = channel
if input_output == 'input':
self.input_output = GPIO.IN
elif input_... |
import os #for reading all smali files in a given directory
import pickle # for reading the list of apks stored as a pickle
import csv #for packaging the op-code:count dictionary into a csv
import collections
#location of the folder where all of the smali files of the disassembled apk is present
def std_codes_list(s... |
import types
class Strategy:
""" Strategy pattern class """
def __init__(self, function=None):
self.name = "Default Strategy"
if function is not None:
self.execute = types.MethodType(function, self)
def execute(self):
print("{} is used!".format(self.name))
# replac... |
from tkinter import *
from tkinter import ttk
# http://blog.csdn.net/maillibin/article/details/46954223
#计算程序
def calculate(* args):
value=float(feet_entry.get())
meters=(0.3048*value*10000.0+0.5)/10000.0
ttk.Label(mainframe,text=meters).grid(column=2,row=2,sticky=W)
print(meters)
#界面设计
root=Tk()
root.... |
# Things you should be able to do.
number_list = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
word_list = [ "What", "about", "the", "Spam", "sausage", "spam", "spam", "bacon", "spam", "tomato", "and", "spam"]
# Write a function that takes a list of numbers and returns a new list with only the odd numbers.
def all_odd(number_l... |
import pickle
import os.path
import datetime
from user import User
from record import Record
from day import Day
def console_interface():
"""Top-level function for console interface.
Handles user creation, user login, and quitting.
Responsible for loading and saving binary files."""
done_with_program... |
def factorial(n):
fact = 1
for i in range(1,n+1):
fact = fact*i
return fact
def combinatorics():
count = 0
for i in range(1,101):
for r in range(1,i+1):
if(factorial(i)/(factorial(r)*factorial(i-r)) >1000000):
count = count+1
print(count)
combinatorics... |
def factorial(n):
fact = 1
for i in range(1,n+1):
fact = fact*i
return fact
def sum_factorial(n):
s = 0
while (n > 0):
r = n%10
s = s+factorial(r)
n = n//10
return s
def sum():
s = 0
for i in range(10,1000000):
if(sum_factorial(i) == i):
... |
from string import ascii_lowercase
from itertools import cycle
alphabet = ascii_lowercase
def encrypt(plain, key):
cipher = ''
key = cycle(key)
for i in plain:
char = i
i = alphabet.find(i.lower())
if i == -1:
cipher += char
continue
... |
fact = 1
n = int(input("Enter a number: "))
for i in range(n,0,-1):
if (i == 0):
fact = 1
else:
fact = fact * i
#print(fact)
print(fact)
def factorial(k):
if(k==0):
return 1
else:
fact1 = k * factorial(k - 1)
return fact1
print(factorial... |
# coding:utf-8
__author__ = 'yinzishao'
# dic ={}
class operation():
def GetResult(self):
pass
class operationAdd(operation):
def GetResult(self):
return self.numberA + self.numberB
class operationDev(operation):
def GetResult(self):
# if(self.numberB!=0):
# return sel... |
import random
"""
populate outlist with character using values in in_list as index
"""
def populate_list(out_list, in_list, character):
for i in range(0,len(in_list)):
out_list[in_list[i]] = character
"""
print a tic-tac-toe frame
"""
def print_list(inlist):
print(inlist[0],inlist[1],inlist[2]) ... |
revenue = int(input("Hello! Write your company's revenue "))
costs = int(input("Write your company's costs."))
if revenue>costs:
print("Great job! Revenue is bigger than costs!")
profit = revenue/costs
print(f"Your profitability is {profit}. ")
staff = int(input("How many staff in your company?"))
p... |
#Profile
#--------------------------------------------Version1-------------------------------------------------------------------
def profile(name, surname, year, city, email, number):
print(name, surname, year, city, email, number)
profile("Masha", "Ivanova", "1910", "Moskow", "MI@mail.ru", "89102223322" )
#-----... |
#--------------------------------------Version1-------------------------------------------------------------------------
the_list = []
"""
while True:
user_answer = input("Input numbers with space:").split(" ")
if user_answer == ["$"]:
print(sum(the_list))
break
elif "$" in user_answer:
... |
#TimeConverter
#Demonstrates sting format
sec = int(input("Whelcom to the TimeConverter! How many seconds would you like to convert? Please, don't write more 86399 seconds."))
hours = ((sec // 3600)) % 24
min = (sec // 60) % 60
sec_ = sec % 60
print('{0}:{1:=02}:{2:=02}'.format(hours, min, sec_)) |
class Worker:
def _init_(self, name, surname, profit, position, bonus):
self.name = name
self.surname = surname
self.position = position
self._income = {"profit": profit, "bonus": bonus}
class Position(Worker):
def get_full_name(self, name, surname):
name = name
surname... |
class Matrix:
def __init__(self, matr):
self.matr = matr
def __str__(self):
return str((([str[i] for i in k]).split("\t") for i in self.matr).split("\n"))
def __add__(self, other):
return Matrix([sum([self.matr[i][k]], [self.other[i][k]]) for i in range(len(self.matr))]
... |
def main(): # 메뉴 선택 및 함수호출을 위한 메인함수
rows=3 # 행 값 3으로 지정
cols=5 # 열 값 5로 지정
kor_score=[] #
math_score=[] # 과목별 점수를 담아두기 위한 리스트
eng_score=[] #
midterm_score=[kor_score,math_score,eng_score] # 모든 점수를 담아두기 위한 리스트
midterm_score=[([0]*cols)for rows in range(rows)] ... |
#mad lib game.
#you add a random word where prompted. A paragraph is then printed out using these random words, can be very funny.
verb = input("verb: ")
verb2 = input("verb: ")
verb3 = input("verb: ")
verb4 = input("verb: ")
verb5 = input("verb: ")
verb6 = input("verb: ")
noun = input("noun: ")
noun2 = input("noun: ")... |
print('{:=^40}'.format(' PROGRESSÃO ARITMÉTICA '))
primeiro = int(input('Informe o primeiro termo: '))
razão = int(input('Informe a razão da PA: '))
termo = primeiro
cont = 1
while cont <= 10:
print('{} → '.format(termo), end='')
termo += razão
cont += 1
print('Fim')
|
salario = float(input('Qual é o salário? '))
if salario > 1250:
nsalario = salario * 1.10
else:
nsalario = salario * 1.15
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora.'.format(salario, nsalario))
|
from random import randint
from time import sleep
computador = randint(0,10)
print('-=-' * 20)
print('Vou pensar em um número entre 0 a 10. Tente adivinhar...')
print('-=-' * 20)
acertou = False
tentativas = 0
while not acertou:
jogador = int(input('Em que número eu pensei? '))
tentativas += 1
if computador... |
print('{:=^40}'.format('TABUADA'))
n = int(input('Digite um número para ver a sua tabuada: '))
print('-' * 13)
for c in range (1, 11, 1):
print('{} x {:2} = {}'.format(n, c, n * c))
print('-' * 13) |
from random import randint
from time import sleep
print('-=-' * 20)
print('Vou pensar em um número entre 0 e 5. Tente adivinha...')
print('-=-' * 20)
computador = randint(0, 5) #Computador "pensa" em um número
jogador = int(input('Em que número eu pensei? ')) #jogador tenta adivinhar
print('PROCESSANDO...')
sleep(3)
if... |
from operator import add
from functools import reduce
prices = [
(6.99, 5),
(2.94, 15),
(156.99, 2),
(99.99, 4),
(1.82, 102)
]
# We have a bunch of prices and sales numbers and wee need to find out our total earnings.
# Let's start by writing a function named product_sales that takes a single two-... |
from timeit import default_timer
import re
def is_match(scramble, word):
word = list(word)
for letter in scramble:
if letter in word:
word.remove(letter)
if len(word) == 0:
return True
return False
def parse_dictionary(filename, scramb... |
# coding: utf-8
# Task description
"""
A zero-indexed array A consisting of N different integers is given.
The array contains integers in the range [1..(N + 1)], which means that exactly
one element is missing.
Your goal is to find that missing element.
Write a function:
def solution(A)
that, given a zero-index... |
#ΕΡΓΑΣΙΑ: 9
#Γράψτε ένα πρόγραμμα σε Python το οποίο παίρνει έναν αριθμό τον τριπλασιάζει, προσθέτει ένα και στην συνέχεια προσθέτει τα ψηφία του. Η διαδικασία επαναμβάνεται μέχρι ο αριθμός να γίνει μονοψήφιος
num =int( input('Give a number:'))
digitsum = 0
num = num * 3 + 1
while len(str(num)) > 1 :
lis... |
#1- Ler uma variável numérica n e imprimi-la somente se a mesma for maior que 100, caso contrário imprimi-la com o
#valor zero.
n=int(input('Insira um número: '))
while n <= 100:
print('Numero menor que 100')
n=int(input('Insira um número: '))
else:
print('OK, número maior que 100, o número é {0}... |
##6- Faça um algorítmo que pergunte quanto você ganha por hora e o número de horas trabalhadas ao mês.
##Calcule e mostre o total do seu salário no referido mês.
#Insira a quantidade de horas que você trabalha por mês
#Insira o valor que você ganha por hora trabalhadas
#Multiplique a quantidade de horas pelo valo... |
#5- Faça um programa que leia um nome de usuário e sua senha e não aceite a senha igual ao nome de usuário, mostrando uma mensagem de erro
#e voltando a pedir as informações.
nome=input('Digite seu nome: ')
senha=input('Digite sua senha: ')
while senha == nome:
print('Senha não pode ser igual ao seu nome.'... |
##3- Teste o algorítmo anterior com os dados definidos por você
#estoquemédio= quantminima + quantmaxima) / 2
#_________________________________________________________
#| Quantidade mínima | Quantidade máxima | Estoque médio |
#|--------------------------------------------------------
#| 10 | ... |
class Bank:
def __init__(self,customers:[],numberOfCustomers:int,bankName:str):
self.__customers = customers
self.__numberOfCustomers = numberOfCustomers
self.__bankName = bankName
def Bank(self):
return self.__bankName
def addCustomer(self,firstName,lastname):
self.... |
#!/usr/bin/env python3
import numpy as np
from matplotlib import image, pyplot
def shift(red: int, green: int, blue: int):
scalars = np.array([red, green, blue])
def func(rgb: np.array):
rgb[:] = np.multiply(rgb, scalars)
return func
def experiment():
trees = "resource/smaller.jpg"
tr... |
print('Задание № 1')
def hello_user():
try:
while True:
user_say = input('Как дела ? ')
user_say = user_say.capitalize()
if user_say == 'Хорошо':
break
else:
print(f'Сам ты {user_say}')
except KeyboardInterrupt:
prin... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 19:03:43 2020
@author: Asifulla K
"""
#pattern
print("*")
print("* * *")
print("* * * *")
print("* * *")
print("*")
print()
#for any number of input
str1="6"
str2=str1*2
str3=str1*3
str4=str1*4
str5=str1*3
str6=str1*1
print(str1)
print(str2)
print(str3)
print(str4)
pr... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 09:22:21 2020
@author: Asifulla K
"""
#Write a function that prints out the odd numbers 1 through 99. Bonus: Use list comprehension.
# list of numbers
list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 20:25:50 2020
@author: Asifulla K
"""
result_str=""
for row in range(0,7):
for column in range(0,7):
if(((column==1 or column==5) and row!=0) or ((row==0 or row==3) and (column>1 and column<5))):
result_str=result_str+"*"
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 21:46:22 2020
@author: Asifulla K
"""
str1="Abc"
str2="Xyz"
print(str1)
print(str2)
print(str1[0])
print(str2[2])
print(str1[1])
print(str2[1])
print(str1[2])
print(str2[0])
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 20:41:35 2020
@author: Asifulla K
"""
#inbuilt functions in lists
a=[10,50,30,40,20]
print(min(a))
print(max(a))
print(len(a))
print(all(a))
b=[5,99,88,0,77]
#all
print(all(a))
#any
print(any(b))
c=[0,0,0,0,0]
print(any(c))
#sorted func
sorted(a)
print(a)
sorted(b, rev... |
a=int(input("A:"))
b=int(input("B:"))
c=int(input("C:"))
if((a>=b)and(a>=c)):
print("A is larger than B and C")
elif((b>=a)and(b>=c)):
print("B is larger than A and C")
else:
print("C is larger than A and B") |
# 条件判断和循环语句
# 逻辑运算符:and or not 两个表达式进行判断
# 1,and:两个表达式都为真的时候,才为真,否则为假
# print(40<60 and 60>40)
# print(40>60 and 60>40)
# 2,or:两个表达式只要一个条件为真,就为真
# print(40<60 and 60>40)
# 3,not:a表达式,a为真的时候,输出的就是假,全部为假的时候就为真
# print(not 70<60)
# 成员运算符: in not in 在字符中找值 in 在...里面, not in 不在.....里面
# 身份运算符: is not is 对于标识符... |
#异常:在程序运行过程中,如果报错了,就会停止,抛出错误信息
# 程序停止并且提示错误信息这个过程就叫做抛出异常
#异常:为了程序的稳定性和健壮性 异常处理:针对突发情况做集中的处理
'''
语法结构:
try:
尝试代码
except:
出现错误的处理
except Exception as e:
错误处理
程序中不确定会不会出现问题的代码,就写try
如果程序出现问题,就执行except里面的代码
'''
#题目:要求用户输入整数
# 用户输入 input 默认string字符串格式,int转型
# try:
# num = ... |
# factorial
def factorial(number):
result = 1
while(number>0):
result = result * number
number = number - 1
return result
print factorial(5)
|
def formula(a,b):
if(b == 0):
print "You can not divide by zero"
else:
return (a+b)/b
print formula(4,4)
print formula(2,0)
|
file_obj = open("file.txt","r")
word_list=file_obj.read().lower().split()
print sorted(word_list)
|
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
a = 0
b = 1
c = 0
logging.debug("a,b successfully initialized")
no = input("Enter range ")
if(no>100 or no<10):
logging.warning('no. too big .....will take some time')
logging... |
import pygame
from pygame.locals import *
import random, math, sys
import time
pygame.init()
#initialize and create some variables
songs = ['Elevator Music.mp3', 'Finisher_2.mp3']
pygame.mixer.music.load('assets/audio/' + songs[0])
pygame.mixer.music.play()
width, height = 800, 500
Surface = pygame.display.set_mode((8... |
def len_check(x):
length = len(str((x)))
if (length == 15) or (length == 16):
return True
else:
return False
def is_valid(x):
card = x
num_list= list((str(card)))
sum_odd = 0
sum_even = 0
even_count = 0
odd_count = 0
total_sum = 0
length = 0
for i in num_list:
leng... |
def binary_search(input_list, target):
if len(input_list) == 0:
return 'Not Found'
else:
midpoint = len(input_list) // 2
if input_list[midpoint] == target:
return 'Found'
elif input_list[midpoint] < target:
return binary_search(input_list[midpoint+1:], ta... |
def test(x):
if(state[(x+1)%5]!=2 and state[(x+4)%5]!=2 and state[x]==1):
state[x]=2
flag[x]=1
def initialisation():
for k in range(5):
state[k]=0
flag[k]=0
def pickup(x):
state[x]=1
test(x)
if(state[x]!=2):
flag[x]=0
if(flag[x]==1):
... |
Task
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entr... |
class UserInput:
def __init__(self, airports_dict):
# Variables to store OWM connection data:
self.airports_dict = airports_dict
self._itinerary_dict = {}
self.size_loop = True
self.itinerary_loop = True
self.input_size = None
def itinerary_size(self):
... |
import xml.etree.ElementTree as etree
myXML = '''
<current>
<temperature value="289.731" min="289.731" max="289.731" unit="kelvin"/>
</current>
'''
tree = etree.fromstring(myXML)
temperatureInfo = tree.find('temperature')
degrees = temperatureInfo.attrib['value']
print(degrees)
|
# encoding: utf-8
from threading import Thread, Lock
from time import sleep
a = 0
b = 0
lock = Lock()
def value():
while True:
sleep(0.2)
lock.acquire()
if a != b:
print('a = %d, b = %d' % (a, b))
lock.release()
t = Thread(target=value)
t.start()
while True:
# wi... |
s = input() #reads input string
n= int(input()) #a number which is used to convert string to cipher
s1 = ""
for x in s: #used to convert the string to a cipher
if(x.isalnum()):
ass = ord(x)
if(ass>=65 and ass<=90):
ass+=n
if(ass>90):
ass = 64+n-1
... |
"""
New exercise:
Given a file with this format (you can use via my github account
https://github.com/jpfnice/OctPyFunDay2AM "data2.txt" for instance):
x1:0.34;x2:0.56
x1:0.24;x2:0.45
x1:0.27;x2:0.55
...
extract out of it the numerical values associated with x1 and x2.
The values a... |
#-*- encoding:utf-8 -*-
#1.静态方法和类方法
#1.1静态方法
#1.2类方法
class washer(object):
#定义类属性
company="Le Xi"
#1.11定义静态方法
@staticmethod
def spins_ml(spins):
#1.13静态方法只能访问类属性不能访问实例属性
print("company:",washer.company)
return spins*0.4
#1.21定义类方法
@classmethod
def get_washer... |
#!/usr/bin/env python3
# coding: utf-8
import copy
def headers_add_host(headers, address):
"""
If there is no Host field in the headers, insert the address as a Host into the headers.
:param headers: a 'dict'(header name, header value) of http request headers
:param address: a string represents a dom... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 18:27:13 2017
@author: Leszek
"""
# Ulubiona liczba - wczytanie danych do pliku
import json
filename = 'favorite_number.json'
num = input("What's your favorite number? ")
with open(filename, 'w') as f_obj:
json.dump(num, f_obj)
# Kod wg książki
import json
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 15:47:44 2017
@author: Leszek
"""
#Pętla while w działaniu
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1 #difference between loops while and for:
#while is running until it is False when
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 21:05:09 2017
@author: Leszek
"""
#Wartosć zwrotna
def get_formatted_name(first_name, last_name):
"""Zwraca elegancko sformatowane imię i nazwisko"""
full_name = first_name + " " + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'h... |
def _forward_mapper(student_answer):
return {
'very much like me' : 5,
'mostly like me' : 4,
'somewhat like me' : 3,
'not much like me' : 2,
'not like me at all' : 1
}[student_answer.lower()]
def _reverse_mapper(student_answer):
r... |
# Let's make a turtle race
from turtle import *
from random import randint
speed(10)
penup()
goto(-140, 140)
for step in range(16):
write(step, align='center')
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20)
ada = Turtle()
ada.color('red')
... |
class TestClass: # 类的定义
DESCRIPTION = "class introduction of sample" # 类变量,可直接通过类名调用
__test = "test" # 属于私有,不可在类外部直接调用以“__”开头
_single = "single" # 属于私有,不可使用from module import *导入使用
def __init__(self, name):
'测试类' # 注释文档
self.name = name # 通过self可以创建类的实例变量
... |
def is_float(x):
'''
This function takes a string as parameter and checks whether it is a Number or not (Integer or Float).
'''
try:
# only integers and float converts safely
num = float(x)
return True
except ValueError as e: # not convertable to float
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.