text stringlengths 37 1.41M |
|---|
"""
julia.py - Implement the Julia set in Python using matplotlib & numpy
https://blog.anvetsu.com/posts/fractals-julia-python-matplotlib-numpy/
"""
import matplotlib.pyplot as plt
import numpy as np
def julia_set(width, height, zoom=1, niter=256):
""" A julia set of geometry (width x height) and iterations 'nite... |
from tkinter import *
import math
# Draws a fractal Sierpinski triangle.
# Parameters:
# canvas: a canvas on which to draw on
# x, y: coordinates of the lower left corner of the triangle
# size: lenght of the side of the triangle
# level: depth of recursion, integer >= 0
def sierpinski(canvas, x, y, size, leve... |
def DigitHangman():
question = input("Enter the question : ")
puzzle = question.split()
answer_list = []
guess_time = 0
WrongGuess = ''
if len(puzzle) != 12:
print('Question must has 12 numbers')
return False
for i in puzzle:
if int(i) > 9 or int(i) < 0:
p... |
from Person import Person
Adam = Person("Adam Ruckman", 27)
print(Adam.name)
print(Adam.age)
print("New Computer Test") |
import os
from typing import Callable
from cryptopals_challenge_roald.crypto_lib import AesEcbCipher, AesCbcCipher, average_hamming_distance_between_blocks
def encryption_oracle(unknown_encryptor: Callable[[bytes, bytes], bytes]) -> str:
"""This function accepts a random encryption function as input argument and... |
import datetime as dt
from cryptopals_challenge_roald.set3.set3_21_mersenne_prng import MersenneTwister
def print_bits(num, bits=32):
print(f'yi = {num:0{bits}b}={num}')
def unscramble(sol: int, y: int, shift: int, bit_mask: int, r: int = 0, dir: str = 'right'):
"""
This function recursively unscramble... |
import argparse, random
class Player:
def __init__(self,name,token):
self.name=name
self.token=token
def __repr__(self):
return self.token.upper()
# def __eq__(self, other):
# if type(other) is Piece:
# if self.color == other.color:
# return Tru... |
class MinHeap(object):
def __init__(self):
self.heap = [0]
self.size = 0
def parent(self, pos):
return pos // 2
def left_child(self, pos):
return pos * 2
def right_child(self, pos):
return (pos * 2) + 1
def is_leaf(self, pos):
return pos <= s... |
# DRY -> ?
# функции
w = 15
h = 20
area = w * h
print('площадь прямоугольника', area)
w = 10
h = 30
area = w * h
print('площадь прямоугольника', area)
w = 5
h = 25
area = w * h
print('площадь прямоугольника', area)
|
def show_user(user):
print('имя:', user[0])
print('фамилия:', user[2])
print('возраст:', user[3])
user_1 = ['Иван', 'Иванович', 'Иванов', 21, 'г.Курган']
# 0 1 2 3 4
user_2 = ['Петр', 'Петрович', 'Петров', 19, 'г.Далматово']
user_3 = ['Сидорова', 'Валерьевна', 'Оксан... |
# range(n) -> 0, 1, 2, n-1, [0, n)
numbers = []
for num in range(10):
numbers.append(num)
print(numbers)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 0 1 2 3 4 5 6 7 8 9
pass
# Pop last O(1)
# last_num = numbers.pop() # like cut in word
# # numbers -> [0, 1, 2, 3, 4, 5, 6, 7, 8]
# 0 1 2 3 4 5 6... |
# inheritance
class People:
def __init__(self):
self.name = None
self.surname = None
self.age = None
self.address = None
self.mail = None
self.phone_number = None
def say_hello(self):
# print('привет, меня зовут ', self.name, '!')
print('hello, m... |
student_marks = []
while True:
mark = input('введите оценку студента:\n')
if not mark:
break
if len(mark) != 1:
print('вы ввели не один символ')
continue
if not 48 <= ord(mark) <= 57:
print('вы ввели не число')
continue
mark = int(mark)
if 1 <= mark <= 5:... |
"""
https://www.dataquest.io/blog/python-api-tutorial/
An API, or Application Programming Interface, is a server that you can use to retrieve and send data to using code.
APIs are most commonly used to retrieve data, and that will be the focus of this beginner tutorial."""
# make sure you've already installed requests... |
#!/usr/bin/env python3
from sys import argv, exit
input_filename = "input"
if len(argv) > 1:
input_filename = argv[1]
try:
input = open(input_filename)
except OSError:
exit(f'Cannot open file "{input_filename}"')
valid = 0
for passphrase in input:
words = passphrase.split()
if len(words) == len... |
from random import seed, random
"""
lista = (1, 2, 3, 4, 5, 6, 7, 8)
i = 0
while i < len(lista):
print(lista[i])
i = i + 1
"""
"""
tamanho = 50
casa_kame = (int(random() * tamanho), int(random() * tamanho))
print(casa_kame)
casa_kame = casa_kame[0] + 3, casa_kame[1]
print(casa_kame)
"""
# start é uma tup... |
from tkinter import *
import math
def drawChessboard(canvas, winWidth, winHeight):
for y in range(8):
for x in range(8):
color = 'white'
if((x+y)%2!=0):
color='#808080'
canvas.create_rectangle(x*winWidth/8.0, y*winHeight/8.0,
(x+1)*winWidth/8.0, (y+1)*winH... |
__author__ = "byteme8bit"
import datetime
# Header
def print_header():
print('----------------------')
print('| Birthday App |')
print('----------------------')
print()
# User info
def getUserBday():
print('When were you born?')
year = int(input('Year [YYYY]: '))
month = int(input(... |
import time;
from sys import argv;
from insertion_sort import insertion_sort;
from merge_sort import merge_sort;
from heap import heap_sort;
from quick_sort import quick_sort;
from counting_sort import counting_sort;
def readFromFile(fileName):
with open(fileName) as file:
lines = [int(line.strip()) for line in fil... |
# Logistic Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
# Splitting the dataset into the Training set and Test se... |
_author_ = 'Sumukha Nadig'
def retfunc(dic, key):
return dic[key] #function to return value, in order to sort according to value
def readingfile():
d = {}
d2 = {}
with open('fruits.txt', 'r') as f1: #opening file to read
f1.readlines()
f1.seek(0) #point to first line in the... |
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
start,max_repeat,max_length = 0,0,0
frequency_map = {}
# Try to extend the window
for end in range(len(s)):
right_char = s[end]
if right_char not in frequency_map:
... |
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
#1. Search trhough the grid for 1
#2. Determine for each direction if it is 0 or out of bounds
def countperimeter(grid,i,j):
count = 0
if j-1 < 0 or grid[i][j-1] == 0: count+=1 #left
... |
'''Trains a simple deep NN on the MNIST dataset.
Choose a small subset of MNIST data and overfit it - get 100% accuracy (and 0 loss) on train data and 85% accuracy (and
some loss) on validation data
Then use dropout to fix overfitting (0.9 does the job)
'''
from __future__ import print_function
import keras
from ke... |
'''Trains a simple deep NN on the MNIST dataset.
Plot how accuracy depends on the dropout rate
'''
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop, Adam
import matplotl... |
for num in range(0,10):
for i in range(2,num):
if num%i == 0:
j=num/i
print('%d bằng %d * %d' %(num,i,j))
break
else:
print(num,'là số nguyên tố') |
# 获得用户输入的一个整数N,计算并输出N的32次方。
n = eval(input('请输入一个整数:'))
print('{}的32次方是{}'.format(n, n**32)) |
# 输入一个年份,输出是否为闰年。
# 闰年条件:能被4整除但不能被100整除,或者能被400整除的年份都是闰年。
year = eval(input('请输入年份:'))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print('是闰年!')
else:
print('不是闰年!') |
# 获得用户输入的一个小数,提取并输出其整数部分。
Decimal = input('请输入一个小数:')
print('{}'.format(Decimal.split('.')[0])) |
import turtle
colors = ['red','orange','yellow','green','blue','indigo','purple']
for i in range(7):
c = colors[i]
turtle.color(c, c)
turtle.begin_fill()
turtle.rt(360/7)
turtle.circle(50)
turtle.end_fill()
turtle.done() |
# 最大公约数计算。获得两个整数,求出这两个整数的最大公约数和最小公倍数。最大公约数的计算一般使用辗转相除法,最小公倍数则
# 使用两个数的乘积除以最大公约数。
def gcd(num1, num2):
while num1 != 0:
num1, num2 = num2 % num1, num1
return num2
int1 = eval(input('请输入第一个整数:'))
int2 = eval(input('请输入第二个整数:'))
print('最大公约数为:{},最小公倍数为:{}'.format(gcd(int1,int2), int1 * int2 / gcd(int1, in... |
row=int(input("enter the number of rows:"))
column=int(input("enter the number of columns:"))
matrix=[]
for i in range(0,row):
rown=[]
for j in range(0,column):
c=int(input(f"enter the element {i}{j}:"))
rown.append(c)
matrix.append(rown)
for i in range(0,row):
for j in range(0... |
input="abcdabcde"
dislen=len(set(input))
output=""
for i in range(0,len(input)):
str1=input[i]
str2=str1
for j in range(i+1,len(input)):
str2+=input[j]
if len(str2)>=3 and len(set(str2))==dislen and len(str2)==dislen:
if len(output)<len(str2):
output=s... |
postfix="23-"
stack=[]
def operation(operator,rnum,lnum):
if operator=="*":
return lnum*rnum
elif operator=="/":
return lnum/rnum
elif operator=="+":
return lnum+rnum
elif operator =="-":
return lnum-rnum
for i in postfix:
if i.isdigit():
... |
#30086585
#Stuart Johnstone
#THis is a file that is supposed to be used in conjunction with the tictactoe.py file
#this file containst the class Board that has the purpose of dealing with the creation of the playing board and other functions
#It also contains the win conditions aswell as: checking if the board is... |
import unittest
from book_tools.dialogue_tool import dialogue_tool
class test_dialogue_tool(unittest.TestCase):
def test_get_dialogues_aps_type(self):
str_test = '“I see pretty and old cat in school” - said Adam. “Ok nice” - answered Sam.'
dialogue_tool_t = dialogue_tool()
dialogues = di... |
#10 함수 - 함수에 값 전달
#내 답안 = 선생님 답안
def mySum(num1: int, num2: int) -> None:
print(f"{num1} +dd {num2} = {num1+num2}")
res1 = mySum(2, 3)
res2 = mySum(5, 7)
res3 = mySum(10, 15)
#추가 내용(함수에서 return이 없을때 함수를 print하면 None이 나온다.
print(res1) # None
print(res2) # None
print(res3) # None
|
#!/usr/bin/env python3
# coding:utf-8
"""
实现singleton
"""
import threading
# 基于类实现
class Singleton(object):
instance = None
lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not cls.instance:
with cls.lock:
if not cls.instance:
cls.inst... |
a=int(input("enter the table you want: "))
c=0
x=0
while x<11:
d=a*c
print("{}*{}={}".format(a,c,d))
c=c+1
x=x+1
|
no=5
if no==2:
print('no=2')
elif no==3:
print('no=3')
else:
print('no is not 2 or 3')
|
import random
colors = [
"Blue",
"OliveGreen",
"Canary",
"Peach",
"Dandelion",
"Mahogany",
"Lavender",
#"SkyBlue",
#"MulBerry",
#"BrickRed",
#"Yellow",
#"Emerald",
#"Red"
]
class Node(dict):
def __init__(self, ID, name, x, y, xfact, yfact, color=None, ... |
Ustring = input("gimme a string bitch ")
if Ustring[::-1] == Ustring:
print("yeah it's a palidrone!")
else:
print("nah it's not still")
|
name = input("what's your name? ")
month = input("what is your birth month? ")
date = input("and the date? ")
year = input("of what year? ")
print("Hi " + name + "! that's a lovely name, I'll wish you a happy birthday on the " + date + " of "
+ month + " " + year)
hundred = int(year) + 100
print("you'll be 100 in... |
import random
import time
from search import *
def linearSearch(numlist, randomNumber):
for i in range(len(numlist)):
if randomNumber == i:
return i
return -1
def main():
lengthOfList = input("GIMMIE A LENGTH: ")
numlist = []
for i in range(lengthOfList):
numlist.ap... |
class Thing:
def __init__(self):
self.begining = "We the people"
obj = Thing()
print("%s" %(obj.begining))
|
def main():
x,y = input("Please enter your x value: "),input("Please enter your y\
value: ")
if x == 0 and y == 0:
print ("Origin")
elif x > 0 and y > 0:
print ("Quadrant 1")
elif x < 0 and y > 0:
print ("Quadrant 2")
elif x < 0 and y < 0:
print ("Quadrant 3")
el... |
import EECS_348_Sudoku as sudoku
import math, operator
variable_assignment_count = {0:0}
def backtrack_forward_mrv_mcv_lcv(assignment, board, domains, variable_assignment_count):
variable_assignment_count[0] = variable_assignment_count[0] + 1
# Tests for completion by adding assignments to board, then restore... |
"""
Kata: Rectangle into Squares
"""
def sqInRect(lng, wdth):
if lng == wdth:
return None
squares = []
while wdth > 0:
cnt = int(lng / wdth)
rem = lng % wdth
for i in range(0, cnt):
squares.append(wdth)
lng = wdth
wdth = rem
return squares
a... |
"""
This problem was asked by Jane Street.
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example,
car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
```python
def cons(a, b):
def pair(f):
return f(a, b)
return pair
```
Implement `... |
"""
This problem was asked by Google.
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
```text
0
/ \
1 0
/ \
1 0
/ ... |
# Animals
# Cats, Dogs, Fish
class Animal:
name = ''
def __init__(self, kind, color):
self.kind = kind
self.color = color
# self.legs = legs
def description(self):
return f'This is a {self.kind}, and its color is {self.color}'
cat = Animal('cat', 'orange')
cat.name = 'Ta... |
# Constant O(1)- takes one step.
def print_one_item(items):
print(item[0])
# Linear O(n) - goes through every item once
def print_every_item(items):
for item in items:
print(item)
# Exponential - Quardratic O(n^2)
def print_pairs(items):
for item_one in items:
for item_two in items:
... |
from math import sqrt, atan, pi, cos, sin
class Vector2D:
'''Class represents Euclidean Vector.
Contains method for method usable on plane'''
def __init__(self, init_pt, delta):
'''Create a vector, basing on coords of its init point and delta'''
self.init_pt = init_pt
self.xdelta = ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project Euler, problem 19: Counting Sundays
(http://projecteuler.net/problem=19).
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project Euler, problem 15: Lattice paths (http://projecteuler.net/problem=15).
Starting in the top left corner of a 2x2 grid, and only being able to move to
the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there thr... |
user_input = input("Enter the text => lol, rofl, lmk, smh:\n")
if user_input == "lol":
print("laughing out loud")
elif user_input == "rofl":
print("rolling on the floor")
elif user_input == "lmk":
print("let me know")
elif user_input == "smh":
print("shake my head")
else:
print("Invalid input") |
# dictionary value access by keys
ages = {"Dave":25, "Mary":65,}
print(ages["Dave"])
print(ages["Mary"])
# dictionary type 2
prim = {"red":[255,0,0],
"blue":[0,0,255],
"green":[0,255,0],}
print(prim["red"])
# giving a key which is not present in the dictionary gives keyerror
print(prim["yellow"])
#run... |
# length of the list
nums = [1, 3, 5, 2, 4]
print(len(nums))
# append list
nums.append(6)
print(nums)
# insert at one particular index
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print(words)
# to find the index of a list
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.index('r'))
print(lett... |
from _functions import *
def find_limits(symbol = 'AAPL', record_position = 2):
records = []
with open(symbol + '.csv') as f:
reader = csv.reader(f)
records = list(reader)
prices = []
for record in records:
prices.append(float(record[int(record_position)]))
bottom_limit =... |
print("Programme to print first n fibbonacci number\n")
n = int(input("Enter the value of n: "))
print("First",n,"fibonacci number")
def fib(n):
if n > 0:
(n1,n2) = fib(n-1)
nth = n1 + n2
print(nth)
return nth, n1 #returning (n-1)th and (nth) value
else:
print(0)
return 0,1
fib(n-1) #calling the funct... |
def combName(fname, lname):
try:
fname = str(fname)
lname = str(lname)
except ValueError:
return "Error"
if fname.isalpha() and lname.isalpha():
return fname + " " + lname
else:
return "Error" |
import unittest
import fibonacci
class TestFibonacci(unittest.TestCase):
def test_fib(self):
self.assertEqual(fibonacci.fib(0), 0)
self.assertEqual(fibonacci.fib(1),1)
self.assertEqual(fibonacci.fib(2),1)
self.assertEqual(fibonacci.fib(6),8)
self.assertEqual(fibonacci.fib(10... |
import random
from typing import NamedTuple
import numpy as np
import settings
EMPTY = 0
TIC = 7
TAC = 8
DRAW = 100
Move = NamedTuple('TicTacToeMove', row=int, col=int)
MoveHistory = NamedTuple('MoveHistory', state=np.array, move=Move)
class TicTacToeGameEngine:
_num_rows: int
_num_columns: int
_fir... |
import random
import string
import tkMessageBox
from Tkinter import *
# Returns a combination of letter & digits
def gen():
return random.choice(list('abcdef' + string.digits))
# prints the first digits until %, and starts printing random generation from the gen function and converts to upper case
# and then ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 17:12:29 2021
@author: eljua
"""
# numerador = 7
# denominador = 2
# división = numerador/denominador
# print(división)
# num1 = 10
# print(num1)
# num1 += 5
# print(num1)
# num1 += numerador
# print(num1)
# unBool = True
# otroBool = F... |
from find_largest_num import find_max
numbers = [3, 6, 2, 8, 4, 10]
# max is also a built in function of python to find max number so we renaming it to maximum for practice purposes
maximum = find_max(numbers)
print(maximum)
|
numbers = input("Введіть послідовність натуральних чисел через пробіл: ").split()
def count_max(list, max = 0, ind = 1, count = 0):
"""
Arguments:
list
Returns:
Count maximum elements of the list
"""
if ind == len(list):
for i in range(len(list)):... |
# <package>
# Word Ladder
# <.package>
# <description>
# Generates a word ladder between two words if it exists
# <.description>
# <keywords>
# BFS, breadth-first search, AI
# <.keywords>
# Date: 9/9/2014
# Author: Stephen Brewster
# Synopsis: Performs a breadth-first search to find the shortest path
# ... |
# Transform the 'original' string into the 'bracketed' string by
# surrounding all vowels - a, e, i, o, u in either case - by square
# <package>
# Practicum 1 - swen250
# <.package>
# <description>
# Performs some basic text manipulation, written in a 50 minute practicum
# <.description>
# <keywords>
# text... |
a = float(input("Digite a altura do triangulo: "))
b = float(input("Digite a base do triangulo: "))
p = (a + a) + b
al = (a * b) / 2
print("O perimetro do triangulo é: {0}".format(p))
print("A área do triangulo é: {0}".format(al))
|
import pygame
""" Class to create and handle InputBoxes"""
class InputBox:
def __init__(self, x, # X Coordinate
y, # Y Coordinate
w, # Width
h, # Heigth
text=''): # Text
"""Initialize pygame"""
pygame.init()
"""In... |
class Contacts(object):
def __init__(self, name,phone, email, address):
self.name = name
self.phone = phone
self.email = email
self.address = address
def get_contact(self):
return f'주소록: 이름 {self.name}, 전화번호 {self.phone}, 이메일 {self.email}. 주소 {self.address}'
@stat... |
#def Bmi(weight,height):
# return weight / height ** 2 * 10000
class Bmi(object):
def __init__(self, height, weight):
self.height = height
self.weight = weight
def getBmi(self):
bmi = ''
index = self.weight / self.height ** 2 * 10000
... |
#Cria um novo jogo
def create_new_game():
print('Um novo jogo se inicia!')
board = [['1a','2a','3a'], ['1b','2b','3b'] , ['1c','2c','3c']]
return board
# atualiza o movimento do brother
def update_board(board, movement, move_count):
for i in board:
for y in range(0, 3):
if i[y] ==... |
#Executes reformatting functions in the ReformatRainfallData module
import ReformatWeatherData
#absolute filepath of input files/output files
filepath = "INSERT FULL FILE PATH HERE"
files = [] #empty list to hold the names of .txt files for input
#add input file names to 'files'
files.append("INSERT FILE1 N... |
from functools import reduce
import utils
def pb1():
"""
Problem 1 : Multiples of 3 or 5
Simple iteration and adding when necessary.
"""
result = 0
for i in range(1000):
if (i%3 == 0) or (i%5 == 0):
result += i
return result
def pb2():
"""
Problem 2 : Even Fibon... |
#!/usr/bin/python
import sys
def translate():
inputString = input("Please enter a string for translate: ")
vowels=('a','e','i','o','u')
cacheWords = []
outputString = ' '
listOfwords = inputString.split(' ')
for i in listOfwords:
cacheLetters = []
for j in i:
if j ... |
#!/usr/bin/python
"""Build a histogram getting values from list as argumments from command line"""
import sys
InputOfNumbers = sys.argv[1:]
def histogram(ListOfNumbers):
for i in ListOfNumbers:
print '*'*int(i)
if __name__=="__main__":
histogram(InputOfNumbers)
|
"""
Simple script to check the influence of male/female distribution in the input on the output.
"""
import random
from collections import Counter
import matplotlib.pyplot as plt
## FUNCTIONS ##
def create_employee_list(reps, input_choices):
"""
Given a list of males / females available, choose at random a... |
def combinationWithBacktracking(inputList,partialSolution,size,start):
if len(partialSolution)==size:
print(partialSolution)
return
if start ==len(inputList):
return
for i in range(start,len(inputList)):
partialSolution.append(inputList[i])
combinationWithBacktracking... |
import time
all_solutions=[]
def sequenceYieldingMax(inputList,partialSolution,target_value,start):
if target_value==0:
all_solutions.append(partialSolution.copy())
return
elif start>len(inputList):
return
for i in range(start,len(inputList)):
choosenOne=inputList[i]
... |
truth="orange"
truth_2="man"
truth_3="bad"
ultimate_truth=truth+" "+truth_2+" "+truth_3
print(ultimate_truth)
man="orange"
if man=="orange":
print("bad")
else:
print("good")
|
import sqlite3 as lite
import sys
try:
con = lite.connect('books1.db')
cursor = con.cursor()
cursor.execute('CREATE TABLE if not exists books1( name text not null ,author text not null,read boolean)')
#cursor.execute("insert into employees values (1,'subbu',30, 'america')")
#con.commit()
... |
# Lab 12 RNN
from string import ascii_uppercase
from collections import OrderedDict
from itertools import count
import torch
import torch.nn as nn
from torch.autograd import Variable
import pre_process as pre
'''
THis is a practice for using torch to implement simple, one cell RNN.
It takes sequence of alphabet lett... |
#definitions
import RPi.GPIO as GPIO #add GPIO library
import time #add time library
import random
GPIO.setmode(GPIO.BOARD) #set how to refer the RPi pins
led=37 #pin number for the led
GPIO.setup(led,GPIO.OUT)#defined pin as output
#program
try:
while True:
GPIO.output(led,1) #turn on the led
time.sleep(0.5)#slee... |
def calculate(first_number, second_number, operator):
result = 0
if operator == "+":
result = first_number + second_number
elif operator == "-":
result =first_number - second_number
elif operator == "*":
result = first_number * second_number
elif operator == "/":
result = first_number / secon... |
import nltk
import numpy as np
from nltk.tokenize import word_tokenize
# question 7
sentence = "The dog was big but it was so doggy and dog"
word_list = word_tokenize(sentence)
word_set = set(word_list)
freq = {}
for word in word_set:
freq[word] = word_list.count(word)
print(word,' : ',freq[word])
print('---... |
print ("SUM OF 2 NUMBERS")
num1=input("Enter first number:")
num2=input("Enter second number:")
sum=int(num1)+int(num2)
print ("Sum:",sum)
|
# i = 1
# while i < 6:
# print(i)
# if i == 3:
# break
# i+=1
# m = 0
# while m<1 or m>12:
# m = int(input('Podaj miesiac:'))
# a = int(input('Podaj a:'))
# b = int(input('Podaj b:'))
# while a != b:
# if a > b:
# a -= b
# else:
# b -= a
# print('NWD: '+ str(a))
# a = i... |
import math
a=float(input())
b=int(input())
c=1
c=a
i=1
while (i<abs(b)):
c*=a
i+=1
if b>0:
print(c)
elif b<0:
print(1/c)
elif b==0:
print("Результат = 1")
|
#note this reqires the simplegui module which is available at www.codeskultor.com
import simplegui
import random
#important global variables
frame_width=700
frame_height=400
player1_score=0
player2_score=0
#Paddle global variables
paddle_width=10
paddle_height=100
paddle1_position=(frame_height/2)-(paddle_height/2)
... |
class Experience:
def __init__(self, name, company, year):
self.__name = name
self.__company = company
self.__year = year
#def getName(self):
# return self.__name
#def setName(self, name):
#self.__name = name
def __str__(self):
return self.__name + ' ' + self.__company + ' ' + str(self.__year... |
def make_map(size_squared):
size_squared += 2
map_string = []
map_string.append(list('0'*(size_squared+1)))
for i in xrange(size_squared-1):
map_string.append(list('0' + '.'*(size_squared-1) + '0'))
map_string.append(list('0'*(size_squared+1)))
map_string[1][1] = 's'
map_st... |
def is_palindrome(n):
s = str(n)
l = len(s)
if l%2!=0:
return s[:l/2] == ''.join(reversed(s[l/2+1:]))
else:
return s[:l/2] == ''.join(reversed(s[l/2:]))
pals = []
for i in xrange(1, 1000000):
if is_palindrome(i) and is_palindrome(bin(i)[2:]):
print i
... |
while True:
print('Plese enter your name')
name = input()
if name != 'Joey':
continue
print("Hey Joey what is the password ? Is it a fish")
password = input()
if password == 'swordfish':
break
print("access granted")
|
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 1 18:56:39 2017
@author: Gert-Jan
"""
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)... |
#!/usr/bin/env python
import argparse
import os
import sys
from src.compressor import Decompressor as cc
def parse():
desc = """\
Sliding Window Decompressor by Zijie Wu
Example usage:
cli_file_decompress book1.txt.s ...
"""
parser = argparse.ArgumentParser(description=desc, formatter_class=argparse.Ra... |
#!python3
"""
Functions related to inversions of elements in arrays.
Author: Erel Segal-Halevi (collected from various sources)
Date: 2017-02
"""
import functools
from typing import Sequence
@functools.lru_cache(maxsize=None)
def numNPermutationsWithAtMostKInversions(N: int, K: int) -> int:
"""
Return the numb... |
number="9,223;372:036 854,775;807"
seperators = ""
for char in number:
if not char.isnumeric():
seperators = seperators+char
print(seperators)
values="".join(char if char not in seperators else " " for char in number).split()
print([int(val) for val in values])
|
from cs50 import get_int
while True:
n = get_int("Height from 1 to 8: ")
if n > 0 and n <= 8:
height = n
width = height
break
print(f"Height: {n}")
for i in range(n):
width -= 1
print(" " * width, end="")
print("#" * (height - width), end="")
print()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.