text stringlengths 37 1.41M |
|---|
#%%
# Open the flat txt file (text of moby dick novel)
# Remember the process of open and close file
file = open("moby_dick.txt", mode = 'r')
# Print file
print(file.read())
# Check whether file is closed
print(file.closed)
# close file
file.close()
# Check again whether file is closed
print(file.closed)
#%%
# ... |
#%%
# Define function plot_pop() which takes 2 arguments:
# 1. The filename of the file to be processed
# 2. the country code of the rows to process in dataset
# The function will do:
# - Loading of the file chunk by chunk
# - Creating the new column of urban population values
# - Plot the urban population data
# %%... |
#%%
# toss game: 1 - tail, 0 for head
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(123)
final_tails = [] #show numbers of tails for each 10 times tosses
# do the work 100 times of toss x times
for x in range(10000):
tails = [0]
# toss 10 times
for x in range(10):
coin = np.rand... |
# IMPORT FLAT FILES USING PANDAS
# 1. What a data scientist needs?
# - Two dimensional labeled data structure(s)
# - Columns of potentially different types
# - Manipulate, slice, reshape, groupby, join, merge
# - Perform statistics
# - Work with time series data
# DataFrames are observations and variables
... |
import sys
import operator
my_operators = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"\\": operator.truediv,
":": operator.truediv
}
def calculator(x,y,z):
try:
return y(int(x),int(z))
except ZeroDivisionError:
re... |
# Given a non-empty array of integers, every element appears twice except for one. Find that single one.
#
# Note:
#
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution:
def singleNumber(self, nums):
for i in range(1, len(nums)):
... |
# Populating Next Right Pointers in Each Node
# Solution
# You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
#
# struct Node {
# int val;
# Node *left;
# Node *right;
# Node *next;
# }
# Populate each nex... |
class Solution():
def bigger_left(self, nums):
stack = []
new_list = nums[::-1]
print('nums:', nums)
print('nes_list:', new_list)
res = [0] * len(nums)
for i in range(len(nums)):
while stack and new_list[stack[-1]] < new_list[i]:
temp = s... |
#
# Daily Temperatures
# Solution
# Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days
# you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
#
# For example, given the list of temperatures ... |
# Target Sum
# Solution
# You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
#
# Find out how many ways to assign symbols to make sum of integers equal to target S.
#
# Example 1:
# Inpu... |
from binarytree import Node
root = Node(3)
root.left = Node(6)
root.right = Node(8)
# Getting binary tree
print('Binary tree :', root)
# Getting list of nodes
print('List of nodes :', list(root))
# Getting inorder of nodes
print('Inorder of nodes :', root.inorder)
# Checking tree properties ... |
#string functions
def starts(sentence):
if sentence.startswith("M"):
print("the given sentence starts with H")
else:
print("the given sentence doesn't start with H")
print(starts("Mad titan"))
|
def generalTuple():
# general tuple - 1
emptyTuple = ()
print(emptyTuple)
numbersTuple = (1, 2, 3, 4, 5)
print(numbersTuple)
stringTuple = ('IND', 'AUS', 'KOR')
print(stringTuple)
generalTuple()
|
# list for loop
def reverseList(my_list):
my_list.reverse()
return my_list
my_list = ['♾Infinity', 'knew', 'who', 'man', 'The']
print(reverseList(my_list))
for i in my_list:
print(i)
|
def dictionary9():
employee_dict = {
'name': 'sam',
'company': 'abc',
'role': 'software architect',
}
# using len()
print(len(employee_dict))
# using keys()
keyCounter = 0
for key, value in employee_dict.items():
print(key + ':', value)
keyCounter = ke... |
def indexing(my_list):
firstItem = my_list[0]
lastItem = my_list[len(my_list) - 1]
negativeIndexing = my_list[-2]
# normal copy
my_list_copy = my_list
print(my_list_copy)
# using copy method
my_list_copy2 = my_list.copy()
print(my_list_copy2)
slicing = my_list[0:4]
return [fi... |
def colours(color1, color2, color3):
return color1 + ' ' + color2 + ' ' + color3
print(colours(color1='red',color2='blue',color3='green')) |
# list concatenate , repeat, length
def opertorsList(list1, list2):
concatenation = list1 + list2
repeat = list1 * 3
return [concatenation, repeat]
print(opertorsList([1, 2, 3], ['what', 'was', 'it ?']))
print(len([5,3,3,2,1]))
|
# default arguments
def default(name, age):
print("Hello {}, and my age is {}.".format(name, age))
print(default("i am sarath",21))
|
# pop(), del, remove(), clear()
def deletions(my_list):
#my_list without any operations on it
print(my_list)
# deleting last element using pop()
my_list.pop()
print(my_list)
# deleting element based on index
my_list.pop(1)
print(my_list)
# using del keyword to delete based on index
... |
height = float(input("Your height in metres:"))
weight = float(input("Your weight in kilograms:"))
bmi = round(weight/ (height * height), 1)
if bmi <= 18.5:
print('Your BMI is', bmi, 'which means you are underweight.')
elif bmi > 18.5 and bmi < 25:
print('Your BMI is', bmi, 'which means you are normal.')
e... |
n1=99
n2=7
n3=15
if (n1>n2) and (n1>n3):
largest=n1
elif (n2>n1) and (n2>n3):
largest=n2
else:
largest=n3
print("Largest between 3 numbers is",largest)
|
'''
if condition1:
statement1
elif condition2:
statement2
else:
statement3
'''
#%%
print('case1')
x = 1
y = 2
if x > y:
print('x is greater than y')
else:
print('x is less or equal to y')
print()
print('case2')
x = 1
y = 1
if x > y:
print('x is greater than y')
elif x < y:
print('x is less ... |
##############################################################
# Project 6: Numeric Computations with Taylor Polynomials #
# #
# Logan Hoots, Stephen Sanders #
# CST - 305 #
... |
from collections import deque
is_balanced = True
string = input()
stack_of_opening = []
stack_of_closing = deque()
for item in string:
if item in ["{","(","["]:
stack_of_opening.append(item)
else:
stack_of_closing.append(item)
if len(stack_of_closing) == len(stack_of_opening):
whi... |
from collections import deque
firework_effects = deque([int(el) for el in input().split(", ") if int(el) > 0])
explosive_powers = [int(num) for num in input().split(", ") if int(num) > 0]
palms = 0
willows = 0
crossettes = 0
ready_with_fireworks = False
while not ready_with_fireworks:
if not firework_effect... |
rows, cols = [int(el) for el in input().split()]
matrix = []
for row in range(rows):
matrix.append(input().split())
counter = 0
for r in range(rows-1):
for c in range(cols-1):
if matrix[r][c] == matrix[r][c+1] and matrix[r][c+1] == matrix[r+1][c] and matrix[r+1][c] == matrix[r+1][c+1]:
... |
countries, capitals = input().split(", "), input().split(", ")
corresponding_info = zip(countries,capitals)
info = {key:value for key,value in corresponding_info}
for pair in info.items():
print(f"{pair[0]} -> {pair[1]}") |
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)# set de modes van pin nummering
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)#dit zet pin 11 op als input met een interne pulldown circuit
GPIO.setup(12, GPIO.OUT)# dit zet pin 12 als output, hier zit de LED op
GPIO.output(12, 0)
try:
while True:
GP... |
>>> a=input("Enter the value ")
Enter the value "My Testing String"
>>> a.count(' ')
2
|
def read_file(filename):
f = open(filename)
input = f.read()
f.close()
return input
if __name__ == "__main__":
filename = 'input'
input = read_file(filename)
pt = 0
for i in input:
#print("this char: {}".format(i))
if i == ')':
pt -= 1
elif i == '(':... |
""" Problem 6a - 2019 """
import sys
import orbit
def traverse(planetary_system, key):
""" Recursive function for traversing the planatary system """
orbits = 1
if planetary_system[key] != "COM":
orbits += traverse(planetary_system, planetary_system[key])
return orbits
def create_planetary_sy... |
import re
def read_file(filename):
data = []
f = open(filename)
for line in f:
data.append(line)
f.close()
return data
def count_hex(line):
p = re.compile(r'\\x[0-9,a-f,A-F][0-9,a-f,A-F]')
a = p.findall(line)
return(len(a))
def count_chars(line):
c = line.count("\"") + ... |
"""This is a Python file"""
input_file = open('./2019/dec_02/input')
line = input_file.read()
input_array = line.split(',')
input_array[1] = 12
input_array[2] = 2
#print(input_array)
PC = 0
while int(input_array[PC]) != 99:
#print("PC: {}, op: {}, {} +* {} => {}".format(PC, input_array[PC], input_array[PC+1],
... |
number = []
print("enter 8 number : ")
for i in range(8):
number.append(int(input()))
largest = number[0]
for i in range(8):
if largest < number[i]:
largest = number[i]
secondLargest = number[0]
for i in range(8):
if secondLargest < number[i]:
if number[i] != largest:
... |
x=int(input("Enter the Year"))
result= "Leap Year"
if x%400==0:
print(result)
elif x % 4 == 0 and x % 100 != 0:
print(result)
else:
print("non leap year")
|
# def whiletest(testvalue):
# numbers = []
# i = 0
# while i < testvalue:
# print "At the top i is %d" % i
# numbers.append(i)
#
# i = i + 2
# print "Numbers now: ", numbers
# print "At the bottom i is %d\n" % i
# return numbers
def whiletest(testvalue):
numb... |
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0 or (x%10==0 and x!=0):
return False
reverse=0
while x>reverse:
reverse=10*reverse+x%10
x=x//10
if x==reverse or x==reverse//10:
... |
print("please input a list of numbers")
L = list(input().split())
print(L)
print(L.__len__())
l = [int(i) for i in L]
print(l)
print("please input the value you want to search")
value = input()
value = int(value)
if not l:
print("no value in list")
low = 0
high = len(l) - 1
while low <=high:
mid = int((low + hi... |
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
low=int(0)
high=x
while low<=high:
mid=low+(high-low)//2
if mid*mid<=x:
low=mid+1
else:
high=mid-1
return high
""... |
from random import randrange as r
def thirtyOne():
#deciding who the hell starts
play = input("Input 1 to jugar, anycosa else to safar de aqui.")
while play=="1":
counter = 0
playsUser = True if r(2) == 1 else False #only r(2) is needed in fact
print(("Player" if playsUser else "Comp... |
import sys
import operator
def define_grid():
grid = []
empty_spaces = list()
preset_chars = dict()
row = 0
col = 0
start = True
with open(sys.argv[1], 'r') as myFile:
for line in myFile:
col = 0
start2 = True
if start == True:
st... |
# Dependencies
import random
from math import gcd
#Variables
with open("./primes.txt", "r") as file:
primes = file.readlines()
#Functions
def define_e(phi_n: int) -> int:
while(True):
e = random.randint(2, phi_n-1)
if(gcd(e, phi_n)==1):
return e
def define_... |
import sys
import time
print("You ready to count? Let's count to 100. It'll go fast, so.. be ready\n")
time.sleep(3)
i = 0
while i < 100:
i += 1
sys.stdout.write("\r{}".format(str(i)))
print("\n\nOh, did I go a little too fast for you? Here, lets count to a million.\n")
time.sleep(3)
i = 0
while i < 1000000:
i +=... |
def find_mlt_inv(cur_mult="input", mod_max="input"):
""" Find the multiplicative inverse of a current multiplier(mod "mod_max")
--------------------------------------------------------------------------
Parameters:
cur_mult: int
The current multiplier
mod_max: int
The... |
board = [' ' for x in range(10)]
def inputmove(letter, pos):
board[pos] = letter
def printboard(board):
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' +... |
import json
"""
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
"""
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.ri... |
#!/usr/bin/env checkio --domain=py run caesar-cipher-encryptor
# https://py.checkio.org/mission/caesar-cipher-encryptor/
# This mission is the part of the set. Another one -Caesar cipher decriptor.
#
# Your mission is to encrypt a secret message (text only, without special chars like "!", "&", "?" etc.) using Caesar ... |
#!/usr/bin/env python3
from typing import List
class Person(object):
name: str = ""
liked_people: List[str] = []
def __init__(self, name: str=""):
self.name = name
def likes(self,person:object):
self.liked_people.append(person.name)
bob = Person("Bob")
alice = Person("Alice")
bo... |
# quick sort
def qsort(lst):
""" Pick an element, called a pivot, from the array.
Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partiti... |
import string
literals = string.ascii_letters+string.punctuation+string.whitespace
'''
Linear Feedback shift register
'''
def stream1(i, a1=1, a2=2):
'''
a1,a2 (int) - taps to randomize key value
e1,e2 (int) - initial keys (seed)
Ei+3=a1*Ei+1+a2*Ei+2 (mod alphabet)
'''
e1, e2 = 2, 4
for ... |
#!/usr/bin/env checkio --domain=py run painting-wall
# https://py.checkio.org/mission/painting-wall/
# Nicola has built a simple robot for painting of the wall. The wall is marked at each meter and the robot has a list of painting operations. Each operation describes which part of wall it needs to paint as a ra... |
from counting_sort import counting_sort
from math import log10
def radix_sort(arr: list, base: int = 10) -> list:
# only for non-negative integers
max_digits = int(log10(max(arr)))+1
F = [[] for l in range(base)]
for p in range(max_digits):
for num in arr:
digit = (num // base**p... |
def solution(arr1: list, arr2: list, target: int) -> tuple:
# all-zeros in both arrays
if arr1 == arr2 and set(arr1) == {0}:
return None
# equivalent arrays
if arr1 == arr2:
pass
s = set(arr1)
def helper(s: set, arr: list, target: int):
for num in arr:
... |
"""
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
"""
import time
from datetime import datetime, timedelta
def foo(*args):
print(f"{time.ctime()}: foo was invoked")
def scheduler(foo, n):
print(f"job {foo} is scheduled after {n}ms at {(datetime.no... |
# Recursively traverse the dictionary [node] to find occurrences of [kv] key and output their values
def findkeys(node, kv):
if isinstance(node, list):
for i in node:
for x in findkeys(i, kv):
yield x
elif isinstance(node, dict):
if kv in node:
yield nod... |
#!/usr/bin/env checkio --domain=py run matrix-pattern
# https://py.checkio.org/mission/matrix-pattern/
# To explore new islands and areas Sophia uses automated drones. But she gets tired looking at the monitors all the time. Sophia wants to teach the drones to recognize some basic patterns and mark them for review... |
def dutch_flag(pivot, myList):
#print(type(myList))
#print(type(pivot))
less = []
higher = []
middle = []
pivot = myList[pivot]
print("privot is " + str(pivot))
#O(n) time
#O(n) space, with n being the length of myList
for item in myList:
if(item > pivot):
higher.app... |
'''
Binary search practice
Let's get some practice doing binary search on an array of integers.
We'll solve the problem two different ways—both iteratively and resursively.
Here is a reminder of how the algorithm works:
Find the center of the list (try setting an upper and lower bound to find the center)
Check to see ... |
from pulp import *
# 0 <= x <= 3
x = LpVariable("x", 0, 3)
# 0 <= y <= 1
y = LpVariable("y", 0, 1)
prob = LpProblem("Just Starting", LpMinimize)
# Constraint x + y <= 2
prob += x + y <= 2
# Objective function -4*x + y
prob += -4*x + y
status = prob.solve()
prob.writeLP("simple.lp")
prob.solve()
if LpStatus[prob.s... |
def testit(s):
print(s)
ret =[]
if len(s) == 0 :
return ""
elif len(s) == 1 :
return s
else:
# if len(s) even
if len(s) % 2 == 0:
for i in range(int(len(s)/2)) :
if ord(s[2*i]) == ord(s[2*i+1]):
ret.append(s[2*i])
... |
def comp(array1, array2):
if array1 == None and array2 == []:
return False
if array2 == None and array1 ==[]:
return False
if array1 == [] and array2 != []:
return False
print(array1, array2)
for i in range(len(array1)):
if array1[i]**2 not in array2:
retu... |
def format_duration(seconds): #super basic approach No use of time functions
if seconds == 0:
return 'now'
min = 60
hour = 60 * min
day = 24 * hour
year = 365 * day
ret = []
y = seconds // year
d = (seconds - y * year) // day
h = (seconds - y * year - d * day) // hou... |
#level 6 print nicely integer with 10 powers
def simplify(n):
if n == 0:
return ''
ret = ''
p = 0
while True:
if n == 0: # n = 0 ou fin du traitement
if ret[-1]=='+':
ret = ret[0:-1]
return ret
break
if p == 0: # firs... |
def am_I_afraid(day,num):
if day == "Monday" and num == 12:
return True
elif day == "Tuesday" and num > 95:
return True
elif day == "Wednesday" and num == 34:
return True
elif day == "Thursday" and num == 0:
return True
elif day == "Friday" and num %2 == 0:
r... |
def mygcd(x, y):
if x < y:
x,y = y, x
if y == 0:
return x
return mygcd(y, x%y)
"""
One way to find the GCD of two numbers is Euclid’s algorithm,
which is based on the observation that if r is the remainder
when a is divided by b, then gcd(a, b)= gcd(b, r).
As a b... |
def points(games):
ret = 0
for i in range(len(games)):
if games[i][0]>games[i][2]:
ret += 3
elif games[i][0] == games[i][2]:
ret += 1
return ret
|
# This program says hello and asks for my name
print('Hello world')
print('What is your name?') #ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') #ask for their age
myAge = input()
print('You will be ' + str... |
test = ' lskjhsjlkh '
import re #import Regex tools
def myStrip(input, subText=''): #if subText='' strip() else remove subText
if subText == '':
exspaceRegex = re.compile(r'(\s+)*(.*)(\s+)*')
return exspaceRegex.search(input).group(2)
else:
subRegex = re.compile(subText)
... |
# iis the input uppercase
def is_uppercase(inp):
if inp == inp.upper():
return True
else:
return False
print(is_uppercase('HELLO'))
|
def sum_even_numbers(seq):
ret = 0
if seq == []:
return 0
else:
for i in range(len(seq)):
if int(seq[i]) == seq[i] and seq[i] % 2 == 0:
ret += seq[i]
return ret
pass
"""
return the sum of even number. 4 or 4.000 included.
"""
|
def is_orthogonal(u, v):
ret = 0
for i in range(len(u)):
ret += u[i]*v[i]
return ret == 0
pass
def is_orthogonal(u, v):
return sum(i*j for i,j in zip(u,v)) == 0
is_orthogonal = lambda u, v: not sum(a * b for a, b in zip(u, v))
|
# @TIME : 2019/4/2 上午8:36
# @File : 有效的括号.py
import time
class Solution1:
def isValid(self, s):
stack = []
dict1 = {"(": ")", "{": "}", "[": "]"}
for elem in s:
if elem in dict1.keys():
stack.append(elem)
elif elem in dict1.values():
... |
# @TIME : 2019/10/9 下午01:04
# @File : 数组中第K大元素_215.py
"""
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
"""
import heapq
import time
b = [3,2,1,5,6,4]
class Solution:
def f... |
# @TIME : 2019/6/9 上午1:19
# @File : Maximum Length of Repeated Subarray_718.py
import numpy as np
# Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.
# Input:
# A: [1,2,3,2,1]
# B: [3,2,1,4,7]
# Output: 3
# Explanation:
# The repeated subarray with maximum length... |
#Autor: Yasmín Landaverde Nava
#Descripción: este programa calcula el cosoto toal de los boletos para un concierto.
def calcularPago(boletosA, boletosB, boletosC):
costoA = boletosA * 3250
costoB = boletosB * 1730
costoC = boletosC * 850
totalPago = costoA + costoB + costoC
return totalPa... |
def substractNumber(num1,num2):
res = num1-num2
return res
vals = substractNumber(20,10)
print(vals) |
num = 123
rev=0
while(num>0):
rem=num%10
rev=(rev*10)+rem
num=num//10
print("reverse:",rev) |
num=int(input("enter a limit"))
lst=[]
even=[]
odd=[]
for i in range(1,(num+1)):
lst.append(i)
for n in lst:
if(n%2==0):
even.append(n)
else:
odd.append(n)
print(lst)
print(odd)
print(even) |
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
cache = set()
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == ".":
continue
row = str(i)+"row"+board[i][j]
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
def overlapping_lists(l1: ListNode, l2: ListNode) -> ListNode:
root1, root2 = detectCycle(l1), detectCycle(l2)
if not root1 and not root2:
return overlapping_lists_w... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
def list_pivoting(l: ListNode, x: int) -> ListNode:
less_head = less = ListNode(0)
equal_head = equal = ListNode(0)
greater_head = greater = ListNode(0)
while l.nex... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
result = ListNode(0, head)
left = result
for i in range(m-1):
... |
from bs4 import BeautifulSoup
import requests
import pyttsx3
def get_info(country='india'):
url = 'https://www.worldometers.info/coronavirus/country/{}/'.format(country)
try:
response = requests.get(url)
#print(response)
soup = BeautifulSoup(response.text,'html.parser'... |
def unija(dict1,dict2):
""" radi uniju nad 2 recnika"""
dictVracanje={} #dict koji se vraca
for (key1, value1) in dict1.items():
dictVracanje[key1]=value1 #ovde dodajem sve iz dict1 u dictVracanje
for (key2, value2) in dict2.items():
if key2 not in dict1.keys(): #pro... |
import multiprocessing
import time
def square(n, result):
for i in n:
time.sleep(0.5)
print(multiprocessing.current_process().name)
result.put(i*i)
def cube(n, result):
for i in n:
time.sleep(0.5)
print(multiprocessing.current_process().name)
result.put(i*i*... |
'''
A surface filled with one hundred medium to small sized circles.
Each circle has a different size and direction, but moves at the same slow
rate.
Display the instantaneous intersections of the circles
Implemented by William Ngan <http://metaphorical.net>
4 April 2004
Processing v.68 <http://processing.org>
Port ... |
# -*- coding: utf-8 -*-
__author__ = 'wangwenjie'
__data__ = '2018/5/28 上午9:24'
__product__ = 'PyCharm'
__filename__ = 'decorator_pattern'
# 装饰器模式 decorator pattern
class LogManager():
@staticmethod
def log(func):
def wrapper(*args):
print('Visit func %s', func.__name__)
return... |
# Aapo Tommila - 0553657
# Let's make a game of guess a number game
# At this game computer generates a number
# and a user should guess it!
#########################################
# Ingredients: #
#---------------------------------------#
# from random import randint #
# ... |
# Let's make a game of guess a number game
# At this game computer generates a number
# and a user should guess it!
#########################################
# Ingredients: #
#---------------------------------------#
# from random import randint #
# print() ... |
import os
# List of Fibonacci numbers
fibonacci_sequence = [0,1,1,2,3,5,8,13,21,34,55]
# We can make a fibonacci sequence by ourselves
our_fibonacci_sequence = []
amount_numbers = 15
first_number = 0
second_number = 1
for number in range(amount_numbers):
print(first_number)
our_fibonacci_sequence.append(firs... |
import matplotlib.pylab as plt
LETTERS=' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def frequency_analysis(plain_text):
plain_text=plain_text.upper()
#using dictionary pair
letter_frequency = {}
for letter in LETTERS:
letter_frequency[letter]=0
for letter in plain_text:
if letter in LETTERS:
letter_frequency[letter]+=... |
#!/usr/bin/env python3.5
import sys
import re
def debug(*args):
print("-----------")
for arg in args:
sys.stdout.write(str(arg) + "\n")
print("- - - - - -")
print("-----------")
class Arguments:
"""
Class for storing program arguments.
Class has these methods:
... |
def generadorPares(limite):
num = 1
while num < limite:
yield num*2
num += 1
num_pares = generadorPares(10)
"""
for i in num_pares:
print(i)
"""
print(next(num_pares))
print("Aquí podría ir mas código")
print(next(num_pares)) |
#--------------------
#REMOVE THINGS
#--------------------
# You can't grow a python list forever. Sooner or later you must remove elements and release disk and memory space
# We will cover list.remove(), list.pop(index), and list.clear()
#list.remove(element) - Removes the first occurance of an element (not all occr... |
n = input('enter the number:')
x=0
y=1
print str(x)
print str(y)
for x in range(n-2):
z=x+y
print str(z)
x=y
y=z
|
'''
Distance between two cities is input through keyboard (in Km)
convert - in m , ft , inches , cm
'''
print("Welcome to conversion startup.We are happy to help you with all your conversions.")
print("Enter name of the cities below(*OPTIONAL- PRESS ENTER TO SKIP*)")
a = input("City1:")
b = input("City2... |
__author__ = 'ariel'
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
# select only ford models
c.execute("select * from inventory where Make = 'Ford'")
ford = c.fetchall()
for l in ford:
print l[0], l[1], l[2]
|
#!/usr/bin/python3
num1 = input('输入的第一个数字:')
num2 = input('输入的第2个数字:')
print("\n两数相加结果:{} \n".format(float(num1) + float(num2)));
print("两数相减结果:{} \n".format(float(num1) - float(num2)));
print("两数相乘结果:{} \n".format(float(num1) * float(num2)));
print("两数相除结果:{} \n".format(float(num1) / float(num2)));
print("x的y次结果:{}... |
import matplotlib.pyplot as plt
VAL = 2
DEGR = 9
def gorner(odds, x):
p = float(1)
i = 1
while i <= DEGR:
p = p * x + odds[i] * VAL**i
i = i + 1
print(x, ': ', p)
return p
def _main():
# interval [1.92, 2.08], step = 10**(-4)
# given (x - 2)**9
odds = [1, -9, 36, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.