text stringlengths 37 1.41M |
|---|
"""
Code for compressing and decompressing using Huffman compression.
"""
from nodes import HuffmanNode, ReadNode
# ====================
# Helper functions for manipulating bytes
def get_bit(byte, bit_num):
""" Return bit number bit_num from right in byte.
@param int byte: a given byte
... |
"""
// Time Complexity : o(1) , constant
// Space Complexity : o(1), constant
// Did this code successfully run on Leetcode : not on leetcode
// Any problem you faced while coding this : no
"""
class Solution:
def helper(self, num):
if num == 0:
return ""
if num < 20:
... |
import time
import os
import random
from random import randrange, randint, sample
# 跑马灯
def main():
str = '北京欢迎你......'
while True:
os.system('cls') # os.system('clear')
print(str)
time.sleep(0.2)
temp = str[1:]
temp2 = str[0]
str = str[1:] + str[0]
# 设计一个函数产... |
import turtle
import random
from tkinter import *
window = turtle.Screen()
window.setup(width=800, height=600,)
window.bgcolor("black")
colors = ['red', 'blue', 'orange', 'yellow', 'magenta', 'purple', 'peru', 'ivory', 'dark orange']
moon = turtle.Turtle()
moon.hideturtle()
star = turtle.Turtle()
star.speed(0)
star... |
cantidad = 0
def quicksort(arr):
global cantidad
if arr==[] :
return []
m=arr[0]
left=[]
right=[]
for k in arr[1:]:
if k<m:
left.append(k)
else:
right.append(k)
cantidad+=1
return quicksort(left)+[m]+quicksort(right)
... |
import datetime
from math import sin, cos, radians
from Util import get_coordinates
class DatesAndTimes:
""" Performs various date and time calculations.
Attributes:
_date : datetime
a timezone aware date
_day_of_year : int
the integer day of the year for today
... |
print ("Lista zakupów")
shopping_dict = {
'piekarnia' : ['chleb', 'pączek', 'bułki'],
'warzywniak': ['marchew', 'seler', 'rukola']
}
for shop, products in shopping_dict.items(): # produkty z jednego sklepu
produkty = [] # zerujemy listę produktów
for p in products: ... |
import re
inpString=input("please enter a string")
pattern=r"()"
matchString=re.search(pattern,inpString)
if matchString:
print("match")
else:
print("not valid")
#Car Registration
pattern=r"([A-HJ-PR-Y]{2})([0-9]{2})([A-HJ-PR]{3})"
#Postcode
pattern=r"([A-Z]{2})([0-9]{2})(\ )([0-9])([A-Z]{2})" |
string = str(input("Enter a string. "))
def encode(string):
if not string:
return ""
x = 1
while x < len(string) and string[0] == string[x]:
x += 1
return string[0]+str(x)+encode(string[x:])
print(encode(string)) |
### Bubble Sort ###
# More efficient version of bubble sort
def bubble(lst):
for i in range(len(lst)-1):
swaps = 0
for j in range(len(lst)-i-1):
if lst[j] > lst[j+1]:
lst[j] , lst[j+1] = lst[j+1] , lst[j]
swaps += 1
if swaps == 0:
return lst
lst = [6,3,89,2,7,3,6,8,4,45]
print(lst)
bubble(lst)
pr... |
'''
def HeapExtractMax(A):
ret = A[1] # biggest element (highest priority)
A[1] = A[heapSize(A)]
HeapSize(A) = HeapSize(A)-1
Heapify(A,1,HeapSize(A))
return ret
'''
def Heapify(A,v,n):
# n is heap size
# find largest among v and 2v (left child)
largest = v
if 2*v <= n and A[2*v] > ... |
import matplotlib.pyplot as plt
from matplotlib.widgets import Button, TextBox
def fx(x, y):
return float(x - x * x * x / 3. - y)
def fy(x, a):
E = 0.05
return float(E * (x + a))
#############################################################################
def Runge_Kutt(x0,y0,t,h):
x.append(x0)
... |
print "There once was an old lady."
print "Who lived in a %s" % 'shoe'
print "And in that shoe there was"
print "." * 15
end1 = "O"
end2 = "t"
end3 = "h"
end4 = "e"
end5 = "r"
end6 = "S"
end7 = "h"
end8 = "o"
end9 = "e"
end10 = "s"
print end1 + end2 + end3 + end4 + end5,
print end6 + end7 + end8 + ... |
from sys import argv
script, username = argv
prompt = '> '
print "Hello %s, I am the %s script." % (username, script)
print "I'd like to ask you a few questions."
print "Do you like me, %s?" % username
likes = raw_input(prompt)
print "Where do you live %s?" % username
lives = raw_input(prompt)
print ... |
VOCALS = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u', 'Á', 'É', 'Í', 'Ó', 'Ú', 'á', 'é', 'í', 'ó', 'ú']
parrafo = str(input('Ingresa un párrafo: '))
for vocal in VOCALS:
parrafo = parrafo.replace(vocal, ' ')
print(parrafo) |
import math
PI = math.pi
def superficieLateral(radio, altura):
supLateral = (2*PI*radio) * altura
supLateral = round(supLateral,1)
print('La superficie lateral del cilindo: {}'.format(supLateral))
def volumenCilinro(radio, altura):
vol = PI * math.pow(radio,3)*altura
vol = round(vol,1)
print('El volumen ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import threading
"""
线程同步机制:
- Semaphore(信号量)
- Lock(互斥锁), 相当于: 信号量为1
- RLock(可重入锁):
- acquire() 能够不被阻塞的被同一个线程调用多次。
- 但release()要调用与acquire()相同的次数才能释放锁。
- Condition(条件):
- 一个线程等待特定条件,而另一个线程发出特定条件满足的信号。
- 最好示例:「生产... |
import cv2
import numpy as np
# Uploading the image and convert it to gray scale
img = cv2.imread('owl.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
# Run harris corners detection
dst = cv2.cornerHarris(gray,2,5,0.002)
# Thresholding for, and mark the corner in blue(because the... |
# A number is Sparse if there are no two adjacent 1s in its binary representation.
# Given a number n, find the smallest Sparse number which greater than or equal to n.
# eg. 5 (binary representation: 101) is sparse, but 6 (binary representation: 110) is not sparse.
# Example
# Given n = 6, return 8
# Next Sparse Num... |
import heapq, random
from collections import deque
def deque_test():
range_deque = deque(maxlen=10)
for i in range(20):
range_deque.append(i)
print(range_deque)
def heapq_test():
nums = []
for i in range(100):
nums.append(random.randint(0, 100))
print(heapq.nlargest(10, nums))
... |
#! /usr/bin/env python
#
# multi inheritance view
# /------ 7-------\
# / | \
# 4 - 5 6
# \\ / /
# 2-/\--- 3------/
# \ /
# ... |
def fibonacci(max=1):
a, b = 0, 1
while a < max:
yield a
a, b = b, a + b
a = fibonacci(1000)
lst = []
while True:
try:
lst.append(next(a))
except StopIteration:
break
print(lst) |
from math import sqrt
import numpy as np
def count_distance(alphabetLength, firstRelativeFrequencies, secondRelativeFrequencies):
firstFrequencySums = [sum(firstRelativeFrequencies[:i]) for i in range(1, alphabetLength+1)]
secondFrequencySums = [sum(secondRelativeFrequencies[:i]) for i in range(1, alphabetLeng... |
fileName = input("파일 이름을 입력하세요:")
f = open(fileName)
t = f.read()
word = t.split()
print(t)
print("단어의 갯수: ", len(word))
print("문자 수: ", len(t))
print("행의 수: ", len(t.split('\n')))
f.close() |
def god(m,n):
if m%n == 0:
return n
return god(n, m%n)
while True:
m,n = eval(input("숫자 2개 입력: "))
print("{0}과 {1}의 최대공약수 : {2}".format(m,n,god(m,n))) |
from datetime import datetime
import time
class StopWatch:
def __init__(self, startTime=0, endTime=0):
self.startTime = startTime
self.endTime = endTime
def start(self):
self.startTime = datetime.now()
def stop(self):
self.endTime = datetime.now()
def getElapsedTime(s... |
#!/usr/bin/env python
#encoding: latin1
from sympy.solvers import solve
from sympy import Symbol
from sympy import sympify
#Una claculadora d'equacions
class EcuationCalc:
def __init__(self,expresio):
self.expresio=expresio;
def calcularEquacio(self):
if "x" in self.expresio:
expr... |
#! python3
# bulletPointAdder.py - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard
import pyperclip
text = pyperclip.paste()
# TODO: Seperate lines and add stars
lines = text.split('\n') # split the text for easier processing
for i in range(len(lines)):
lines[i] = '*... |
import pandas as pd
def load_data(fn):
return pd.read_csv(fn)
def report_violations(results):
print("Reporting violations for correction...")
def do_stats(results):
print("Calculating statistics...")
stats = {}
for k in results.keys():
stats[k] = results[k].shape[0]
return stats
def ... |
def blank_board(width, height):
"""
This function should return a "2-D array" that
we can use to represent a 2-D board for a game
like Tic-Tac-Toe or Battleships. For more on
using 2-D arrays, see:
* https://robertheaton.com/2018/06/12/programming-projects-for-advanced-beginners-ascii-art/
... |
from coordinate import Coordinate
from exceptions import NegativeValueException, InvalidBoundingBox
class BoundingBox(object):
"""
Represents a bounding box
"""
def __init__(self, top_right_coordinate: Coordinate,
width: int, height: int):
"""
class constructor
... |
'''
>> Pong Game with PyGame and Class
>> Developed by : tinyCoder
'''
import pygame
from pygame.locals import *
import time
import random
import sys
#pygame.mixer.pre_init(44100,16,2,4096)
pygame.init()
screen=pygame.display.set_mode((600,600))
pygame.display.set_caption("Pong by TinyCoder")
clock = pygame.time.C... |
def divide(a, b):
return a % b
def calculate_gcd(first_number, second_number):
if first_number < second_number:
big = second_number
small = first_number
else:
big = first_number
small = second_number
remainder = small
while remainder > 1:
remainder = divide... |
hand_1 = input("Hand van speler 1? ")
hand_2 = input("Hand van speler 2? ")
blad_v_steen = hand_1 == "blad" and hand_2 == "steen"
steen_v_schaar = hand_1 == "steen" and hand_2 == "schaar"
schaar_v_blad = hand_1 == "schaar" and hand_2 == "blad"
if hand_1 == hand_2:
uitkomst = "onbeslist"
elif (blad_v_steen == True... |
def dronken_voeren(woord):
dronken_woord = woord[0]
for i in range(1, len(woord)):
if i % 2 == 0:
letter = woord[i].upper()
elif i % 2 != 0 and dronken_woord[-1] in "AEOUI":
letter = woord[i].upper()
else:
letter = woord[i].lower()
dronken_wo... |
woord = input("verborgen woord: ")
geldbedrag = int(input("Gedraaide geldbedrag: "))
letter = input("Geef een letter: ")
gebruikt = ""
som = 0
while letter in woord and not letter in gebruikt:
som += geldbedrag
gebruikt += letter
letter = input("Geef een letter: ")
print(som) |
# When Jack Black plays BlackJack does Jack Black become Black Jack?
# I have no idea what I just said, but it sounds funny.
kaart = int(input("Kaartwaarde: "))
som = kaart
while kaart > 0 and som < 21:
kaart = int(input("Kaartwaarde: "))
som += kaart
if som > 21:
print("Verbrand ({})".format(som))
elif ... |
from random import randint
number = randint(0, 100)
cheats_answer = input("Hello! Would you like to enter a cheatcode? \n")
if cheats_answer.lower() == "yes" or cheats_answer.lower() == "y":
password = input("Enter the cheatcode: \n")
if password.lower() == "hayasaka ftw":
print("The number you're lo... |
def printbaar_rek(rek):
# Bovenste rij eerst plaatsen:
rek.reverse()
string = ""
for rij in rek:
string += "".join(rij) + "\n"
return string[:-1]
def speel(kleur, kolom_index, rek):
placed = False
i = -1
while not placed:
# Als geen 0: ofwel geplaatst ofwel geen plaat... |
#convert Binary to decimal
def BinToDec(n):
if (len(n))== 0:
return 0
else:
return BinToDec(n[:-1]) * 2 + (n[-1] == '1')
Num = input("enter a binary code:")
print(BinToDec(Num))
|
# File: non-repeatpass.py
#Imports random, choice, and time
import random
import time
from random import choice
#Sets the password that needs to be found
password = "89bd"
#Sets the number of password attempts
attempts = 0
#List that contains possible digits
possibleDigits = ['0', '1', '2', '3', '4', '5', '6', ... |
from random import randint
class Randsentence:
def __init__(self):
print("hello from Talha Yılmaz :)")
def sentence_generator(self, rules, symbol, non_terminal, sentence):
matching_rules = []
if symbol not in non_terminal:
sentence.append(symbol)
els... |
from partida import Partida
from repositorios import Repositorios
from random import choice
class ServicesPartidas():
def iniciar_partida(self, nombre_jugador, dificultad, nombre_palabra="",
tipo_palabra=""):
if int(dificultad) < 1 or int(dificultad) > 10:
raise ValueEr... |
def median_string(dna, k):
distance = 10**100
median = ''
for i in range(0, 4**k -1):
pattern = number_to_pattern(i, k)
if distance > distance_between_pattern_and_string(pattern, dna):
distance = distance_between_pattern_and_string(pattern, dna)
median = patter... |
"""
Условие
Даны координаты [x, y] точки на плоскости. Определить, попадает ли точка в область [x0, y0] [x1, y1].
Для простоты считать:
[x0, y0] = [0, 0];
[x1, y1] >= 0.
Условие для входных данных: 4 вещественных числа: x1, y1, x, y, каждое с новой строки;
Формат вывода: вывести в консоль булево значение True (если ... |
"""
Условие
Напишите программу, которая принимает на вход строку и проверяет, является ли она палиндромом
(читается одинаково с начала и с конца). Программа должна игнорировать пробельные символы и регистр.
Входные данные: строка.
Выходные данные: True если строка является палиндромом, False если не является.
"""
# ... |
#-*- coding:utf-8 -*-
class A(object):
def __init__(self):
self.name = "A"
print "__init__ is called."
def __new__(cls, *args, **kwargs):
print "__new__ is called."
return super(cls.__class__, cls).__new__(cls, *args, **kwargs)
def getName(self):
return self.name
... |
import numpy as np
#l = np.array([1,2,3])
#print(l.size())
def forloop():
l = [ 'a','b','c']
for i in range(0,3,1):
print(i, "=", l[i])
else:
print("afterloop")
forloop()
class Hey:
arg = 'memberData'
def __init__ (self,arg='default'):
self.arg=arg
print('assigne... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Write a function that calculates mass of an element after decay for provided time.
Mass must be calcuted using half-life formula:
mass = initial_mass * (1/2)^(t/T)
mass - output mass [grams]
initial_mass - mass of element at begining [grams]
t - time of decay ... |
def myBinarySearch(alist, element):
first = 0
last = len(alist)-1
indexFound = 0
done = False
while not done and first <= last:
midpoint = (first + last)//2
if alist[midpoint] == element:
print "Found at index %d" % midpoint
done = True
elif element < alist[midpoint]:
... |
def factorial(x):
total = 1
for i in range(1,x):
total += total * i
return total
print factorial(5)
#function to create factorial of any number
def anti_vowel(text):
new_text = ""
for ch in text:
if ch in "aeiouAEIOU":
pass
else:
new_text += ch
return new_text
print ... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
递归法
1. 访问到根节点后,将路径 append 到 res 中
2. 没有访问到根节点,则依次递归访问左子树、右子树
3. 访问完一课子树后,从 path 中 pop 子树的根节点
"""
class Solution:
def binaryTreePaths(self, root: TreeNode):
... |
# Define binary tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def serialize(self, root: 'TreeNode'):
if not root:
return '$,'
return str(root.val) + ',' + self.serialize(root.left) + self.seriali... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]:
# 在层序遍历的基础上,引入 inv 标志位
nodes, layers, inv = [root], [], False
... |
"""
借助辅助栈
1. 如果下一个弹出的数字恰好在辅助栈顶,则直接弹出
2. 如果不在,就在压栈序列中还没入栈的数字中查找
3. 如果找到了,依次入栈直到该数字
4. 如果没找到,False
5. 最后 while 循环结束,说明验证完了
"""
class Solution:
def validateStackSequences(self, pushed: list[int], popped: list[int]) -> bool:
# 都空 True
if not pushed and not popped:
return True
# 长度不一致... |
"""
快排 partition 思想
1. 需要熟悉快速排序的方法
2. 每次快排结束,枢纽左侧的数都比枢纽小,右侧的数都比它大
3. 利用这个特性,进行如下判断:
如果枢纽正好在第 k 大元素对应的位置上,就是结果;
如果枢纽在第 k 大元素位置的左侧,说明需要在右侧查找;
反之,需要在左侧查找
4. 上述过程不断循环,直到找到目标元素
时间复杂度: O(n)
空间复杂度:O(1)
注意:
1. 该方法会改变原数组
2. 适用于少量数据
"""
class Solution1:
def findKthLargest(self, nums, k: int) -> int:
if not... |
import matplotlib.pyplot as plt
import numpy as np
def n_max(*args):
m = sorted(range(len(args)), key=lambda x: args[x][0], reverse=True)[0]
return args[m]
def n_min(*args):
m = sorted(range(len(args)), key=lambda x: args[x][0])[0]
return args[m]
def distance_frechet(P, Q):
"""
Function fo... |
class Node:
def __init__(self, value):
self.nodeValue = value
self.nextNode = None
class LinkedList:
def __init__(self, value=None):
self.head = value
def append(self, value):
new_node = Node(value)
current_node = self.head
while current_node:
... |
# implementation of selection sort algorithm
def selection_sort(item_list):
lenOfList = len(item_list)
for i in range(lenOfList - 1):
min_index = i # track index of minimum item
for j in range(i+1, lenOfList):
if item_list[j] < item_list[min_index]:
# min value found... |
# to check that entered number is a special number or not
from math import *
x = int(input('Enter a number : '))
b = str(x)
s = 0
for i in range(len(b)):
a = x%10
s += factorial(a)
x = x//10
if s == float(b):
print('It is special number')
else:
print('It is not specia... |
# to find the common factors of two numbers
x = int(input('Enter the first number : '))
y = int(input('Enter the second number : '))
l = [x]
m = [y]
def fac(a,b):
for i in range(1,(a//2)+1):
if a % i == 0:
b.append(i)
else:
pass
b.sort()
return b
f1 = fac(x,l)
f2 =... |
#import random
bordje = [" _ "] * 9
x = "|"
#deze input moet om een of andere reden iets gan veranderen in het bord
def retarded_printen(bordje):
print(bordje[0] + x + bordje[1] + x + bordje[2])
print(bordje[3] + x + bordje[4] + x + bordje[5])
print(bordje[6] + x + bordje[7] + x + bordje[8])
#deze var geeft aan of ... |
"""This class methods are used in the main program to make the user
interactions easier"""
class ClientInterface:
def __init__(self):
pass
def ask_safely(self, question, max):
response = input(question)
while True:
try:
response = int(response)
... |
#!/usr/bin/env python3
# all possible words
words = ["about", "after", "again", "below", "could", "every", "first", "found", "great", "house", "large", "learn",
"never", "other", "place", "plant", "point", "right", "small", "sound", "spell", "still", "study", "their",
"there", "these", "thing", "thin... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 22:21:41 2017
@author: Prathyusha Mallela
"""
#Assignment 3.1.1
def myreduce(func, iterable, start=None):
it = iter(iterable)
if start is None:
try:
start = next(it)
except StopIteration:
raise TypeError('r... |
arr=[-2,1,-3,4,-1,2,1,-5,4]
local_max = 0
global_max= 0
print(arr)
for item in arr:
local_max = max(0,local_max+item)
print(local_max)
if(local_max>global_max):
global_max=local_max
print(global_max)
|
# ## PyBank
# 
# * In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company. You will give a set of financial data called [budget_data.csv](PyBank/Resources/budget_data.csv). The dataset is composed of two columns: `Date... |
names = ("Navin","Kiran","Harsh","Anandhu")
comp = ("Dell","HP","Apple","Asus")
zipped = dict(zip(names,comp))
print(zipped)
zipp = zip(names,comp)
for (a,b) in zipp:
print(a,b)
|
def calc(purchase_interval, heloc_interval, credit_limit, years):
duration = years * 12
house_price = 40000
credit_limit -= house_price
houses = 1
net_rent = 400
heloc = 0
income = 0
#monthly calculations
for months in range(1, duration + 1):
cashflow = houses * net_rent
... |
import sqlite3
conn = sqlite3.connect('demo_data.sqlite3')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS demo ( \
s TEXT NOT NULL, \
x INT NOT NULL, \
y INT NOT NULL \
)')
cur.execute("INSERT INTO demo(s,x,y) \
VALUES \
('g', 3, 9), \
('v', 5, 7), \
('f', 8, 7)")
test = cur.execute('SELECT * FROM demo').f... |
file = open('GFG.txt', 'w')
# Data to be written
for e in range (0,10):
data =input("Enter a number - ")
# Writing to file
file.write(data)
# Closing file
file.close()
# program for reading
# open file
h = open('GFG.txt', 'r')
# Reading from the file
content = h.readlines()
# List for sto... |
# 1.Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
number = 15
name = "Alex"
print(number)
print(name)
number1 = input('Введите первое число : ')
print("Вы ввели " + number1)
number2 = input("Введите вт... |
"""a simple implementation for the greedy Maximum Matching algorithm
"""
def max_matching(sentence, S):
if not sentence:
return list()
for i in reversed(range(0, len(sentence)+1)):
first_word = sentence[:i]
remainder = sentence[i:]
if first_word in S:
return [first_w... |
#take the user's weight as an input
weight=input("Enter your weight in kg: \n")
#take the user's height as an input
height=input("Enter your height in m: \n")
#calculate and output the BMI
BMI=float(weight)/(float(height)**2)
result=int(BMI)
if BMI<18.5:
print(f"Your BMI is {result}, you are underweight.")
elif BM... |
def is_palindrome(s):
l = len(s)
return s[:l // 2] == s[(l+1) // 2:][::-1]
largest = -1
for a in reversed(range(1000)):
for b in reversed(range(1000)):
c = a*b
if is_palindrome(str(c)):
largest = max(largest, c)
print(largest)
|
m = int(1e6)
is_prime = [True for _ in range(m+1)]
is_prime[0] = False
is_prime[1] = False
k = 2
while k * k <= m:
if is_prime[k]:
for i in range(k*k, m+1, k):
is_prime[i] = False
k += 1
primes = [p for p in range(1000) if is_prime[p]]
def longest(a, b):
n = 0
while is_prime[n*n+a*... |
from matplotlib import pyplot as plt
x = [0, 1, 2, 3, 4, 3, 2, 1]
y = [0, 0, 1, 3, 6, 6, 5, 3]
xx = x[:]
yy = y[:]
for p in x:
for k in x:
xx.append(p-k)
for p in y:
for k in y:
yy.append(p-k)
fig = plt.figure()
plt.xticks(range(-10, 11))
plt.yticks(range(-10, 11))
plt.xlim([-10, 10])
plt.ylim... |
# number of additional cells for loop: (2i + 1) * 4 - 4 = 8i
# where the new side length is 2i + 1
# and corner numbers are 2i + 1, 4i + 1, 6i + 1, and 8i + 1
# (offset by the number of previous cells)
import math
# from functools import lru_cache
# @lru_cache(int(1e6))
def is_prime(n):
if n <= 1:
return ... |
fruits = ['apple','banna','orange','strawberry']
vegetables = ['lettuce','cucumber', 'carrots']
fruits_and_vegetables = fruits + vegetables
print fruits_and_vegetables
salad = 3 * vegetables
print salad
|
# pet1 = {'name': 'frankie', 'age': 6,'fur': 'golden'}
# print pet1
# pet2 = {'name': 'sunny', 'age': 12,'fur': 'yellow'}
class Pet(object):
def __init__(self, name, age, fur):
self.name = name
self.age = age
self.fur = fur
self.legs = 4
def speak(self):
print ... |
# Rekursive Funktion: Fibonacci Reihe
def fib(n=5):
if n<2:
return n
else:
return fib(n-1)+fib(n-2)
def fiblist(m=5):
i = 0
L = None
L = []
while i <= m:
L.append(fib(i))
i += 1
return "Die Fibonacci Reihe von 0 bis " + str(m) + " lautet: \n" + str(L)
|
#!/usr/bin/env pybricks-micropython
"""
Example LEGO® MINDSTORMS® EV3 Robot Educator Color Sensor Down Program
----------------------------------------------------------------------
This program requires LEGO® EV3 MicroPython v2.0.
Download: https://education.lego.com/en-us/support/mindstorms-ev3/python-for-ev3
Buil... |
# Create a program which is looking for a files bigger than ' X ' in a folder
import shutil, os, re
list=[]
X=int(input('For how big files are You looking for(mb) ? '))*1000000
for folderName, subfolders, filenames in os.walk('F:\\python\\2007-07-04 Wycieczka'): # Write path of folder from which You wante... |
petDictionary = {
"name":"Maggi",
"age":14,
"hobbies":("sleeping", "walking", "eating"),
"wakeUpHours":{
"monday":6,
"tuesday":7,
"friday":9
}
}
print(petDictionary)
#Print out Your pet's name and age.
print(f'{petDictionary["name"]} is {petDictionary["age"]} years old.')... |
#import modules needed for reading csv and outputting .txt results
import os
import csv
#file path for csv to read
file = 'Resources/election_data.csv'
#function which returns number of votes for a given candidate
def candidate_votes(candidate):
with open(file) as csvfile:
csvreader = csv.reader(csvfile, ... |
import re
T = int(input("no if test cases-"))
while T> 0:
password = input("Enter your password-")
flag = 0
while True:
if (len(password)<8 or len(password)>15):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
... |
# url https://leetcode.com/problems/base-7/
# writtenby:anhty9le
def base7(num):
s = ""
while num != 0:
s += str(num % 7)
num = num // 7
return s[::-1]
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
... |
# url https://leetcode.com/problems/search-a-2d-matrix-ii/
# writtenby:anhty9le
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m == 0:
... |
# url https://leetcode.com/problems/add-digits/
# writtenby:anhty9le
class Solution(object):
def addDigits(self, num):
if num < 10:
return num
else:
return self.addDigits(num % 10 + self.addDigits((num // 10)))
|
# url https://leetcode.com/problems/intersection-of-two-arrays/
# writtenby:anhty9le
def fixNums(nums):
nums.sort()
i = 0
n = len(nums)
while i < n - 1:
if nums[i] == nums[i + 1]:
nums.pop(i)
n -= 1
i -= 1
i += 1
return nums
... |
# url https://leetcode.com/problems/minimum-index-sum-of-two-lists/
# writtenby:anhty9le
class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
n1 = len(list1)
n2 = ... |
# url https://leetcode.com/problems/lexicographical-numbers/
# writtenby:anhty9le
class Solution(object):
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
arrS = []
arrI = []
for i in range(1, n + 1):
arrS.append(s... |
"""Quick routines to convert machine-friendly data types to human-friendly strings."""
import datetime
import time as _time
from metabot.util import unicodeutil
def _now_copy_tz(dtime):
now = datetime.datetime.fromtimestamp(_time.time(), getattr(dtime, 'tzinfo', None))
return isinstance(dtime, datetime.date... |
def check_user_input(prompt):
while True:
try:
value=float(input(prompt))
except ValueError:
print("Invalid")
if value < 0:
print("Please key in a positive number")
else:
break
return value
annual_salary=check_user_input("Annual salary: ... |
i = int(input())
for j in range (2,i):
for m in range (2,j):
if j % m == 0:
print (j, 'equals', m, 'x', j//m)
break
else:
print(j, 'is a prime number') |
# A Sample Python program for beginners with Competitive Programming
# Returns index of x in arr if it is present,
# else returns -1
def search(arr,x):
n = len(arr)
for j in range(0,n):
if x==arr[j]:
return j
return -1
#Input number of test cases
print ("Enter input number ... |
string= "petite"
count = 0
for x in "pettite":
if x is :
count += 1
print(j,count)
|
import pydoc
import stack
import cita
class Historial:
'''CLASE:
-----------------------------------------------------------------------------------
La clase Historial me permite almacenar los datos de cadaa cita por separado en
forma de lista.
----------------------------------------------------------------------... |
num = int(input('Digite um numero: '))
f = 1
print(f'Calculando {num}!= ', end='')
while num > 0:
print(f'{num}', end=' ')
if num > 1:
print('x ', end= '')
f *= num
num -= 1
print(f'= {f}')
|
from datetime import date
anoN = int(input('Digite o seu ano de Nasimento: '))
anoA = date.today().year
idade = anoA - anoN
idadeF = 18 - idade
idadeP = idade - 18
print('A sua idade atual é de {} anos no ano de {}.'.format(idade, anoA))
if idade < 18:
ano = anoN + 18
print('Você ainda não esta na idade de alis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.