text stringlengths 37 1.41M |
|---|
# Hangman
# Tejas Gokhale
# 2015-12-02
import string
import random
name = raw_input("Enter your name: ")
print "**** WELCOME TO HANGMAN, %s!" % name ," ****"
print "."
print "."
print "."
path = 'words.txt'
def load_words():
print "Loading words from dictionary ..."
wordFile = open(path, 'r', 0)
line = wordFile.readline()
wordList = string.split(line)
print len(wordList), " words loaded from dictionary"
return wordList
def choose_word(wordList):
return random.choice(wordList)
def reveal_letter(hidden_word, word, user_input):
for i in range(0, len(word)):
if user_input == word[i]:
hidden_word[i] = user_input
return hidden_word
def hangman():
wordList = load_words()
word = choose_word(wordList).lower()
word = list(word)
length = len(word)
print "Chappy is thinking of a word that is ... %d letters long. Guess away!" % length
nGuess = 10
hidden_word = '-'*length
hidden_word = list(hidden_word)
while(nGuess > 0):
print "You have %d guesses left." %(nGuess)
user_input = raw_input("Enter your guess: ")
available = list("abcdefghijklmnopqrstuvwxyz")
if user_input in available:
hidden_word = reveal_letter(hidden_word, word, user_input)
else:
print "Invalid input. Please enter a letter."
print ''.join(hidden_word)
if hidden_word == word:
print "You have guessed the word!"
break
if user_input in hidden_word:
print "Good guess!"
else:
nGuess = nGuess - 1
print "The word was %s" % ''.join(word)
hangman() |
# CLASSES
# ****************************************
class parentClass:
var1 = "I'm Iron Man"
var2 = "Let's put a smile on that face"
class childClass(parentClass):
pass
# don't want to copy everything, aka laziness
parentObject = parentClass()
parentObject.var1
childObject = childClass()
childObject.var1
childObject.var2
# the child class will inherit the parent characteristics
# ---------------------------------------
class parent:
var1 = "bacon"
var2 = "sausage"
class child(parent):
#keep var1 the same
var2 = "beef"
pob = parent()
cob = child()
print cob
pob.var2
cob.var2
# multiple parents
# ----------------------------------
class mom:
var1 = "hey I'm mom!"
class dad:
var2 = "hey there son"
class child(mom, dad):
var3 = "am i like a new var?"
childObject = child()
print childObject.var1
|
__author__ = 'tmsbn'
a = [[0, 1],
[1, 2],
[4, 5]]
b = [[11, 1, 2],
[1, 12, 3]]
result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# print(len(a[0]), len(b), a[0][1]) # len(a) give the row count, len(a[0] gives the column count of 1st column
# a[row][column])
for i in range(len(a)):
for j in range(len(a)):
for k in range(len(a[0])):
result[i][j] += a[i][k] * b[k][j]
# Multiplication is done from horizontal to vertical ,
# the result is always a square matrix
# a[m][n] * b[n][m] = c[m][m]
print(result)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 10:33:28 2018
@author: Vijay
"""
cars = ['bmw','audi','honda']
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
squares = [value**2 for value in range(1,11)]
print(squares)
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
squares = []
for value in range(1,11):
squares = value**2
print(squares)
import numpy as np
numbers = []
for number in range(1,200):
numbers.append(number)
print(numbers)
max(numbers)
min(numbers)
max(numbers)
numbers[-2]
numbers[1]
np.mean(numbers)
np.median(numbers)
np.percentile(numbers,0)
number2 = [number for number in range(1,100)]
number2
middle= int(len(numbers)/2)
middle
if middle/2==0:
print(numbers[middle])
else:
print(numbers[middle-1])
for number in range(numbers):
if number<max(numbers) and number>max(number):
print(number)
secondhigh = |
def replaceVowels(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
ans = ''
for c in word:
if c not in vowels:
ans = ans + '.' + c
return ans
x = input().lower()
print(replaceVowels(x))
|
# funcion len propia
def len(objeto):
contador=0
for i in objeto:
contador+=1
return contador
print (len([1, 2,3,4]))
print (len ("hola"))
|
phrase = "Don't panic!"
plist = list(phrase)
print(phrase)
print(plist)
# newlist=plist[1:8]
'''newlist1=plist[4:8]
newlist1=newlist1.remove(" ")
newlist2=newlist1.insert(1,newlist1.pop())'''
# newlist.remove("'")
# # ['o', 'n', 't', ' ', 'p', 'a']
# newlist1 = newlist.insert(3,newlist.pop(5))
# print(newlist)
# print(newlist1)
# print(newlist,newlist1)
newphrase = ''.join(plist[1:3])
newphrase = newphrase + ''.join([plist[5], plist[4], plist[7], plist[6]])
print(newphrase) |
sum = 2
for x in range(3, 101):
for i in range(2, x):
if x%i == 0 :
break
else:
sum += x
print('一百以内素数之和为',sum)
|
import math
def check_prime(num):
if num > 2 and num % 2 == 0:
return False
else:
# I tried using a generator here,
# but it is slower by a noticeable amount.
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True
def find_sum(limit):
sum = 0
for i in range(2, limit):
if check_prime(i):
sum += i
return sum
print(find_sum(2000000))
|
# This is a single line comment
"""
This is a multiline comment,
that takes up,
multiple lines
"""
# Prints "Hello" to the terminal
print("Hello")
"""
PRIMITIVE DATA TYPES
- integer (1, 2, 3)
- float (1.0, 1.5)
- string ("Hello", "Hi!", "40", "4.5")
- boolean (True, False)
"""
firstVariable = 5
print(firstVariable) #prints 5
print(type(firstVariable)) #prints <class 'int'>
secondVariable = 5.0
print(secondVariable) #prints 5.0
print(type(secondVariable)) #prints <class 'float'>
thirdVariable = "5"
print(thirdVariable) #prints 5
print(type(thirdVariable)) #prints <class 'str'>
fourthVariable = True
print(fourthVariable) #prints True
print(type(fourthVariable)) #prints <class 'bool'>
a = 5
b = 10
c = a + b
print(c) #prints 15
print(type(c)) #prints <class 'int'>
"""
ARITHMETIC OPERATORS
+
-
*
/
%
"""
# modulus (remainder when you divide)
d1 = 10%3
print(d1) #prints 1
d2 = 12%3
print(d2) #prints 0
e1 = 1
f1 = 2
g1 = e1 + f1
print(g1) #prints 3
print(type(g1)) #prints <class 'int'>
e2 = 1
f2 = 1.0
g2 = e2 - f2
print(g2) #prints 0.0
print(type(g2)) #prints <class 'float'>
h = 10
i = 3
j = h/i
print(j) #prints 3.333
print(type(j)) #prints <class 'float'>
k = "Hello!"
l = "Nice to meet you!"
m = k + l
print(m) #prints Hello!Nice to meet you!
print(type(m)) #prints <class 'str'>
o = 5
p = "Hello"
q = str(o) + p
print(q) #prints 5Hello
print(type(q)) #prints <class 'str'>
r1 = 5
s1 = "10"
t1 = r1 + int(s1)
print(t1) #prints 15
print(type(t1)) #prints <class 'int'>
r2 = 5
s2 = "10"
t2 = str(r2) + s2
print(t2) #prints 510
print(type(t2)) #prints <class 'str'>
"""
If statements/Conditions
"""
u = False
v = 7
w1 = 6
if (u):
print("Hi!")
elif(v != w1):
print("Blue!")
else:
print("Pineapple!")
"""
COMPARISON OPERATORS
==
!=
<
>
<=
>=
"""
"""
LOGICAL OPERATORS
and
or
not
"""
w2 = 12
x = 8
y = 9
z = 10
#Both conditions must be True
#prints "Hello"
if (x < y and y < z):
print("Hello")
#Either of the conditions must be True
#prints "Hi"
if (x < y or w2 < z):
print("Hi")
#Flips a condition to the opposite
#prints "Red"
aa = False
if(not aa):
print("Red")
"""
LOOPS
for
while
"""
for i in range(5, 10):
print("i", i)
bb = 1
while (bb < 10):
print("bb", bb)
bb = bb + 1
print("end of while loop")
"""
DATA STRUCTURES
list
set
dictionary
"""
"""
LISTS
maintains order of elements
"""
myList = []
myList.append("Apples") #adds element to the end of the list
myList.append("Apples")
myList.append("Apples")
myList.append("Eggs")
myList.append(1)
print(myList)
print(len(myList)) #prints number of elements in the list
print(myList[1]) #prints the 2nd element in the list
poppedOff = myList.pop() #removes last element in list
print(myList)
print(poppedOff) #prints the element removed from the end of the list
for i in range(len(myList)):
print(myList[i])
#special loop for lists
for food in myList:
print(food)
"""
SETS
cannot contain duplicate elements
"""
mySet = set()
mySet.add("Apples") #adds element to the set
mySet.add("Apples")
mySet.add("Apples")
mySet.add("Eggs")
mySet.add(True)
mySet.add(7)
print(mySet)
print(len(mySet)) #prints number of elements in the set
print("Grapes" in mySet) #prints True or False if the element is in the set
mySet.remove("Apples") #removes specific element from set
print(mySet)
"""
DICTIONARIES
key:value pairs
keys are all unique
"""
myDictionary = {}
myDictionary['apple'] = "pie" #add key:value pair to dictionary
myDictionary['happy'] = True
myDictionary['go'] = "bears"
myDictionary['blue'] = 42
print(myDictionary)
print('purple' in myDictionary) #prints True or False if the element is a key in the dictionary
print(myDictionary.keys()) #prints the keys of the dictionary
print(myDictionary.values()) #prints the values of the dictionary
del myDictionary['blue'] #removes specific key from set
print(myDictionary)
"""
FUNCTIONS
like rubber stamps of code that you can put in multiple places
"""
def sayHello():
print("Hello")
sayHello() #function call that runs the code in the function definition
sayHello()
sayHello()
sayHello()
"""
Functions with Parameters
"""
def sayHi(name):
print("Hi " + name)
sayHi("John") #prints Hi John
sayHi("April") #prints Hi April
def addition(a, b):
print(a + b)
addition(1, 2) #prints 3
addition(3, 5) #prints 8
def hugs(a, b):
print(a + " hugs " + b)
hugs("April", "John") #prints April hugs John
hugs("John", "April") #prints John hugs April
|
#!/usr/bin/python3
cigarros = int(input('Cigarros fumados por dia: ' ))
anos = int(input('Anos que fumou: '))
qntCigarros = anos*365*cigarros
dias = int((qntCigarros*10)/1440)
print('Redução do tempo de vida em ' + str(dias) + ' dias')
|
class Person(object):
def __init__(self,name):
self.name=name
def play_with_dog(self,Dog):
print("%s 在和 %s 玩耍——————" % (self.name,Dog.name))
Dog.play()
class Dog(object):
def __init__(self,name):
self.name=name
def play(self):
print("%s 在玩耍------" % self.name)
class Y_Dog(Dog):
def play(self):
print("%s 在玩耍-汪汪--"% self.name)
xiao_Y=Dog("原狗")
#xiao_Y=Y_Dog("原狗")
xiao_S=Person("小宋")
xiao_S.play_with_dog(xiao_Y)
|
class Gun:
#枪的属性需要从外部输入,但是如果默认每把枪初始子弹都为0,
# 都需要装填子弹,即可不需要外部输入
def __init__(self,model):
self.model=model
self.bullet_count=0
def add_bullet(self,count):
self.bullet_count+=count
def shoot(self):
#要判断子弹数量
if(self.bullet_count>0):
#发射子弹
self.bullet_count-=1
print("%s 在射击>>>>>[%d]"% (self.model,self.bullet_count))
class Soldier:
#假设新兵都没有枪
def __init__(self,name):
self.name=name
#初始化的时候 赋值None
self.gun=None
def fire(self):
#self.gun时一个 Gun类的对象,可以调用 Gun类的方法
#一般在与 None 比较时,通常使用 is / is not 而不用等号
#if self.gun!=None:
if self.gun is not None:
self.gun.add_bullet(60)
print("我是%s,GO GO GO" % self.name)
self.gun.shoot()
return
print("我没有枪")
#创建一把枪对象 AK47
AK=Gun("AK47")
#创建一个士兵对象 许三多
sol=Soldier("许三多")
#把枪给许三多 士兵类的对象的一个属性,可以是另外一个类的对象
sol.gun=AK
sol.fire()
|
a = str(input())
#print(a)
#print("." in a)
if ("." in a) == True:
b ,_= a.split(".")
# print("True")
else:
b=a
print(b) |
pages = int(input())
pages_per_hour = int(input())
days = int(input())
hours_for_reading = pages / pages_per_hour / days
print(hours_for_reading)
|
# plot feature importance manually
from numpy import loadtxt
from xgboost import XGBClassifier
from matplotlib import pyplot
# load data
dataset = loadtxt('pima-indians-diabetes.csv', delimiter=",")
# split data into X and y
X = dataset[:,0:8]
y = dataset[:,8]
# fit model on training data
model = XGBClassifier()
model.fit(X, y)
# feature importance
print(model.feature_importances_)
# plot
pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_)
pyplot.show() |
import os
import csv
import numpy as np
csvpath = os.path.join("election_data.csv")
output_path = os.path.join("election_data_output.txt")
month_total = 0
file_data = []
vote_values = []
cand_values = []
# NEED TO CREATE THE FUNCTION THAT ALLOWS YOU TO EXPORT AS A CSV
# Extract the information in a dictionary or list that allows you to manipulate it from there
with open(csvpath, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
csv_header = next(csvreader)
for row in csvreader:
file_data.append(row)
vote_values.append(row[0])
cand_values.append(row[2])
# This creates the count of how many votes there are
vote_count = len(vote_values)
#print(vote_count)
#CHECK FOR DUPLICATES?
# This checks for duplicates by converting the list into a set
check_and_set = set(cand_values)
#print(check_and_set)
# Counts how many votes each candidate gets
khan_count = cand_values.count("Khan")
#print(khan_count)
li_count = cand_values.count("Li")
correy_count = cand_values.count("Correy")
otooley_count = cand_values.count("O'Tooley")
# Calculates the percentages of each vote candidate. Create a FUNC
def percent_create(candidate_votes):
percent_calc = (candidate_votes / vote_count)
percent_calc = "{:.2%}".format(percent_calc)
return percent_calc
khan_percent = percent_create(khan_count)
li_percent = percent_create(li_count)
correy_percent = percent_create(correy_count)
otooley_percent = percent_create(otooley_count)
# create an if statement that determines the winner, create a list with the candidiate, percent, and votes
cand_outcomes = {"Khan":{khan_count},"Li":{li_count},"Correy":{correy_count},"O'Tooley":{otooley_count}}
#print(cand_outcomes)
cand_winner = max(cand_outcomes, key=cand_outcomes.get)
print("Election Results")
print("-------------------------")
print(f"Total Votes: {vote_count}")
print("-------------------------")
print(f"Khan: {khan_percent} {khan_count}")
print(f"Correy: {correy_percent} {correy_count}")
print(f"Li: {li_percent} {li_count}")
print(f"O'Tooley: {otooley_percent} {otooley_count}")
print("-------------------------")
print(f"Winner: {cand_winner}")
print("-------------------------")
with open(output_path, 'w') as csvfile:
# Initialize csv.writer
csvwriter = csv.writer(csvfile, delimiter=',')
# Write the first row (column headers)
csvwriter.writerow(["Election Results"])
csvwriter.writerow(["-------------------------"])
csvwriter.writerow([f"Total Votes: {vote_count}"])
csvwriter.writerow(["-------------------------"])
csvwriter.writerow(["-------------------------"])
csvwriter.writerow([f"Khan: {khan_percent} {khan_count}"])
csvwriter.writerow([f"Correy: {correy_percent} {correy_count}"])
csvwriter.writerow([f"Li: {li_percent} {li_count}"])
csvwriter.writerow([f"O'Tooley: {otooley_percent} {otooley_count}"])
csvwriter.writerow(["-------------------------"])
csvwriter.writerow([f"Winner: {cand_winner}"])
csvwriter.writerow(["-------------------------"])
|
<<<<<<< HEAD
def drawlines(screen,width,x1,x2,y):
byte_width = width//8
height = len(screen)//byte_width
if x1>x2:
x1,x2 = x2,x1
byte = y*byte_width+x1//8
byte_end = y*byte_width+x2//8
screen[byte] = (1<<(x1%8))-1
byte +=1
while byte<byte_end:
screen[byte]= 255
byte += 1
screen[byte] = 255 ^((1<<(x2%8))-1)
import unittest
class Test(unittest.TestCase):
def test_swap_odd_even_bits(self):
screen = [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0]
drawlines(screen, 64, 20, 42, 1)
self.assertEqual(screen, [0]*8 + [0, 0, 15, 255, 255, 252, 0, 0] + [0]*8)
if __name__ == "__main__":
unittest.main()
=======
def drawlines(screen,width,x1,x2,y):
byte_width = width//8
height = len(screen)//byte_width
if x1>x2:
x1,x2 = x2,x1
byte = y*byte_width+x1//8
byte_end = y*byte_width+x2//8
screen[byte] = (1<<(x1%8))-1
byte +=1
while byte<byte_end:
screen[byte]= 255
byte += 1
screen[byte] = 255 ^((1<<(x2%8))-1)
import unittest
class Test(unittest.TestCase):
def test_swap_odd_even_bits(self):
screen = [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0]
drawlines(screen, 64, 20, 42, 1)
self.assertEqual(screen, [0]*8 + [0, 0, 15, 255, 255, 252, 0, 0] + [0]*8)
if __name__ == "__main__":
unittest.main()
>>>>>>> 45e00abd356375b5fb384fa23f21f34195b99a48
|
def stack_boxes(boxes):
sorted_boxes = sorted(boxes,key=lambda x: x.height, reverse=True)
return stack_more_boxes(sorted_boxes,None,0)
def stack_more_boxes(boxes,base,index):
if index>=len(boxes):
return 0
without_box_height = stack_more_boxes(boxes,base,index+1)
box = boxes[index]
if not base or box.fits_on(base):
with_box_height = box.height + stack_more_boxes(boxes,box,index+1)
if with_box_height > without_box_height:
return with_box_height
return without_box_height
class Box:
def __init__(self,height,width,depth):
self.height,self.width,self.depth = height,width,depth
def fits_on(self,base):
return base.height>self.height and base.width>self.width and base.depth>self.depth
import unittest
class Test(unittest.TestCase):
def test(self):
boxes = [Box(100, 100, 100)]
self.assertEqual(stack_boxes(boxes), 100)
boxes.append(Box(25, 25, 25))
self.assertEqual(stack_boxes(boxes), 125)
boxes.append(Box(20, 5, 30))
boxes.append(Box(17, 4, 28))
self.assertEqual(stack_boxes(boxes), 137)
if __name__ == "__main__":
unittest.main()
|
def peaks_and_valleys(array):
if len(array)<3:
return
for ix in range(len(array)-1):
if ix%2:
if array[ix]<array[ix+1]:
array[ix],array[ix+1]=array[ix+1],array[ix]
else:
if array[ix]>array[ix+1]:
array[ix],array[ix+1]=array[ix+1],array[ix]
import unittest
class Test(unittest.TestCase):
def test(self):
a = [12, 6, 3, 1, 0, 14, 13, 20, 22, 10]
peaks_and_valleys(a)
self.assertEqual(a, [6, 12, 1, 3, 0, 14, 13, 22, 10, 20])
b = [34, 55, 60, 65, 70, 75, 85, 10, 5, 16]
peaks_and_valleys(b)
self.assertEqual(b, [34, 60, 55, 70, 65, 85, 10, 75, 5, 16])
pass
if __name__ =="__main__":
unittest.main()
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################################################
#
# Program name: traverse.py
# Created: Sun Jan 7 2018 13:03
# author: Stephen Flowers Chávez
#
##############################################################################
#library import
import math
import os
# clear screen and input values
os.system('clear')
distance=float(input("What's the value for 'distance' in miles? "))
bearing=float(input("What's the value for 'bearing'in degrees? "))
#changing to radians from degrees
radbearing=math.radians(bearing)
#compute difference in latitude
diffLat=distance*math.cos(radbearing)
#header info
print("\n")
print('Traverse Table Output:')
print('----------------------\n')
print('Distance: ', distance, ' miles')
print('Bearing: ', bearing, 'degrees\n')
#convert decimal degrees to degrees and minutes
if abs(diffLat)>=60:
diffLatMinutes=diffLat % 60
diffLat=diffLat/60
#print results
# print("difflat/60", diffLat) - used for debugging
# print("diffLatMinutes", diffLatMinutes) - used for debugging
print('Difference in Latitude = {0:.0f}'.format(math.trunc(diffLat)), "degrees"," {0:.2f} ".format(round(diffLatMinutes,2)), "minutes")
else:
# print("difflat", diffLat) - used for debugging
print("Difference in Latitude = {0:.2f}".format(round(diffLat,2)), "minutes")
departure=distance*math.sin(radbearing)
print("Departure = {0:.2f}".format(round(departure,2)), "miles")
|
# !/bin/python3
import math
import os
import random
import re
import sys
def solve(s):
# list1 = []
for _ in range(len(s)):
# list1.append(s[i].capitalize())
list1 = [word.capitalize() for word in s.split(' ')]
return (' '.join(list1))
if __name__ == '__main__':
with open(os.environ['hello'], 'w') as fptr:
s = input()
result = solve(s)
fptr.write(result + '\n')
|
import os
import conversions
import functions
import input_padding
import tkinter as tk
# CREATE FILES CONTAINING INITIAL VALUES #
"""
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,
67,71,73,79,83,89,97,101,103,107,109,113,127,131,
137,139,149,151,157,163,167,173,179,181,191,
193,197,199,211,223,227,229,233,239,241,251,
257,263,269,271,277,281,283,293,307,311]
# FRACTIONAL PART OF SQUARE ROOTS OF THE FIRST 8 PRIMES #
try:
os.mkdir('initial_hash_values')
os.mkdir('constant_words_K')
except FileExistsError:
pass
os.chdir('initial_hash_values')
for i in range(1, 9):
f = open("H0_"+str(i), 'w')
f.write(conversions.fraction_to_hex(primes[i-1]**0.5))
f.close()
os.chdir('..')
# FRACTIONAL PART OF CUBE ROOTS OF THE FIRST 64 PRIMES #
os.chdir('constant_words_K')
for i in range(1, len(primes)+1):
f = open("K"+str(i), 'w')
f.write(conversions.fraction_to_hex(primes[i-1]**(1/3)))
f.close()
os.chdir('..')
"""
# CREATE A GUI FOR ALGORITHM SETUP #
root = tk.Tk()
root.title("SHA256 Encryptor")
root.geometry('{}x{}'.format(600, 80))
enterframe = tk.Frame(root)
enterframe.pack(side=tk.TOP)
enterlabel = tk.Label(enterframe, text="Enter String (less than 56 characters): ")
enterlabel.pack(side = tk.LEFT)
enterstring = tk.Entry(enterframe, width = 60)
enterstring.pack(side = tk.RIGHT)
def update_label():
output["text"] = hash(enterstring.get())
button = tk.Button(root, text="Encrypt!", command=update_label)
button.pack(side = tk.BOTTOM)
outputframe = tk.Frame(root)
outputframe.pack(side= tk.LEFT)
outputlabel = tk.Label(outputframe, text="SHA256 KEY:")
outputlabel.pack(side= tk.LEFT)
output = tk.Label()
def hash(string):
# COLLECT INITIAL HASH VALUES FROM FILE #
A = conversions.hex_to_binary(open('initial_hash_values/H0_1', 'r').read())
B = conversions.hex_to_binary(open('initial_hash_values/H0_2', 'r').read())
C = conversions.hex_to_binary(open('initial_hash_values/H0_3', 'r').read())
D = conversions.hex_to_binary(open('initial_hash_values/H0_4', 'r').read())
E = conversions.hex_to_binary(open('initial_hash_values/H0_5', 'r').read())
F = conversions.hex_to_binary(open('initial_hash_values/H0_6', 'r').read())
G = conversions.hex_to_binary(open('initial_hash_values/H0_7', 'r').read())
H = conversions.hex_to_binary(open('initial_hash_values/H0_8', 'r').read())
input_padding.blocking(string)
# PRETTY FORMATTED PRINTING #
# print(' ', 'A', ' ', 'B', ' ', 'C', ' ', 'D', ' ', 'E', ' ', 'F', ' ', 'G', ' ', 'H')
# print(' ', conversions.binary_to_hex(A), conversions.binary_to_hex(B), conversions.binary_to_hex(C), conversions.binary_to_hex(D), conversions.binary_to_hex(E), conversions.binary_to_hex(F), conversions.binary_to_hex(G), conversions.binary_to_hex(H))
# HASHING ALGORITHM #
for i in range(64):
ch = functions.choice(G, F, E)
maj = functions.majority(A, B, C)
sum0 = functions.sum0(A)
sum1 = functions.sum1(E)
K = conversions.hex_to_binary(open('constant_words_K/K'+str(i+1), 'r').read())
W = open('input_string/W'+str(i+1), 'r').read()[:-1]
T1 = functions.binary_adder(functions.binary_adder(functions.binary_adder(functions.binary_adder(H, sum1), ch), K), W)
T2 = functions.binary_adder(sum0, maj)
H = G
G = F
F = E
E = functions.binary_adder(D, T1)
D = C
C = B
B = A
A = functions.binary_adder(T1, T2)
# print(str(i), conversions.binary_to_hex(A), conversions.binary_to_hex(B), conversions.binary_to_hex(C), conversions.binary_to_hex(D), conversions.binary_to_hex(E), conversions.binary_to_hex(F), conversions.binary_to_hex(G), conversions.binary_to_hex(H))
# RECOLLECTING THE INITIAL HASH VALUES #
H0_1 = conversions.hex_to_binary(open('initial_hash_values/H0_1', 'r').read())
H0_2 = conversions.hex_to_binary(open('initial_hash_values/H0_2', 'r').read())
H0_3 = conversions.hex_to_binary(open('initial_hash_values/H0_3', 'r').read())
H0_4 = conversions.hex_to_binary(open('initial_hash_values/H0_4', 'r').read())
H0_5 = conversions.hex_to_binary(open('initial_hash_values/H0_5', 'r').read())
H0_6 = conversions.hex_to_binary(open('initial_hash_values/H0_6', 'r').read())
H0_7 = conversions.hex_to_binary(open('initial_hash_values/H0_7', 'r').read())
H0_8 = conversions.hex_to_binary(open('initial_hash_values/H0_8', 'r').read())
# FINAL ADDITION OF LAST HASHING VALUES WITH THE INITIAL ONES #
H1 = functions.binary_adder(H0_1, A)
H2 = functions.binary_adder(H0_2, B)
H3 = functions.binary_adder(H0_3, C)
H4 = functions.binary_adder(H0_4, D)
H5 = functions.binary_adder(H0_5, E)
H6 = functions.binary_adder(H0_6, F)
H7 = functions.binary_adder(H0_7, G)
H8 = functions.binary_adder(H0_8, H)
return conversions.binary_to_hex(H1+H2+H3+H4+H5+H6+H7+H8)
output.pack()
root.mainloop()
|
from typing import List, Optional
class View:
children: List["View"]
def __init__(self, name: str, cost: float, is_materialized=False):
self.name = name
self._cost = cost
self.parents: List["View"] = []
self.children: List["View"] = []
self.is_materialized = is_materialized
def __str__(self):
return self.name
def add_child(self, child: "View"):
child.parents.append(self)
self.children.append(child)
def add_children(self, children: List["View"]):
for c in children:
if c == self:
raise RuntimeError("Cannot add self")
if c in self.children or self in c.parents:
raise RuntimeError("Cannot add twice")
c.parents.append(self)
self.children += children
@property
def cost(self):
"""
Get the cost of the current view.
Returns: the cost
"""
if self.is_materialized:
return self._cost
else:
costs = [p.cost for p in self.parents]
return min(costs)
|
"""This module provides an implementation of the Bag ADT.
The ADT is implemented in class Vector.
Author: Yue Hu
"""
from array import Array
class Vector:
def __init__ ( self, size ):
""" Constructs an empty vector with an initial capacity of two elements."""
size=2
self._theVect = Array( size )
self.length=0
def __len__ ( self ):
""" Returns the number of items in the vector."""
return self.length
def __contains__ ( self, item ):
""" Determines if an item is contained in the vector."""
return item in self._theVect
def __getitem__ ( self, ndx ):
""" Get the item at the ndx position."""
assert ndx>0 and ndx<self.length, "Out of range"
return self._theVect[ndx]
def __setitem__ ( self, ndx, item ):
""" Set the item at the ndx position."""
assert ndx>=0 and ndx<self.length, "Out of range"
self._theVect[ndx] = item
def append ( self, item ):
""" Add the given item to the end of the list."""
theVector=Array(len(self._theVect))
for i in range(len(thenewVector)):
theVector[i]=self._theVect[i]
self._theVect=Array(len(self._theVect)*2)
for i in range(len(self._theVect)-1):
self._theVect[i]=theVector[i]
self._theVect[len(theVector)]=item
def insert ( self, ndx, item ):
"""Insert an item in the vector based on the given index."""
assert ndx>0 and ndx<=self.length, "Out of Scope"
def extend ( self, otherVector ):
thecmbVector
def remove ( self, ndx):
"""Remove an index of the item in the vector."""
assert ndx>=0 and ndx<self.length, "Out of Scope"
for i in range(ndx-1,len(self._theVect)):
self._theVect[i]=self._theVect[i+1]
def indexof ( self, item ):
"""Returns an index of the item in the vector."""
assert item in self._theVect, "The item is not in the vector."
for index in range(len(self._theVect)):
if self._theVect[index]=item:
return index
def subVector ( self, from, to ):
return self._theVect[from,to+1]
def __iter__ (self):
"""Returns an iterator for traversing the list of items in the vector."""
return _VectorIterator(self._theItems)
class _VectorIterator:
def __init__( self, theArray ):
self._vectorItems = theArray
self._curItem = 0
def __iter__ (self):
return self
def __next__ (self):
if self.curItem < len(self._vectorItems):
item = self._vectorItems[self._curItem]
self.curItem += 1
return item
else:
raise StopIteration
|
'''
https://codefights.com/arcade/intro/level-2/xskq4ZxLyqQMCLshr
Created on 2018年2月5日
@author: rocky.wang
'''
def matrixElementsSum(matrix):
total = 0
for w in range(len(matrix[0])): # width
for h in range(len(matrix)): # height
if matrix[h][w] == 0:
break
else:
total += matrix[h][w]
return total
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
total = matrixElementsSum(matrix)
print("sum is %s" %(total))
'''
First version not good.
'''
def matrixElementsSumOld(matrix):
noteArr = []
for i in range(len(matrix[0])):
noteArr.append("O")
total = 0
for arr in matrix:
for i in range(len(arr)):
if noteArr[i] == "X":
pass
else:
if arr[i] == 0:
noteArr[i] = 'X'
else:
total += arr[i]
return total
|
import time
file_name = input("Enter text file name => ") + ".txt"
try:
with open(file_name, "r") as file:
find_word = input("Enter word you want to replace => ")
replace_word = input("Enter word you want to replace with => ")
file_data = file.read()
while True:
word_index = file_data.find(find_word)
if word_index == -1:
print("No more word found")
with open(file_name, "w") as final_file:
final_file.write(file_data)
print(file_data)
time.sleep(2)
break
else:
file_data = file_data[0:word_index] + replace_word + file_data[word_index+len(find_word):]
except:
print("File not found")
time.sleep(2)
|
# -*- coding: utf-8 -*-
# @Time : 2021/4/24 下午6:14
# @Author : ShaHeTop-Almighty-ares
# @Email : yang6333yyx@126.com
# @File : 05.private_property_demo.py
# @Software: PyCharm
class A:
_y = '_y'
__y = '__y'
def _a(self):
print('_a')
def __a(self):
print('__a')
def get_y2(self):
print(self.__y)
if __name__ == '__main__':
a = A()
print(A.__dict__)
print(a._y)
print(a._A__y) # 正确调用双下划线的方式,在开发过程中不建议使用
a._a()
a._A__a() # 正确调用双下划线的方式,在开发过程中不建议使用
a.get_y2() # 正确调用双下划线的方式,建议使用
# 直接调用双下划线的属性或方法会报错
a.__a()
a.__y()
|
# -*- coding: utf-8 -*-
"""
This is for Jon Snow using Uniform Cost Search
This is to find the quickest route to his goal.
John Snow's goal is to reach the white walkers as
they leave the wall
@author: Ashley
"""
import queue as que
def ucsJS(nodeMap, start, goal):
visited = set()
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
if node == goal:
#return current visited list when back at the wall
return visited
for neighbor in nodeMap[node]:
if neighbor not in visited:
stack.append(neighbor)
#return visited
|
"""
Factorial of a number (without using recursion)
"""
def fact_no_recursion(num):
fact = 1
if num == 0:
return fact
else:
for i in range(1,num+1):
fact = fact * i
return fact
x = 7000
y = fact_no_recursion(x)
print("Factorial of {} is {}".format(x, y)) |
a = 1 > 2 # Is 1 greater than 2?
print(a)
a = 1 < 2 # Is 1 less than 2?
print(a)
a = 1 >= 1 # Is 1 greater than or equal to 1?
print(a)
a = 1 <= 4 # Is 1 less than or equal to 4?
print(a)
a = 1 == 1 # is 1 equal to 1?
print(a)
a = 'hi' == 'bye' # is 'hi' equal to 'bye'
print(a)
|
"""
Using the Python map() function
"""
def my_square(x):
y = x * x
return y
numbers = (1, 2, 3, 4)
# First way
y = []
for num in numbers:
y.append(my_square(num))
print("Without using map function ", y)
# A better way
z = map(my_square,numbers) # map applies the my_square on the tuple numbers
# Each value in tuple is passed to the function
print("After using map function ", list(z)) |
# solution for https://www.hackerrank.com/challenges/icecream-parlor/problem
import sys
def icecreamParlor(m, arr):
arr = quickSort(m, arr)
for i in range(0,len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == m:
return [a[i], a[j]]
# Complete this function
def quickSort(m, a):
if len(a) < 2:
return a
pivot = a.pop(0)
return quickSort(m, list(filter(lambda c: c < pivot and c < m, a))) + \
[pivot] + \
quickSort(m, list(filter(lambda c: c > pivot and c < m, a)))
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
m = int(input().strip())
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = icecreamParlor(m, arr)
print (" ".join(map(str, result)))
|
# solution for https://www.hackerrank.com/challenges/caesar-cipher-1/problem
def caesarCipher(s, k):
res = []
for char in s:
if char.islower():
res.append(rotate(char, 96))
elif char.isupper():
res.append(rotate(char, 64))
else:
res.append(char)
return ''.join(res)
def rotate(char, offset):
chr((ord(char) - offset + k % 26) % (26 + (1 if (ord(char) - offset + k) % 26 == 0 else 0)) + offset)
|
import math
def hourglassSum(arr):
maxSum = -math.inf
for i in range(0, len(arr) - 2):
for j in range(0, len(arr[i]) - 2):
sum = hourglass(arr, i, j)
if maxSum < sum:
maxSum = sum
return maxSum
def hourglass(arr, i, j):
return sum(arr[i][j:(j+3)]) + arr[i+1][j+1] + sum(arr[i+2][j:(j+3)])
|
'''
Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário,
mostrando uma mensagem de erro e voltando a pedir as informações.
'''
usuario = input("Informe o nome: ")
senha = input("Informe a senha: ")
while (senha == usuario):
print("Erro!")
print("Digite uma senha que não seja igual ao nome do usuário!")
usuario = input("Informe o nome: ")
senha = input("Informe a senha: ")
|
'''
Faça um programa que receba dois números inteiros e gere os números
inteiros que estão no intervalo compreendido por eles.
'''
n1 = int(input("Informe o primeiro número: "))
n2 = int(input("Informe o segundo número: "))
for Nintervalo in range (n1, n2):
print(Nintervalo)
|
import random
chars = '012345uewuwoirjeiwuruwi54683959048Y489jroieury78o2349u9498yruieiikj4283wujuiy39jr9eijrh78w36789'
number = int(input('Ծածկագրերի քանակը․'))
lenght = int(input('Տողի երկարությունը․'))
for user_name in range(number):
password = ''
for per_user in range(lenght):
password += random.choice(chars)
print(password)
file = open('password.txt', 'a')
file.write('\n' + password)
file.close() |
import numpy as np
import pandas as pd
class Optimizer:
"""
A class that performs general optimization
todo: list should be changed to numpy
todo: filter and criteria have to have 2 arguments each
todo: add store and load to documentation
Attributes
----------
accepted_choices : list
A list containing all objects that passed the filter test sorted by their scores descending
rejected_choices : list
A list containing all objects that could not pass the filter test
scores : ndarray
An 1d ndarray containing the scores of the accepted_choices in the same order
"""
def __init__(self, choices=[], filter=lambda x,y: True, criteria=lambda x,y: 0, store=None):
"""
:param list choices: The competing objects.
:param function filter: A filter used to exclude some of the choices. It is a function that takes
a choice with a generic parameter and gives a boolean value which specify whether to include the
choice or not. If True, the choice is included.
:param function criteria: The criteria used for optimization. It is a function that takes a choice
with a generic parameters and gives a numeric score used for comparison.
"""
self.accepted_choices = np.array([]).astype(np.object)
self.scores = np.array([])
self.rejected_choices = np.array([]).astype(np.object)
self._choices = choices
self._filter = filter
self._criteria = criteria
self._updated = False
self._unprocessed_choices = []
self._filter_parameters = None
self._criteria_parameters = None
self._store = store
def from_io(self, load, filename):
return load(filename)
def __str__(self):
string = ''
for i,choice in enumerate(self.accepted_choices):
string = string + str(i) + ' : ' + str(choice) + ' ---- score : ' + str(self.scores[i]) + '\n'
return string
def optimize(self, store_filename=None, verbose=False):
"""
Performs the optimization process
It sets accepted_choices, rejected_choices and scores accordingly. This method performs the
entire process only in the following cases: 1.The first time it is called. 2.Criteria, filter or
the entire choices list has been setted to a new value. This method performs a partial process
when new choices are added where only these choices pass through the entire process and then they
are inserted in the sorted list according to their scores. Otherwise, this method does not do
anything.
"""
if not self._updated:
self._unprocessed_choices = self._choices.copy()
self.accepted_choices = np.array([]).astype(np.object)
self.rejected_choices = np.array([]).astype(np.object)
self.scores = np.array([])
self._updated = True
choices_buffer = self._unprocessed_choices.copy()
for i,choice in enumerate(choices_buffer):
if verbose:
print(str(i) + ' : ')
if self._filter(choice, self._filter_parameters):
score = self._criteria(choice, self._criteria_parameters)
i = np.searchsorted(self.scores, score)
self.scores = np.insert(self.scores, i, score)
self.accepted_choices = np.insert(self.accepted_choices, i, choice)
else:
self.rejected_choices = np.append(self.rejected_choices, choice)
self._unprocessed_choices.pop(0)
if store_filename != None:
self.store_self(store_filename)
def set_filter(self, filter):
"""
Sets the filter member variable
:param function filter: The new value of filter variable
"""
self._filter = filter
self._updated = False
def set_criteria(self, criteria):
"""
Sets the criteria member variable
Calling this method between two optimize calls will make the second call to optimize performs the
entire process.
:param function criteria: The new value of criteria variable
"""
self._criteria = criteria
self._updated = False
def set_choices(self, choices):
"""
Sets the choices member variable
Calling this method between two optimize calls will make the second call to optimize performs the
entire process.
:param list choices: The new value of choices variable
"""
self._choices = choices
self._updated = False
def add_choice(self, choice):
"""
Adds a choice to the choices member variable
Calling this method between two optimize calls will make the second call to optimize only handles
the added choices.
:param object choice: The new choice to be added to the choices variable
"""
self._choices.append(choice)
self._unprocessed_choices.append(choice)
def add_choices(self, choices):
"""
Adds choices to the choices member variable
Calling this method between two optimize calls will make the second call to optimize only handles
the added choices.
:param list choice: The new choices to be added to the choices variable
"""
self._choices = self._choices + choices
self._unprocessed_choices = self._unprocessed_choices + choices
def set_criteria_parameters(self, parameters):
"""
sets a parameters variable to used in criteria calls
Calling this method between two optimize calls will make the second call to optimize performs the
entire process.
:param object parameters: The new value of _critera_parameters variable
"""
self._criteria_parameters = parameters
self._updated = False
def set_filter_parameters(self, parameters):
"""
sets a parameters variable to used in filter calls
Calling this method between two optimize calls will make the second call to optimize performs the
entire process.
:param object parameters: The new value of _filter_parameters variable
"""
self._filter_parameters = parameters
self._updated = False
def store_self(self, filename):
self._store(self, filename) |
import numpy as np
class FeatureExtractor:
"""
A base class for feature extraction classes
This class performs no extraction; it returns the dataset as it is. It should be overriden to create feature
extraction classes, in which case, at least fit method should be overriden.
Attributes
----------
features : ndarray
array repreents the indices of the columns to be selected
methods
-------
fit(dataset) : None
selects the best features from a dataset and sets the attribute features accordingly
extract(dataset) : ndarray
returns a dataset that represents a given one but with the extracted features
fit_extract(dataset) : ndarray
selects the best features from a dataset and return a modified version of the dataset
"""
def __init__(self, num_of_features=None):
"""
Initializes the object attributes
features parameter is set to None.
:param int num_of_features: the required number of features
"""
self.num_of_features = num_of_features
self.features = None
def fit(self, dataset):
"""
selects the best features from a dataset and sets the attribute features accordingly
This method should be overriden to implement a feature extraction class. Currently it sets the features
to be all the columns of the dataset.
:param ndarray dataset: The dataset according which the features are selected.
"""
self.features = np.arange(dataset.shape[1])
def extract(self, dataset):
"""
Extracts features from a dataset according to scheme decided through fit
:param dataset: The dataset to apply feature extraction on.
:return ndarray: A dataset that represents a given one but with the extracted features
"""
return dataset[:, self.features]
def fit_extract(self, dataset):
"""
Selects the best features from a dataset and return a modified version of the dataset
It extracts features from a dataset using a schema decided based on the dataset itself. It is equivalent
to calling fit and then predict to the same dataset.
:param dataset: The dataset to extract features from.
:return ndarray: A dataset that represents a given one but with the extracted features
"""
self.fit(dataset)
return self.extract(dataset) |
'''
For this assignment you should read the task, then below the task do what it asks you to do.
EXAMPLE TASK:
'''
#EX) Make a variable called name and assign it to your name. And print the variable.
from builtins import False, True
name = "Michael"
print(name)
'''
END OF EXAMPLE
'''
'''
START HERE
'''
name = "Laura"
'''INTEGERS'''
var1 = 4
print(var1)
var2 = 10
print(var2)
var3 = var2
print(var3)
varX = 24
print(varX)
varY = 100
print(varY)
'''FLOATS'''
Z = 1.1
print(Z)
A = 2.75
print(A)
B = A
print(B)
C = 100.1
print(C)
D = 12.3
print(D)
'''STRINGS'''
name = "laura"
print(name)
e = "l"
print(e)
f = "a"
print(f)
g = "chicken"
print(g)
h = "lau"
print(h)
'''BOOLEANS'''
done = False
print(done)
smart = True
print(smart)
i = done
print(i)
j = False
print(j)
almostDone = True
print(almostDone)
'''LISTS'''
listInt = [var1, var2, var3, x, y]
print[var3]
listStrings = [name, e, f, g, h]
print[g]
listBooleans = [done, smart, i, j, almostDone]
print[done]
print[smart]
print[i]
print[j]
print[almostDone]
|
# 앞에서부터 읽을 때나 뒤에서부터 읽을 때나 모양이 같은 수를 대칭수(palindrome)라고 부릅니다.
# 두 자리 수를 곱해 만들 수 있는 대칭수 중 가장 큰 수는 9009 (= 91 × 99) 입니다.
# 세 자리 수를 곱해 만들 수 있는 가장 큰 대칭수는 얼마입니까?
set_A = []
set_B = []
set_C = []
for i in range(100, 1000):
A = i
for k in range(100, 1000):
B = k
C = A * B
str_C = str(C)
if list(str_C) == list(reversed(str_C)):
set_A.append(A)
set_B.append(B)
set_C.append(C)
ans_A = set_A[set_C.index(max(set_C))]
ans_B = set_B[set_C.index(max(set_C))]
ans_C = set_C[set_C.index(max(set_C))]
ans = dict(zip(['A', 'B', 'C'], [ans_A, ans_B, ans_C]))
print(ans) |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
# reference : http://projecteuler.net/problem=1
mul3_5 = [] # 3의 배수와 5의 배수를 포함한 리스트
for i in range(1,1001):
if i % 3 == 0 or i % 5 == 0:
mul3_5.append(i) # 1부터 1000 사이의 숫자 중 3이나 5로 나누어 떨어지는 수를 mul3_5에 추가.
sum(mul3_5)
# answer : 234168
|
def mas_grande(num1, num2, num3, d):
menor = min(num1, num2, num3)
mayor = max(num1, num2, num3)
medio = (num1 + num2 + num3) - menor - mayor
if d == "N":
print("Los Valores Son: {}, {}, {}".format(mayor, medio, menor))
else:
print("Los Valores Son: {}, {}, {}".format(menor, medio, mayor))
print("Dame Tres valores: ")
val1 = int(input())
print("Dame el segundo valor: ")
val2 = int(input())
print("Dame el tercer valor: ")
val3 = int(input())
while True:
print("Quieres ordenar los Valores de manera: Ascendente(Y) o Descendente(N) , Choose: Y/N ")
decicion = input()
if decicion == "Y" or decicion == "N":
mas_grande(val1, val2, val3, decicion)
break
else:
print("tienes que ingresar Y o N")
|
def compute(x, y):
return x * y
def main():
x = int(input())
y = int(input())
result = compute(x, y)
print(result)
if __name__ == '__main__':
main()
|
def check(num1,num2):
return format(num1^num2,'b').count('1')
c = 0
for i in range(31):
if check(i,0) <= 3 and check(i,3) <= 3:
print(""+"0"*(5-len(format(i,'b')))+format(i,'b'))
c += 1
print(c)
|
S = input()
#print(S)
ans = []
for str in S:
if str == '0':
ans.append('0')
elif str == '1':
ans.append('1')
else:
if len(ans) > 0:
ans.pop()
for a in ans:
print(a,end ="")
print()
|
#import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#importing the dataset
df = pd.read_csv('50_startups.csv')
x = df.iloc[: , :-1].values
y = df.iloc[: , 4].values
#Convert categorical data by Label Encode/One-Hot Encoding
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelEncoder_x = LabelEncoder()
x[:,3] = labelEncoder_x.fit_transform(x[:,3])
onehotencoder = OneHotEncoder(categorical_features = [3])
x = onehotencoder.fit_transform(x).toarray()
#Avoiding Dummy Variable Trap (See Readme for info on Dummy Variable Trap)
x = x[:,1:]
#Test Train Split to be made
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0)
#Fitting the Regression
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(x_train,y_train)
y_pred = lm.predict(x_test)
#Calculate the accuracy(r2 score and MSE)
from sklearn.metrics import r2_score,mean_squared_error
r2_accuracy = r2_score(y_test,y_pred)
MSE = mean_squared_error(y_test,y_pred)
#r2_score = 0.9347068473282965 MSE = 83502864.0325083
|
# Import combinations from itertools
from itertools import combinations
# Create a combination object with pairs of Pokémon
combos_obj = combinations(pokemon, 2)
print(type(combos_obj), '\n')
# Convert combos_obj to a list by unpacking
combos_2 = [*combos_obj]
print(combos_2, '\n')
# Collect all possible combinations of 4 Pokémon directly into a list
combos_4 = [*combinations(pokemon, 4)]
print(combos_4) |
"""Determine if number is palindrome."""
def isPalindrome(x):
"""
Take integer number and determine if palindrome.
:type x: int
:rtype: bool
"""
if x < 0:
return False
# convert to string
x = str(x)
if x[-1] == '0' and len(x) > 1:
return False
if x == x[::-1]:
return True
return False
|
"""Reverse Linked List II."""
def reverse_between(head, m, n):
"""Reverse linked list between m and n."""
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
|
"""Append the sum of prior 3 elements into original 3 element list."""
def tribonacci(signature, n):
"""Render iterative solutions."""
res = signature[:n]
for i in range(n - 3):
res.append(sum(res[-3:]))
return res
"""
[:n], from start to n - 1.
In case n = 0, returns []
range(n - 3) ensure n should be greater than 3
"""
|
# encoding: utf-8
"""
@author: Liangzi Rong
@contact: 289770334@qq.com
"""
import copy
import time
def copy_deepcopy():
# copy is much more efficient
a = range(10000)
last_time = time.time()
for i in range(10000):
_ = copy.copy(a)
print('time(s) for copy: ', time.time() - last_time)
last_time = time.time()
for i in range(10000):
_ = copy.deepcopy(a)
print('time(s) for deepcopy: ', time.time() - last_time)
def dif_copy_func():
a = 1
b = a
a = 2
print('b value after a value is changed to 2: ', b)
print('id(a): ', id(a), ',id(b): ', id(b))
raw = [1, [2, 3]]
# = just give the id(raw) to copy_0, meaning raw and copy_0 point at the same memory block
copy_0 = raw
# copy.copy() is shallow copy, which just store the contents of raw not containing sub-variable. For the contents
# containing sub-variables, it choose to point at the same memory block just as '=' does, such as raw[1]=[2, 3]
copy_1 = copy.copy(raw)
# copy.deepcopy() is deep copy, which create a memory block to store the whole contents of raw
copy_2 = copy.deepcopy(raw)
print('id(raw):{0}, id(copy_0):{1}, id(copy_1):{2}, id(copy_2):{3}'.format(id(raw), id(copy_0), id(copy_1), id(copy_2)))
print('id(raw[1]):{0}, id(copy_1[1]):{1}'.format(id(raw[1]), id(copy_1[1])))
raw[0] = 0
print('raw:{0}, copy_0:{1} ,copy_1:{2}, copy_2:{3}'.format(raw, copy_0, copy_1, copy_2))
raw[1].append(5) # but if write like: raw[2]=[3, 4, 5], copy_1[2] will be [3, 4] not [3, 4, 5]
print('raw:{0}, copy_0:{1} ,copy_1:{2}, copy_2:{3}'.format(raw, copy_0, copy_1, copy_2))
raw.append(100)
print('raw:{0}, copy_0:{1} ,copy_1:{2}, copy_2:{3}'.format(raw, copy_0, copy_1, copy_2))
if __name__ == '__main__':
# copy_deepcopy()
dif_copy_func()
|
# 1046. Last Stone Weight
"""
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x
and y with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)
"""
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
heap: push to the top, pop the minimum
+ set for uniqueness
"""
#-------------------------------------------------------------------------------
# Soluton1
#-------------------------------------------------------------------------------
class Solution(object):
def lastStoneWeight(self, stones):
"""
:type stones: List[int]
:rtype: int
"""
stones = [-1*i for i in stones]
while len(stones) > 1:
heapq.heapify(stones)
s1 = heapq.heappop(stones)
s2 = heapq.heappop(stones)
if s1 != s2:
heapq.heappush(stones, s1 - s2)
return -1*stones[0] if stones else 0
#-------------------------------------------------------------------------------
# Test
#-------------------------------------------------------------------------------
|
# 735. Asteroid Collision
"""
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents
its direction (positive meaning right, negative meaning left). Each asteroid moves
at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet,
the smaller one will explode. If both are the same size, both will explode.
Two asteroids moving in the same direction will never meet.
"""
#-------------------------------------------------------------------------------
# Approach-
#-------------------------------------------------------------------------------
"""
stack
"""
#-------------------------------------------------------------------------------
# Soluton1
#-------------------------------------------------------------------------------
class Solution(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
res = [] #Used to track the first num of the pair
for asteroid in asteroids:
while len(res) and asteroid < 0 and res[-1] > 0:
# example: 5 and -5
if res[-1] == -asteroid:
res.pop()
break
# example 2 and -5, 2 get destroyed, -5 still needs to be append
elif res[-1] < -asteroid:
res.pop()
continue
# example 5 and -2, -2 get destroyed
elif res[-1] > -asteroid:
break
else:
res.append(asteroid)
return res
#-------------------------------------------------------------------------------
# Test
#-------------------------------------------------------------------------------
|
# 394. Decode String(M)
"""
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the
square brackets is being repeated exactly k times. Note that k is guaranteed
to be a positive integer.
You may assume that the input string is always valid; No extra white spaces,
square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits
and that digits are only for those repeat numbers, k. For example, there won't
be input like 3a or 2[4].
Exs:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
"""
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
stack: last in first out (LIFO)
"""
#-------------------------------------------------------------------------------
# Soluton1
#-------------------------------------------------------------------------------
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = [] # stack is used to keep track of the num
curNum = 0 # curNum is used since num could have multiple digits
curString = '' # curString is used for keeping track of the result
for c in s:
if c == '[':
stack.append(curString)
stack.append(curNum)
curString = ''
curNum = 0
elif c == ']':
num = stack.pop()
prevString = stack.pop()
curString = prevString + num * curString
elif c.isdigit():
curNum = 10*curNum + int(c)
else:
curString += c
return curString
#-------------------------------------------------------------------------------
# Soluton2 - DP
#-------------------------------------------------------------------------------
|
#102. Binary Tree Level Order Traversal
"""
Given a binary tree, return the level order traversal of its nodes' values. (ie,
from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
"""
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
bfs
"""
#-------------------------------------------------------------------------------
# Soluton1 --- BFS
#-------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
from collections import deque
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
level, levels = 0, []
queue = collections.deque([root,])
while queue:
levels.append([])
level_length = len(queue)
for i in range(level_length):
node = queue.popleft()
levels[level].append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
level += 1
return levels
#-------------------------------------------------------------------------------
# Soluton2 ---Recursive
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Test
#-------------------------------------------------------------------------------
|
# 206. Reverse Linked List
# Reverse a singly linked list.
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Array
"""
#-------------------------------------------------------------------------------
# Soluton1 - Iterative, O(n) and O(1)
#-------------------------------------------------------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
while head:
temp = head.next
#reverse the direction
head.next = prev
# moving the two pointers: prev and head to the same direction
prev = head
head = temp
return prev
#-------------------------------------------------------------------------------
# Soluton2 - Recursive, O(n) and O(n)
#-------------------------------------------------------------------------------
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
return self._reverse(head)
def _reverse(self, node, prev=None):
if not node:
return prev
n = node.next
node.next = prev
return self._reverse(n, node)
|
# 234. Palindrome Linked List
"""
Given a singly linked list, determine if it is a palindrome.
"""
#-------------------------------------------------------------------------------
# Approach-
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Soluton 1 - List
#-------------------------------------------------------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
res= []
curr_node = head
while curr_node is not None:
res.append(curr_node.val)
curr_node = curr_node.next
return res == res[::-1]
#-------------------------------------------------------------------------------
# test
#-------------------------------------------------------------------------------
|
# 127. Word Ladder
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
"""
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Graph + bfs
"""
#-------------------------------------------------------------------------------
# Soluton
#-------------------------------------------------------------------------------
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList or not endWord or not beginWord or not wordList:
return 0
L = len(beginWord)
# Dictionary to hold combination of words that can be formed,from any given word.
all_combo_dict = defaultdict(list)
for word in wordList:
for i in range(L):
# Key is the word:Value is a list of words.
all_combo_dict[word[:i] + "*" + word[i+1:]].append(word)
# queue for bfs
queue = collections.deque([(beginWord, 1)])
visited = {beginWord: True}
while queue:
current_word, level = queue.popleft()
for i in range(L):
intermediate_word = current_word[:i] + '*' + current_word[i+1:]
for word in all_combo_dict[intermediate_word]:
if word == endWord:
return level + 1
if word not in visited:
visited[word] = True
queue.append((word, level + 1))
all_combo_dict[intermediate_word] = []
return 0
#-------------------------------------------------------------------------------
# Test
#-------------------------------------------------------------------------------
|
# 953. Verifying an Alien Dictionary
# In an alien language, surprisingly they also use english lowercase letters,
# but possibly in a different order. The order of the alphabet is some permutation of
# lowercase letters.
# Given a sequence of words written in the alien language, and the order of the alphabet,
# return true if and only if the given words are sorted lexicographicaly in this alien language.
# Example1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
# Output: true
# Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Using Dictionary
"""
#-------------------------------------------------------------------------------
# Soluton O(nlogn) O(A)
#-------------------------------------------------------------------------------
class Solution(object):
def isAlienSorted(self, words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
# change the order into char:index dictionary
order_index = {char:index for index, char in enumerate(order)}
# compare neighbours and according to transitive property, it could all work out
for i in xrange(len(words) - 1):
word1 = words[i]
word2= words[i + 1]
## for char in each adjacent words at same order, if they are reverse in order return False
for k in xrange(min(len(word1), len(word2))):
if word1[k] != word2[k]:
if order_index[word1[k]] > order_index[word2[k]]:
return False
break
## Corresponding to example 3, if len of word1 > len of word2, return False
else:
if len(word1) > len(word2):
return False
return True
#-------------------------------------------------------------------------------
# Test
#-------------------------------------------------------------------------------
|
#88. Merge Sorted Array
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# #-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Two pointers, start from the end
"""
#-------------------------------------------------------------------------------
# Soluton - O(m+n) and O(1)
#-------------------------------------------------------------------------------
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
# two pointers for num1 and num2 as well as the point for num1(in-place)
p1, p2, p = m-1, n-1, m + n - 1
while p1 >= 0 and p2 >= 0:
if nums1[p1] < nums2[p2]:
nums1[p] = nums2[p2]
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
# add missing elements from num2 if n > m
nums1[:p2 + 1] = nums2[:p2 + 1] |
## 611. Valid Triangle Number
# Given an array consists of non-negative integers, your task is to count the number
# of triplets chosen from the array that can make triangles if we take them as side
# lengths of a triangle.
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Two pointer
"""
#-------------------------------------------------------------------------------
# Soluton1
#-------------------------------------------------------------------------------
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
nums = nums[::-1]
res= 0
for i in range(len(nums)-2):
j = i+1
k = len(nums) - 1
while j < k:
diff = nums[i] - nums[j]
while nums[k] <= diff and k > j:
k -= 1
res += k-j
j += 1
return res
return nums[::-1]
#-------------------------------------------------------------------------------
# Solution2 - Use two pointer O(nlogn) & o(1)
#-------------------------------------------------------------------------------
nums= [2,7,11,15]
soln = Solution()
print(soln.triangleNumber(nums)) |
#141. Linked List Cycle
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
# To represent a cycle in the given linked list, we use an integer pos which represents the position
#(0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
# Note: Do not modify the linked list.
# #-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Two pointers: fast goes by two steps and slow goes by one step and they meet. One stays at the intersect
and the other start from head, they move in the same speed this time. The second intersect is the entrance of the circle.
"""
#-------------------------------------------------------------------------------
# Soluton1 - Recursive, O(n) and O(n)
#-------------------------------------------------------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersect(self, head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return slow
return None
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
intersect = self.getIntersect(head)
if intersect is None:
return None
ptr1, ptr2 = head, intersect
while ptr1 != ptr2:
ptr1 = ptr1.next
ptr2 = ptr2.next
return ptr1
|
#298. Binary Tree Longest Consecutive Sequence
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
DFS
"""
#-------------------------------------------------------------------------------
# Soluton1 - Recursive
#-------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res = [0]
self.dfs(root, res)
return res[0]
def dfs(self, node, res):
if not node:
return 0
L = self.dfs(node.left, res) + 1
R = self.dfs(node.right, res) + 1
if node.left is not None and node.val + 1 != node.left.val:
L = 1
if node.right is not None and node.val + 1 != node.right.val:
R = 1
length = max(L, R)
res[0] = max(res[0], length)
return length
#-------------------------------------------------------------------------------
# Solution2 - Iterative
#-------------------------------------------------------------------------------
class Solution(object):
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
stack = [(root, 1)]
res = 0
while stack:
node, length = stack.pop()
if node.left:
stack.append((node.left, length + 1 if node.left.val == node.val + 1 else 1))
if node.right:
stack.append((node.right, length + 1 if node.right.val = node.val + 1 else 1))
res = max(res, length)
return res
|
#426. Convert Binary Search Tree to Sorted Doubly Linked List
#Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Iterative: root, left, right
"""
#-------------------------------------------------------------------------------
# Soluton1 ---D & C
#-------------------------------------------------------------------------------
class Solution(object):
head = None
prev = None
def treeToDoublyList(self, root):
if not root: return None
self.treeToDoublyListHelper(root)
self.prev.right = self.head
self.head.left = self.prev
return self.head
def treeToDoublyListHelper(self, node):
if not node: return
self.treeToDoublyListHelper(node.left)
if self.prev:
node.left = self.prev
self.prev.right = node
else: # We are at the head.
self.head = node
self.prev = node
self.treeToDoublyListHelper(node.right)
|
#!/usr/bin/python3
print('Hi how are you?')
feeling= input()
if feeling.lower()== 'great':
print('i feel great too')
else:
print('too bad!')
|
# name = "Srini"
# age = 23
print ("Hello world")
print("My name is " + name + "my age " + str(age))
print("My name is %s and my age %d" % (name,age))
print("My name is {name} and my age {age}".format(age=age,name=name))
# this syntc work only python 3.6
print(f'My name is {name} my age next year {age+1}')
# writing a function to generate stroy
# this syntax in python 3.X
def story(name,age,email='basic@gmail.com'):
return ("My name is {name} and my age {age} and my email is {email}" .format(age=age,name=name,email=email))
def make_upper_and_give_first_twoval(mystr):
upcasestr = mystr.upper()
return upcasestr[:2]
# name = "srini"
# age = 23
# email = "hello@gmail.com"
# story(name,age,email)
# print(story(age=23,name='srini',email='hello@gmail.com'))
# full_story= story(age=23,name='srini',email='hello@gmail.com')
# print(full_story)
print(story(age=23,name='srini'))
person = {'name': 'Jenn', 'age': 23}
# sentence = 'My name is ' + person['name'] + ' and I am ' + str(person['age']) + ' years old.'
# print(sentence)
# sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age'])
# print(sentence)
# sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
# print(sentence)
# tag = 'h1'
# text = 'This is a headline'
# sentence = '<{0}>{1}</{0}>'.format(tag, text)
# print(sentence)
sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
print(sentence)
# pi = 3.14159265
# sentence = 'Pi is equal to {}'.format(pi)
# print(sentence)
sentence = '1 MB is equal to {} bytes'.format(1000**2)
print(sentence)
import datetime
my_date = datetime.datetime(2016, 9, 24, 12, 30, 45)
# print(my_date)
# March 01, 2016
sentence = '{:%B %d, %Y}'.format(my_date)
print(sentence)
# March 01, 2016 fell on a Tuesday and was the 061 day of the year.
sentence = '{:%B %d, %Y} fell on a {} and was the {} day of the year'.format(my_date)
print(sentence) |
#codewars link
#https://www.codewars.com/kata/546d15cebed2e10334000ed9/train/python
def solve_runes(runes):
temp = runes
print(temp)
for i in "0123456789":
if i in temp or i == '0' and (temp[0] in '0?' and \
temp[1] in '?1234567890' or \
any([ True for i,s in enumerate(temp) \
if s in '=+-*' and temp[i+1] == '?'and i+2 < len(temp) and temp[i+2] in '?0123456789'])):
continue
temp = temp.replace('?',i)
temp = temp.replace('=','==')
print(temp)
if eval(temp):
return int(i)
temp = runes
return -1
test = "?38???+595???=833444"
print(solve_runes(test))
|
import datetime
class Logger:
def __init__(self, log_file_name, console):
self.logs = []
self.log_file_name = log_file_name
self.console = console
def get_formatted_time(self):
""" Returns the current time for use in the .log and console in day/month/year hour:minute.second format"""
dttm = datetime.datetime.now()
return f"{dttm.day}/{dttm.month}/{dttm.year} {dttm.hour}:{dttm.minute}.{dttm.second}"
def log(self, txt: str, type: str = None):
""" Log events to console and the .log file """
formatted_time = self.get_formatted_time()
self.logs.append({
"txt": txt,
"type": type,
"formatted_time": formatted_time
})
# keep a log
log_file = open(self.log_file_name, 'a')
log_file.write(f"[{formatted_time}] {str(txt)}\n")
log_file.close()
self.console.update(self.logs)
|
def main():
sentence = input("Introduce la frase que quieres ver al reves: ")
print("")
firstchar= input("Cambia la primera letra de lo que has introducido: ")
sentence_new= firstchar + sentence[1:]
print("")
print("Tu frase al reves es=", sentence_new[::-1])
if __name__ == "__main__":
main() |
def main():
a = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40] # Declaramos la lista con los números.
b = list() # Creamos una lista vacía que guardara los números que no se repitan.
for i in a: # Dentro de la lista a.
if i not in b: # Validamos que no se repita ningún número.
b.append(i) # Lo guardamos dentro de la lista b.
print("La lista sin repeticiones es esta:", end=" ") # Mostramos al usuario la lista sin repeticiones.
for i in b:
print(i, end=" ")
if __name__ == "__main__":
main() |
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return
Q = deque([root])
res = []
flag = True
while Q:
temp_q = deque()
temp = []
while Q:
x = Q.popleft()
if x.left:
temp_q.append(x.left)
if x.right:
temp_q.append(x.right)
temp.append(x.val)
if flag is False:
temp.reverse()
res.append(temp)
flag = not flag
Q = temp_q
return res
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def dfs(root, res):
if not root:
return
res.append(root.val)
dfs(root.left, res)
dfs(root.right, res)
res = []
dfs(root, res)
return res
def iterativePreorderTraversal(self, root):
stack = []
res = []
while True:
while root:
res.append(root.val)
stack.append(root)
root = root.left
if not stack:
return res
node = stack.pop(-1)
root = node.right
|
# # Next Palindrome
# def np(num):
# count=1
# while(1):
# i=num+count
# if(str(i)==str(i)[::-1]):
# return f"The palindrome for {num} is: {i}"
# else:
# count+=1
# if __name__ == '__main__':
# a=int(input("Enter the number of cases:"))
# b=[]
# for i in range(0,a):
# b.append(int(input(f"\nEnter the {i+1} case:")))
# for i in range(0,a):
# print(np(b[i]))
|
# -*- coding: utf-8 -*-
import urllib
import os
import sys
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def mkdir(path):
#判断参数
if len(sys.argv) < 2:
pass
else:
path = sys.argv[1]
#绝对路径
path = os.path.join(os.getcwd(), path)
#相对路径
#path = path.strip()
#建立文件夹
if not os.path.exists(path):
os.makedirs(path)
os.chdir(path)
else:
print '%s 文件已建立 ' % path
if __name__ == '__main__':
path = 'folder'
mkdir(path)
url = "http://mzzz.site/"
print getHtml(url) |
# -*- coding: utf-8 -*-
#RF1:Obtener la mayor nota y la menor nota
#RF2:Imprimir la nota promedio del curso
#RF3:Cuántos estudiantes aprobaron y cuántos reprobaron
#RF4:imprimir el código y un mensaje de acuerdo con la nota:
#❖ Cuántos obtuvieron una nota Muy bien [ 4.0 5.0]
#❖ Cuántos obtuvieron una nota Bien [ 3.0 4.0 )
#❖ Cuántos obtuvieron una nota suficiente [ 2.0 3.0 )
#❖ Cuántos obtuvieron una nota Insuficiente [ 0,5 2.0 )
#RF5:Decir cuántos estudiantes quedaron en cada una de las categorías anteriores
#RF6:mostrar el porcentaje de estudiantes aprobados y reprobados.
#RF7:Imprimir un listado con los códigos de los estudiantes que obtuvieron la más alta nota
#solicito el tamaño del vector
n=(input("digite el numero de estudiantes: "))
#inicializo/creo vectores
v1=["" for x in range(0,n)]
v2=[0.0 for x in range (0,n)]
#doy valor inicial a las variables
#variable para la suma de las notas
a=0
#variable para la condicion "insuficiente"
b=0
#variable para la condicion de estudiantes aprobados
c=0
#variable para la condicion de "suficiente"
d=0
#variable para la condicion "insuficiente"
e=0
#variable para la condicion "bien"
f=0
#variable para la condicion "muy bien"
g=0
#solicitar datos de los vectores
for i in range (0,n):
print ("codigo----->", i+1)
#solicito codigo
v1[i]=raw_input("")
#solicito nota
nota=(input("digite la nota"))
#condicion nota entre 0.0 y 5.0
while(nota<0.0 or nota>5.0):
nota=(input("nota"))
#se guarda la nota dentro del vector
v2[i]=nota
#se va sumando y guardando en a la suma de todas las notas
a=a+v2[i]
#Doy valor inicial a k(mayor nota) y m(menor nota)
k=v2[0]
m=v2[0]
for i in range(0,n):
#condicionales para el RF4
if (v2[i]<3 and v2[i]>2):
#contador est.reprob
b=b+1
#contador para esta condicion
d=d+1
#mostrar datos
print (v1[i],v2[i],"suficiente")
elif(v2[i]>=3 and v2[i]<4):
#contador est.aprob
c=c+1
#contador para esta condicion
f=f+1
#mostrar datos
print (v1[i], v2[i], "bien")
elif(v2[i]>=4 and v2[i]<=5):
#mostrar datos
print (v1[i], v2[i], "muy bien")
#contador est. aprob
c=c+1
#contador para esta condicion
g=g+1
else:
#contador para esta condicion
e=e+1
#mostrar datos
print (v1[i], v2[i], "insuficiente")
#contador est.reprob
b=b+1
for i in range(0,n):
#condicion para sacar la menor nota
if v2[i]<m:
m=v2[i]
#condicion para sacar la mejor nota
if v2[i]>k:
k=v2[i]
#mostrar la mayor(k) y menor nota(m)
print("la menor nota fue ", m)
print ("la mayor nota fue de ",k)
for i in range(0,n):
#condicion para hayar posicion
if k==v2[i]:
l=i
#se busca la misma posicion en la otra lista para mostrar su codigo
print("el/los estudiante(s) que tiene(n) dicha nota es/son",v1[i])
#porcentaje est. reprob.
h=float(b*100)/n
#porcentaje est aprob
j=float(c*100)/n
#promedio
p=float(a)/n
#se muestran los datos sacados los datos
print("el promedio del curso es: ", p)
print("Reprueban ",b," estudiantes y aprueban ",c," estudiantes")
print (d," estudiantes quedaron en suficiente ",e,"estudiantes quedaron en insuficiente")
print (f," estudiantes quedaron en bien y ",g,"estudiantes quedaron en muy bien")
print (h,"% reprobaron ",j,"% aprobaron")
|
k=str(input())
if "+" not in k:
print(k)
else:
s=k.split("+")
s.sort()
x='+'
print(x.join(s)) |
# Find the largest palindrome made from the product of two 3-digit numbers
def palindrome_count(n):
n = str(n)
if len(n) <= 1:
return 0
if n[0] == n[-1]:
return 1 + palindrome_count(n[1:len(n) - 1])
else:
return 0 + palindrome_count(n[1:len(n) - 1])
def main():
count = 0 # highest palindrome count
largest_palindrome = 0
d1, d2 = 0, 0
for i in range (100, 1000):
for j in range (100, 1000):
if (palindrome_count(i * j) >= count) and ((i * j) > largest_palindrome):
largest_palindrome = i * j
count = palindrome_count(i * j)
d1, d2 = i, j
print (count)
print (d1, d2, d1 * d2)
main()
|
# Solution to Project Euler #11
def hor_sum(num_list):
product = 1
for row in range (len(num_list)):
temp = 1
for column in range (len(num_list[row])):
temp *= num_list[row][column]
product = max(product, temp)
return product
def vert_sum(num_list):
product = 1
for row in range (len(num_list)): # check # of row
temp = 1
row_list = num_list[row]
try:
for column in range (len(num_list[row])):
temp *= num_list[column][row]
product = max(product, temp)
except IndexError:
continue
return product
def diagonal_sum(num_list):
product = 1
for row in range (len(num_list)):
rtemp = 1
ltemp = 1
try:
for column in range (len(num_list[row])):
rtemp *= num_list[column][column]
ltemp *= num_list[len(num_list[row]) - column - 1][column]
product = max(product, rtemp)
product = max(product, ltemp)
except IndexError:
continue
return product
def window(num_list, r, c, length): # matrix in a selected scope denoted by length
w = []
for i in range (length):
temp = []
for j in range (length):
if c + j < len(num_list[r]) and r + i < len(num_list):
temp.append(num_list[r + i][c + j])
w.append(temp)
return w
if __name__ == "__main__":
in_file = open('./P11.txt', 'r')
grid = []
gp = 0 # greatest product
for line in in_file:
line = line.strip()
line = line.split()
line = [int(i) for i in line]
grid.append(line)
for row in range (len(grid)):
for column in range (len(grid[row])):
scope = window(grid, row, column, 4)
gp = max(gp, hor_sum(scope), vert_sum(scope), diagonal_sum(scope))
print (gp)
|
# task 1
def random_num(n):
for i in range(1, n, 2):
yield i
numb = random_num(16)
while (numbers := next(numb)) is not None:
print('my_generator_15')
print(numbers)
# task 2
#numb = iter(range(1, 16, 2))
|
import time
class Library:
def __init__(self, booksList, libraryName, lendDict = {}):
self.booksList = booksList
self.libraryName = libraryName
self.lendDict = lendDict
def displayBook(self):
for book in self.booksList:
print(book, "\n")
def donateBook(self):
name = input("Enter Your Name\n")
age = int(input("Enter Your Age\n"))
number = int(input("Enter Your Mobile Number\n"))
userInputForBook = input("Enter The Name Of The Book\n")
userInputForAuthor = input("Enter The Name Of The Author\n")
self.booksList.append(f"{userInputForBook} by {userInputForAuthor}")
with open("DonatedBooks.txt", "a") as f2:
currentTime = time.asctime(time.localtime(time.time()))
f2.write(f"\n\nName : {name}\nAge : {age}\nMobile Number : {number}\nDonated Book : {userInputForBook} by {userInputForAuthor}\nTime : {currentTime}")
return f"\nThank You Very Much!!\nYou Have Successfully Donated The Book\n"
def lendBook(self):
name = input("Enter Your Name\n")
age = int(input("Enter Your Age\n"))
number = int(input("Enter Your Mobile Number\n"))
print("Which Book You Want To Lend, Please Write In The Same Format As You Saw In The Display")
nameOfTheBook = input("Name : ")
authorOfTheBook = input("Author : ")
bookUserWantsToLend = f"{nameOfTheBook} by {authorOfTheBook}"
if f"{nameOfTheBook} by {authorOfTheBook}" not in self.booksList:
print(f"Sorry, But The Book Is Already Received By {self.lendDict[bookUserWantsToLend]}")
else:
book = f"{nameOfTheBook} by {authorOfTheBook}"
self.lendDict.update({f"{book}" : name})
self.booksList.remove(book)
with open("Lend.txt", "a") as f4:
currentTime = time.asctime(time.localtime(time.time()))
f4.write(f"\n\nName : {name}\nAge : {age}\nMobile Number : {number}\nBook : {nameOfTheBook} by {authorOfTheBook}\nTime : {currentTime}\n")
return f"\nYou Have Successfully Received The Book\n"
def returnBook(self):
name = input("Enter Your Name\n")
age = int(input("Enter Your Age\n"))
number = int(input("Enter Your Mobile Number\n"))
print("Which Book You Want To Return")
nameOfTheBook = input("Name : ")
authorOfTheBook = input("Author : ")
self.booksList.append(f"{nameOfTheBook} by {authorOfTheBook}")
with open("ReturnBook.txt", "a") as f6:
currentTime = time.asctime(time.localtime(time.time()))
f6.write(f"\n\nName : {name}\nAge : {age}\nMobile Number : {number}\nBook : {nameOfTheBook} by {authorOfTheBook}\nTime : {currentTime}\n")
return f"\nYou Have Successfully Returned The Book\nThanks, See You Again!!\n"
if __name__ == '__main__':
library = Library(["ULYSSES by James Joyce", "THE GREAT GATSBY by F. Scott Fitzgerald", "A PORTRAIT OF THE ARTIST AS A YOUNG MAN by James Joyce", "LOLITA by Vladimir Nabokov", "BRAVE NEW WORLD by Aldous Huxley", "THE SOUND AND THE FURY by William Faulkner", "CATCH-22 by Joseph Heller", "DARKNESS AT NOON by Arthur Koestler", "SONS AND LOVERS by D.H. Lawrence", "THE GRAPES OF WRATH by John Steinbeck","UNDER THE VOLCANO by Malcolm Lowry", "THE WAY OF ALL FLESH by Samuel Butler", "1984 by George Orwell", "I, CLAUDIUS by Robert Graves", "TO THE LIGHTHOUSE by Virginia Woolf", "AN AMERICAN TRAGEDY by Theodore Dreiser", "THE HEART IS A LONELY HUNTER by Carson McCullers", "SLAUGHTERHOUSE-FIVE by Kurt Vonnegut", "INVISIBLE MAN by Ralph Ellison", "NATIVE SON by Richard Wright"], "National")
while True:
try:
userinput = int(input(f"\n**Welcome To {library.libraryName} Library**\n\n1. Press 1 To Display Available Books\n2. Press 2 To Donate Books\n3. Press 3 To Lend Books\n4. Press 4 To Return Books\n"))
if userinput == 1:
library.displayBook()
elif userinput == 2:
print(library.donateBook())
elif userinput == 3:
print(library.lendBook())
elif userinput == 4:
print(library.returnBook())
print("Press 'C' To Continue Or Press 'E' To Exit\n" )
userinput = input()
userinput = userinput.upper()
if userinput == "C":
continue
elif userinput == "E":
exit()
except Exception as e:
print("Please Enter valid Inputs!!") |
# Health Management System #
import time
userinput = int(input("Press\n1 For Brock\n2 For Roman\n3 For Dean\n"))
if userinput == 1:
print("Do You Want Log Or Retrieve ?")
userinputforbrock = int(input("Press\n1 For Log\n2 For Retrieve\n"))
if userinputforbrock == 1:
print("What Do You Want To Log For Brock ?")
userinputforlog = int(input("Press\n1 For Diet\n2 For Exercise\n"))
timevar = time.asctime(time.localtime(time.time()))
if userinputforlog == 1:
userinputfordiet = str(input("Add Diet Food\n"))
f1 = open("Diet For Brock.txt","a")
f1.write(timevar)
f1.write(" - ")
f1.write(userinputfordiet)
f1.write("\n")
print()
print("Your Diet Food Added Successfully")
if userinputforlog == 2:
userinputforexercise = str(input("Add Exercise\n"))
f2 = open("Exercise For Brock.txt","a")
f2.write(timevar)
f2.write(" - ")
f2.write(userinputforexercise)
f2.write("\n")
print()
print("Your Exercise Added Successfully.")
if userinputforbrock == 2:
print("What Do You Want To Retrieve For Brock ?")
userinputforretrieve = int(input("Press\n1 For Diet\n2 For Exercise\n"))
if userinputforretrieve == 1:
f1 = open("Diet For Brock.txt","r")
print(f1.read())
print("Your Diet Food Retrieved Successfully")
if userinputforretrieve == 2:
f2 = open("Exercise For Brock.txt","r")
print(f2.read())
print("Your Exercise Retrieved Successfully.")
if userinput == 2:
print("Do You Want Log Or Retrieve ?")
userinputforroman = int(input("Press\n1 For Log\n2 For Retrieve\n"))
if userinputforroman == 1:
print("What Do You Want To Log For Roman ?")
userinputforlog = int(input("Press\n1 For Diet\n2 For Exercise\n"))
timevar = time.asctime(time.localtime(time.time()))
if userinputforlog == 1:
userinputfordiet = str(input("Add Diet Food\n"))
f3 = open("Diet For Roman.txt", "a")
f3.write(timevar)
f3.write(" - ")
f3.write(userinputfordiet)
f3.write("\n")
print()
print("Your Diet Food Added Successfully")
if userinputforlog == 2:
userinputforexercise = str(input("Add Exercise\n"))
f4 = open("Exercise For Roman.txt", "a")
f4.write(timevar)
f4.write(" - ")
f4.write(userinputforexercise)
f4.write("\n")
print()
print("Your Exercise Added Successfully.")
if userinputforroman == 2:
print("What Do You Want To Retrieve For Roman ?")
userinputforretrieve = int(input("Press\n1 For Diet\n2 For Exercise\n"))
if userinputforretrieve == 1:
f3 = open("Diet For Roman.txt", "r")
print(f3.read())
print("Your Diet Food Retrieved Successfully")
if userinputforretrieve == 2:
f4 = open("Exercise For Roman.txt", "r")
print(f4.read())
print("Your Exercise Retrieved Successfully.")
if userinput == 3:
print("Do You Want Log Or Retrieve ?")
userinputfordean = int(input("Press\n1 For Log\n2 For Retrieve\n"))
if userinputfordean == 1:
print("What Do You Want To Log For Dean ?")
userinputforlog = int(input("Press\n1 For Diet\n2 For Exercise\n"))
timevar = time.asctime(time.localtime(time.time()))
if userinputforlog == 1:
userinputfordiet = str(input("Add Diet Food\n"))
f5 = open("Diet For Dean.txt", "a")
f5.write(timevar)
f5.write(" - ")
f5.write(userinputfordiet)
f5.write("\n")
print()
print("Your Diet Food Added Successfully")
if userinputforlog == 2:
userinputforexercise = str(input("Add Exercise\n"))
f6 = open("Exercise For Dean.txt", "a")
f6.write(timevar)
f6.write(" - ")
f6.write(userinputforexercise)
f6.write("\n")
print()
print("Your Exercise Added Successfully.")
if userinputfordean == 2:
print("What Do You Want To Retrieve For Brock ?")
userinputforretrieve = int(input("Press\n1 For Diet\n2 For Exercise\n"))
if userinputforretrieve == 1:
f5 = open("Diet For Brock.txt", "r")
print(f5.read())
print("Your Diet Food Retrieved Successfully")
if userinputforretrieve == 2:
f6 = open("Exercise For Brock.txt", "r")
print(f6.read())
print("Your Exercise Retrieved Successfully.")
|
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3,
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
total = 0
for fruits in prices:
print(fruits)
print("price:", prices[fruits])
for n in stock:
if n == fruits:
print("stock:", stock[n])
print()
sell = prices[fruits] * stock[n]
total += sell
print("Total:", total)
|
amount = int(input("entert the amount you want to make it change"))
print("number of 500 rupees notes u got are:",amount//500)
amount = amount%500
print("number of 200 rupees notes u got are:",amount//200)
amount = amount%200
print("number of 100 rupees notes u got are:",amount//100)
amount = amount%100
print("number of 50 rupees notes u got are:",amount//50)
amount = amount%50
print("number of 20 rupees notes u got are:",amount//20)
print("number of 10 rupees notes u gor are:",amount%20)
|
import re
n = int(input())
for i in range(1, n + 1):
dias = ["SEGUNDA", "TERCA", "QUARTA", "QUINTA", "SEXTA"]
final = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
regex = r"^[A-Z]{3}-[0-9]{4}$"
placa = input()
if not re.match(regex, placa):
print('FALHA')
else:
finalplaca = int(placa[7])
for k in range(6):
if finalplaca in final[k]:
print(dias[k])
break
|
#if, else,elife.
nome = str(input('Qualo o seu nome: ')).title()
if nome == 'Mosiah':
print('Que nome bonito!')
elif nome == 'Pedro' or nome == 'Maria' or nome == 'João':
print('Seu nome é bem popular!')
elif nome in 'Ana Claudia Jessica':
print('Belo nome feminino')
else:
print('Seu nome é bem normal!')
print('Tenha um bom dia, \033[32m{}\033[m! '.format(nome))
|
#xercício Python 049: Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher,
# só que agora utilizando um laço for.
t = int(input("A tabuada de qual numero voce quer ver? "))
for c in range(0, 11):
print("| {:2} x {:2} = {:2} |".format(t, c, (c*t)))
|
#Exercício Python 039: Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade,
# se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do
# alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
from datetime import date
print('Sexo\n[1] Masculino\n[2] Feminino')
sexo = int(input('Digite a resposta: '))
if sexo == 2:
print('O serviço nao é obrigatorio pra você.')
print('saindo...')
elif sexo == 1:
ano = int(input('Qual ano você nasceu? '))
ano_atual = date.today().year
idade = ano_atual - ano
if ano > ano_atual:
print('\033[31mERRO, TENTE NOVAMENTE')
else:
print("Quem nasceu no ano {} tem \033[32m{} anos \033[mem {}".format(ano, idade, ano_atual))
if idade == 18:
print('Você deve se alistar \033[31mIMEDIATAMENTE. ')
elif idade > 18:
print('Você já devia ter se alistado há \033[31m{} anos\033[m.'.format(idade-18))
print('Seu alistamento foi em \033[31m{}'.format(ano + 18))
elif idade < 18:
falta = 18 - idade
if falta == 1:
print('Ainda falta \033[32m{} ano\033[m para seu alistamento.'.format(falta))
else:
print('Ainda faltam \033[32m{} anos\033[m para seu alistamento.'.format(falta))
print('Seu alstamento será em \033[32m{}.'.format(ano + 18))
else:
print('\033[31mERRO')
|
#crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome 'santo'
#nome = str(input('Digite uma cidade: ')) .strip().upper().split()
#print('Essa cidade começa com santo? {}'.format('SANTO' in nome[0]))
cid = str(input('Digite uma cidade: ')).strip()
print('Essa cidade começa com santo? {}'.format(cid[:5].upper() == 'SANTO'))
|
'''Exercício Python 061: Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA, mostrando os 10 primeiros
termos da progressão usando a estrutura while.'''
print('=' * 30)
print('{:^30}'.format('10 termos de uma PA'))
print('=' * 30)
x = int(input("Digite o primeiro termo: "))
y = int(input("Digiete a razão: "))
termo = x
cont = 1
while cont <= 10:
print('{} -> '.format(termo), end='')
termo += y
cont += 1
print('FIM')
|
#!/usr/bin/python3
"""
created by alex on 2/2/18
Fits the GDP data into the Cobbs Discrete model using matrices
"""
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as mpatches
import numpy as np
import pandas as pd
from python import rmse_fitter
def normalize(x, min_x, max_x):
"""
Goal of this function is to normalize passed data given the min and max of the data to fit in 0 - 1
:param x: Array Like structure: The data to be normalized
:param min_x: Float like: The minimum of the data set
:param max_x: Float like: The maximum of the data set
:return: Array: The normalized data in an array with values ranging from 0 to 1
"""
return (x - min_x) / (max_x - min_x)
# Index_col=58 represents dropping out the unnamed column from the csv
df = pd.read_csv("data/North_America_GDP.csv", header=0, index_col=58)
# Generates an numpy nd array with the indexes of 0th index as country array with 57 years as position in array and gdp
# Being the value at that 'year'. With index 0 being the name of the country
gdp_matrix = df.as_matrix()
# Find max/min of all years and all countries gdp and set up for construction of 3D array
gdp_list = []
countries = []
years = np.arange(1960, 2017, 1)
# Loop through the matrix, each array is a country and its gdp for each year so need double for loop
for country in gdp_matrix:
for gdp in country:
# If it is a string ignore it and continue (Strings are the 0th index in the array of each country
if type(gdp) == str:
countries.append(gdp)
continue
gdp_list.append(gdp)
gdp_min = np.nanmin(gdp_list)
gdp_max = np.nanmax(gdp_list)
# reshape array with rows as countries and columns as year
gdp_array = np.asarray(gdp_list).reshape(len(countries), len(years))
# Normalize the gdp from values of 0 to 1
normalized_gdp = normalize(gdp_array, gdp_min, gdp_max).reshape(len(countries), len(years))
# Plotting normalized gdp
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
#
# X, Y = np.meshgrid(range(len(years)), range(len(countries)))
# print(X.shape)
# print(Y.shape)
#
# surface = ax.plot_surface(X, Y, normalized_gdp, rstride=1, cstride=1, cmap=cm.coolwarm)
#
# ax.set_title('Normalized GDP of North American countries')
# ax.set_ylabel('countries corresponding to adjacency list')
# ax.set_xlabel('Time points in years')
#
# plt.savefig('figs/normalized_gdp.png')
# Data Fitting
# Setup
normalized_gdp_nans = normalized_gdp[~np.isnan(normalized_gdp)]
network_total = np.zeros((len(countries), len(years)))
network_tmp = np.zeros((1, len(years)))
adj_matrix = np.loadtxt("data/adjacencyAmericas.csv", delimiter=",", usecols=list(range(1, 19)), skiprows=1)
g = np.mean(normalized_gdp_nans)
params = rmse_fitter.param_value_finder()
r = params[0]
e = params[1]
for year in range(len(years)):
for country in range(len(countries)):
u_i = normalized_gdp[country][year] # Current node value
neighbors = np.where(adj_matrix[country] == 1) # Check for the neighbors of the current node
neighbors_i = -1
if len(neighbors[0] > 0): # Meaning if they have neighbors or not
size = len(neighbors[0])
while size > 0: # Add up the neighbors
size -= 1
neighbors_i = normalized_gdp[neighbors[0][size]][year] + normalized_gdp[neighbors[0][size - 1]]
neighbors_i = 0.5 * neighbors_i
# the feedback effect to return to natural internal state G upon deviation
fb_i = r * (g - u_i)
# contribution of neighbors upon polarisation extent
pol_i = e * u_i * (1 - u_i) * (neighbors_i - g)
# put all the contributions together for the iteration
u_i_t = u_i + fb_i + pol_i
network_tmp = u_i_t
network_total[country] = network_tmp
# Plotting
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(range(len(years)), range(len(countries)))
surface = ax.plot_surface(X, Y, network_total, rstride=1, cstride=1, cmap=cm.coolwarm)
ax.view_init(azim=-20, elev=10)
ax.set_title('Polarized model')
ax.set_xlabel('Time points in years')
ax.set_zlabel('Change in GDP')
majorLocator = MultipleLocator(1)
majorFormatter = FormatStrFormatter('%s')
ax.yaxis.set_major_locator(majorLocator)
ax.yaxis.set_major_formatter(majorFormatter)
ax.set_yticklabels(countries, rotation=90)
extraString = 'epsilon={}\nr={}'.format(e, r)
handles, labels = ax.get_legend_handles_labels()
handles.append(mpatches.Patch(color='none', label=extraString))
ax.legend(handles=handles, loc='best')
plt.savefig('figs/polarizations_beautified.png')
plt.show()
|
#Author: Thy H. Nguyen
import turtle
wn = turtle.Screen()
wn.bgcolor("#E0FFFF")
mom = turtle.Turtle()
mom.color("#0000CD")
mom.shape("circle")
thy = int(input())
i=1
while i < thy:
mom.right(10)
mom.forward(100)
mom.stamp()
mom.backward(thy)
mom.dot()
i +=1
wn.exitonclick()
|
import time
from decorator import decorator
SLEEP_PENALTY = .0001 # penalty in second for sleeping / context switching, etc.
UPDATE_EVERY_N_SECONDS = 2
class safe(object):
"""
a decorator for keeping a function from
raising an exception to its caller
"""
def __init__(self, function_description):
self.function_description = function_description
def __call__(self, f):
def wrapped_f(func, *args, **kwargs):
try:
print args
print kwargs
func(*args, **kwargs)
except Exception as e:
print 'ERROR [%s]: %s' % (self.function_description, e)
return decorator(wrapped_f, f)
class loop_at_target_frequency(object):
"""
a decorator for executing a function in a loop at
a specified frequency
params:
service the thing that needs to be running
for this loop to be executing. The loop
will continue to execute until <service>.running
is False-ish
target_frequency the target frequency at which the
function should be executed
"""
def __init__(self, service, target_frequency):
self.service = service
self.target_frequency = target_frequency
def __call__(self, f):
def wrapped_f(*args, **kwargs):
last = 0
last_updated_time = 0
while self.service.running:
# special case for if the frequency is 0
if self.target_frequency() == 0:
time.sleep(UPDATE_EVERY_N_SECONDS)
continue
now = time.time()
if now - last_updated_time > UPDATE_EVERY_N_SECONDS:
last_updated_time = now
target_period = 1. / self.target_frequency()
now = time.time()
since_last = now - last
if since_last > target_period:
last = now
f()
else:
sleep_for = target_period - since_last - SLEEP_PENALTY
if sleep_for > 0:
time.sleep(sleep_for)
return decorator(wrapped_f, f)
|
# Association Rules for Market Basket Analysis (Python)
# import package for analysis and modeling
from rpy2.robjects import r # interface from Python to R
r('library(arules)') # association rules
r('library(arulesViz)') # data visualization of association rules
r('library(RColorBrewer)') # color palettes for plots
r('data(Groceries)') # grocery transactions object from arules package
# show the dimensions of the transactions object
r('print(dim(Groceries))')
r('print(dim(Groceries)[1])') # 9835 market baskets for shopping trips
r('print(dim(Groceries)[2])') # 169 initial store items
# examine frequency for each item with support greater than 0.025
r('pdf(file="fig_market_basket_initial_item_support.pdf", \
width = 8.5, height = 11)')
r('itemFrequencyPlot(Groceries, support = 0.025, \
cex.names=0.8, xlim = c(0,0.3), \
type = "relative", horiz = TRUE, col = "dark red", las = 1, \
xlab = paste("Proportion of Market Baskets Containing Item", \
"\n(Item Relative Frequency or Support)"))')
r('dev.off()')
# explore possibilities for combining similar items
r('print(head(itemInfo(Groceries)))')
r('print(levels(itemInfo(Groceries)[["level1"]]))') # 10 levels... too few
r('print(levels(itemInfo(Groceries)[["level2"]]))') # 55 distinct levels
# aggregate items using the 55 level2 levels for food categories
# to create a more meaningful set of items
r('groceries <- aggregate(Groceries, itemInfo(Groceries)[["level2"]])')
r('print(dim(groceries)[1])') # 9835 market baskets for shopping trips
r('print(dim(groceries)[2])') # 55 final store items (categories)
r('pdf(file="fig_market_basket_final_item_support.pdf", \
width = 8.5, height = 11)')
r('itemFrequencyPlot(groceries, support = 0.025, \
cex.names=1.0, xlim = c(0,0.5),\
type = "relative", horiz = TRUE, col = "blue", las = 1,\
xlab = paste("Proportion of Market Baskets Containing Item",\
"\n(Item Relative Frequency or Support)"))')
r('dev.off()')
# obtain large set of association rules for items by category and all shoppers
# this is done by setting very low criteria for support and confidence
r('first.rules <- apriori(groceries, \
parameter = list(support = 0.001, confidence = 0.05))')
r('print(summary(first.rules))') # yields 69,921 rules... too many
# select association rules using thresholds for support and confidence
r('second.rules <- apriori(groceries, \
parameter = list(support = 0.025, confidence = 0.05))')
r('print(summary(second.rules))') # yields 344 rules
# data visualization of association rules in scatter plot
r('pdf(file="fig_market_basket_rules.pdf", width = 8.5, height = 8.5)')
r('plot(second.rules, \
control=list(jitter=2, col = rev(brewer.pal(9, "Greens")[4:9])), \
shading = "lift")')
r('dev.off()')
# grouped matrix of rules
r('pdf(file="fig_market_basket_rules_matrix.pdf", \
width = 8.5, height = 8.5)')
r('plot(second.rules, method="grouped", \
control=list(col = rev(brewer.pal(9, "Greens")[4:9])))')
r('dev.off()')
# select rules with vegetables in consequent (right-hand-side) item subsets
r('vegie.rules <- subset(second.rules, subset = rhs %pin% "vegetables")')
r('inspect(vegie.rules)') # 41 rules
# sort by lift and identify the top 10 rules
r('top.vegie.rules <- head(sort(vegie.rules, \
decreasing = TRUE, by = "lift"), 10)')
r('inspect(top.vegie.rules)')
r('pdf(file="fig_market_basket_farmer_rules.pdf", width = 11, height = 8.5)')
r('plot(top.vegie.rules, method="graph", \
control=list(type="items"), \
shading = "lift")')
r('dev.off()')
# Suggestions for the student:
# Suppose your client is someone other than the local farmer,
# a meat producer/butcher, dairy, or brewer perhaps.
# Determine association rules relevant to your client's products
# guided by the market basket model. What recommendations
# would you make about future marketplace actions?
|
'to samo co ćw 4. tylko na sterydach'
def IsPrime(Number):
ListOfNumbers = range(2,Number)
Divisors = []
[Divisors.append(elements) for elements in ListOfNumbers if Number % elements == 0]
if len(Divisors) == 0:
return True
else:
return False
Liczba = int(input('Wprowadź liczbę naturalną. '))
if Liczba != 1 and IsPrime(Liczba) == True:
print('Podana liczba to liczba pierwsza')
else:
print('Podana liczba to nie liczba pierwsza')
|
def ReverseWordOrder(txt):
txt2 = " ".join(txt.split()[::-1])
return txt2
txt1 = input('Wprowadź długie zdanie\n')
txt2 = ReverseWordOrder(txt1)
print(txt2)
|
print('Pomyśl liczbę od 0 do 100, a ja spróbuję ją odgadnąć.')
Start = 0
End = 100
Counter = 0
answer = 'XD psie'
Oszust = False
ComputerGuess = []
while 1:
C = (Start + End)//2
Counter+=1
if C not in ComputerGuess:
ComputerGuess.append(C)
else:
Oszust = True
break
print('Czy Twoja liczba to {}? Wprowadź 0 - Tak, 1 - moja liczba jest wyższa, 2 - moja liczba jest niższa ' .format(C))
while answer != '0' and answer != '1' and answer != '2':
answer = input()
if answer == '0':
break
elif answer == '1':
Start = C+1
elif answer == '2':
End = C-1
answer = 'XD psie'
if not Oszust:
print('Zgadłem w {} próbach, EZ' .format(Counter))
else:
print('Jesteś jebanym kłamliwym psem')
|
print('Enter four names')
theNames=[]
for name in range(0,4):
theNames.append(input())
print('The name that is longest is\n')
print(max(theNames,key=len))
|
EMPTY_LINE = '\n'
def solution():
fields = {}
field_names = []
with open('input.txt') as file:
for line in file:
if line == EMPTY_LINE:
break
field, rules = line.strip().split(": ")
first_rule, second_rule = rules.split(" or ")
first_start, first_end = first_rule.split("-")
second_start, second_end = second_rule.split("-")
fields[field] = (
range(int(first_start), int(first_end) + 1),
range(int(second_start), int(second_end) + 1)
)
field_names.append(field)
ignore_lines_in(file, lines=1)
main_ticket = [int(ticket) for ticket in file.readline().strip().split(',')]
ignore_lines_in(file, lines=2)
tickets = file.readlines()
total_of_invalid_ticket_numbers = 0
ticket_field_index = {}
valid_tickets = 0
for ticket in tickets:
ticket_numbers = [int(ticket) for ticket in ticket.strip().split(',')]
invalid_ticket_numbers = get_invalid_ticket_numbers(ticket_numbers, fields)
total_of_invalid_ticket_numbers += sum(invalid_ticket_numbers)
# Ignore invalid tickets
if invalid_ticket_numbers:
continue
valid_tickets += 1
field_count_map = get_field_count(ticket_numbers, fields)
# Merge field count
for index, field_count in field_count_map.items():
ticket_field_index.setdefault(index, {})
global_field_map = ticket_field_index.get(index)
for field_name, count in field_count.items():
global_field_map.setdefault(field_name, 0)
global_field_map[field_name] = global_field_map.get(field_name) + count
final_names = []
for index, ticket_number in enumerate(main_ticket):
possible_fields = ticket_field_index.get(index)
for field_name in field_names:
count = possible_fields.get(field_name)
if count == valid_tickets and field_name not in final_names:
final_names.append(field_name)
break
multiple_result = 1
for index, field_name in enumerate(final_names):
if field_name.startswith("departure"):
multiple_result *= main_ticket[index]
print('Part 1: ', total_of_invalid_ticket_numbers)
# TODO: Incorrect - Answer is too high
print('Part 2: ', multiple_result)
def get_invalid_ticket_numbers(ticket_numbers, fields):
invalid_ticket_numbers = []
for index, ticket_number in enumerate(ticket_numbers):
valid_ticket_number = False
for first_range, second_range in fields.values():
if ticket_number in first_range or \
ticket_number in second_range:
valid_ticket_number = True
break
if not valid_ticket_number:
invalid_ticket_numbers.append(ticket_number)
return invalid_ticket_numbers
def get_field_count(ticket_numbers, fields):
ticket_field_index = {}
for index, ticket_number in enumerate(ticket_numbers):
ticket_field_index.setdefault(index, {})
fields_for_index = ticket_field_index.get(index)
for field_name, ranges in fields.items():
first_range, second_range = ranges
if ticket_number in first_range or ticket_number in second_range:
fields_for_index.setdefault(field_name, 0)
fields_for_index[field_name] = fields_for_index.get(field_name) + 1
return ticket_field_index
def ignore_lines_in(file, lines=1):
for i in range(lines):
file.readline()
solution()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.