blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
fb93332121126c94a22c1ad2710399043c5fae43 | jessnswift/my_python_exercises | /class_inheritance/main.py | 414 | 4.09375 | 4 | # instantiate a new Dog and print out the results of making it speak
# Then...when youre done with making your Pet class
# 1.Create an instance of the Pet class and compose the Dog instance into it by adding the dog as a property of the new Pet
# 2.Add an owner by calling your pet's set_owner method (or whatever you called it)
# 3.Print a human-readable output thanks to our the __str__ method you defined in Pet |
9641c0b2e43295223460960622901a50de4600bb | Darpan28/Python | /untitled/venv/MultilevelInhe.py | 1,540 | 3.734375 | 4 | class Product:
def __init__(self,name,brand,price):
self.name = name
self._brand = brand
self.__price = price
def __ShowProductDetails(self):
print(">>>>>",self.name,"<<<<<")
print("The Brand is:",self._brand)
print("The price is:",self.__price)
class Mobile(Product):
def __init__(self,name,brand,price,ram,memory,os):
Product.__init__(self,name,brand,price)
self._ram = ram
self.__memory = memory
self.os = os
def ShowMobileDetails(self):
Product._Product__ShowProductDetails(self)
print("The ram is:",self._ram,"gb")
print("The memory is:",self.__memory,"gb")
print("The os is:",self.os)
class Mobile1(Mobile):
def __init__(self,name,brand,price,ram,memory,os,camera,processor):
Mobile.__init__(self,name,brand,price,ram,memory,os)
self.camera = camera
self.processor = processor
def _showMobile1Details(self):
Mobile.ShowMobileDetails(self)
print("The camera is:", self.camera, "mp")
print("The processor is:", self.processor)
#p1 = Product("iPhoneX","Apple",80000)
#m1 = Mobile("iPhoneX","Apple",80000,4,128,"iOs")
#m1.ShowMobileDetails()
m2 = Mobile1("OnePlus 6T","OnePlus",55000,8,256,"Android",20,"SnapDragon845")
m2._showMobile1Details()
print("==================================")
#print("The prod dict",p1.__dict__)
#print("The prod dict",Product.__dict__)
print("The Mob1 dict",m2.__dict__)
print("The Mob1 dict ",Mobile1.__dict__) |
0e10fc539154a145d2d6d1329a93749dfdcaf774 | cjulliar/home | /python/learn/fichier1/package1/fonction1bis.py | 447 | 3.71875 | 4 | """Ce module contient une fonction multiplication"""
def table(nb, max=10):
"""Cette fonction affiche la table de multiplication
de 0 jusqu'à nb max (par defaut: 10)"""
i = 0
while i <= max:
print(i, "*", nb, "=", i * nb)
i += 1
# test de la fonction table
if __name__ == "__main__":
table(4)
# si name = main, cela veut die que
# le fichier éxécuté est celui la et
# qu'il n'est pas appelé
if __name__ != "__main__":
table(7) |
c69834a4e517a7056919a3d4da155b726627241b | dhruvghulati-zz/unsupervised-learning-workshop | /mnist_pca_knn.py | 1,826 | 3.703125 | 4 | from __future__ import print_function
from sklearn.datasets import fetch_mldata
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import numpy as np
# Download the MNIST digits dataset and store in the variables
digits = fetch_mldata('MNIST original')
X, y = digits.data, digits.target
N, d = X.shape
# Take only part of dataset for training and testing for faster execution
train_percentage = 0.2
test_percentage = 0.1
N_train = int(train_percentage * N)
N_test = int(test_percentage * N)
X_train, y_train = digits.data[:N_train, :], digits.target[:N_train]
X_test, y_test = digits.data[N_train:N_train+N_test, :], digits.target[N_train:N_train+N_test]
# Create a classifier
classifier = KNeighborsClassifier(n_neighbors=1)
# Create a list of number of principal components to examine
# note: they have to be be integers so cast floats to ints
n_pcs = np.linspace(1, d, 10).astype(int)
accuracies = []
for n_pc in n_pcs:
# Create a PCA model and fit it with training data
pca = PCA(n_components=n_pc)
pca.fit(X_train)
# Reduce the training and the test data according to fitted model
X_train_reduced = pca.transform(X_train)
X_test_reduced = pca.transform(X_test)
# Fit the classifier with reduced training data
classifier.fit(X_train_reduced, y_train)
# Make predictions
y_pred = classifier.predict(X_test_reduced)
# Calculate the accuracy on the test set
accuracy = accuracy_score(y_test, y_pred)
accuracies.append(accuracy)
print("For n_pc = {0:3d}, accuracy = {1}").format(n_pc, accuracy)
# Plot the accuracy of the classifier on test set versus number of principal components
plt.plot(n_pcs, accuracies)
plt.xlabel("Number or PCs taken")
plt.ylabel("Accuracy with 1NN")
plt.show() |
61f5ae21b969282a2aa4e6a707dcb2478c325d6c | Arashgs/python-object-oriented-programming-course | /chapter-2/getter.py | 601 | 3.703125 | 4 | class BankAccount:
def __init__(self, first_name, last_name, initial_balance):
self.first_name = first_name
self.last_name = last_name
self.balance = initial_balance
@property
def full_name(self):
return f'{self.first_name} {self.last_name}'
account_1 = BankAccount('Kate', 'Smith', 100)
print(f'Last name value: {account_1.last_name}')
print(f'Full name: {account_1.full_name}')
account_1.last_name = 'Taylor'
print(f'New last name value: {account_1.last_name}')
print(f'Full name after change: {account_1.full_name}')
# account_1.full_name = 'Jenny Jones' |
9b965e547c71db01eaa5d10f7356c0a2952f36a1 | Rider66code/PythonForEverybody | /bin/p3p_c2w5_final003.py | 1,366 | 4.46875 | 4 | #Next, copy in your strip_punctuation function and define a function called get_neg which takes one parameter, a string which represents one or more sentences, and calculates how many words in the string are considered negative words. Use the list, negative_words to determine what words will count as negative. The function should return a positive integer - how many occurrences there are of negative words in the text. Note that all of the words in negative_words are lower cased, so you’ll need to convert all the words in the input string to lower case as well.
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
negative_words = []
def strip_punctuation(someword):
for char in punctuation_chars:
someword=someword.replace(char, '')
dpword=someword
return dpword
def get_pos(somesent):
tmpcount=0
tmplist=somesent.split()
for word in tmplist:
if strip_punctuation(word).lower() in positive_words:
tmpcount+=1
return tmpcount
def get_neg(somesent2):
tmpcount=0
tmplist=somesent2.split()
for word in tmplist:
if strip_punctuation(word).lower() in negative_words:
tmpcount+=1
return tmpcount
with open("negative_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
negative_words.append(lin.strip())
|
6e5e8b841f73b13573983f985f82f3f8c1e39beb | GirijaHarshith/InnovationWithPython_Girija | /Python-Project/Elevator.py | 2,822 | 3.71875 | 4 | from time import sleep
import pyttsx3
from gtts import gTTS
# Function to convert text to speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init()
engine.say(command)
print(command)
engine.runAndWait()
# Voice Converter - female version
voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"
voice = int(input("Enter 1 for female voice else 0 for male voice:"))
if voice == 1:
# Use female voice
converter = pyttsx3.init()
converter.setProperty('voice', voice_id)
converter.runAndWait()
current_floor_lift = 0
while True:
# Input from the user to operate lift
SpeakText("Enter the floor you are in : ")
current_floor_person = eval(input())
SpeakText("Enter the floor you want to go : ")
floor_to_go = eval(input())
# If lift and person are on the same floor or different floor, lift moves according to the user input.
if floor_to_go == current_floor_person:
SpeakText("You are on the same floor")
elif current_floor_person != current_floor_lift:
while current_floor_person > current_floor_lift:
current_floor_lift += 1
sleep(1)
print("Currently in floor {}".format(current_floor_lift))
sleep(2)
while current_floor_person < current_floor_lift:
current_floor_lift -= 1
sleep(1)
print("Currently in floor {}".format(current_floor_lift))
sleep(2)
SpeakText("Doors are opening..Please Enter")
sleep(1)
SpeakText("Doors are closing")
sleep(2)
# Once Person enters Lift moves to the desired floor.
if floor_to_go > current_floor_person:
while floor_to_go > current_floor_person:
current_floor_person += 1
current_floor_lift += 1
print("Currently in floor {}".format(current_floor_person))
sleep(2)
if current_floor_person == floor_to_go:
SpeakText("you reached your floor. Doors are opening")
sleep(1)
SpeakText("Doors are closing")
sleep(1)
break
elif floor_to_go < current_floor_person:
while floor_to_go < current_floor_person:
current_floor_person -= 1
current_floor_lift -= 1
print("Currently in floor {}".format(current_floor_person))
sleep(2)
if current_floor_person == floor_to_go:
SpeakText("You reached your floor. Doors are opening")
sleep(1)
SpeakText("Doors are closing")
sleep(1)
break
exit_lift = eval(input("Please press 1 if you want to exit else press 0 to continue: "))
if exit_lift:
break
|
7d0901f54d8ba9e8119be0ff147e7fcec805436f | JBustos22/Physics-and-Mathematical-Programs | /animations/Cradle.py | 1,296 | 4.03125 | 4 | """
This program simulates Newton's Cradle. Tow balls of equal radius are simulated and animated
to show harmonic motion with energy and momentum conservation. Two smaller balls are placed
on top of them to show the pivot for each pendulum.
Jorge Bustos
Feb 17, 2019
"""
from __future__ import division, print_function
import vpython as vp
import numpy as np
#initializing the constants
vp.canvas(width=400,height=600)
l=500 #radius of harmonic motion
r=l/10 #radius of the spheres, one tenth of it
g=9.81
theta_0 = 0.5 #initial angle of pendulum in radians
#pivots
pivot1 = vp.sphere(pos=vp.vector(-1*r,0,0), radius=10, color=vp.color.white)
pivot2 = vp.sphere(pos=vp.vector(r,0,0), radius=10, color=vp.color.white)
#pendulums
p1 = vp.sphere(pos=vp.vector(-1*r,-1*l,0), radius=r, color=vp.color.yellow)
p2 = vp.sphere(pos=vp.vector(0,-1*l,0), radius=r, color=vp.color.cyan)
for t in np.arange(0,10000,0.01): #harmonic motion
vp.rate(500)
theta=theta_0*np.cos(np.sqrt(g/l)*t)
x = l*np.sin(theta)
y = -1*l*np.cos(theta)
if theta <= 0: #if statements are used to stop the motion of one pendulum and begin the motion
p1.pos = vp.vector(x-r,y,0) #of the other one to simulate the transfer of energy and momentum.
if theta >= 0:
p2.pos = vp.vector(x+r,y,0)
|
7ae009ae148fa099e6b710b0aba4e27866ca2a82 | andreamandioDEV/iscte | /_scraping/bf_3_uc.py | 2,323 | 3.546875 | 4 | # Autor do ficheiro: André Amândio
# Nº aluno: 14900
# UC: Linguagens de Programação 2017/2018
# Ficheiro: bf_3_uc.py
# Ultima modificação: 01/02/2018
# Refs: http://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
import requests, json
from bs4 import BeautifulSoup
def restore_name(str):
return " ".join(str.split())
#Message console
print('Start scraping...')
url = "https://www.iscte-iul.pt/curso/3/licenciatura-engenharia-informatica/planoestudos"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, 'lxml')
data_ucs = {}
data_ucs['uc'] = []
uc_tr = soup.find_all('tr', attrs={'class': 'yearsemester-info'})
i=0;
for uc in uc_tr:
uc_name = uc.find('a', attrs={'class':'curricular-course-text'}).getText()
uc_language = uc.find('span', attrs={'class':'lang-value'}).getText()
uc_etcs = uc.find('span', attrs={'class':'ects-value'}).getText()
uc_desc = soup.find_all('tr', attrs={'class': 'curricular-info'})[i].find_all('p', attrs={'class':'curricular-course-text'})
#print(len(uc_desc))
i+=1
uc_optional = 0
uc_style = 1
if (i <= 6):
uc_year = 1
uc_semester = 1
elif(i>6 and i<=11):
uc_year = 1
uc_semester = 2
elif(i>11 and i<=16):
uc_year = 2
uc_semester = 1
elif(i>16 and i<=21):
uc_year = 2
uc_semester = 2
elif(i>21 and i<=26):
uc_year = 3
uc_semester = 1
elif(i>26 and i<=31):
uc_year = 3
uc_semester = 2
elif(i>31 and i<=33):
uc_year = 1
uc_semester = 2
uc_style = 2
elif(i>33 and i<=55):
uc_year = 1
uc_semester = 2
uc_optional = 1
uc_style = 2
uc_goals = uc_desc[0].getText()
uc_program = uc_desc[1].getText()
uc_evaluation = uc_desc[2].getText()
if (uc_language == 'Português'):
uc_language = 1
else:
uc_language = 2
data_ucs['uc'].append({
'name': restore_name(uc_name),
'etcs': restore_name(uc_etcs),
'semester': uc_semester,
'year': uc_year,
'goals': restore_name(uc_goals),
'program': restore_name(uc_program),
'evaluation_process': restore_name(uc_evaluation),
'program': restore_name(uc_program),
'language': uc_language,
'uc_style': uc_style,
'uc_optional': uc_optional
})
#Message console
print('Finish scraping.')
print('Start json file...')
with open('3_ucs.txt', 'w', encoding='utf8') as outfile:
json.dump(data_ucs, outfile)
#Message console
print('Finish json file.') |
6c8e9219308a209c4f2507824f50552099376d98 | HebertFB/Exercicios-de-Python | /secao_5_exercicios/ex03.py | 192 | 4.03125 | 4 | # Ex03
import math
num = float(input('Digite um número real: '))
if num < 0:
print(f'\nO quadrado de {num} é {num ** 2}')
else:
print(f'\nA raiz de {num} é {math.sqrt(num):.2f}')
|
a9140c76b3aae997492a82f90c17b6280d50c221 | Rajveer3311/PYTHON | /sets.py | 553 | 4.125 | 4 | #create set ist method
sets={1,2,3,4,4.0,'raj'}
print(sets)
#list to set
# li=[1,2,3,4,3,"rajveer"]
# sets=set(li)
# print(sets)
# sets=list(set(li)) #set to list
# print(sets)
# add method
# sets.add(5)
# sets.add('singh')
# print(sets)
# delete or remove method
# sets.remove(7)
# print(sets)
#discard method
# sets.discard(7)
# print(sets)
#clear method
# sets.clear()
# print(sets)
#check if item is present or not
# if 'raj' in sets:
# print("present")
# else:
# print("not present")
#for loop
for i in sets:
print(i) |
1c69ca8eb690966c46da20ea947e54c50e16031b | dheeraj281/dataStructureProgrammes | /data_structure/strings.py | 792 | 4.09375 | 4 | #### reverse a string using recursion #####
def reverseWithRecursion(data):
size = len(data)
if size == 0:
return
print(data[size-1], end="")
reverseWithRecursion(data[0:size-1])
### reverse a string using stack ##########
class Stack:
def __init__(self):
self.item = []
def push(self,data):
self.item.append(data)
def pop(self):
if self.item == []:
return None
else:
return self.item.pop()
def isEmpty(self):
return self.item == []
def reverse(mystr):
stack = Stack()
newstr = ""
for i in mystr:
stack.push(i)
while not stack.isEmpty():
newstr += stack.pop()
return newstr
if __name__ == "__main__":
print(reverse("dheeraj"))
|
fbbf5b904f2df758cb0df76683d0a438d052db35 | Jingliwh/python3- | /pythonio.py | 3,039 | 3.5 | 4 | #python-IO学习
#open("路径","r/w")
#读写字符注意编码错误
#绝对路径与相对路径
#1读文件
#1.1文件打开
'''
f1=open("c:/Users/Administrator/Desktop/python_stydy/py3test/py3test.py","r")
str1=f1.read()
print(str1)
f1.close()
'''
#1.2打开文件捕获异常
'''
try:
f = open("py3test/py3test.py","r")
print(f.read())
except Exception as e:
print("file not found")
finally:
print("finally")
if f:
f.close()
'''
#1.3with语句来自动调用close()方法
'''
with open("py3test/py3test.py","r") as f:
print(f.read())
#f.read()一次性读取完
#f.readlines()按行读取,可用于读取配置文件
#f.read(size) 按固定size读取文件,在不知道文件具体大小的情况下
'''
#1.4读二进制文件
'''
f = open('mode/haha.jpg', 'rb')
print(f.read())
'''
#2写文件
#2.1写入文件
'''
with open('py3test/py3test.py', 'w') as f:
f.write('Hello, world!---')
print("写入成功")
'''
#按某种编码读取,有错就忽略
'''
f1 = open('minmax.py', 'r', encoding='UTF-8', errors='ignore')
print(f1.read())
'''
#3StringIO and BytesIO
#3.1StringIO 读取内存中的字符串
'''
from io import StringIO
f=StringIO()
f.write("hello")
f.write("hehe")
f.write("000000")
print(f.getvalue())
'''
#3.2BytesIO 读取内存中的二进制数据
'''
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
'''
#4操作文件和目录
#4.1判断操作系统
#nt 表示windows posix表示Linux Unix macos
'''
import os
print(os.name)#操作系统名
#print(os.uname())#操作系统详情,只在Linux等上提供
print(os.environ) #环境变量
print(os.environ.get('path'))
'''
#4.2操作文件和目录
'''
import os
print(os.path.abspath('.')) #当前绝对路径
cdir=os.path.abspath('.')
#os.mkdir(os.path.join(cdir, 'testdir'))#在此路径下创建dir,存在会报错 FileExistsError:
#os.rmdir(os.path.join(cdir, 'testdir'))#在此路径下删除dir
#os.path.split('/Users/michael/testdir/file.txt')拆分路径
#os.path.splitext('/path/to/file.txt')#直接获取文件名
f0=os.path.split('/Users/michael/testdir/file.txt')
print(f0[1])#file.txt
f1=os.path.splitext('/path/to/file.txt')
print(f1[1])#.txt
print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'])#输出当前目录下所有的.py文件
'''
#4.3序列化
#Python提供了pickle模块来实现序列化。
#4.3.1保存到文件
'''
import pickle
d = dict(name="lijing",age=24,addres="cq")
f = open('dump.txt', 'wb')
pickle.dump(d,f)
f.close()
'''
#4.3.2从文件读取
'''
import pickle
f = open('dump.txt', 'rb')
d = pickle.load(f)
f.close()
print(d)
'''
#4.4 json数据
#对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON
import json
d = dict(name="hello",age=24,addres="cq")
e = {"name":"hello","age":24,"addres":"cq"}
f = open('dump.txt', 'wb')
json.dump(e,f)
f.close()
|
e994ad4fc1aa12874506c8c3279807d9e5eb6884 | pwang867/LeetCode-Solutions-Python | /0670. Maximum Swap.py | 1,739 | 3.828125 | 4 | # time/space O(n), scan backwards, record the index of the pair to swap
class Solution2(object):
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
s = list(str(num))
left, right = -1, -1 # (left, right) are the index of the pair to swap
max_i = len(s) - 1
for i in range(len(s) - 1, -1, -1):
if s[i] < s[max_i]:
left, right = i, max_i
elif s[i] > s[max_i]:
max_i = i
if left == -1:
return num
else:
s[left], s[right] = s[right], s[left]
return int("".join(s))
# time/space O(n*log(n)), n = length of num
# compare num with sorted num (if we can do unlimited swaps)
# find the first digit that is smaller than any digit after it, then swap
class Solution1(object):
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
s = list(str(num))
sorted_s = sorted(s, reverse=True) # sort in reverse
for i in range(len(s)):
if s[i] != sorted_s[i]:
target = sorted_s[i]
for j in range(len(s) - 1, i, -1): # must search backwards
if s[j] == target:
s[i], s[j] = s[j], s[i]
return int("".join(s))
return num
"""
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number.
Return the maximum valued number you could get.
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Note:
The given number is in the range [0, 108]
"""
|
a6e419bd52c067ec4add6405cf8739f0d87593a5 | simplesmall/Python-FullStack | /Day0625/Day24_3主动调用其他类的成员.py | 1,429 | 3.84375 | 4 | #############################方法一######################
class Base():
def f1(self):
print('5个功能')
class Foo():
# class Foo(object): 这样写也可以调用到Base()里面的函数,跟自动调用以及这节涉及的东西没有关系
def f1(self):
print('3个功能')
# self不会自动传参
Base.f1(self)
# obj = Foo()
# obj.f1()
# 主动调用其他类的成员
###########################方法二##########################
class Base():
def f1(self):
print('5个功能')
class Foo(Base):
# class Foo(object): 这样写也可以调用到Base()里面的函数,跟自动调用以及这节涉及的东西没有关系
def f2(self):
print('Super Testing....')
# super 按照类的继承顺序找下一个
super().f1()
# obj = Foo()
# obj.f2()
###### 方式二:按照类的继承顺序,找下一个
class First(object):
def f1(self):
super().f1() #print('Second function')
print('First function')
class Second():
def f1(self):
# super().f1()
print('Second function')
class Info(First, Second):
pass
# obj = Info()
# obj.f1()
class Four(First,Second):
def bb(self):
super().f1()
# 5个功能
# Second function
# First function
print('111')
obb = Four()
obb.bb() |
94fa9e20600237d815201ca77511668a8429e5dd | hufslion8th/Python-Basic | /Assignment1/Minji-Choi/c-min-ji-hw.py | 756 | 3.984375 | 4 | #1
max_weight = 500
object1=float(input('첫번째 물건 무게: '))
object2=float(input('두번째 물건 무게: '))
current_weight = max_weight-(object2+object1)
print('첫번째 물건 무게:',object1,'두번째 물건 무게:',object2,'현재 엘레베이터의 허용무게는 ', current_weight,'kg 입니다')
#2
n = int(input())
for i in range(n):
print('■ '*n, end='\n')
#3
address = '용인시 처인구 모현읍'
print('시: '+address[0:4])
print('구: '+address[4:7])
print('읍: '+address[8:])
#4
wrong = 'Life is too short you need Tython'
correct1 = wrong[:27]+'P'+wrong[28:]
correct2 = wrong.replace('T','P')
print(correct1)
print(correct2)
#5
sentence = 'Life is too short you need Python'
upper = sentence.upper()
print(upper) |
ce9623c085d82a3d251343b63fbd0f58bce87199 | SehnazRefiye/Python-Data-Structure | /lab3.py | 274 | 3.921875 | 4 | #Write a short python function that takes a string s, representing a
#sentence and returns a copy of the string with all punctuation removed.
s = input("Please enter sentence: ")
x = ",:.;_-?*()[]'!/"
a = ""
for i in s:
if i not in x:
a = a + i
print(a)
|
9a49812810fcb6f40802f74afbadf09d8e2af7ee | ism-hub/cryptopals-crypto-challenges | /set1_5.py | 1,119 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Implement repeating-key XOR
Here is the opening stanza of an important work of the English language:
Burning 'em, if you ain't quick and nimbleI go crazy when\nI hear a cymbal
Encrypt it, under the key "ICE", using repeating-key XOR.
In repeating-key XOR, you'll sequentially apply each byte of the key; the first byte of plaintext will be XOR'd against I, the next C, the next E, then I again for the 4th byte, and so on.
It should come out to:
0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f
Encrypt a bunch of stuff using your repeating-key XOR function. Encrypt your mail. Encrypt your password file. Your .sig file. Get a feel for it. I promise, we aren't wasting your time with this.
"""
from set1_3 import cyclicXor
import base64
text = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
key = "ICE"
keyBytes = bytes(key, 'utf-8');
textBytes = bytes(text, 'utf-8')
resBytes = cyclicXor(textBytes, keyBytes)
resHex = base64.b16encode(resBytes).decode('utf-8')
wantedOutcome = "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"
assert(resHex.lower() == wantedOutcome)
print(resHex.lower())
|
eb10ae691ad6be372045aa3088a73d42765448b6 | EricaGuzman/PersonalProjects | /Python/conversion/KilometerConverson.py | 1,260 | 4.46875 | 4 | #Erica Guzman
#Lab 2
#This program calculates
#the number of miles traveled based on user input of kilometers traveled
#Define main
def main():
#Declare and initilaize float variables
#String userName
#Float Kilometers
#Float miles
#Float conversion = 0.621371
UserName = " "
Kilometers = miles = 0.0
conversion = 0.621371
#display "Welcome to the miles conversion program Enter the Kilometers travelled and I convert it to miles
print("Welcome to the miles conversion program!")
print("Enter the Kilometers travelled and I will convert it to miles! ")
#set userName to input "What is your name?
userName =(input("\nEnter your first name: "))
#set Kilometers to hold user input "How many kilometers did you travel?
Kilometers = float(input("How many Kilometers did you travel? "))
#calculate (miles = Kilometers divided by conversion)
miles = Kilometers * conversion
#display "Great job ",userName, "\n", kilometers , " kilometers equals " , miles ," miles!",
#"\nThank you for using my program, keep up the good work!"
print("\nGreat job ",userName, "!\n", Kilometers , "kilometers equals %0.02f" % miles ,"miles!", end="")
print("\nThank you for using my program. Keep up the good work!!")
main()
|
31a96cbaa1ee6548316c43887769bd3d5423a7f1 | adriansgrrx/Assignment-2-PLD-BSCOE-1-6 | /maxApplesAndChange.py | 281 | 4.0625 | 4 | yourMoney = int(input("Enter the amount of money you have: "))
applePrice = int(input("How much for an apple?: "))
maxApples = yourMoney // applePrice
yourChange = (yourMoney - maxApples * applePrice)
print(f"You can buy {maxApples} apples and your change is {yourChange} pesos") |
fac79c9b9f008743e5d0d6000bb88a5aa9339efa | timpark0807/self-taught-swe | /Algorithms/Leetcode/1324 - Print Words Vertically.py | 1,516 | 3.78125 | 4 | class Solution(object):
def printVertically(self, s):
"""
:type s: str
:rtype: List[str]
s = "HOW ARE YOU"
words = ['HOW', 'ARE', 'YOU']
^ ^ ^
['HAY', 'ORO', 'WEU' ]
['CONTEST', 'IS', 'COMING']
^ ^ ^
['CIC',
'OSO',
'N_M'
'T_I']
'T__P'
# Step 1. Convert string to list of stirngs
# Step 2. Find max length of a word
# Step 3. For index in range(max_word_length)
# temp_word = ''
# Step 4. For word in words
# Check if index is valid for the word
# If is, append letter
# If not, append ' '
"""
words = s.split(' ')
longest_word = max(words, key=len)
retval = []
for index in range(len(longest_word)):
temp_arr = []
for word in words:
if index < len(word):
temp_arr.append(word[index])
else:
temp_arr.append(' ')
for letter in temp_arr[::-1]:
if letter == ' ':
temp_arr.pop()
else:
break
temp_word = ''.join(temp_arr)
retval.append(temp_word)
return retval
|
69937625807a4506c0fec270b811849aa49920db | PWynter/LPTHW | /ex32.py | 1,047 | 4.625 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ["apples", "oranges", "pears", "apricots,"]
change = [1, "pennies", 2, "dimes", 1, "quaters"]
# this kind of for loop goes through a list
for number in the_count:
# variable number is being assigned to each element of the_count
print(f"This is count {number}")
for fruit in fruits:
# variable fruits is assigned to each element of fruits
print(f"A fruit of type {fruits}")
# also we can got through mixed lists too
# notice how we use {} since we dont know whats in it
for i in change:
# variable i is assigned to each elment in change
print(f"I got {i}")
# we can build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0,6):
# varaible i is assigned to each element in range
print(f"Adding {i} to the list.")
# append is a function thats adds on to lists
elements.append(i)
# now we can print them out too
for i in elements:
# variable i is assigned to each element og elements
print(f"Element was: {i}") |
87c3d71c27b2af1609cbee3b0c6f385f4899f1b7 | PriyankaKhire/ProgrammingPracticePython | /Database Sharding/HelperFunctions/Database.py | 775 | 3.625 | 4 | import os.path
class Database(object):
def read(self, fileName):
output = ""
if not self.ifFile(fileName):
return output
file_object = open(fileName, "r")
for line in file_object:
output = output + line
file_object.close()
return output
def ifFile(self,fileName):
if not os.path.isfile(fileName):
#print "File does not exist"
return False
return True
def write(self, fileName, string):
file_object = open(fileName, "a")
file_object.write(string+"\n")
file_object.close()
def createFolder(self, folderName):
if not os.path.exists(folderName):
os.makedirs(folderName)
|
0a63defc123bc6a4176e1be9e65acf1e6b2e081d | finddeniseonline/sea-c34-python.old | /students/MeganSlater/session06/static.py | 474 | 3.71875 | 4 | """ Question 1:
Can I use a static method to count the number of times
any particular class has been initiated?
"""
class Spam(object):
"""class counts number of times class was used.
Could add more features to this class if desired"""
numInstances = 0
def __init__(self):
Spam.numInstances += 1
def printNumInstances():
print("Number of instances: %s" % Spam.numInstances)
printNumInstances = staticmethod(printNumInstances)
|
76ffa268fe760208943a46db3ee367aa56e67599 | brainaulia/dumbways | /2.py | 279 | 3.5 | 4 | # input: [19,22,3,28,26,17,18,4,28,0]
# output: [0,28,4,18,17,26,28,3,22,12]
def rev_array(lst):
rev=[]
for i in range(len(lst)-1,-1,-1):
rev.append(lst[i])
return rev
arr=[19,22,3,28,26,17,18,4,28,0]
print("input:",arr)
print("output:",rev_array(arr)) |
e2035a38d36064acedc8f4eac1a51b70cf24935f | liaison/LeetCode | /python/701_Insert_into_a_Binary_Search_Tree.py | 1,021 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
def dfs(node, value):
next_node = None
if value < node.val:
if node.left is None:
# insert as the new left child
node.left = TreeNode(value)
return
else:
next_node = node.left
else: # value > node.val
if node.right is None:
node.right = TreeNode(value)
return
else:
next_node = node.right
# continue the search
dfs(next_node, value)
if root is None:
return TreeNode(val)
else:
dfs(root, val)
return root
|
85e8bc9c59ae5e0bd788a1f5bf45887a5536849f | hatamleh12/htu-ictc5-webapps-using-python | /W1/S2/ex0.py | 1,347 | 4.34375 | 4 | # Declaring a list
linux_distros = ['Debian', 'Ubuntu', 'Fedora',
'CentOS', 'OpenSUSE', 'Arch', 'Gentoo']
# Print the list
print("The list contains %s." % linux_distros)
print("The type of 'linux_distros' is '%s'." % type(linux_distros))
# Finding the length
print("The list contains %d elements." % len(linux_distros))
# Append an element
linux_distros.append("Mint")
print("The new list contains %s." % linux_distros)
# Pop an element
my_element = linux_distros.pop()
print("The popped element is: '%s'." % my_element)
print("After popping the element the new list contains %s." % linux_distros)
linux_distros.pop(4)
print(linux_distros)
# # Insert an element
print(linux_distros[4])
linux_distros.insert(2, "Mint")
print(linux_distros)
print(linux_distros[4])
# Remove an element
linux_distros.remove("Arch")
print(linux_distros)
# Extending a list
debian_distros = ['Debian', 'Ubuntu', 'Mint']
linux_distros.extend(debian_distros)
print(linux_distros)
# Find the index of an element
# print(linux_distros.index("Arch"))
print(linux_distros.index("Mint"))
# Reverse the list
print(linux_distros)
linux_distros.reverse()
print(linux_distros)
# # Sort the list
# print(linux_distros)
# linux_distros.sort()
# print(linux_distros)
# What does this do?
linux_distros.sort()
linux_distros.reverse()
print(linux_distros)
|
3eaaec1d68c740b52537722c222f14855d87f0d3 | lxl0928/learning_python | /code/91_recommendations/quick_sort.py | 798 | 4.09375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: quick_sort.py
# author: Timilong
def quicksort(array):
less = []
greater = []
print("1: ", "array: ", array, "len(array): ", len(array))
if len(array) <= 1:
print("2: ", "array: ", array, "len(array): ", len(array))
return array
pivot = array.pop()
print("3: ", "array: ", array, "len(array): ", len(array), "pivot: ", pivot)
for x in array:
if x <= pivot:
less.append(x)
else:
greater.append(x)
current_array = quicksort(less) + [pivot] + quicksort(grater)
print("4: ", "array: ", array, "len(array): ", len(array), "pivot: ", pivot, "current_array:", current_array)
return current_array
array = [1, 4, 3, 0]
print(quicksort(array))
|
712a5cbb6594ab223886264efb0f15a1e37634d7 | ouriblife/Game | /projectprototypeLatest (3).py | 10,525 | 4.03125 | 4 | #Trivia Game Sample Project by Fred Winters
#10 questions, predetermined order
#Topic - World History
import tkinter as tk #Label wraparound, wraplength=400 (ex), anchor = 'center'(ex)
import os
import sys
global runningscore,stage,questionset,photo
stage = 0
runningscore = 0
chancelevel = 0
count = 0
def initclue(): #Creates the clue window
global answer,clue,count
cdisplay = tk.Toplevel() #defines the tkinter toplevel, this actually creates the window
cdisplay.minsize(400,120) #400x80 defined
cdisplay.maxsize(400,120)
cdisplay.title("Clue")
cmess = tk.Label(cdisplay,text=clue)
cmess.place(x=0,y=0,width=400,height=40)
chancestring = "You have: "+str(count)+" chance(s) left"
cmess2 = tk.Label(cdisplay,text=chancestring)
cmess2.place(x=0,y=40,width=400,height=40)
cmessfin = tk.Button(cdisplay,text="Finish",command=lambda: cdisplay.destroy()) #use of lambda is to prevent the function from being immediately called upon initilization.
cmessfin.place(x=150,y=80,width=100,height=40)
cdisplay.wm_attributes("-topmost", 1)
cdisplay.focus_force()
def initdifficulty(): #Creates the clue window
global answer,clue,chancelevel,count
def prompt():
gobal
def difficultyselect(setting):
global chancelevel, count
if setting == 'Easy':
chancelevel = "Easy"
count = 3
elif setting == 'Medium':
chancelevel = "Medium"
count = 2
elif setting == 'Hard':
chancelevel = "Hard"
count = 1
ddisplay.destroy()
importinginit()
ddisplay = tk.Toplevel() #defines the tkinter toplevel, this actually creates the window
ddisplay.minsize(360,300) #400x80 defined
ddisplay.maxsize(400,200)
ddisplay.title("Difficulty select")
dmess = tk.Label(ddisplay,text="This game offers three difficulty settings, Easy, Medium, and Hard. Easy gives you three chances per question, Medium two chances and Hard only one chance per quesiton. Please make your choice by clicking the corresponding button",wraplength=360)
dmess.place(x=0,y=0,width=360,height=200)
dmessfin = tk.Button(ddisplay,text="Easy",command=lambda: difficultyselect("Easy")) #use of lambda is to prevent the function from being immediately called upon initilization.
dmessfin.place(x=0,y=200,width=120,height=40)
dmessfin = tk.Button(ddisplay,text="Medium",command=lambda: difficultyselect("Medium")) #use of lambda is to prevent the function from being immediately called upon initilization.
dmessfin.place(x=120,y=200,width=120,height=40)
dmessfin = tk.Button(ddisplay,text="Hard",command=lambda: difficultyselect("Hard")) #use of lambda is to prevent the function from being immediately called upon initilization.
dmessfin.place(x=240,y=200,width=120,height=40)
ddisplay.wm_attributes("-topmost", 1)
ddisplay.focus_force()
def importinginit():
global idisplay
idisplay = tk.Toplevel()
idisplay.minsize(400,200)
idisplay.maxsize(400,200)
idisplay.title("Trivia File Importing")
imess = tk.Label(idisplay,text="Please enter the name of the file to import, with extension.")
imess.place(x=0,y=0,width=400,height=50)
imessentry = tk.Entry(idisplay)
imessentry.place(x=0,y=50,width=400,height=40)
imessfin = tk.Button(idisplay,text="Finish",command=lambda: importingfile(imessentry.get()))
imessfin.place(x=150,y=150,width=100,height=50)
potentialimports1 = os.listdir(".")
finallist = []
for a in potentialimports1:
if a.endswith(".txt"):
finallist.append(a)
displaystringlist = "Potential imports: "
for b in finallist:
displaystringlist = displaystringlist + str(b)+","
guipotential = tk.Message(idisplay,text=displaystringlist,width=400)
guipotential.place(x=0,y=100,width=400,height=50)
idisplay.wm_attributes("-topmost", 1)
idisplay.focus_force()
def importingfile(namefile):
global questionset, idisplay,questionset,answer,clue
choice1 = namefile
f = open(choice1,'r',encoding='UTF-8') #use of UTF-8 encoding to ensure that the file can be sucessfully opened regardless of operating system.
questionset = f.read()
questionset = questionset.split("\n")
idisplay.destroy()
window.wm_attributes("-topmost", 1) #topmost and focus_force() are used to call user attention to the display window rather than having it be buried by the main display window.
window.focus_force()
maindisplay.configure(text=questionset[stage])
answerdisplay.configure(text=questionset[(stage+1)])
answerdisplay2.configure(text=questionset[(stage+2)])
answerdisplay3.configure(text=questionset[(stage+3)])
answerdisplay4.configure(text=questionset[(stage+4)])
clue=questionset[stage+5]
answer = questionset[stage+6]
def questions(givenanswer):
global answer,display,runningscore,count
while count > 0:
if givenanswer == answer: #if the correct answer is given,
display2 = "Correct!"
if count >= 2: #with both chances left, two points are given
runningscore = runningscore + 2
count = 0
elif count == 1: #if only one chance is left, one point is given.
runningscore = runningscore + 1
count = 0
else: #if the incorrect answer is given, subtract one chance and informs the user that they are incorrect.
display2 = "Incorrect."
count = count - 1
if count == 1 or count == 2:
initclue()
break
if count == 0:
display = tk.Toplevel()
display.minsize(350,80)
display.maxsize(350,80)
display.title("Answer:")
msg1str = "The answer was: "+str(answer)
msg1 = tk.Label(display,text=msg1str)
msg1.grid(row=0,column=0,columnspan=4,sticky='N')
msg2str = tk.Label(display,text=display2)
msg2str.grid(row=1,column=0,columnspan=4,sticky='N')
prompt1 = tk.Button(display,text="Finish",command=lambda: main1())
prompt1.grid(row=2,column=0,columnspan=4,sticky='N')
display.wm_attributes("-topmost", 1)
display.focus_force()
for N in range(0,3):
display.columnconfigure(N,weight=1)
display.rowconfigure(N,weight=1)
def main1():
global questionset, stage, answer, display,runningscore,count,chancelevel
if chancelevel == 'Easy':
count = 3
elif chancelevel == 'Medium':
count = 2
elif chancelevel == 'Hard':
count = 1
display.destroy() #destroys the answer window.
stage = stage + 7 #shifting of "stage" in increments of 7, to jump to the next set.
if stage < 70:
maindisplay.configure(text=questionset[stage])
answerdisplay.configure(text=questionset[(stage+1)])
answerdisplay2.configure(text=questionset[(stage+2)])
answerdisplay3.configure(text=questionset[(stage+3)])
answerdisplay4.configure(text=questionset[(stage+4)])
clue = questionset[stage+5]
answer = questionset[stage+6]
elif stage == 70: #if 10 games are finished(7 stages per game), terminates the game and displays a game over display.
maindisplay.configure(text="Game finished.")
edisplay = tk.Toplevel()
edisplay.minsize(350,125)
edisplay.maxsize(350,125)
edisplay.title("Game Completed")
endmessage = tk.Label(edisplay,text="Thank you for playing.")
endmessage2 = tk.Label(edisplay,text="Final score:")
endmessage3 = tk.Label(edisplay,text=runningscore)
if runningscore > 15: #grading levels, from A to D
gradelevel = "Grade: A-Good Job!"
elif runningscore > 10 and runningscore < 16:
gradelevel = "Grade: B-Good work."
elif runningscore > 5 and runningscore < 11:
gradelevel = "Grade: C-Some room for improvement.."
elif runningscore < 6 and runningscore != 0:
gradelevel = "Grade: D-???"
elif runningscore == 0:
gradelevel = "Grade: F-You failed completely."
endfinal = tk.Label(edisplay,text=gradelevel)
endbutton = tk.Button(edisplay,text="End",command=window.destroy)
endmessage.place(x=0,y=0,width=350,height=25)
endmessage2.place(x=0,y=25,width=350,height=25)
endmessage3.place(x=0,y=50,width=350,height=25)
endbutton.place(x=150,y=100,width=50,height=25)
endfinal.place(x=0,y=75,width=350,height=25)
edisplay.wm_attributes("-topmost", 1)
edisplay.focus_force()
window = tk.Tk() #creates main tkinter window
window.wm_title("History Trivia: By Fred Winters") #sets title
window.minsize(width=450,height=1000) #450x1000 size
window.maxsize(width=450,height=1000)
maindisplay = tk.Label(window,text="Question Display",width=400,font=("Courier", 20),wraplength=450)
maindisplay.place(x=0,y=0,width=450,height=100)
answerdisplay = tk.Label(window,text="Answer Display",width=700,font=("Courier", 20),wraplength=450)
answerdisplay.place(x=0,y=100,width=450,height=100)
answerdisplay2 = tk.Label(window,text="Answer Display",width=700,font=("Courier", 20),wraplength=450)
answerdisplay2.place(x=0,y=200,width=450,height=100)
answerdisplay3 = tk.Label(window,text="Answer Display",width=700,font=("Courier", 20),wraplength=450)
answerdisplay3.place(x=0,y=300,width=450,height=100)
answerdisplay4 = tk.Label(window,text="Answer Display",width=700,font=("Courier", 20),wraplength=450)
answerdisplay4.place(x=0,y=400,width=450,height=100)
photoA = tk.PhotoImage(file="ButtonA.gif") #use of photos via tkinter, defined via tk.PhotoImage.
photoB = tk.PhotoImage(file="ButtonB.gif")
photoC = tk.PhotoImage(file="ButtonC.gif")
photoD = tk.PhotoImage(file="ButtonD.gif")
button1 = tk.Button(window,text="A",width=400,command=lambda: questions("A"),image=photoA) #lambda is used here to prevent the function from being called automatically upon creation of the button.
button1.place(x=0,y=600,width=450,height=100) #use of place
button2 = tk.Button(window,text="B",width=400,command=lambda: questions("B"),image=photoB)
button2.place(x=0,y=700,width=450,height=100)
button3 = tk.Button(window,text="C",width=400,command=lambda: questions("C"),image=photoC)
button3.place(x=0,y=800,width=450,height=100)
button4 = tk.Button(window,text="D",width=400,command=lambda: questions("D"),image=photoD)
button4.place(x=0,y=900,width=450,height=100)
initdifficulty()
window.mainloop() #tkinter mainloop
|
a69d60b06d67fa37adb95eb7a148677b2ffba31b | Aniket-Bhagat/Computing_tools_2 | /Q3.py | 937 | 3.953125 | 4 | print """------------------------------------------------------
| Extract Binary numbers only divisible by 5 |
------------------------------------------------------\n"""
def check(n):
binary=True
for i in str(n):
if i!='0' and i!='1':
binary=False
break
if binary==True:
if n%5==0 and n!=0:
return n
# else:
# return 'Nothing'#print 'Not Divisible by 5'
# else:
# return 'Nothing'#print 'Not a binary'
print "Input each number seperated by comma (,)\ne.g. 1000,1010,125,1111,011101"
print "Give at least one number\n"
seq=input("Give your input :\n")
print "\n------------------------------------------------------"
try:
print "Binary number(s) which are Divisible by 5 :"
result=(map(lambda x: check(x),seq))
result=list(x for x in result if x!=None)
if result!=[]: print result
else: print "None"
except TypeError:
print check(seq)
print "------------------------------------------------------" |
4214a11caff2b7a8e42955bb6cdb524ae639abc5 | Langzzx/OMOOC2py | /_src/om2py1w/1wex1/dialy_gui2.py | 528 | 3.890625 | 4 | # coding=utf-8
#exercise for Tkinter
import Tkinter as tk
from dialy import *
root = tk.Tk()
tk.Label(root, text="Hello world").pack()
var = tk.StringVar(value="Hi, please enter here:")
text_input = tk.Entry(root, textvar=var)
text_input.pack()
def update_text():
append_text(var.get())
text_output.config(text=get_text())
var.set('')
tk.Button(root, text="print", command=update_text).pack()
root.bind('<Return>', lambda event:update_text())
text_output = tk.Message(root,text='')
text_output.pack()
root.mainloop()
|
9cc542c3b8721d3c1a9eac830ed28b7c2caf0a5e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2433/60749/234323.py | 160 | 3.640625 | 4 | class Interval(object):
def _init_(self,s=0,e=0):
self.start=s
self.end=e
input=input()
lenint=len(input)
if lenint<2:
print(input)
|
8e7c6b38ef7805ac613ace50fe004123cd13e715 | Matias-Gutierrez/practica-con-python | /clase 2 semestre/clase 3/pangramas.py | 892 | 4.0625 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# Nombre del Autor: Matías Gutierrez
# Bibliotecas importadas
# Definir funciones
def valPangramas(palabra):
letras = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","v","w","x","y","z"]
palabra = palabra.lower()
palabra = palabra.replace("á","a")
palabra = palabra.replace("é","e")
palabra = palabra.replace("í","i")
palabra = palabra.replace("ó","o")
palabra = palabra.replace("ú","u")
palabra = palabra.replace("ü","u")
palabra = palabra.replace("ñ","n")
for ele in letras:
if palabra.count(ele) == 0:
return False
return True
# Codigo Principal
if (__name__=="__main__"):
entrada = input()
resultado = valPangramas(entrada)
if (resultado):
print("Si es un pangrama")
else:
print("No es un pangrama") |
8976e8c7d285c9b60d3740abeb421e772e70c089 | visalakshi-annamalai/python_exercises | /problemset03/pbsiii5.py | 199 | 3.640625 | 4 | def avoids(str,forbidden):
for i in forbidden:
if i in str:
return False
else:
return True
str="rnbw"
forbidden=['a','e','i','o','u']
print avoids(str,forbidden)
|
5f0868392163cfd3a2063948710bc2292ddcbf52 | vonzhou/py-learn | /byte-python/chapter7/break.py | 216 | 3.984375 | 4 | #!/usr/bin/python
while True:
s = raw_input('Enter a string: ')
if ('quit'==s):
print 'The loop is exited.'
break;
print 'The len of your input is: ',len(s)
else:
print 'can you get here?'
print 'Done'
|
49c4b6116a513b47e3b585d44c593fed67fc7ef9 | angelusualle/algorithms | /cracking_the_coding_interview_qs/2.8/detect_loop.py | 891 | 3.953125 | 4 | class Linked_List():
def __init__(self, head):
self.head = head
class Node():
def __init__(self, data):
self.data = data
self.next = None
def detect_loop(linked_list):
slow = linked_list.head
fast = linked_list.head
while slow is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if slow is None or fast.next is None:
return None
slow = linked_list.head
while True:
if slow == fast:
return slow
slow = slow.next
fast = fast.next
'''
# O(n) time and space
def detect_loop(linked_list):
nodes = set()
next_one = linked_list.head
while next_one is not None:
if next_one in nodes:
return next_one
nodes.add(next_one)
next_one = next_one.next
return None
''' |
e78b2b73c18e86d6eeedf1d23945a536cad57577 | martinbonneau/api-generator | /generator/functions.py | 878 | 3.90625 | 4 | from sys import exc_info
def replace_text(vars:dict, text:str):
for key, value in vars.items():
key = '$' + key + '$'
text = text.replace(key, value)
return text
#end replace(vars, text)
def replace_in_file(file, values):
try:
f = open(file, 'r')
f_content = f.read()
f.close()
f_content = replace_text(values, f_content)
f = open(file, 'w')
f.write(f_content)
f.close()
except:
print("Error in replacing variables in file " + file + "\nError : " + str(exc_info()[0]))
exit(1)
#end replace_in_file(file, new_text)
def get_answer(question, default="") -> str:
answer = ""
while (answer == ""):
answer = input(question)
if (answer == "" and default != ""):
answer = default
return answer
#end get_answer(question) |
c200b88edcb3ce8f6b752b9844bbdd85a22c7558 | bendanon/Riddles | /python/delete_node.py | 755 | 3.828125 | 4 | import unittest
"""
Delete a node from a singly-linked list, given only a variable pointing to that node..
"""
def delete_node(ptr):
if ptr.next is None:
raise Exception("Can't delete the last node!")
return
ptr.value = ptr.next.value
ptr.next = ptr.next.next
return False
class LinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
class TestDeleteNode(unittest.TestCase):
def test_trivial(self):
a = LinkedListNode('A')
b = LinkedListNode('B')
c = LinkedListNode('C')
a.next = b
b.next = c
delete_node(b)
self.assertEqual(a.next.value, c.value)
if __name__ == '__main__':
unittest.main()
|
d12dd5e22bfc0cee0279fe04122c392361663fb6 | gkdmssidhd/Python | /Python_day02/Day01Ex03.py | 917 | 3.859375 | 4 | from main import strr
user_name = input('성명 입력 >> ')
# input() 결과 형은 문자열이기 때문에
# 정수형으로 사용하기 위해서 정수형은 형변환 해줘야함.
#age = input("나이 입력 >> ")
#age = int(age)
age = int(input('나이 입력 >> '))
address = input('주소 입력 >> ')
str = """
성명 : {0}
나이 : {1}
주소 : {2}
""".format(user_name, age, address)
print(strr)
print('성명 : ' + user_name)
print('나이 : ' + str(age))
print('주소 : ' + address)
# 정수와 문자열을 연산하면 오류가 발생한다.
# 연산을 하기 위해서는 두항의 타입이 같아야 한다.
# 10년 후에 ~~님은 ~~세 입니다.
print('{}년후에 {}님은 {}세 입니다.'.format(10,user_name,age+10))
# 에러가 나는데, input() 결과형은 문자열이기 때문에
# 정수형으로 사용하기 위해서 형변환해야한다.
# int(input()) 해주기~
|
db3d3082a22fab463748a6fdaf8aca03eceffa9c | psyvalvrave/Crime_Border_Rate | /crime_data.py | 3,829 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Names:Zhecheng Li
Program: Crime and Border project
Description: Extract data from wikipedia about cities
Calculate correlation between crime rate and distance to border
Last Modified: 02 Feb 2019
"""
from bs4 import BeautifulSoup
import urllib
import os
import csv
import math
import scipy
def getURL(link):
wikipedia = 'https://en.wikipedia.org'
return wikipedia + link
def getFilename(link):
filename = link.rsplit('/', 1) #split 1 from the right, city name is last item in list
filename = filename[-1].split(',', 1) #split state from city name
filename = '../data/' + filename[0] + '.html' #city name is first item in list, add html extension
return filename
def getDocument(link):
filename = getFilename(link)
if os.path.exists(filename):
with open(filename, 'r', encoding='utf-8') as file:
file_r = file.read()
soup = BeautifulSoup(file_r, 'lxml')
else:
url = getURL(link)
with urllib.request.urlopen(url) as source:
soup = BeautifulSoup(source, 'lxml')
urllib.request.urlretrieve(url, filename)
return soup
def getSmallestDistance(city_link, borders):
soup = getDocument(city_link)
coordinates = (soup.find('span', class_='geo').text).split(';')
x_lat = float(coordinates[0])
x_lon = float(coordinates[1])
distances = [greatCircleDistance(x_lat, x_lon, y['lat'], y['lon']) for y in borders]
return(min(distances))
def greatCircleDistance(x_lat, x_lon, y_lat, y_lon):
EARTH_RADIUS = 6367
RADIANS = math.pi/180
lat = (x_lat * RADIANS) - (y_lat * RADIANS)
lon = (x_lon * RADIANS) - (y_lon * RADIANS)
distance = ((math.sin((lat)/2))**2 + math.cos(x_lat * RADIANS) *
math.cos(y_lat * RADIANS) * (math.sin((lon)/2))**2)
distance = 2 * math.atan2(math.sqrt(distance), math.sqrt(1-distance))
return EARTH_RADIUS * distance
DATA_PATH = '../data'
LIST_LINK = '/wiki/List_of_United_States_cities_by_crime_rate'
#create directory if does not exist
if not os.path.exists(DATA_PATH):
os.mkdir(DATA_PATH)
#list of border's latitude and longitude
borders = [{'name':'San Diego', 'lat':32.71500, 'lon': -117.16250},
{'name':'Yuma', 'lat':32.69222, 'lon': -114.61528},
{'name':'Tucson', 'lat':32.22167, 'lon': -110.92639},
{'name':'El Paso', 'lat':31.7592056, 'lon': -106.4901750},
{'name':'Laredo', 'lat':27.52444, 'lon': -99.49056},
{'name':'Del Rio', 'lat':29.370833, 'lon': -100.89583},
{'name':'Brownsville', 'lat':25.93028, 'lon': -97.48444}]
#get data and create list
city_list = list()
count = 0
soup = getDocument(LIST_LINK)
print('Retrieving Data...')
for data in soup.find('table', class_='wikitable').find_all('td'):
if count == 1 and data.text != 'Anchorage':
city_name = data.text.rstrip('0123456789*')
smallest = round(getSmallestDistance(data.a['href'], borders), 4)
elif count == 3 and city_name != 'Anchorage':
crime_rate = float(data.text)
city = {'city':city_name, 'crime rate':crime_rate, 'distance':smallest}
city_list.append(city)
print('Got: ' + city_name)
elif count == 13:
count = 0
count += 1
print('Done')
print('Writing CSV file...')
with open('../report/crime_data.csv', 'w') as csvfile:
fields = ['city', 'crime rate', 'distance']
file_w = csv.DictWriter(csvfile, fieldnames = fields)
file_w.writeheader()
file_w.writerows(city_list)
print('Done')
#Print Correlation
smallestDistance=[]
crimeRate=[]
for city in city_list:
smallestDistance.append(city['distance'])
crimeRate.append(city['crime rate'])
print('\nThe coefficient of correlation is: ')
print(scipy.corrcoef(smallestDistance, crimeRate)[0][1]) |
841f8fb53701708482047ee644bd59108ccb63c8 | ZainRaza14/gedcom_Agile | /userstories/sprint02_us/userStory16.py | 1,570 | 3.65625 | 4 | from ParserModule import parse_main
from utils import compare_date_to_todays_date,get_first_name
from print_main import printTables
'''
US16 Male last names All male members of a family should have the same last name
'''
def us16_male_last_names(file):
error_list = list()
#printTables(file)
'''
loop over family records
for each family
a) get the husband first name
1. see wife name and if wife first name and husband name is not same
a) add that individual Id error to wife Name
2. for each children
a) get ind formation and see if the first name of ind is matching with husband firstname
b) if does not match
if yes add to error_list
'''
indDict,famDict,errorList = parse_main(file)
for key,familyData in famDict.items():
husband_first_name = get_first_name(indDict[familyData.Husband].Name)
for eachchild in familyData.multChild:
child_full_name= indDict[eachchild].Name
child_first_name= get_first_name(child_full_name)
if child_first_name != husband_first_name:
error_string= f"ERROR: FAMILY: US16: Individual {eachchild} Name: {child_full_name} not matched with family first name: {husband_first_name}"
error_list.append(error_string);
return error_list
def user_story16_main():
error_list= us16_male_last_names("us16testdata.ged")
for eacherror in error_list:
print(eacherror)
if __name__ == "__main__":
user_story16_main() |
13725bc5859e9eb572639a0ed7a93f60473901da | jrantunes/URIs-Python-3 | /URIs/URI1014.py | 397 | 3.8125 | 4 | #Consumption
#criar uma função para calcular o consumo medio de um automovel(distancia_percorrida / combustivel gasto)
def consumo(dp, cb):
res = dp / cb
print("{:.3f} km/l".format(res))
#ler a distancia percorrida(int)
dist = int(input())
#ler o combustivel gasto(float)
combs = float(input())
#chamar a função usando dist e combs como parametro
consumo(dist, combs) |
4e0f0d2c9293e0882e023c23cb7d265664b0ed86 | Flor246/PythonFlor | /Modulo1/scripts/nombre.py | 71 | 3.671875 | 4 | nombre = input('Ingrese su nombre: ')
print('Hola {}!'.format(nombre)) |
ab0240ec05dd3939031569d1b95363c930d04804 | zacps/invis-encoder | /encoder.py | 1,793 | 4.1875 | 4 | #!/usr/bin/env python3
import gzip
import os
import sys
if len(sys.argv) != 3:
print("Expected two arguments, in file and out file")
sys.exit(1)
FILE = sys.argv[1]
OUT = sys.argv[2]
print('Opening file')
print(f'File length: {os.stat(FILE).st_size} bytes')
with open(FILE, encoding='utf8') as file:
print('Compressing text')
compressed = file.read()
# Taken from https://en.wikipedia.org/wiki/Whitespace_character#Unicode
ALPHABET = "\u200B\u200C\u200D\u2060\uFEFF"
NULL = "\u180E"
# From https://github.com/yamatt/python-dencoder
class Dencoder():
def __init__(self, alphabet):
"""
Set up the decoder/encoder alphabet.
"""
self.alphabet = alphabet
self.base = len(self.alphabet)
def encode(self, number):
"""
Turns a number in to a string that represents it.
"""
if number == 0:
return self.alphabet[0]
s = ''
while number > 0:
s += self.alphabet[number % self.base]
number = number // self.base
return s[::-1] # reverse string
def decode(self, s):
"""
Turns string encoding back in to a number.
"""
i = 0
for char in s:
i = i * self.base + self.alphabet.index(char)
return i
print('Encoding')
encoder = Dencoder(ALPHABET)
encoded = []
for byte in compressed:
encoded.append(encoder.encode(ord(byte)))
print('Consistence check')
for i, byte in enumerate(encoded):
assert chr(encoder.decode(byte)) == compressed[i]
print('Writing encoded file to out.txt')
with open(OUT, 'w', encoding='utf8') as out:
out.write(NULL.join(encoded))
print(f'File length: {os.stat(OUT).st_size} bytes')
|
7276cff4b6d1d25fcec328169fd462561b7c829b | xiaohugogogo/python_study | /python_work/chapter_2/name_cases.py | 512 | 4.21875 | 4 | name = "Eric"
print("Hello " + name + ", would you like to learn some Python today?")
name = "zHAO yU Hu"
print(name.lower())
print(name.upper())
print(name.title())
sentence = 'Albert Einstein once said, "A person who never made a mistake never tried anything new."'
print(sentence)
famous_person = "Albert Einstein"
message = "A person who never made a mistake never tried anything new."
print(famous_person + ' once said, "' + message + '"')
name = " \t David \n "
print(name.lstrip())
print(name.rstrip())
print(name.strip())
|
e37419585cf837002df1a9aa4a8a379082ac23f3 | FaderVader/CPH_AdvancedProg | /Dag07/bintree.py | 3,494 | 3.984375 | 4 | from collections import namedtuple
class BinTree:
"""
A binary tree.
>>> b = BinTree()
>>> b
BinTree(None)
>>> b[2] = "b"
>>> b[1] = "x"
>>> b[3] = "c"
>>> b[1] = "a"
>>> list(b)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> b.pprint()
- None
+ 1 = a
- None
+ 2 = b
- None
+ 3 = c
- None
>>> b.bfpprint()
| 2=b |
| 1=a 3=c |
| None None None None |
"""
Node = namedtuple("Node", "key value sml lrg")
def __init__(self, root=None):
self.root = root
def __setitem__(self, key, value):
def setit(node):
if node is None:
return BinTree.Node(key, value, None, None)
elif key == node.key:
return BinTree.Node(key, value, node.sml, node.lrg)
elif key < node.key:
return BinTree.Node(node.key, node.value, setit(node.sml), node.lrg)
else:
return BinTree.Node(node.key, node.value, node.sml, setit(node.lrg))
self.root = setit(self.root)
def __iter__(self):
# in order
def iterx(node):
if not node is None:
yield from iterx(node.sml)
yield (node.key, node.value)
yield from iterx(node.lrg)
return iterx(self.root)
def pprint(self):
UNPRINTED = 0
AFTER_SMALLER = 1
AFTER_LARGER = 2
Zipper = namedtuple("Zipper", "parent node depth state")
zipper = Zipper(None, self.root, 0, UNPRINTED)
while zipper:
if zipper.state == UNPRINTED:
node = zipper.node
if node:
zipper = Zipper(
zipper._replace(state=AFTER_SMALLER),
node.sml,
depth=zipper.depth + 1,
state=UNPRINTED,
)
else:
print(" " * zipper.depth + "- None")
zipper = zipper.parent
elif zipper.state["state"] == AFTER_SMALLER:
print(" " * indent + "+", zipper.node.key, "=", zipper.node.value)
zipper = Zipper(
zipper._replace(state=AFTER_LARGER),
zipper.node.lrg,
depth=zipper.depth + 1,
state=UNPRINTED,
)
else:
zipper = zipper.parent
def bfpprint(self):
level = [(self.root, 60)]
new_level = []
all_is_empty = False
while not all_is_empty:
print("|", end="")
old_level, level = level, []
all_is_empty = True
for (node, size) in old_level:
if node is None or node == "":
print(str(node).center(size), end="")
level.append(("", size))
else:
all_is_empty = False
level.append((node.sml, size // 2))
level.append((node.lrg, size - size // 2))
print(f"{node.key}={node.value}".center(size), end="")
print("|")
def __repr__(self):
return f"BinTree({self.root!r})"
if __name__ == "__main__":
import doctest
doctest.testmod()
|
42c92e5875600612058a7d8a94a5aa1368c93e9e | alexander-jiang/RL2048 | /reinforcement_learning/experience_replay_utils.py | 4,399 | 3.5 | 4 | from collections import namedtuple
from typing import List
import numpy as np
BaseExperienceReplay = namedtuple(
"BaseExperienceReplay", ["state_tiles", "action", "successor_tiles", "reward"]
)
# action is encoded as an int in 0..3
ACTIONS = ["Up", "Down", "Left", "Right"]
class ExperienceReplay(BaseExperienceReplay):
"""
An experience replay tuple with helper functions to convert to and from
a flattened representation (e.g. for a neural net).
"""
def __repr__(self):
return (
f"Previous state\n{tiles_repr(self.state_tiles)}\n"
f"Action: {int(self.action)} ({ACTIONS[int(self.action)]})\n"
f"New state\n{tiles_repr(self.successor_tiles)}\n"
f"Reward: {self.reward}"
)
@property
def state_bitarray(self) -> np.ndarray:
return convert_tiles_to_bitarray(self.state_tiles)
@property
def successor_bitarray(self) -> np.ndarray:
return convert_tiles_to_bitarray(self.successor_tiles)
def flatten(self) -> np.ndarray:
"""stores the (s, a, s', r) in a flattened representation"""
return np.hstack(
(
self.state_bitarray,
np.array([self.action]),
self.successor_bitarray,
np.array([self.reward]),
)
)
@classmethod
def from_flattened(cls, flat_tuple: np.ndarray):
assert flat_tuple.shape == (2 * 16 * 17 + 2,)
current_state_bitarray = flat_tuple[0 : (16 * 17)]
action = flat_tuple[16 * 17]
new_state_bitarray = flat_tuple[(16 * 17 + 1) : (2 * 16 * 17 + 1)]
reward = flat_tuple[(2 * 16 * 17 + 1)]
current_state_tiles = convert_bitarray_to_tiles(current_state_bitarray)
new_state_tiles = convert_bitarray_to_tiles(new_state_bitarray)
return cls(current_state_tiles, action, new_state_tiles, reward)
def convert_tiles_to_bitarray(tiles) -> np.ndarray:
"""
Convert from a 4x4 array, where each cell is the log base 2 value of the tile,
into a flattened bitarray representation, where each of the 16 cells is represented by 17 bits,
with the first bit set if the tile value is 2, the second bit set in the tile value is 4,
and so on up to 2^17 (the maximum possible tile value on a 4x4 board with 4-tiles being
the maximum possible spawned tile).
"""
flat_tiles = np.ravel(tiles)
bitarray_input = np.zeros((16, 17))
for i in range(16):
if flat_tiles[i] != 0:
# value of 1 (means the the tile is 2) should set bit 0 in bitarray
bitarray_input_idx = flat_tiles[i] - 1
bitarray_input[i, bitarray_input_idx] = 1
return np.ravel(bitarray_input)
def convert_bitarray_to_tiles(bitarray: np.ndarray) -> list:
"""
Convert from flattened bitarray representation, where each of the 16 cells is
represented by 17 bits (first bit is set if tile value is 2), to a 4x4 array,
where each cell is the log base 2 value of the tile.
"""
assert bitarray.size == 16 * 17
bitarray_reshape = np.reshape(bitarray, (4, 4, 17))
tiles = []
for r in range(4):
tile_row = []
for c in range(4):
one_hot_tile_encoding = bitarray_reshape[r, c]
if np.count_nonzero(one_hot_tile_encoding) == 0:
tile_row.append(0)
else:
assert np.sum(one_hot_tile_encoding) == 1
assert np.count_nonzero(one_hot_tile_encoding) == 1
tile_row.append(np.argmax(one_hot_tile_encoding) + 1)
tiles.append(tile_row)
return tiles
# def parse_flattened_experience_tuple(flat_tuple: np.ndarray):
# assert flat_tuple.shape == (2 * 16 * 17 + 2,)
# current_state_bitarray = flat_tuple[0:(16 * 17)]
# action = flat_tuple[16 * 17]
# new_state_bitarray = flat_tuple[(16 * 17 + 1):(2 * 16 * 17 + 1)]
# reward = flat_tuple[(2 * 16 * 17 + 1)]
# return (current_state_bitarray, action, new_state_bitarray, reward)
def tiles_repr(tiles: List[List[int]]) -> str:
output = ""
for row_idx in range(len(tiles)):
row = tiles[row_idx]
for col_idx in range(len(row)):
output += f"{row[col_idx]:2d}"
if col_idx < len(row) - 1:
output += " "
if row_idx < len(tiles) - 1:
output += "\n"
return output
|
a8cceb5cb380d26e5cecf192f65cd776a35ebe8e | govardhananprabhu/DS-task- | /longest palindrome with N digits.py | 1,293 | 4.15625 | 4 | """
Given a value n, find out the largest palindrome number which is product of two n digit numbers.
In des
First line contain integer N,denotes the range of digits.
Ot des
Print the palindrome.
2
9009
3
906609
Exp
From sample
9009 is the largest number which is product of two
2-digit numbers. 9009 = 91*99.
Hint
1) Find a lower limit on n digit numbers. For example, for n = 2, lower_limit is 10.
2) Find an upper limit on n digit numbers. For example, for n = 2, upper_limit is 99.
3) Consider all pairs of numbers where ever number lies in range [lower_limit, upper_limit]
H 6
T 3000
"""
def larrgestPalindrome(n):
upper_limit = 0)
for i in range(1, n+1):
upper_limit =upper_limit * 10
upper_limit =upper_limit + 9
lower_limit = 1 + upper_limit//10
max_product = 0
for i in range(upper_limit,lower_limit-1, -1):
for j in range(i,lower_limit-1,-1):
product = i * j
if (product < max_product):
break
number = product
reverse = 0
while (number != 0):
reverse = reverse * 10 + number % 10
number =number // 10
if (product == reverse and product > max_product):
max_product = product
return max_product
N = int(input())
print(larrgestPalindrome(n))
|
519981a7db5d32029a3efcdb9f915cee4077524d | monsterofhell/DSA-Python | /merge_sort.py | 814 | 3.875 | 4 | def merge_sort(a):
if(len(a) >1 ):
mid = (len(a))//2
part_one = merge_sort(a[0:mid])
part_two = merge_sort(a[mid:])
return merge(part_one,part_two)
return a
def merge(part_one,part_two):
final_list = []
len_one = len(part_one)
len_two = len(part_two)
ind_one = 0
ind_two = 0
while(ind_one < len_one and ind_two < len_two):
if(part_one[ind_one] < part_two[ind_two]):
final_list.append(part_one[ind_one])
ind_one += 1
else:
final_list.append(part_two[ind_two])
ind_two += 1
if(ind_one >= len_one):
final_list += part_two[ind_two:]
else:
final_list += part_one[ind_one:]
return final_list
print(merge_sort([98]))
|
7e4b2f1a632d39c2b8227cc0a8321f4c61eb1775 | gauravcool/python-access-webdata | /ex_11_02.py | 197 | 3.59375 | 4 | fname = input("Enter file name: ")
if len(fname) < 2 : fname = 'mbox-short.txt'
handle = open(fname)
for line in handle:
line = line.rstrip()
if line.startswith('From'):
print(line) |
d6ec3f83772fa71bab1e0ffd2271980fceb16d70 | srinathalla/python | /algo/recursion/powerset.py | 507 | 3.90625 | 4 | #
# T.C : O(n*2^n) we have 2^n subsets created and at each subset creation we iterate through a list of size n for cloning
# S.C : O(n*2^n) we have 2^n subsets created and each subset can store a elements of size n.
#
#
#
def powerset(array):
subsets = [[]]
for x in array:
addElementToExistingSets(subsets, x)
return subsets
def addElementToExistingSets(sets, x):
for i in range(len(sets)):
sets.append(sets[i] + [x])
print(powerset([1, 2, 3]))
print(powerset([1]))
|
6932f734e6614adde78ad8aad83307d1dfd79aed | faterazer/LeetCode | /2399. Check Distances Between Same Letters/Solution.py | 333 | 3.609375 | 4 | from typing import List
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
last = [0] * 26
for i, c in enumerate(s):
c = ord(c) - ord("a")
if last[c] and i - last[c] != distance[c]:
return False
last[c] = i + 1
return True
|
eb8862200dd6802189f233ec811af4f751b5a29f | lucifermorningstar1305/deeplearning | /NLP/brown.py | 3,566 | 3.625 | 4 | from nltk.corpus import brown
import operator
import re
class Brown():
def __init__(self):
pass
def remove_punctuation(self, sentence):
"""
--------------------------------------------
Description :
Funcion to remove punctuation from a sentence
Input :
sentence : a string value
Return :
new_sentence : a string value
---------------------------------------------
"""
words = re.findall(r"""\w+[']+\w|\w+|[.]""", sentence)
new_sentence = ' '.join(words)
return new_sentence
def get_vocab(self):
"""
-----------------------------------------
Description :
Function to get the compelete Vocabulary list in a brown_corpus
Return :
word2idx : a dict-object having word:index pair
sentences : a list of list object containing indices of every word as they are in sentence
word2idx_count : a dict-object having word:count of word pair
------------------------------------------
"""
brown_sentences = brown.sents()
brown_sentences = list(map(lambda x: ' '.join(x).lower(), brown_sentences))
new_brown_sentence = [self.remove_punctuation(sents) for sents in brown_sentences]
word2idx = {"START" : 0, "END" : 1}
idx2word = ["START", "END"]
word2idx_count = {0 : float('inf'), 1 : float('inf')}
idx = 2
sentences = []
for sent in new_brown_sentence:
words = sent.split()
for token in words:
if token not in word2idx:
word2idx[token] = idx
idx += 1
idx2word.append(word2idx[token])
word2idx_count[word2idx[token]] = word2idx_count.get(word2idx[token], 0) + 1
sentences_by_idx = [word2idx[token] for token in words]
sentences.append(sentences_by_idx)
return word2idx, sentences, word2idx_count
def get_limited_vocab(self, vocab_size = 200):
"""
----------------------------------------
Description :
Function to obtain limited brown corpus vocabulary
Input:
vocab_size : int value
Return :
word2idx_small : a dict object
sentences_small : a list of list structure
----------------------------------------
"""
word2idx, sentences, word2idx_count = self.get_vocab()
idx2word = [k for k,v in word2idx.items()]
sorted_word2idx_count = sorted([(k, v) for k,v in word2idx_count.items()], key = operator.itemgetter(1), reverse = True)
# print("Hello",sorted_word2idx_count)
new_idx2idx_map = {}
word2idx_small = {}
sentences_small = []
idx = 0
for wordidx, count in sorted_word2idx_count[:vocab_size]:
# print(wordidx)
token = idx2word[wordidx]
if token not in word2idx_small:
word2idx_small[token] = idx
new_idx2idx_map[wordidx] = idx
idx += 1
word2idx_small["UNKNOWN"] = idx
unknown = idx
for sentence in sentences:
if len(sentence) > 1:
new_sentence = [new_idx2idx_map[idx] if idx in new_idx2idx_map else unknown for idx in sentence]
sentences_small.append(new_sentence)
return word2idx_small, sentences_small
|
8fc23d51a49141c891d174c73be11063faa3289a | JinFree/cac.kias.re.kr-2017-3rd-day | /python_tutorial01/python_tutorial/basic/iteration.py | 249 | 4.25 | 4 | #!/usr/bin/env python
a = [ 'a', 'b', 'c', 'd', 'e' ]
for b in a:
print b
for i in range(len(a)):
print i, a[i]
a = { 'a': 1, 'b': 2, 'c': 3 }
for key in a:
print key, a[key]
for key, value in a.iteritems():
print key, value
|
ef3cf549c0f4d914b9fe24c4130dec9cffb5ddd0 | tuess/python | /others/基本/求最大值的顺序处理.py | 415 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def main():
n=int(input("输入你有多少个数字要比较"))
max=float(input("输入一个数"))
for i in range(n-1):
i=float(input("输入一个数"))
if i>max:
max=i
print("最大值是:",max)
main()
##x1,x2,x3=eval(input("输入三个数字"))
##print("最大的是:",max(x1,x2x,x3))
##只有eval能同时多项赋值
|
17bca313d34e578c0992169925b4356f2bc5087a | amarshahaji/pythonprograms | /Assignment3/assignment3_2.py | 594 | 4.4375 | 4 | # 2.Write a program which accept N numbers from user and store it into List.
# Return Maximum number from that List.
# Input : Number of elements : 7
# Input Elements : 13 5 45 7 4 56 34
# Output : 56
import Assignment3Module as NumModal
size = int(input("how much number you want to enter "))
listofNumbers = NumModal.acceptNumbers(size)
print("list of number is",listofNumbers)
def maxNumber(NumList):
max = NumList[ 0 ]
for num in NumList:
if num > max:
max = num
return max
maxNumber = maxNumber(listofNumbers)
print("max number is ",maxNumber) |
4f237b76624c0509d5d1dbb897032145d41658e9 | sabareesh123/pythonprogamming | /A6.py | 603 | 3.65625 | 4 | import sys, string, math
def IsIso(string1, string2):
W = len(string1)
n = len(string2)
if W != n:
return False
marked = [False] * 256
map = [-1] * 256
for J in range(n):
if map[ord(string1[J])] == -1:
if marked[ord(string2[J])] == True:
return False
marked[ord(string2[J])] = True
map[ord(string1[J])] = string2[J]
elif map[ord(string1[J])] != string2[J]:
return False
return True
# Driver program
s1,s2 = input().split()
if IsIso(s1,s2) : print('yes')
else : print('no')
|
dd7e62a6b03cde077b782bf468ac1764c4822ecc | mondon11/leetcode | /0141hasCycle.py | 542 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
a = head
b = head
if not a:
return False
while(1):
a = a.next.next if a.next else None
b = b.next
if a == None:
return False
if a == b:
return True |
7d35cf4babe3ddc108f163fadae4deafddc683c7 | karloscalvillo18/Chapter_4 | /Backwards.py | 238 | 4.09375 | 4 | #Backwards.py
#By: Karlos Calvillo
#10/22/14
print("Hello! Lets type a word backwards for you.")
message=input("Type a word: ")
backward=""
counter=len(message)
while counter !=0:
backward+=message[counter-1]
counter-=1
print(backward)
|
0b2624a685615e6967f62ff1126bbeb49f66b563 | capric8416/leetcode | /algorithms/python3/palindrome_pairs.py | 771 | 4.125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e.
words[i] + words[j] is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:
Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
"""
""" ==================== body ==================== """
class Solution:
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
""" ==================== body ==================== """
|
b8b86b73970c461cb2544e16e31f2a0094274451 | tyree88/Object-Oriented-Programming | /PRACTICESORTING.py | 7,896 | 3.96875 | 4 | # File: sorting.py
# Description: Compares different sorting algorithms
# Student's Name: Charles Lybrand
# Student's UT EID: cbl652
# Course Name: CS 313E
# Unique Number: 51915
#
# Date Created: 04/07/2017
# Date Last Modified: 04/08/2017
################### GIVE CODE ###################
import random
import time
import sys
sys.setrecursionlimit(10000)
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i] > alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax = 0
for location in range(1,fillslot+1):
if alist[location] > alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position] = alist[position-1]
position = position-1
alist[position] = currentvalue
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i += 1
else:
alist[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i += 1
k += 1
while j < len(righthalf):
alist[k] = righthalf[j]
j += 1
k += 1
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first < last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first]
leftmark = first + 1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark += 1
while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark -= 1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
################### END GIVE CODE ###################
class RandomList:
'''
Create an n-length list of sorted numbers
Several methods create certain "shuffled" versions of the list
'''
# init a sorted list
def __init__(self, n):
self.length = n
self.list = list(range(1, n+1))
# randomize the list
def random(self):
random.shuffle(self.list)
# recreate the list in sorted order
def sort(self):
self.list = list(range(1, self.length+1))
# reverse the list
def reverse(self):
self.list = list(reversed(self.list))
# shuffle 10% of the list
def almostSorted(self):
elements = self.length//10
indices = []
while len(indices)//2 < elements:
rand1 = random.randint(0,self.length-1)
rand2 = random.randint(0,self.length-1)
# if the numbers are the same, restart process
if rand1 == rand2:
continue
# proceed if the new random numbers are unique from previous numbers
if not ( (rand1 in indices) and (rand2 in indices) ):
# swap list[rand1] with list[rand2]
indices.append(rand1); indices.append(rand2)
temp = self.list[rand1]
self.list[rand1] = self.list[rand2]
self.list[rand2] = temp
def __str__(self):
return str(self.list)
def runTrial(alg, myList):
'''
Run and time a given sorting algorithm on a specified list
5 times and return the average
'''
trials = 5
elapsedTime = 0.0
# time Bubble Sort
if(alg == "bubbleSort"):
for i in range(trials):
startTime = time.time()
bubbleSort(myList)
endTime = time.time()
elapsedTime += endTime - startTime
# time Selection Sort
elif(alg == "selectionSort"):
for i in range(trials):
startTime = time.time()
selectionSort(myList)
endTime = time.time()
elapsedTime += endTime - startTime
# time Insert Sort
elif(alg == "insertionSort"):
for i in range(trials):
startTime = time.time()
insertionSort(myList)
endTime = time.time()
elapsedTime += endTime - startTime
# time Merge Sort
elif(alg == "mergeSort"):
for i in range(trials):
startTime = time.time()
mergeSort(myList)
endTime = time.time()
elapsedTime += endTime - startTime
# time Quick Sort
elif(alg == "quickSort"):
for i in range(trials):
startTime = time.time()
quickSort(myList)
endTime = time.time()
elapsedTime += endTime - startTime
# return the average
return elapsedTime/trials
def printTrial(inputType, lists):
'''
run the trials and print the results
'''
# algorithms keys for trial
algs = ["bubbleSort", "selectionSort", "insertionSort", "mergeSort", "quickSort"]
# variables for spacing
space = " "*3
col1 = 14
col2 = 8
listsn = len(lists)
lengths = list(lists.keys())
lengths.sort()
print()
# create and print the header
print("Input type = %s" % (inputType))
header = space + ' '*col1
for i in range(listsn):
header += space + "avg time".center(col2)
header += "\n"
header += space + "Sort function".ljust(col1)
for i in range(listsn):
header += space + ("(n=%d)" % lengths[i]).center(col2)
header += "\n"
header += "-"*53
print(header)
print()
for alg in algs:
print(space + alg.ljust(col1), end="")
for n in lengths:
# make a copy of the list
myList = lists[n].list[:]
print(space + "%.6f" % runTrial(alg, myList), end="")
print()
print()
def main():
# tests
tests = ["Random", "Sorted", "Reverse", "Almost sorted"]
lists = {}
for i in range(1, 4):
n = 10**i
l = RandomList(n)
lists[n] = l
print(lists)
for inputType in tests:
# adjust list for each sorting algorithm
if(inputType == "Random"):
for l in lists:
lists[l].random()
elif(inputType == "Sorted"):
for l in lists:
lists[l].sort()
elif(inputType == "Reverse"):
for l in lists:
lists[l].reverse()
elif(inputType == "Almost sorted"):
for l in lists:
# make sure list is sorted first
lists[l].sort()
lists[l].almostSorted()
# print the results for specific inputType
printTrial(inputType, lists)
if __name__ == "__main__":
main()
|
2dd404a24a97541480000e106a29692324df8c90 | cikent/Python-Projects | /LPTHW/ex12-PromptingPeople-InputPrompts.py | 2,426 | 4.15625 | 4 | # prompt on-screen a question and save the value
age = input("How old are you? ")
# prompt on-screen a question and save the value
height = input(f"You're {age}? Nice. How tall are you? ")
# prompt on-screen a question and save the value
weight = input("How much do you weight? ")
# print to screen the results from the questions
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
# print to screen indication we're going to try something new
print("\nWe're going to try something a little more fun now!")
# print to screen a question: What Class does the user like to play in Diablo 3?
d3Class = input("\nThe new Diablo 3 Season starts today! Which Class are you going to choose?! ")
# print to screen a question: What role does the user like to execute in group content
d3Style = input(f"\nSo you like {d3Class}, cool. In group content, what role do you like to play? ")
# print to screen a question: What is their favorite Item
d3Item = input(f"\nDo you have a favorite Item for your {d3Class} when you play {d3Style}? ")
#print to screen their responses
print(f"\nSo you like to use your {d3Item} to {d3Style} with your {d3Class}?! Thats cool! ")
# =======================================================================================
# ++ Study Drills ++
# =============================
# 1. Go back through and write a comment on what each line does.
# 2. Read each one backward or out loud to find your errors.
# 3. Annotate mistakes & avoid them in the future
# 4. Plus whatever the specific Lesson entails
# Mistakes
# =============================
# mistakes = {
# 1st = Not remembering how to write an F-string
# 2nd = Forgetting that Print Commands always end with the newline (\n) parameter unless otherwise specified
# 3rd =
# }
# ++ Things to Remember ++
# =============================
# Escape Characters:
# -------------------------
# Command | What id Does
# \\ | Backslash (\)
# \' | Single-quote (')
# \" | Double-quote (")
# \a | ASCII bell (BEL)
# \b | ASCII backspace (BS)
# \f | ASCII formfeed (FF)
# \n | ASCII linefeed (LF)
# \N{name} | Character named name in the Unicode database (Unicode only)
# \r | Carriage Return (CR)
# \t | Horizontal Tab
# \uxxxx | Character with 16-bit hex value xxxx
# \Uxxxxxxxx | Character with 16-bit hex value xxxxxxxx
# \v | ASCII vertical tab (VT)
# \ooo | Character with octal value ooo
# \xhh | Character with hex value hh
|
d1ff162981c12e016ffb5e06372f0582c0f20c73 | bandiafatima/exo3.py | /exo2.py | 166 | 3.8125 | 4 | # pair ou impair
n = input (tapez la valeur n:")
n =int (n)
r = n % 2
-if (r=0) :
print ("le nombre n est pair")
-else :
print("le nombre n tapé est impair") |
f08be3cfadf06664f23ced5be7b9fe3f19448329 | Trietptm-on-Coding-Algorithms/ProjectEuler-2 | /4/palindrome.py | 853 | 3.75 | 4 | #############################
# Created By: Sean Moriarty #
# Created On:1/29/13 #
# Last Edit: 1/29/13 #
#############################
#Total of numbers multiplied and that number reversed
total = 0
totalBackwards = 0
#Variable for largest palindrome
largestPalindrome = 0
#For all numbers inbetween a and b multiply by each other and then reverse and compare
for num in range(700,1000):
for secondNum in range(700,1000):
total = num * secondNum
total = str(total)
totalBackwards = total[::-1]
totalBackwards = int(totalBackwards)
total = int(total)
#If number is palindrome and larger than currrent largest change to current largest
if total == totalBackwards and total > largestPalindrome:
largestPalindrome = total
print largestPalindrome
|
ba01b8068e954f115f39d131c787cd7758f15635 | mattclarke/advent_of_code_20 | /day_15/day_15.py | 877 | 3.625 | 4 | PUZZLE_INPUT = "9,3,1,0,8,4"
# PUZZLE_INPUT = "0,3,6"
puzzle_input = [int(x) for x in PUZZLE_INPUT.split(",")]
print(puzzle_input)
turn = 0
record = {}
last = 0
for i in puzzle_input:
if turn == 0:
turn += 1
last = i
continue
# Put the previous value in to record
record[last] = turn
turn += 1
last = i
while turn < 2020:
prev = record.get(last, -1)
# Put the previous value into the record
record[last] = turn
if prev == -1:
# New value
last = 0
else:
last = turn - prev
turn += 1
# print(last)
# 371
print(f"answer = {last}")
tracker = []
# Part 2
while turn < 30_000_000:
prev = record.get(last, -1)
record[last] = turn
if prev == -1:
last = 0
else:
last = turn - prev
turn += 1
# print(last)
# 352
print(f"answer = {last}")
|
f7194f8e1f742f05e4bf800bef8242aea0990509 | sivagopi204/python | /day 3-1.py | 500 | 4.1875 | 4 | #Write a program that declares and initializes a character variable.
#It prints true if the character corresponds to a digit i.e. one of 0, 1, 2, ..., 9; otherwise it prints false.
#Extend the program to check if it is an alphabet (i.e. one of a, b, ..., z or A, B, ..., Z) or a digit. Such characters are called alphanumerics.
ch = "1"
ch1=ch.isdigit()
ch2 = ch.isalpha()
if ch1 == True:
print ("%s is a digit ?:" %ch, ch1)
if ch2 == True:
print ("%s is a alphabet ?:" %ch, ch2)
|
f49f53e380001700c173022149fe060d07072026 | Prachithakur27/Python- | /dic.py | 542 | 4.34375 | 4 | dict = {};
print("Empty dictonary : ",dict);
#Dictionary holds key:value pair
dict = {1:'prachi',2:'manu',3:'gauri',4:'jayesh',5:'neha'};
print("Dictonary with some key:value pair : ",dict);
#Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
dict = {1:'p',1:'m',3:'g',4:'j',3:'n'};
print("Dictonary with some repeated key:value pair : ",dict);
dict = {1:'pr',2:'manu',3:'pr',4:'jayesh',5:'neha'};
print("Dictonary with some key:repeated value pair : ",dict);
|
076d72294177d8d771060dffa9a855d76b55e372 | Dylrak/CSNalarm | /main.py | 2,568 | 3.5625 | 4 | import RPi.GPIO as GPIO
import threading
import time
# constants
WINDOW_PORT = 13 # GPIO port for the 'window' (a.k.a. alarm initiation)
ALARM_PORT = 11 # port for alarm(s)
LOGIN_PORT = 15 # port for button to initiate login protocol
LOGIN_PASS = 'test' # password for login
TIME_PER_STEP = 10
MAX_STEPS = 100
class State:
IDLE = 0
ALARM = 1
LOGIN = 2
# initiating GPIO header
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(WINDOW_PORT, GPIO.IN)
GPIO.setup(ALARM_PORT, GPIO.OUT)
GPIO.setup(LOGIN_PORT, GPIO.IN)
state = State.IDLE
isflashing = False
flash_time = 0.25
running = True
def flashing():
"""Thread flashing function"""
while True:
if isflashing:
GPIO.output(ALARM_PORT, True)
time.sleep(flash_time)
GPIO.output(ALARM_PORT, False)
time.sleep(flash_time)
else:
time.sleep(flash_time)
print('starting')
flash_thread = threading.Thread(target=flashing)
print('other program')
running = True
flash_thread.start()
while running: # MAIN while-loop, checks for program state.
if state == State.IDLE and GPIO.input(WINDOW_PORT): # IDLE State means detecting if someone 'broke in'
state = State.ALARM
GPIO.output(ALARM_PORT, True)
isflashing = True
# Else, the state is ALARM or LOGIN. This means we wait for login press to enter password.
elif GPIO.input(LOGIN_PORT):
state = State.LOGIN
elif state == State.LOGIN:
if LOGIN_PASS == input('Voer uw wachtwoord in: '):
state = State.IDLE
isflashing = False
GPIO.output(ALARM_PORT, False)
while True:
result = input('which setting would you like to change?\n[1] Flash time\n[2] Password\n[3] exit menu\n:')
if result == '1':
try:
flash_time = eval(input("How long should the alarm wait inbetween flashes?: "))
except:
print('invalid value')
elif result == '2':
TEMP_PASS = input('Enter Password: ')
TEMP_PASS2 = input('Password again: ')
if TEMP_PASS == TEMP_PASS2:
LOGIN_PASS = TEMP_PASS
else:
print('Password doesn\'t match.')
else:
break
else:
print('Uw wachtwoord klopt niet.')
time.sleep(0.1)
print('starting threads')
GPIO.cleanup()
|
a412d099986f79f8a6dcc577bf60c57652cc2e01 | julianhasse/Python_course | /24_accesing_items.py | 558 | 4.28125 | 4 | letters = ["a", "b", "c", "d"]
print(letters[0])
letters[0] = "Julian"
for item in range(len(letters)):
print(letters[item])
# slicing a string
print(letters[0:3]) # returns 3 first items
print(letters[:3]) # zero is assumed
print(letters[0:]) # from first to the final item are returned
print(letters[:]) # a copy of the list is returned
print(letters[::2]) # returns every other element on the list
print(letters[::-1]) # returns every element on the list in reversed order
numbers = list(range(20))
print(numbers[::2])
print(numbers[::-1])
|
41954adab4c6a36bcc67604d35adc9e5eeed62de | banga19/Personality-Guesser | /SecondPage.py | 594 | 3.796875 | 4 | from tkinter import *
HEIGHT = 450
WIDTH = 350
root = Tk()
frame2 = Frame(root, height=HEIGHT, width=WIDTH)
frame2.pack()
canvas2 = Canvas(root, height=HEIGHT, width=WIDTH, bg="#ffff99")
canvas2.pack()
L3 = Label(canvas2, bd=7, text="WHAT IS YOUR FAVORITE COLOR ?", )
L3.place(relx=0.5, rely=0.25, relwidth=0.6, relheight=0.09, anchor="n")
E2 = Entry(canvas2, bd=7, )
E2.place(relx=0.25, relwidth=0.5, rely=0.45, relheight=0.09)
B2 = Button(canvas2, bd=7, text="FIND OUT!")
B2.place(relx=0.47, rely=0.7, anchor="s", relwidth=0.3, relheight=0.1)
root.mainloop()
|
361193ccc4dcb92021f67c2ae7147acda2ce9d31 | christabella/code-busters | /pancakeflipper_linear.py | 1,221 | 3.984375 | 4 | #!/usr/bin/env python
'''The idea is that we can greedily determine whether a flip needs to be
made at each position in order for the pancakes to be happy.'''
import itertools
def all_combinations(l):
all_lengths = range(0, len(l)+1)
return itertools.chain.from_iterable(
itertools.combinations(l, i)
for i in all_lengths
)
def flip(pancakes, position, flipper_size):
''' Position to start flipping from '''
right_pos = position + flipper_size
flipped = ''.join(
['+' if p == '-' else '-' for p in pancakes[position:right_pos]]
)
return pancakes[:position] + flipped + pancakes[right_pos:]
def is_happy(pancakes):
return pancakes == "+" * len(pancakes)
def solve(pancakes, flipper_size):
flips = 0
for pos in range(len(pancakes) - flipper_size + 1):
if (pancakes[pos]) == '-':
pancakes = flip(pancakes, pos, flipper_size)
flips += 1
if is_happy(pancakes):
return flips
return "IMPOSSIBLE"
if __name__ == "__main__":
cases = int(input())
for case in range(1, cases+1):
pancakes, flipper = input().split()
print("Case #{}: {}".format(case, solve(pancakes, int(flipper))))
|
e6616e98b6e1ed3afd73778acc750a89e95cb15d | SurakietArt/Programming.in.th | /03_Min Max.py | 139 | 3.5 | 4 | list = []
amount = int(input())
for i in range (1,amount+1):
num = int(input())
list.append(num)
print(min(list))
print(max(list)) |
881bbca0c9fb9de944545f45b9bfd4e27025cc9c | sagarnikam123/learnNPractice | /hackerRank/tracks/coreCS/algorithms/sorting/maximumSubarraySum.py | 2,305 | 3.84375 | 4 | # Maximum Subarray Sum
#######################################################################################################################
#
# We define the following:
# A subarray of an n-element array, A, is a contiguous subset of A's elements in the inclusive range from some
# index i to some index j where 0 <= i <= j < n.
# The sum of an array is the sum of its elements.
# Given an n-element array of integers, A, and an integer m, determine the maximum value of the sum of any of its
# subarrays modulo m. This means that you must find the sum of each subarray modulo , then print the maximum result
# of this modulo operation for any of the n.(n+1)/2 possible subarrays.
#
# Input Format
# The first line contains an integer q, denoting the number of queries to perform.
# Each query is described over two lines:
# The first line contains two space-separated integers describing the respective n (the array length) and
# m (the right operand for the modulo operations) values for the query.
# The second line contains n space-separated integers describing the respective elements of array
# A = a0, a1,...., an-1 for that query.
#
# Constraints
# 2 <= n <= 10^5
# 1 <= m <= 10^14
# 1 <= ai <= 10^18
# 2 <= the sum of n over all test cases <= 5 x 10^5
#
# Output Format
# For each query, print the maximum value of subarray sum % m on a new line.
#
# Sample Input
# 1
# 5 7
# 3 3 9 9 5
#
# Sample Output
# 6
#
# Explanation
# The subarrays of array A = [3,3,9,9,5] and their respective sums modulo m=7 are ranked in order of length
# and sum in the following list:
# 1.
# [9] => 9 % 7 = 2 and [9] -> 9 % 7 = 2
# [3] => 3 % 7 = 3 and [3] -> 3 % 7 = 3
# [5] => 5 % 7 = 5
#
# 2.
# [9,5] => 14 % 7 = 0
# [9,9] => 18 % 7 = 4
# [3,9] => 12 % 7 = 5
# [3,3] => 6 % 7 = 6
#
# 3.
# [3,9,9] => 21 % 7 = 0
# [3,3,9] => 15 % 7 = 1
# [9,9,5] => 23 % 7 = 2
#
# 4.
# [3,3,9,9] = 24 % 7 = 3
# [3,9,9,5] = 26 % 7 = 5
#
# 5.
# [3,3,9,9,5] = 29 % 7 = 1
#
# As you can see, the maximum value for subarray sum % 7 for any subarray is 6, so we print 6 on a new line.
#
#######################################################################################################################
|
f5e8aad949f66be0727a8b4fad9f8e913b1566f5 | OnildoNeto/Aplica-oEscolaVers-o | /DDL.py | 3,032 | 3.78125 | 4 | import sqlite3
conn = sqlite3.connect('EscolaApp_versao2.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE tb_escola(
id_escola INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(45) NOT NULL,
FK_id_endereco INTEGER NOT NULL,
FK_id_campus INTEGER NOT NULL,
FOREIGN KEY(fk_id_endereco) REFERENCES tb_endereco (idtb_endereco),
FOREIGN KEY(fk_id_campus) REFERENCES tb_campus (id_campus)
);
""")
print('Tabela tb_escola foi criada.')
cursor.execute("""
CREATE TABLE tb_aluno(
id_aluno INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(45) NOT NULL,
matricula VARCHAR(12) NOT NULL,
cpf VARCHAR(11) NOT NULL,
nascimento DATE NOT NULL,
FK_id_endereco INTEGER NOT NULL,
FK_id_curso INTEGER NOT NULL,
FOREIGN KEY(fk_id_endereco) REFERENCES tb_endereco (id_endereco),
FOREIGN KEY(fk_id_curso) REFERENCES tb_curso (id_curso)
);
""")
print('Tabela tb_aluno foi criada.')
cursor.execute("""
CREATE TABLE tb_curso(
id_curso INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(45) NOT NULL,
FK_id_turno INTEGER NOT NULL,
FOREIGN KEY(fk_id_turno) REFERENCES tb_turno (id_turno)
);
""")
print('Tabela tb_curso foi criada.')
cursor.execute("""
CREATE TABLE tb_turma(
id_turma INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(45) NOT NULL,
FK_id_curso INTEGER NOT NULL,
FOREIGN KEY(fk_id_curso) REFERENCES tb_curso (id_curso)
);
""")
print('Tabela tb_turma foi criada.')
cursor.execute("""
CREATE TABLE tb_disciplina(
id_disciplina INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(45) NOT NULL,
FK_id_professor INTEGER NOT NULL,
FOREIGN KEY(fk_id_professor) REFERENCES tb_professor (id_professor)
);
""")
print('Tabela tb_disciplina foi criada.')
cursor.execute("""
CREATE TABLE tb_endereco(
id_endereco INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
logradouro VARCHAR(70)NOT NULL,
complemento VARCHAR(45)NOT NULL,
bairro VARCHAR(45)NOT NULL,
cep VARCHAR(8)NOT NULL,
numero INTEGER NOT NULL
);
""")
print('Tabela tb_endereco foi criada.')
cursor.execute("""
CREATE TABLE tb_campus(
id_campus INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
sigla VARCHAR(3) NOT NULL,
cidade VARCHAR(45) NOT NULL
);
""")
print('Tabela tb_campus foi criada.')
cursor.execute("""
CREATE TABLE tb_professor(
id_professor INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(45) NOT NULL,
FK_id_endereco INT NOT NULL,
FOREIGN KEY(fk_id_endereco) REFERENCES tb_endereco (id_endereco)
);
""")
print('Tabela tb_professor foi criada.')
cursor.execute("""
CREATE TABLE tb_turno(
id_turno INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(10) NOT NULL
);
""")
print('Tabela tb_turno foi criada.')
|
3819d8be9271675530111bb3c4d6246ed166ea5f | deyukong/pycharm-practice | /practice/calculate prime.py | 673 | 4.0625 | 4 |
def countPrimes(n):
lst = list(range(4, n))
# print(lst)
nonprime = set()
if n in range(0, 3):
return 0
if n == 3:
return 1
for value in lst:
# print("the value is:",value)
i = 2
while i * i <= value:
# print("i is:",i)
if value % i == 0:
nonprime.add(value)
# print("it is not prime")
i += 1
# print(nonprime)
return (n-len(nonprime)-2)
# i = 0
# for value in lst:
# if value in nonprime:
# i += 1
#
# return((n-i)-2)
# # print("number of primes", (n-i)-2)
print(countPrimes(10000)) |
6df51a881da4331eac2441cfb5daa1534f41813b | odedf23232/Author-Verification-and-Determination-System | /document.py | 5,347 | 3.5 | 4 | import string
from typing import List, Tuple
from scipy import sparse
from scipy.sparse import csr_matrix
from sklearn.feature_extraction.text import TfidfVectorizer
def _get_stop_words() -> List[str]:
"""
Loads stop words for using when transforming.
:return: list of stop words.
"""
# In "A Time Series Model of the Writing Process.pdf" page 8,
# it is specified that stop words from the following link were used:
# from https://www.ranks.nl/stopwords -> Long Stopword List
with open('stopwords.txt') as f:
return f.read().split('\n')
# a global stop_words variable, so that we don't load it each time
_stop_words = _get_stop_words()
def _text_process(text: str) -> List[str]:
"""
Processor for finding words the interest us in each document.
:param text: document text
:return: list of words/terms which interest us when transforming
"""
# Removal of Punctuation Marks
text = ''.join([char for char in text if char not in string.punctuation])
# Removal of anything that is not a stop word
# Any uppercase characters in the texts involved in the experiments are con-
# verted to the corresponding lowercase characters, and all other characters are
# unchanged
# - from "A Time Series Model of the Writing Process.pdf" page 8
text = text.lower()
# In this paper, a Vector Space Model is built, resting upon the content-free
# words and the stop words. The joint occurrences of the content-free words can
# provide valuable stylistic evidence for authorship
# - from "A Time Series Model of the Writing Process.pdf" page 8
return [word for word in text.split() if word in _stop_words]
def _transform(texts: List[str], chunk_size: int) -> Tuple[List[csr_matrix], List[str]]:
"""
Transforms all the documents into vector space models.
The transformation shows each document as a collection of chunks of a given size,
where each chunk is a vector-space model. The chunk models are Term-Frequency
Inverse-Document-Frequency vectors, showing the frequency of term usages in the document.
Most terms from the document are stripped, such that only stop-words and content-free
terms remain, since they can be used to describe a writing style.
:param texts: list of documents to transform
:param chunk_size: length of each chunk, in character count
:return: a tuple holding:
- list of the transformed documents
- list of terms in the TF-IDF vectors
"""
# What we do here is a bit premature, as the chunks are needed specifically
# for use in author verification algorithm which require dividing the documents
# into chunks.
# Instead of doing this each time, and then having to transform the chunks
# into vector space models, which will take some work...
# We just do this here once for all the documents, and represent
# each as a csr_matrix, where each row of the matrix is a vector representing
# a chunk
# Divide each documents into chunks
chunks = [[text[i:i + chunk_size] for i in range(0, len(text), chunk_size)]
for text in texts]
# Transform each document chunks using TFIDF
# We use the raw texts from the documents as the "training data" for the
# vectorizer. From those texts, we extract terms using `_text_process`,
# and map the frequency of those terms in each chunk.
transformer = TfidfVectorizer(use_idf=False, analyzer=_text_process).fit(texts)
chunks = [transformer.transform(doc_chunks) for doc_chunks in chunks]
return chunks, transformer.get_feature_names()
def load_documents_from_dataset(chunk_size: int, dataset: Tuple[List[str], List[str]]) \
-> Tuple[List[str], List[csr_matrix], List[str]]:
"""
Loads and transforms a dataset into documents for the algorithm
Each document in the dataset is divided into chunks of a constant size,
and each chunk is transformed into a vector space model which is used to
describe the writing style used.
:param chunk_size: length of each chunk, in character count
:param dataset: a tuple of list of authors to list of documents, where `authors[i] is author of documents[i]`.
:return: a tuple holding:
- list of authors from the dataset
- list of transformed documents, where `authors[i] is author of documents[i]`,
and each document is made up of several chunks of a given size
- list of words which are described in the model of each documents chunk
"""
authors, texts = dataset
chunks, feature_names = _transform(texts, chunk_size)
return authors, chunks, feature_names
def merge_documents(document1_chunks: csr_matrix, document2_chunks: csr_matrix) -> csr_matrix:
"""
Merges two documents into one matrix, where the resulting matrix
will contain the rows of document2 bellow the rows of document1, such
that the length of the resulting matrix is `len(document1) + len(document2)`.
:param document1_chunks: a vector space model representations of all chunks in the first document
:param document2_chunks: a vector space model representations of all chunks in the second document
:return: a new document matrix
"""
return sparse.vstack((document1_chunks, document2_chunks), format='csr')
|
5e2dd354b7bbd8b1be5576aface1c16686d93910 | ddowns-afk/python | /exercise_8.py | 1,099 | 4.09375 | 4 | #quit = input('Type "enter" to quit: ')
#while quit != "enter":
# quit = input('Type "enter" to quit: ')
import sys
player_1 = input('Player 1 enter your name: ')
player_2 = input('Player 2 enter your name: ')
player_1_input = input(player_1 + ' choose rock, paper, or scissor: ')
player_2_input = input(player_2 + ' choose rock, paper, or scissor: ')
def compare(u1,u2):
if u1 == u2:
return('Its a tie!')
elif u1 == 'rock' and u2 == 'scissors':
return(player_1 + ' wins!')
elif u1 == 'rock' and u2 == 'paper':
return(player_2 + ' wins!')
elif u1 == 'scissors' and u2 == 'paper':
return(player_1 + ' wins!')
elif u1 == 'scissors' and u2 == 'rock':
return(player_2 + ' wins!')
elif u1 == 'paper' and u2 == 'rock':
return(player_1 + ' wins!')
elif u1 == 'paper' and u2 == 'scissors':
return(player_2 + ' wins!')
else:
return("Invalid input, you have not entered rock, paper, or scissors! Try again.")
sys.exit()
print(compare(player_1_input, player_2_input)) |
7247b8ca499ad0a0d436ca35c2ee07c3a3bdbec6 | BE-Project-Catastrophic-Forgetting/brain-inspired-replay | /models/fc/excitability_modules.py | 4,010 | 3.5 | 4 | import math
import torch
from torch import nn
from torch.nn.parameter import Parameter
def linearExcitability(input, weight, excitability=None, bias=None):
"""
Applies a linear transformation to the incoming data: :math:`y = c(xA^T) + b`.
Shape:
- input: :math:`(N, *, in\_features)`
- weight: :math:`(out\_features, in\_features)`
- excitability: :math:`(out\_features)`
- bias: :math:`(out\_features)`
- output: :math:`(N, *, out\_features)`
(NOTE: `*` means any number of additional dimensions)
"""
if excitability is not None:
output = input.matmul(weight.t()) * excitability
else:
output = input.matmul(weight.t())
if bias is not None:
output += bias
return output
class LinearExcitability(nn.Module):
'''Applies a linear transformation to the incoming data: :math:`y = c(Ax) + b`
Args:
in_features: size of each input sample
out_features: size of each output sample
bias: if 'False', layer will not learn an additive bias-parameter (DEFAULT=True)
excitability: if 'False', layer will not learn a multiplicative excitability-parameter (DEFAULT=True)
Shape:
- input: :math:`(N, *, in\_features)` where `*` means any number of additional dimensions
- output: :math:`(N, *, out\_features)` where all but the last dimension are the same shape as the input.
Attributes:
weight: the learnable weights of the module of shape (out_features x in_features)
excitability: the learnable multiplication terms (out_features)
bias: the learnable bias of the module of shape (out_features)
excit_buffer: fixed multiplication variable (out_features)
Examples::
>>> m = LinearExcitability(20, 30)
>>> input = autograd.Variable(torch.randn(128, 20))
>>> output = m(input)
>>> print(output.size())
'''
def __init__(self, in_features, out_features, bias=True, excitability=False, excit_buffer=False):
super(LinearExcitability, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.Tensor(out_features, in_features))
if excitability:
self.excitability = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('excitability', None)
if bias:
self.bias = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
if excit_buffer:
buffer = torch.Tensor(out_features).uniform_(1,1)
self.register_buffer("excit_buffer", buffer)
else:
self.register_buffer("excit_buffer", None)
self.reset_parameters()
def reset_parameters(self):
'''Modifies the parameters "in-place" to reset them at appropriate initialization values'''
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.excitability is not None:
self.excitability.data.uniform_(1, 1)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input):
'''Running this model's forward step requires/returns:
INPUT: -[input]: [batch_size]x[...]x[in_features]
OUTPUT: -[output]: [batch_size]x[...]x[hidden_features]'''
if self.excit_buffer is None:
excitability = self.excitability
elif self.excitability is None:
excitability = self.excit_buffer
else:
excitability = self.excitability*self.excit_buffer
return linearExcitability(input, self.weight, excitability, self.bias)
def __repr__(self):
return self.__class__.__name__ + '(' \
+ 'in_features=' + str(self.in_features) \
+ ', out_features=' + str(self.out_features) + ')' |
5f582c6451bf0284b243a1a7b7612f3991221289 | pivoda-madalina/word-counter | /main.py | 880 | 4.03125 | 4 | def word_counter(file_name):
"""This function counts the words from file! \
Return's word dictionary."""
word_dict = {}
with open(file_name) as f:
for line in f:
for chr in (",", "!"):
line = line.replace(chr, "")
for word in line.split():
if word_dict.get(word):
word_dict[word] += 1
else:
word_dict[word] = 1
total = sum(word_dict.values())
word_dict.update(total=total)
return word_dict
def result(file_name, word_dict):
"""Writes the results to the file! """
with open(file_name, "w") as f:
total = word_dict.pop("total")
f.write(f"words: {word_dict}.\n")
f.write(f"total: {total}")
if __name__ == "__main__":
words = word_counter("example")
result("results", words)
print(words)
|
86c6c54ddb43e73e3fef652c6a81986d313286bf | zz-zhang/some_leetcode_question | /source code/151. Reverse Words in a String.py | 698 | 3.5625 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
words = s.split()
res1 = []
res2 = []
# print(words)
left, right = 0, len(words) - 1
while left <= right:
while len(words[left]) == 0 and left < right:
left += 1
while len(words[right]) == 0 and left < right:
right -= 1
res1.append(words[right])
if left != right:
res2.append(words[left])
left += 1
right -= 1
# print(res1, res2)
return ' '.join(res1+res2[::-1])
if __name__ == '__main__':
sol = Solution()
s = " "
print(sol.reverseWords(s)) |
9c14cc2a5dffd4ff7b4ecb35bafa98086cf81194 | SupratimH/learning-data-science | /statistics/concepts/regressionAnalysis.py | 3,016 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 02 2018
@author: Supratim Haldar
"""
import math
import summaryStatistics as ss
from functools import reduce
""" Calculate Correlation Coefficient, r = 1/(n-1)*Sum(Z_X * Z_Y) """
def CorrCoeff(data_X, data_Y):
nX, nY = len(data_X), len(data_Y)
assert nX == nY and nX != 0, "Length of X and Y datasets do not match!"
result = 0
sd_X, sd_Y = ss.StdDev(data_X), ss.StdDev(data_Y)
mean_X, mean_Y = ss.Mean(data_X), ss.Mean(data_Y)
for i in range(0, nX, 1):
result = result + (((data_X[i] - mean_X)/sd_X) * ((data_Y[i] - mean_Y)/sd_Y))
r = result/(nX - 1)
return r
""" Calculate Pearson Correlation Coefficient """
def PearsonCorrCoeff(data_X, data_Y):
nX, nY = len(data_X), len(data_Y)
assert nX == nY and nX != 0, "Length of X and Y datasets do not match!"
n = nX
# Traditional implementation with for loop
# sum_X = sum_Y = sum_XY = sum_X2 = sum_Y2 = 0
# for i in range(0, n, 1):
# sum_X = sum_X + data_X[i]
# sum_Y = sum_Y + data_Y[i]
# sum_XY = sum_XY + (data_X[i] * data_Y[i])
# sum_X_sq = sum_X2 + pow(data_X[i], 2)
# sum_Y_sq = sum_Y2 + pow(data_Y[i], 2)
# Declarative style implementation
sum_X = reduce(lambda a,b: a+b, data_X)
sum_Y = reduce(lambda a,b: a+b, data_Y)
sum_XY = sum(map(lambda x,y: x*y, data_X, data_Y))
sum_X_sq = sum(map(lambda a: a**2, data_X))
sum_Y_sq = sum(map(lambda a: a**2, data_Y))
result_Num = float((n*sum_XY - sum_X*sum_Y))
result_Den = float(n*sum_X_sq - pow(sum_X, 2)) * float(n*sum_Y_sq - pow(sum_Y, 2))
result = float(result_Num)/float(math.sqrt(result_Den))
return result
""" Calculate Pearson Correlation Coefficient """
def SpearmanCorrCoeff(data_X, data_Y):
nX, nY = len(data_X), len(data_Y)
assert nX == nY and nX != 0, "Length of X and Y datasets do not match!"
data_X, data_Y = list(data_X), list(data_Y)
sorted_X, sorted_Y = sorted(data_X), sorted(data_Y)
rank_X = []
rank_Y = []
# Store the rank of data_X[rec_X] in rank_X
for rec_X in data_X:
rank_X.append(sorted_X.index(rec_X)+1)
# Store the rank of data_X[rec_X] in rank_X
for rec_Y in data_Y:
rank_Y.append(sorted_Y.index(rec_Y)+1)
mean_X, mean_Y = ss.Mean(rank_X), ss.Mean(rank_Y)
num = sum(map(lambda x, y: (x - mean_X)*(y - mean_Y), rank_X, rank_Y))
den = (sum(map(lambda x: pow((x - mean_X), 2), rank_X))
* sum(map(lambda x: pow((x - mean_X), 2), rank_X)))
den = math.sqrt(float(den))
return (float(num)/float(den))
""" Calculate Covariance """
def Covariance(data_X, data_Y):
nX, nY = len(data_X), len(data_Y)
assert nX == nY and nX != 0, "Length of X and Y datasets do not match!"
n = nX
mean_X, mean_Y = ss.Mean(data_X), ss.Mean(data_Y)
sum_XY_dev = sum(map(lambda x, y: (x - mean_X)*(y - mean_Y), data_X, data_Y))
cov = float(sum_XY_dev/n)
return cov
|
01c1d0b2074f85a066bae10cbdea096962c16b64 | Proffett/testsPY | /57.py | 56 | 3.546875 | 4 | str = input()
space = str.replace('@', '')
print(space)
|
5287a37129630dddb9ee0dccc6a9cc223584cfc5 | Aasthaengg/IBMdataset | /Python_codes/p03210/s600936103.py | 66 | 3.65625 | 4 | age = int(input())
print("YES") if age in (3,5,7) else print("NO") |
86e5da92b6fbcc9cba0147edd3b43d3fd4a5a391 | Schrodingfa/PY3_TRAINING | /day6/func_demo/ex13.py | 382 | 3.9375 | 4 | # Author:jxy
# day3 ex1 升级版
# 定义根据月份判断季节的方法
def season(month):
if month < 1 or month > 12:
return 'invalid parameter'
if month <= 3:
return 'spring'
if month <= 6:
return 'summer'
if month <= 9:
return 'autumn'
return 'winter'
m = int(input('please input a mouth:'))
res = season(m)
print(res)
|
5edce2bc9c3fde39962da9d16adfb5a28b747630 | ZhengZixiang/interview_algorithm_python | /jianzhi/09.斐波那契数列.py | 408 | 3.734375 | 4 | # 输入一个整数 n ,求斐波那契数列的第 n 项。
#
# 假定从0开始,第0项为0。(n<=39)
#
# 样例
# 输入整数 n=5
#
# 返回 5
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return n
a, b = 0, 1
for i in range(2, n + 1):
a, b = b, a + b
return b |
fed713acac0b749e6388f42b1626a66acabdb9df | jangwoni79/Programming-Python- | /VIII. 파일 처리/read_text_FILE.py | 267 | 3.625 | 4 | # f = open("file.txt","r")
#
# text = f.read()
# print(text)
#
# f.close()
f = open("file.txt", "r", encoding = "utf8") #r : read text
text0 = f.readline() # \n까지 읽기
print(text0)
text1 = f.readline()
print(text1)
text2 = f.readline()
print(text2)
f.close() |
637dddcecf8d94694ca72ef9b2e3c39c5290db06 | Alex-Au1/Matrix_Calculator | /string.py | 655 | 4.125 | 4 | from typing import Dict, List
# word_replace(str, word_dict) Replaces every instance of the
# keys from 'word_dict' that are found in 'str' with its
# corresponding value in 'word_dict'
def word_replace(str: str, word_dict: Dict[str, str]) -> str:
for w in word_dict:
replace_word = word_dict[w]
str = str.replace(w, replace_word)
return str
# format_lst(lst) Formats all the elements in 'lst' into a
# single string
def format_lst(lst: List[str]) -> str:
lst_len = len(lst)
result_str = ""
for i in range(lst_len):
if (not i):
result_str += lst[i]
else:
result_str += f", {lst[i]}"
return result_str
|
5f621cfcba22794060c52eb473ee25be8fd2026e | farh33n/building-restAPI-for-MLmodel-using-flask | /model.py | 378 | 3.640625 | 4 | from sklearn.linear_model import LinearRegression
class Model(object):
def __init__(self):
self.reg = LinearRegression()
def train(self, X, y):
"""Trains the regression model
"""
self.reg.fit(X, y)
def predict(self, X):
"""Returns the predicted value
"""
y_pred = self.reg.predict(X)
return y_pred
|
41dcc07e49e88815684d4646620ae1ca50b19404 | gksheethalkumar/Python_Practice | /BSTree-prac.py | 971 | 3.9375 | 4 | class node():
def __init__(self,data = None):
self.data = data
self.rightval = None
self.leftval = None
def insert_tree(self,data = None):
newval = node(data)
if self.data:
if data < self.data:
if self.leftval is None:
self.leftval = newval
else:
self.leftval.insert_tree(data)
elif data > self.data:
if self.rightval is None:
self.rightval = newval
else:
self.rightval.insert_tree(data)
else:
self.data = data
def print_tree(self):
if self.leftval:
self.leftval.print_tree()
print(self.data)
if self.rightval:
self.rightval.print_tree()
root = node()
root.insert_tree(6)
root.insert_tree(2)
root.insert_tree(4)
root.insert_tree(7)
root.insert_tree(1)
root.print_tree()
|
acebab89ec3945473d19be6650d7ff40b08762bb | LPIX-11/ChessPyGame | /playChess.py | 9,003 | 3.546875 | 4 | # Importing pygame library for game environement building
import pygame
import os
from pygame.locals import *
# Importing the chess board
from board.chessBoard import Board
from board.move import Move
from ai.minimax import Minimax
# Initializing the environment
os.environ['SDL_VIDEO_CENTERED'] = '1' # You have to call this before pygame.init()
pygame.init()
info = pygame.display.Info() # You have to call this before pygame.display.set_mode()
screen_width,screen_height = info.current_w,info.current_h
# Setting up the game frame layout
gameDisplay = pygame.display.set_mode((800, 800), RESIZABLE)
pygame.display.set_caption("Johnson Chess")
# Keeping track of our game
clock = pygame.time.Clock()
# Initializing the chess board
chessBoard = Board()
# Creating the board
chessBoard.create_board()
# Printing the board on console
chessBoard.print_board()
# Keeping track of tiles and pieces
all_tiles = []
all_pieces = []
## Experiment ##
current_player = chessBoard.current_player
## End ##
# Drawing the chess game on screen
############################
def createSqParams():
allSqRanges = []
xMin = 0
xMax = 100
yMin = 0
yMax = 100
for _ in range(8):
for _ in range(8):
allSqRanges.append([xMin, xMax, yMin, yMax])
xMin += 100
xMax += 100
xMin = 0
xMax = 100
yMin += 100
yMax += 100
return allSqRanges
def squares(x, y, w, h, color):
pygame.draw.rect(gameDisplay, color, [x, y, w, h])
all_tiles.append([color, [x, y, w, h]])
def draw_chess_pieces():
x_pos = 0
y_pos = 0
color = 0
width = 100
height = 100
black = (99, 99, 89)
white = (210, 203, 121)
number_of_tile = 0
for _ in range(8):
for _ in range(8):
if color % 2 == 0:
squares(x_pos, y_pos, width, height, white)
else:
squares(x_pos, y_pos, width, height, black)
if not chessBoard.game_tiles[number_of_tile].piece_on_tile.to_string() == '-':
img = pygame.image.load('./ChessArt/'
+ chessBoard.game_tiles[number_of_tile].piece_on_tile.alliance[0]
+ chessBoard.game_tiles[number_of_tile].piece_on_tile.to_string().upper()
+ '.png')
# Reformat the image by 100 x 100
img = pygame.transform.scale(img, (90, 90))
all_pieces.append([img, [x_pos, y_pos], chessBoard.game_tiles[number_of_tile].piece_on_tile])
x_pos += 100
color += 1
number_of_tile += 1
# Ended the first raw
color += 1
x_pos = 0
y_pos += 100
## Experiment ##
def updateChessPieces():
xpos = 0
ypos = 0
number = 0
newPieces = []
for _ in range(8):
for _ in range(8):
if not chessBoard.game_tiles[number].piece_on_tile.to_string() == "-":
img = pygame.image.load(
"./ChessArt/" + chessBoard.game_tiles[number].piece_on_tile.alliance[0].upper() + chessBoard.game_tiles[
number].piece_on_tile.to_string().upper() + ".png")
img = pygame.transform.scale(img, (100, 100))
newPieces.append([img, [xpos, ypos], chessBoard.game_tiles[number].piece_on_tile])
xpos += 100
number += 1
xpos = 0
ypos += 100
return newPieces
## End ##
############################
#### Experiment ###
selectedImage = None
selectedLegals = None
resetColors = []
## End ##
draw_chess_pieces()
allSqParams = createSqParams()
quitGame = False
while not quitGame:
# Every frame that're going to be displayed
for event in pygame.event.get():
# Quiting the game
if event.type == pygame.QUIT:
quitGame = True
pygame.quit()
quit()
####################
# Experiment #
####################
if event.type == pygame.MOUSEBUTTONDOWN:
if selectedImage == None:
mx, my = pygame.mouse.get_pos()
for piece in range(len(all_pieces)):
if all_pieces[piece][2].alliance == current_player:
if all_pieces[piece][1][0] < mx < all_pieces[piece][1][0] + 100:
if all_pieces[piece][1][1] < my < all_pieces[piece][1][1] + 100:
selectedImage = piece
prevx = all_pieces[piece][1][0]
prevy = all_pieces[piece][1][1]
selectedLegals = all_pieces[selectedImage][2].calculate_legal_moves(chessBoard)
for legals in selectedLegals:
resetColors.append([legals, all_tiles[legals][0]])
if all_tiles[legals][0] == (66, 134, 244):
all_tiles[legals][0] = (135, 46, 40)
else:
pass
all_tiles[legals][0] = (183, 65, 56)
if event.type == pygame.MOUSEMOTION and selectedImage is not None:
mx, my = pygame.mouse.get_pos()
all_pieces[selectedImage][1][0] = mx - 50
all_pieces[selectedImage][1][1] = my - 50
# #TODO highlight all legal moves
# selectedLegals = all_pieces[selectedImage][2].calculate_legal_moves(chessBoard)
# for legals in selectedLegals:
# resetColors.append([legals ,allTiles[legals][0]])
#
if event.type == pygame.MOUSEBUTTONUP:
for resets in resetColors:
all_tiles[resets[0]][0] = resets[1]
try:
piece_moves = all_pieces[selectedImage][2].calculate_legal_moves(chessBoard)
legal = False
theMove = 0
for moveDes in piece_moves:
if allSqParams[moveDes][0] < all_pieces[selectedImage][1][0] + 50 < allSqParams[moveDes][1]:
if allSqParams[moveDes][2] < all_pieces[selectedImage][1][1] + 50 < allSqParams[moveDes][3]:
legal = True
theMove = moveDes
if legal == False:
all_pieces[selectedImage][1][0] = prevx
all_pieces[selectedImage][1][1] = prevy
else:
all_pieces[selectedImage][1][0] = allSqParams[theMove][0]
all_pieces[selectedImage][1][1] = allSqParams[theMove][2]
# TODO make it so it updates board
# TODO update moved piece's legal moves some how
# print(all_pieces[selectedImage][2])
# print(theMove)
# print(chessBoard)
thisMove = Move(chessBoard, all_pieces[selectedImage][2], theMove)
newBoard = thisMove.createNewBoard()
if not newBoard == False:
chessBoard = newBoard
# else:
# print(newBoard)
# chessBoard.printBoard()
# TODO update game pieces
newP = updateChessPieces()
all_pieces = newP
# print(len(newP))
# print(chessBoard.current_player)
current_player = newBoard.current_player
# TODO add logic that it is AI player
if current_player == "Black":
aiBoard = True
minimax = Minimax(chessBoard, 1)
aiBoard = minimax.getMove()
# aiBoard.printBoard()
# aiBoard.printBoard()
chessBoard = aiBoard
# TODO update game pieces
newP = updateChessPieces()
all_pieces = newP
current_player = aiBoard.current_player
# pygame.time.delay(1000)
# minimax.board.printBoard()
# all_pieces[selectedImage][2].position = theMove
# all_pieces[selectedImage][2].position = theMove
# print(all_pieces[selectedImage][2].position)
except:
pass
prevy = 0
prevx = 0
selectedImage = None
for info in all_tiles:
pygame.draw.rect(gameDisplay, info[0], info[1])
### End ####
# Placing pieces on board
for img in all_pieces:
gameDisplay.blit(img[0], img[1])
# Setting up the FPS
pygame.display.update()
# Every 60 Secs 60 Frame
clock.tick(60)
|
e8b8408bfa25e06286596c9d9457465f2d9479bf | Raghavendrajoshi45/python | /cel2fer.py | 173 | 4.09375 | 4 |
print("enter your num")
celsius = int(input())
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) |
38b386bb3c26567e1a9e0c82ae2dc857e9e7f5d2 | wanbibi/crawDemo | /interpy/4.1.py | 338 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
items = [2,4,5,6,7]
res = []
for i in items:
res.append(i*i)
print res
list1 = list(map(lambda x:x**x,items))
print list1
def jia(x):
return x+1
def jian(x):
return x-1
funcs = [jia,jian]
for i in range(1,5):
print i
value = map(lambda x:x+10, items)
print(list(value)) |
25e3d5239667030e4c8f95f23c355b96fb3440f1 | mrunmayichuri/reverse_engineering_little_fish | /fish_keygen.py | 499 | 3.671875 | 4 | #! /usr/bin/python
#Mrunmayi Churi
#Keygen for http://crackmes.de/users/vik3790/little_fish./
import sys
def generate_key(username):
C = 0
m = min(len(username),4)
for i in range (0, m):
C |= ord(username[i]) << (3 - i) * 8
C = (C*15 + 0xFF) & 0xFFFFFFFF
return "%X" %C
if __name__ == "__main__":
if len(sys.argv) !=2:
print "Use the following format: %s username" % sys.argv[0]
sys.exit(1)
print "The password is: %s" % generate_key(sys.argv[1])
|
33fe26368d6c12ce729f6256af2b670d971bdec6 | Somraz/Detect-ORF | /data_preprocessing.py | 1,641 | 3.59375 | 4 | #This code was used to pre-process textual features
import re
import csv
import os
import pandas as pd
from string import punctuation
from nltk import stem
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from ftfy import fix_text
stopwords = set(stopwords.words('english'))
stemmer = stem.SnowballStemmer('english')
lemmatizer = WordNetLemmatizer()
def lemmetization(text):
text = " ".join([stemmer.stem(word) for word in text.split()])
text = " ".join([lemmatizer.lemmatize(word, pos='v') for word in text.split()])
return text
def stop_words(text):
text=fix_text(text)
text=fix_encoding(text)
return text
def url1(text):
text = " ".join([word for word in text.split() if not word.startswith('url')])
return text
def clean_email(text):
text = re.sub(r'http\S+', ' ', text)
text = re.sub("\d+", " ", text)
text = text.replace('\n', ' ')
text = text.lower()
text = re.sub('\W+',' ',text )
text = re.sub(r"[,.;@#?!&$]+\ *", " ", text)
return text
#All the changes were made in this loop to perform preprocessing
with open('Tanisha_dataset.csv', 'r',encoding="latin1") as readFile:
reader = csv.reader(readFile)
lines = list(reader)
for data in lines:
if data[9]=='f':
data[9]=0;
else:
data[9]=1
#Writing back all the changes on the file
with open('dataset1.csv', 'w', newline='',encoding="latin1") as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
readFile.close()
writeFile.close()
|
1b26e38f72c8778b9645d8e26b3e89b0d1939f5d | maro199111/programming-fundamentals | /programming_lab/lab021019/anonimo5.py | 305 | 3.796875 | 4 | fl1 = float(input('Inserire il valore 1: '))
fl2 = float(input('Inserire il valore 2: '))
fl3 = float(input('Inserire il valore 3: '))
def x1x2(a,b,c):
x1 = -fl2 + ((fl2**2 - 4*fl1*fl3)**(1/2))/(2*a)
x2 = -fl2 - ((fl2**2 - 4*fl1*fl3)**(1/2))/(2*a)
return x1, x2
print(x1x2(fl1,fl2,fl3))
|
bfa12e0c452a9d4095c350de0095efbbf6003e83 | cassac/twitter_sentiment | /happiest_state.py | 2,028 | 3.828125 | 4 | """
ASSIGNMENT 1.5 FOR UOW COURSERA DATA SCI COURSE
SUMMARY: Calculates happiest state in continental
USA based on sentimental scores of tweets grouped
by states.
Run script:
python happiest_state.py AFINN-111.txt [tweets filename].txt
DATE: 2015/07/09
"""
import sys
import json
import re
from collections import defaultdict
from states_helper import states, timezone_list
def start_prompt():
print 'Program running...'
def get_points_dict(sent_file):
sent_content = sent_file.readlines()
scores = {}
sentiment_score = 0
for line in sent_content:
term, score = line.split("\t")
scores[term] = int(score)
return scores
def get_sent_score(terms_list, sent_dict):
sent_score = 0
for term in terms_list:
if term in sent_dict:
sent_score += sent_dict[term]
return float(sent_score) / len(terms_list)
def get_tweets(tweet_file, sent_dict):
sent_by_state = defaultdict(int)
tweet_content = tweet_file.readlines()
for tweet in tweet_content:
tweet = json.loads(tweet)
try:
if tweet['user']['time_zone'] in timezone_list and tweet['lang'] == 'en':
location = re.split('[\W\d]', tweet['user']['location'].lower())
for k, v in states.iteritems():
if k.lower() in location or v.lower() in location:
terms_list = tweet['text'].split()
if len(terms_list) > 0:
sent_score = get_sent_score(terms_list, sent_dict)
sent_by_state[k] += sent_score
except:
pass
return sent_by_state
def display_results(sent_scores):
happiest_state = ''
happiest_score = 0
for k, v in sent_scores.iteritems():
if v > happiest_score:
happiest_state = k
happiest_score = v
print 'The happiest state is', happiest_state,\
'with a score of', happiest_score
def finish_prompt():
print 'Program finished.'
def main():
start_prompt()
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
sent_dict = get_points_dict(sent_file)
sent_scores = get_tweets(tweet_file, sent_dict)
display_results(sent_scores)
finish_prompt()
if __name__ == '__main__':
main()
|
e21741bb453c28884f83eec112ff854c788963d1 | ShiXianzheng/python-learning | /Built_in_Functions.py | 11,962 | 4.15625 | 4 | """
author: xzshi19
date: 2019.08.28
Aim: learn python's built-in functions
"""
# abs(x) --return the absolute value of a number; a complex number --> it's magnitude
# all(iterable) --return true if all elements of the iterable are true(or empty)
def all(iterable):
for element in iterable:
if not element:
return False
return True
# any(iterable) --return true if any element of the iterable is true(empty --> false)
def any(iterable):
for element in iterable:
if element:
return True
return False
# ascii(object) --return a string containing a printable representation of an object
# bin(x) --convert an integer number to a binary string prefixed with '0b'
# class bool([x]) --return a boolean value
# breakpoint(*args, **kws) --drop you into the debugger at the call site(sys.breakpointhook(), ignore args and kws)
# class bytearray([source[, encoding[, errors]]]) --return a new array of bytes
# class bytes([source[, encoding[, errors]]]) --return a new 'bytes' object(an immutable sequence)
# callable(object) --return true if the object argument appears callable; Note that classes are callable
# (calling a class returns a new instance); instances are callable if their class has a __call__() method.
# chr(i) --return the string representing a character
# @classmethod --transform a method into a class method
# A class method receives the class as implicit first argument, just like an instance method receives the instance.
# To declare a class method, use this idiom:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
# compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) --compile the source into a code or AST object
# class complex([real[, imag]]) --return a complex number with the value real+ imag*1j or
# convert a string or number to a complex number
# When converting from a string, the string must not contain whitespace around the central + or - operator.
# For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.
# delattr(object, name) --delete the named attribute(--> del object.name)
# class dice(**kwarg) --create a new dictionary
# dir([object]) --Without arguments, return the list of names in the current local scope.
# With an argument, attempt to return a list of valid attributes for that object
"""
>>> import struct
>>> dir() # show the names in the module namespace # doctest: +SKIP
['__builtins__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module # doctest: +SKIP
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
'__initializing__', '__loader__', '__name__', '__package__',
'_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
"""
# divmod(a, b) --Take two (non complex) numbers as arguments and
# return a pair of numbers consisting of their quotient and remainder when using integer division.
# With mixed operand types, the rules for binary arithmetic operators apply.
# For integers, the result is the same as (a // b, a % b).
# For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that.
# In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).
# enumerate(iterable, start=0) --return a enumerate object(start, value)...
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
# eval(expression, globals=None, locals=None) --The expression argument is parsed and evaluated as a Python expression
# (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.
# exec(object[, globals[, locals]]) -- supports dynamic execution of Python code
# filter(function, iterable) --(item for item in iterable if function(item))
# class float([x]) --return a floating point number constructed from a number of string x
# sign ::= "+" | "-"
# infinity ::= "Infinity" | "inf"
# nan ::= "nan"
# numeric_value ::= floatnumber | infinity | nan
# numeric_string ::= [sign] numeric_value
"""
>>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
"""
# format(value[, format_spec]) --Convert a value to a “formatted” representation, as controlled by format_spec
# class frozenset([iterable]) --return a new frozenset object, elements taken from iterable.
# getattr(object, name[, default]) --return the value of the named attribute of object(--> object.name)
# globals() --return a dictionary representing the current global symbol table
# hasattr(object, name) --the result is true if the string is the name of one of the object's attributes
# hash(object) --return the hash value of the object.hash values are integers.
# help([object])
# hex(x) --convert an integer number to a lowercase hexadecimal string prefixed with '0x'
"""
>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')
"""
# id(object) --return the 'identity' of an object
# input([prompt]) --If the prompt argument is present, it is written to standard output without a trailing newline.
# The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
# When EOF is read, EOFError is raised
"""
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
"""
# class int([x]) --Return an integer object constructed from a number or string x, or return 0 if no arguments are given
# isinstance(object, classinfo) --Return true if the object argument is an instance of the classinfo argument,
# or of a (direct, indirect or virtual) subclass thereof
# issubclass(class, classinfo) --Return true if class is a subclass (direct, indirect or virtual) of classinfo.
# iter(object[, sentinel]) --return an iterator object
from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), b''):
process_block(block)
# len(s) --return the length (the number of items) of an object.
# class list([iterable])
# locals() --update and return a dictionary representing the current local symbol table
# map(function, iterable, ...) --return an iterator that applies function to every item of iterable, yielding the results
# max(iterable, *[, key, default]) max(arg1, arg2, *arg[, key]) --Return the largest item in an iterable or the largest of two or more arguments.
# memoryview(obj) --Return a “memory view” object created from the given argument
# min(iterable, *[, key, default])
# next(iterator[, default]) --Retrieve the next item from the iterator by calling its __next__() method
# class object --Return a new featureless object
# object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.
# oct(x) --convert an integer number to an octal string prefixed with '0o'
# open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closed=True, opener=None)
# Open file and return a corresponding file object
# 'r' open for reading (default)
# 'w' open for writing, truncating the file first
# 'x' open for exclusive creation, failing if the file already exists
# 'a' open for writing, appending to the end of the file if it exists
# 'b' binary mode
# 't' text mode (default)
# '+' open a disk file for updating (reading and writing)
"""
>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
... return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
... print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd) # don't leak a file descriptor
"""
# ord(c) --Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.
# inverse of chr()
# pow(x, y[, z]) --return x to the power of y, modulo z(pow(x, y) % z)
# print(*object, sep='', end='\n', file=sys.stdout, flush=False) --Print objects to the text stream file
# class property(fget=None, fset=None, fdel=None, doc=None) --return a property attribute
"""
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
class Parrot:
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"Get the current voltage."
return self._voltage
class C:
def __init__(self):
self._x = None
@property
def x(self):
"I'm the 'x' property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
"""
# range(start, stop[, step]) --an immutable sequence type
# repr(object) --Return a string containing a printable representation of an object
# reversed(seq) --return a reverse iterator
# round(number[, ndigits]) --Return number rounded to ndigits precision after the decimal point
# class set([iterable]) --return a new set object, optionally with elements taken from iterable.
# setattr(object, name, value) --setattr(x, 'foobar', 123) is equivalent to x.foobar = 123
# class slice(start, stop[, step]) --Return a slice object representing the set of indices specified by range(start, stop, step)
# sorted(iterable, *, key=None, reverse=False) --Return a new sorted list from the items in iterable.
# staticmethod --Transform a method into a static method.
"""
A static method does not receive an implicit first argument.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
class C:
builtin_open = staticmethod(open)
"""
# class str(object=b'', encoding='utf-8', errors='strict') --Return a str version of object
# sum(iterable[, start]) --Sums start and the items of an iterable from left to right and returns the total
# super([type[, object-or-type]]) --Return a proxy object that delegates method calls to a parent or sibling class of type
# tuple([iterable]) -- tuple is actually an immutable sequence type
# class type(object) type(name, bases, dict) -- return the type of an object
# vars([object]) --Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.
# zip(*iterables) --Make an iterator that aggregates elements from each of the iterables.
"""
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
zip() in conjunction with the * operator can be used to unzip a list:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
"""
# __import__(name, globals=None, locals=None, fromlist=(), level=0)
|
42cbf660b2edacb5f21e818c32e725825e78bbc3 | mscwdesign/ppeprojetcs | /debuggando_com_pdb.py | 300 | 3.78125 | 4 | """
Debuggando com PDB
PDB -> Python Debugger
# Exemplo com PyCharm
def dividir(a, b):
try:
return int(a) / int(b)
except ValueError:
return ('Valor Incorreto')
except ZeroDivisionError:
return 'Não é possivel dividir por zero'
print(dividir(4, 7))
"""
|
7bd9650d367076410e57b118277d26612946b7b0 | Tech-at-DU/CS-1.0-Introduction-To-Programming | /T002-Working-with-Variables/assets/T2-CheckPlease.py | 852 | 4.28125 | 4 | # Check Please!
# Step 1: Assign the integer value 94102 to a variable named zip in the console.
# Step 2: Check the type of the variable zip by entering the line type(zip) in the console.
# Step 3: Assign the string value "San Francisco" to a variable named city. Remember to surround your string value with either single or double quotes! Then check the type of your new variable.
# Step 4: Assign the value 3.60 to a variable named avg_coffee_cost. Then check the type of your new variable.
# Step 5: The price of coffee in SF is $0.25 above the national average. Assign the boolean value True to a variable named above_average. Then check the type of your new variable.
# Step 6: What happens if you don't follow some of the rules of Python's data types? Try creating a string without using quotes or a boolean without capitalizing the value. |
2cc8e7e7918ec620a9969c1fa9f7df24e3605d28 | Hungs20/INT3117 | /phanhoach.py | 707 | 3.546875 | 4 | import unittest
def get_price(weight):
if weight > 0.0 and weight < 5.0:
return 5
elif weight >= 5.0 and weight < 10.0:
return 10
elif weight >= 10.0 and weight < 30.0:
return 15
else:
return "Không hợp lệ"
class TestMethods(unittest.TestCase):
def test1(self):
self.assertEqual(get_price(3), 5)
def test2(self):
self.assertEqual(get_price(7), 10)
def test3(self):
self.assertEqual(get_price(12), 15)
def test4(self):
self.assertEqual(get_price(-5), "Không hợp lệ")
def test5(self):
self.assertEqual(get_price(35), "Không hợp lệ")
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.