text stringlengths 37 1.41M |
|---|
# temp_convert_function.py
# Matthew Shaw
# Sunday, 4 October 2015 14:40:03
def c2f(celcius):
fahrenheit = celcius * 9/5 + 32
print (celcius, "degrees Celcius is", fahrenheit , "degrees fahrenheit")
celcius = float(input("Please enter the tempreature to be converted: "))
c2f(cel... |
#quadratic solver
from math import sqrt
a = int(input('Enter a value for a: '))
b = int(input('Enter a value for b: '))
c = int(input('Enter a value for c: '))
discriminant = b*b - 4*a*c
discriminant = sqrt(discriminant)
xplus = (-b + discriminant) / (2*a)
xminus = (-b - discriminant) / (2*a)
print ('The roots o... |
a = [3, 4, 5, 6]
b = ['a', 'b', 'c', 'd']
def zipper(a,b):
newZip = []
if len (a) == len(b):
for i in range(len(a)):
newZip.append([a[i], b[i]])
print (newZip)
if len(a)!= len(b):
print("lists do not match")
zipper(a,b)
|
from math import sqrt
prev = 1
L = [prev]
for n in range (19):
rooted_number = sqrt(prev + 1)
L.append(rooted_number)
prev = rooted_number
for i in L:
print(i)
|
user_sum = input("keep entering numbers, end with q or Q: ")
total = []
while user_sum != 'q':
total.append(int(user_sum))
user_sum = input("keep entering numbers, end with q or Q: ")
print(sum(total)/len(total))
|
S = 'A'
n = 10
rules = {'A':'AB', 'B' : 'A'}
def srs_print(S):
"""Re-write an axiom according to given rules"""
newaxiom = ''
for i in S:
## if i in rules.items():
## newaxiom +=
for k, v in rules.items():
if i ==k:
newaxiom += v ... |
# Program name: Ch 11 Example 2 transfer film records.py
# transfer records to film database from text file
import sqlite3
# function to read text records and store in record filmDBRec[]
def readTextFile(filmFile):
connection = sqlite3.connect("./Chapt 11/MyFilms.db")
cursor = connection.cursor()
numRecs... |
# Creates a table called tbleTemps in database CityTemperatures.db
# then adds temperatures for several cities to tblTemps
import sqlite3
conn = sqlite3.connect("./Chapt 11/CityTemperatures.db")
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE tblTemps
(city TEXT,
... |
"""
You are climbing a stair case. it takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
"""
import unittest
def climb_stairs(n):
# n represents number of steps on the stairs
prev_steps = {1: 1,
2: 2}
if n no... |
"""
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
"""
def reorder(head):
if not head:
return
slow, curr, fast = head, head, head
prev = No... |
"""
Invert the tree given the root
"""
def invert_tree(root):
if root:
stack = [root]
else:
return root
while len(stack) > 0:
curr = stack.pop()
hold = curr.left
curr.left = curr.right
curr.right = hold
if curr.left:
stack.append(curr... |
"""
Write a program that outputs the string representation of numbers from 1 to n
Multiples of three should output Fizz
Multipes of five should output Buzz
Multiples of three and five should output FizzBuzz
"""
def fizz_buzz(n):
for num in range(1, n+1):
if num % 3 == 0 and num % 5 == 0:
print... |
import pygame
from pygame import sprite
import sys
import random
import time
import math
TIME_TO_WAIT = 100
DROP_ALL = False
SHOTS = []
MARCH_RIGHT = True
PLAYING_GAME = True
pygame.init()
class Move(sprite.Sprite):
def __init__(self):
pass
def move_up(self):
self.rect.y -= 1
pass
... |
mylists = ["banana", "cherry", "apple"]
print(mylists)
item = mylists.sort()
print(mylists)
mylists.sort()
new_list = sorted(mylists)
print(mylists)
item = mylists.reverse()
print(mylists)
mylists2 = [5, True, "apple", "apple"]
print(mylists2)
item = mylists[0]
print(item)
for i in mylists:
... |
#
# Project Euler: https://projecteuler.net/problem=4
#
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 × 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
# (Solution: )
#
def solve():
print(solve())... |
import turtle
from turtle import *
turtle.setup(1000, 600)
screensize(2000, 1200)
def r(a,color): #a es el ancho
fillcolor(color)
b = int(a/2)
begin_fill()
goto(a,0)
goto(a,a*2)
goto(a*3,0)
goto(a*4,0)
goto(a*2,a*2)
LinInv(a*2,a*5)
turtle.circle(-(b*3),180)
... |
buildings = [0, 0, 3, 5, 2, 4, 9, 0, 6, 4, 0, 6, 0, 0]
result = 0
view_building = 0
for i in range(2, len(buildings) - 2):
if buildings[i] > buildings[i - 1] and buildings[i] > buildings[i - 2] and buildings[i] > buildings[i + 1] and \
buildings[i] > buildings[i + 2]:
max_building = max(building... |
from collections import deque
numbers = int(input())
for number in range(numbers):
N, M = map(int, input().split())
arrays = [list(map(int, input().split())) for i in range(M)]
result = deque() # result를 deque로 설정해서 최종적인 수열을 여기에 넣을거다.
result.extend(arrays[0][:]) # 그리고 시작점을 설정한다. 첫번째 수열은 딱 다 들어가기!! in... |
numbers = int(input())
for number in range(numbers):
str1 = input()
str2 = input()
Maxval = 0
str_dict = {}
for i in str1:
str_dict[i] = 0
for i in str2:
if i in str_dict:
str_dict[i] = str_dict[i] + 1
for key, val in str_dict.items():
if val > Maxval... |
TF = [0]*2
def makingRoom(room, dipth, wantN, TF):
TF[0] = 1
TF[1] = 0
return 2
def backtrack(room, dipth, wantN):
global powerset
if dipth == wantN:
result = 0
for jj in range(1, 11):
if room[jj] == 1:
result += powerset[jj-1]
if result == 10:
... |
# UNION --> Perform union of 2 arrays .
list1 = [1,23,7,89,231,45,78,11]
list2 = [2,78,23,111,56,78,0,9]
list3=[]
print("List 1 : ",list1)
print("List 2 : ",list2)
length=len(list1)+len(list2)
for i in list1:
list3.extend([i])
for i in list3:
for j in list2:
if j in list3:
contin... |
# TriangleAsum --> In case of 3*3 matrix , TriangleAsum contains elements of index (00,01,02,11,22,22)
# Condition to check if triangle exists in the matrix --> No. of rows = No. of columns of the given matrix
list1=[[10,20,30],[40,50,60],[70,80,90]]
len_r=len(list1)
len_c=[] # To store number of colu... |
"""Custom Variable classes"""
import tkinter as tk
class PrefixNumberVar(tk.DoubleVar):
"""A number unit that can have an ISO prefix """
prefixes = {
'pico': 10 ** -12,
'nano': 10 ** -9,
'micro': 10 ** -6,
'milli': 10 ** -3,
'': 1,
'kilo': 10 ** 3,
'meg... |
# Given an array of integers, print all subarrays having 0 sum.
# O(n^2)
def subarray_sum_0(array):
for i in range(len(array)):
total = 0
for j in range(i, len(array)):
total += array[j]
if total == 0:
print('Subarray: {}...{}'.format(i, j))
l = [3, 4, -... |
# Given an binary array, find maximum length sub-array having equal number of 0's and 1'.
# O(n^2)
def max_length_subarray(array):
start = 0
end = -1
length = 0
for i in range(len(array)):
zeros = ones = 0
for j in range(i, len(array)):
if array[j] == 0:
z... |
import numpy as np
# Create a matrix
A = np.array([[1,2],[3,4]])
print "A"
print A
# Find inverse
Ainv = np.linalg.inv(A)
print "A inverse"
print Ainv
# Find whether Identity matrix arrives
print "Identity Matrix = Ainv * A"
print Ainv.dot(A)
print A.dot(Ainv)
# Find determinant
D = np.linalg.det(... |
# Create a nice greeting to welcome your users to your Brand Name Generator App
# code...
# initialize the two variables as empty strings
#code..
# simple check to make sure the user has entered the first word {Hint: use while loop}
# if there's no input, ask again
# if there's any input at all, contin... |
number1 = int(input("Sisesta number: "))
number2 = int(input("Sisesta number: "))
print ("Esimene number on" + str(number1)+ "ja teine number on"+ str(number2), end="")
#liidab teise lause esimesega: end=""
print ("Esimene number on " + str(number1)+ " ja teine number on "+ str(number2))
print ("Numberite 1 ja 2 summa... |
# line 2 prints the text "I will now count my chickens:"
print("I will now count my chickens:")
# line 4 prints the word "Hens" then does a calculation for the result of 25 + 30 / 6
print("Hens", 25 + 30 / 6)
# line 6 prints the word "Roosters then does a calculation for the result of 100 - 25 * 3 % 4
print("Roosters",... |
import numpy as np
class MatMul:
def __init__(self, W):
self.params = [W]
self.grads = [np.zeros_like(W)] # W와 같은 크기의 0행렬 생성
self.x = None
def forward(self,x):
W, = self.params
out = np.matmul(x,W)
self.x = x
return out
def backward(self,dout):
... |
# python-day-1-assignment
#dictionary
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
print(person.items())
print(person.copy())
print(person.keys())
print(person.values())
print ('name: ',person.get('name'))
|
import random
class Max_Heap:
def __init__(self,arr=[]):
self.Heapify(arr)
self.h=arr
self.removed=set()
def Heapify(self,arr):
for i in range(len(arr)//2,-1,-1):
self.NodeHeapifyDown(arr,i)
def NodeHeapifyDown(self,arr,i=0):
largest=i
if (2*i)+1<l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 16:33:47 2020
@author: max
"""
def taxi_zum_zum(moves):
x=0
y=0
direction= 1
for i in range(len(moves)):
if moves[i] == 'F':
if direction == 1:
y+= 1
if direction == 2:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 22:48:02 2020
@author: max
"""
def dubfind(a_list):
compstart=1
for i in a_list:
comps= a_list[compstart:]
for c in comps:
print(i,c)
if c == i:
return True
compstart+= 1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 18:01:08 2020
@author: max
"""
def factorial(num):
if num==0:
return 1
return num*factorial(num-1)
vowels= ['a', 'i', 'e', 'o', 'u']
def all_strings(letters):
print(all_strings)
all_string... |
def evenNumber():
n = int(input())
a = list(map(int, input().split()))
for x in a:
if(x % 2 == 0):
print(x)
evenNumber() |
def solution():
m = input()
a = []
previous = ""
for x in range(len(m)):
if(previous == "" or previous == " "):
a.append(m[x].upper())
previous = m[x]
l = len(a)
for y in range(l):
if(y == l - 1):
print(a[y])
else:
print(a... |
def solution():
n = int(input())
t = recursive(n)
print(t)
def recursive(n):
if(n == 0 or n == 1):
return 1
return recursive(n - 1) + recursive(n - 2)
solution() |
import math
class Triangle:
def __init__(self, a = 1, b = 1, c = 1):
self.a = a
self.b = b
self.c = c
def dt(self):
s = (self.a + self.b + self.c) / 2
dt = math.sqrt(s*((s - self.a)*(s - self.b)*(s - self.c)))
return dt
class Point:
def __init__(self, x = 0, ... |
def resursive(ar, index):
if(index == len(ar) - 1):
return ar[index]
return ar[index] + resursive(ar, index + 1)
def simpleArraySum(ar):
total = resursive(ar, 0)
print(total)
simpleArraySum([1,2,3,4,10,11]) |
def maxLike():
n = int(input())
a = list(map(int, input().split()))
max = 0
for l in a:
if(l > max):
max = l
print(max)
maxLike() |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv('50_Startups.csv')
X = dataset.iloc[:,:-1].values
y= dataset.iloc[:,4].values
# Encoding categotrical data
#encoding the Independant Variable
from sklearn.preprocessing i... |
def compare (a,b):
if len(a)==len(b):
l = len(a)
result = ""
remains_a, remains_b = "",""
for i in range(l):
if a[i]==b[i]:
result += "1"
else:
remains_a += a[i]
remains_b += b[i]
for char in remains_a:... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 11 09:57:55 2018
@author: usov
"""
class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set ... |
#import time
#start_time = time.time()
# the outstanding balance on the credit card
balance = 3329
# annual interest rate as a decimal
annualInterestRate = 0.2
avgMonthPayment = ((balance + annualInterestRate * balance)//12)//10*10
def dept(monthBalance, annualInterestRate, minMonthPayment):
# print(minMonthPayme... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 11:09:44 2018
@author: ART
"""
def longestRun(L):
tmp = 1
ans = 1
for idx in range(len(L[:-1])):
# print(L[idx], L[idx+1])
if L[idx] <= L[idx+1]:
tmp += 1
if tmp > ans:
ans = tmp
else:
... |
#!/usr/bin/env python
""" Given scores of N athletes, find their relative ranks and the people with
the top three highest scores, who will be awarded medals: "Gold Medal", "Silver
Medal" and "Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanati... |
TYPES:
how python represents different type of data.
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
EX: type(11)= int
type(21.21)= float
type("Hello")= str
TYPECASTIN... |
a=int(input('vvedi chislo'))
def chisla(a):
'''выводит четные числа'''
for i in range(2, a, 2):
print(i)
chisla(a)
print(chisla.__doc__) |
def sayHello(name):
print('hello {0}'.format(name))
coun=input('how many users?')
for i in range(1,int(coun)+1):
n=input('{0} user name?'.format(i))
sayHello(n)
print('end')
|
import random
from asciicards import assignArt
class Player():
def __init__(self):
self.name = ""
self.age = 0
self.stack = 0
self.position = ""
self.card = []
def print_register(self):
print("-------------------------------------------------------------------... |
def reverse(word):
x = ''
for i in range(len(word)):
x += word[len(word) - 1 - i]
return x
word = raw_input('Give a text: ')
y = reverse(word)
if y == word:
print 'It is a Palindrome'
else:
print 'It is NOT a Palindrome'
|
num = int(raw_input("Please choose a number to divide: "))
list_range = list(range(1, num + 1))
divisors = []
for i in list_range:
if num % i == 0:
divisors.append(i)
print divisors
|
'''
Gauss Seidel :
Number of Inputs (4) :
- (Ax = b) A matrix of coffecients,
- b vector ,
- initial vector,
- espilon(stopping criteria)
Number of outputs (2) :
- solution(vector) ,
- approximate error.
SOR :
Number of Inputs(5) :
- A matrix of coffecients,
- b vector ,
- initial vector,
- omega ,
- espilon(sto... |
import numpy as np
def curve_fitting(x,y,degree=1):
"""
calculates the coefficients to fit (x, y) using a polynomial
of the specified degree
:param x the input data points
:param y the output data points
:return the coefficients of the polynomial that best fits (x, y)
"""
x=np.array(x)
... |
print("FOLLOW THE INSTRUCTIONS TO FIND THE USER")
print("*************************************************************")
In1="To search by ID: Go to Facebook.com and find the UserID which would look something like this: 10003340872XXXX"
In2="To search by Phone Number: Type the phone number in the prompt"
print(In1)... |
"""Custom topology example
Two directly connected switches plus a host for each switch:
3 switches, 4 hosts
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class MyTopo( Topo ):
... |
#!/usr/bin/python
import sys
import os
import re
import copy
#import networkx as nx
#import matplotlib.pyplot as plt
#atom = value[]
def atom_intersection(atom1,atom2):
ans = []
for i in range(len(atom1)):
if (atom1[i] == atom2[i]):
ans.append(atom1[i])
elif (atom1[i] == -1):
ans.append(atom2[i])
elif... |
# Function based Test Case
def test_one_plus_one():
assert 1 + 1 == 2
# Grouping similar Test Case into a Class
class TestArithmetic:
def test_addition(self):
assert 1 + 1 == 2
def test_multiplication(self):
assert 2 * 3 == 6
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 10 22:00:27 2018
@author: Alina
"""
def foo(x, y = 5):
def bar(x):
return x + 1
return bar(y * 2)
foo(3, 0)
print(foo(3, 0) )
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 26 15:22:28 2018
@author: Alina
"""
def factorial(x):
multiply = 1
while x > 0:
multiply *= x
x=x-1
return multiply
print(factorial(4)) |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 22:56:40 2018
@author: Alina
"""
n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
# Don't forget to return your new list!
print(double_list(n)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 10 23:03:06 2018
@author: Alina
"""
def recur_power(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
if exp == 0:
return 1
elif exp == 1:
return base
else:
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
a = set()
output=""
n = int(raw_input())
for i in range(0,n):
line = raw_input()
input = re.split("(<\w.*?>)", line)
for x in input:
m = re.search("<([^/].*?)[\s>]", x)
if m:
a.add(str(m.group(1)))
ou... |
import random
import time
DELAY = 0.5
SUITS = ["hearts", "diamonds", "clubs", "spades"]
NAMES_SCORES = [
("one", 1),
("two", 2),
("three", 3),
("four", 4),
("five", 5),
("six", 6),
("seven", 7),
("eight", 8),
("nine", 9),
("ten", 10),
("jack", 10),
("queen", ... |
import unittest # Importing the unittest module
from password2 import Credential # Importing the contact class
class TestCredential(unittest.TestCase):
'''
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test case... |
# names = ["Joanna", "Luis", "Anna"]
#
# print(names)
# print(type(names))
#
#
# #indexing
# print(names[0])
#
# #index 1 to the last element
# print(names[1:])
ten_objects = ["orange", "banana", "pear", "strawberry", 500, "grape", "cherry", "pineapple", "eggs", "milk"]
print(type(ten_objects))
print("The 3rd elemen... |
import random
def starting():
user_input = input("\ndo you want to play a game? Y/N ")
if user_input == "Y" or user_input == "y":
start_game()
else:
print("Goodbye..!")
def start_game():
print("i will try to guess your number\n")
random_number_to_add_later = random.randrange(1,500)
... |
lst = [1,4,2,6,-2,3]
sml = lst[0]
for i in lst:
if(i < sml):
sml = i
print("Smallest Number = ",sml)
|
# abrindo arquivo excel
from openpyxl import load_workbook
# a função load_workbook('arquivo.xlsx') retorna um objeto
# book com os dados do arquivo excel. Para saber quais os nomes
# das planilhas existentes pode usar a propriedade book.sheetnames
book = load_workbook('sample.xlsx')
# print(book.sheetnames)
# obter... |
start = '''
It is the year 2030, global warming has not been solved, and because humans suck
we have broke out in a zombie apocalypse. Your goal is to survive, but if you
decide that you don't want to anymore than that is cool too. You do you homie.
'''
keepplaying = "yes"
print(start)
while keepplaying == "Yes" or ... |
def isPalindrome(s):
return s == s[::-1]
def dec_to_bin(x):
return int(bin(x)[2:])
# Driver code
i = 11
s = str(11)
b = dec_to_bin(i)
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
print(b)
|
class PiggyBank:
def __init__(self,dollars,cents):
if cents < 100:
self.dollars = dollars
self.cents = cents
else:
self.dollars = dollars + cents // 100
self.cents = cents - 100 * (cents//100)
def add_money(self,dollars,cents):
self.dollars... |
##### 2.2
# Write Python code that prints out the number of hours in 7 weeks.
print
7 * 7 * 24
# 1176
##### 2.6 Bodacious Udacity
# Given the variables s and t defined as:
s = 'udacity'
t = 'bodacious'
# write Python code that prints out udacious
# without using any quote characters in
# your code.
print
s[:2] + t... |
#!/usr/bin/env python
# import re
# import math
# import collections
DEFAULT_INPUT_FILE = "input/part1.txt"
def perform_calculation(codes, index=0):
code = codes[index]
if code == 1:
a = codes[index+1]
b = codes[index+2]
c = codes[index+3]
codes[c] = codes[a] + codes[b]
elif code == 2:
a = codes[index+... |
#!/usr/bin/env python
import re
# import math
# import collections
from itertools import permutations
from fractions import gcd
# Wrong answer: 9172794540
DEFAULT_INPUT_FILE = "input/part1.txt"
DEFAULT_STEPS = 5
class Moon(object):
def __init__(self, name, x, y, z):
self.name = name
self.x = x
self.y = y
... |
#!/usr/bin/env python
from math import floor
DEFAULT_INPUT_FILE = "input/part1.txt"
def main(args):
with open(args.file, "r") as fh:
total = 0
for line in fh:
if line.strip() == '':
pass
x = int(line.strip())
total += floor(x/3) - 2
print(int(total))
if __name__ == '__main__':
import argparse
... |
# -*- coding: utf8
'''ContiguousID class'''
from __future__ import print_function, division
from collections import Mapping
class ContiguousID(Mapping):
'''
A ContiguousID is a dict in which keys map to integer values where values
are contiguous integers.
Example:
>>> x = ContiguousID()
... |
import time
import os
import sys
import transposition
class InvalidInputException(Exception):
pass
def main():
mode = input("Enter 'E' to encrypt or 'D' to decrypt ")
input_filename = input('Enter filename for input text: ')
if not os.path.exists(input_filename):
raise InvalidInputException(... |
from tkinter import *
class VentanaPrincipal(Frame):
def __init__(self, geom):
Frame.__init__(self, )
self.hig, self.wid = geom
Label(self, text='Cantidad de alimentos escogidos por grupo etario Diario', font=18).place(x=20, y=30)
Label(self, text='Edad', font=12).place... |
class Person:
def __init__(self, f, l):
self.first = f
self.last = l
def print(self):
print(self.first, self.last)
def swapFirstLast(p):
p.first , p.last = p.last, p.first
person = Person("Jon", "Snow")
person.print()
swapFirstLast(person)
person.print()
|
import time
DIR_RIGHT = 0
DIR_UP = 1
DIR_LEFT = 2
DIR_DOWN = 3
class AdventOfCode:
def __init__(self, filename):
with open(filename) as f:
self.input = f.read().splitlines()
def make_grid(self):
grid = Grid(len(self.input[0]), len(self.input))
for y, lin... |
class AdventOfCode:
def __init__(self, filename):
with open(filename) as f:
lines = f.read().splitlines()
self.nodes = {}
for line in lines:
node = TreeNode(line)
self.nodes[node.id] = node
self.top_node = None
def part1(self):
for n... |
#the game!
import random
print("This is me making a game!")
#character_stats():
name=""
level=1
max_hp=10+(level*5)
current_hp=15
current_exp=0
req_exp=10*level
max_level=10
#name=input("What is your name? ")
print("Your name is",name)
print("level:",level)
print("Max HP:", max_hp)
print("Current HP:", current_hp)
... |
import numpy as np
import elliptical_u_est as ellip
# household functions
def FOCs(b_sp1, n_s, *args):
'''
For the S-period problem, we have 2S-1 FOCs corresponding to the savings variable b, and the labor supply variable n
Note that we were dealing with three dimensional vectors earlier. We now have an ... |
# MIT 6.189
# Project 1
# Author: Denis Savenkov
# File: questions sol.py
def all_less_6(a_list):
for val in a_list:
if val >= 6:
return False
return True
list1 = [1, 5, 3, 4]
list2 = [5, 3, 7, 5]
print all_less_6(list1)
print all_less_6(list2)
def one_less_6(a_list):
... |
# Savenkov Denis
# rps.py
#create variables for rock,paper,scissor and for results:
r = "rock"
p = "paper"
s = "scissors"
t = "Tie."
p1 = "Player 1 wins."
p2 = "Player 2 wins."
#get figure from players
player1 = raw_input("Player 1? ")
player2 = raw_input("Player 2? ")
#create conditions for output
i... |
# Denis Savenkov
# zellers.py
# collect date of birth from user
print "Enter your date of birth:"
month = input("Month as a number between 1 and 12, starting from March? ")
day = input("Day? ")
year = input("Year? ")
#create zellers algorithm
a = month
if a == 11 or a == 12:
c = c - 1
b = day
c = ye... |
a = int(input("Введите А = "))
b = int(input("Введите B = "))
ch = 0
nech = 0
n = a
while (n >= a) and (n <= b) and (a <= 100) and (b <= 100):
if n % 2 == 0:
ch = ch + n
n = n + 1
else:
nech = nech + n
n = n + 1
print("Сумма четных = " + str(ch))
|
"""Defines class responsible for cars' table in database."""
import sqlite3
class CarsDatabase:
"""This class operates on a table 'cars' in database."""
def __init__(self, db):
"""Inits CarsDatabase."""
self.conn = sqlite3.connect(db)
self.c_cursor = self.conn.cursor()
self.c_... |
def swap(index1, index2, array):
temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
return array
def bubble_sort(array):
length = len(array)
for i in range(length):
swaps = 0
for n in range(length - 1 - i):
if array[n] > array[n+1]:
swap(n, n+1, array)
swaps += 1
if swaps... |
# Princeton algo course
# Linear time
import random
def shuffle(alist):
# Iterate through all positions of alist
for i in range(1, len(alist)):
# Generate a random number between 0 and i
random_index = random.randrange(0, i)
# Swap the values of random number and i
temp = alist[i]
alist[i] = alist[random_... |
from tkinter import *
root = Tk()
label1 = Label(root, text="First label", bg="Grey", fg="White")
# the fill=X adjusts the size of the label in the horizontal plane with change in the size of the window
label1.pack(fill=X)
label2 = Label(root, text="Second label", bg="Black", fg="White")
# the fill=Y adjusts the s... |
'''
dengan membaca file kita bisa menampilkan isi dari sebuah file
sumber referensi: https://www.petanikode.com/python-file/
ditulis pada padal: 14-02-2021
'''
#membuka isi dari sebuah file
#r = read, memungkinkan untuk membaca isi dari sebuah file
file = open('file.txt', 'r')
#membaca hanya 1 baris
isi_file = file.... |
'''
dengan menggunakan metode ini kita bisa menentukan jenis variable yang akan digunakan
sumber referensi: pintaar module
ditulis pada: 06-03-2021
'''
class Variable:
def __init__(self):
'''
Public Variable
Merupakan Variable yang dapat diakses semua orang dan dapat dipanggil dengan muda... |
entradaNum = list(map(int, input().split()))
entradaNum.sort()
entradaLet = input()
if (entradaLet == 'ABC'):
print(entradaNum[0], entradaNum[1], entradaNum[2])
elif (entradaLet == 'ACB'):
print(entradaNum[0], entradaNum[2], entradaNum[1])
elif (entradaLet == 'BAC'):
print(entradaNum[1], entradaNum[0... |
import json
import requests
from datetime import datetime
from local import USERNAME, PASSWORD
def translate(text, source_language, target_language):
# GET REQUEST
url = "https://gateway.watsonplatform.net/language-translator/api/v2/translate"
querystring = {"text":text,"model_id":"{0}-{1}".format(source_l... |
#!/usr/bin/env python
'''
Counting DNA Nucleotides
'''
def count_dna_nucleobases(data):
'''
Count the number of times each DNA nucleobase occurs in data.
Input:
- data: string of DNA nucleotides
Output:
- A: number of times A occurs in data
- C: number of times C occurs in data
... |
if __name__ == '__main__':
klist = [
"good ", "good ", "study",
" good ", "good", "study ",
"good ", " good", " study",
" good ", "good", " study ",
"good ", "good ", "study",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
... |
if __name__ == '__main__':
s=[1,2,3,4,5]
q=s.__len__()
print(q)
q=len(s)
print(q)
for l in s:
print("下标为{1}[{0}]".format(l.__index__()-1,l)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.