blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
46c297698e33dd11c58bb2d67ad11775fddfa3e1 | Jacob-Sunny/cognixia-python | /function.py | 723 | 4 | 4 | def weird_arithmetic(x,y,z): #function definition
print((x**x + y**z)//z) #code block
weird_arithmetic(5,6,7) #function call
def myFunction(greeting,name):
print(greeting + " " + name)
myFunction("Hello","Jacob")
def returnFunction(x):
return x
someNumber = returnFunction(10)
print(someNumber)
print("**********Area Of Circle**************")
#AREA OF CIRCLE
def areaFunction(radius):
PI = 3.14
return PI*(radius**2)
r = 4
AreaOFCircle = areaFunction(4)
print(AreaOFCircle)
print("***********Volume Of Cylinder******************")
#vOLUME OF CYLINDER
def volumeFunction(radius,height):
PI = 3.14
return PI*radius**2*height
h = 10
VolumeOFCyl = volumeFunction(r,h)
print(VolumeOFCyl)
|
a1aebb502daca30d90630b996592c76fa5a3e5c8 | mwrouse/Python | /Design Exercises/dd58.py | 3,732 | 3.71875 | 4 | """
Program......: dd58.py
Author.......: Michael Rouse
Date.........: 3/7/14
Description..: Modify dd57 by adding a rolling counter for number of problems correct and attempted
"""
from tkinter import *
from random import randint
# Class for GUI
class Application(Frame):
""" GUI Application """
def __init__(self, master):
# Initialize the frame
super(Application, self).__init__(master)
self.grid()
# Variables for the Problem
self.i_number1 = 0
self.i_number2 = 0
self.s_answer = "0"
self.s_userAnswer = "0"
# Variables for problem counter
self.i_totalCorrect = 0
self.i_totalWrong = 0
# Create Widgets
self.create_widgets()
# Generate first problem
self.new_problem()
def create_widgets(self):
""" Create Buttons, Labels, etc... """
# Problem Label
self.lbl_problem = Label(self, text=str(self.i_number1) + " + " + str(self.i_number2))
self.lbl_problem.grid(column=13, row=1, pady=10, columnspan=5, rowspan=5)
# Answer Label
self.lbl_answer = Label(self, text="Your Answer:")
self.lbl_answer.grid(column=7, row=6, columnspan=10, sticky=W)
# Answer Entry Box
self.ent_answer = Entry(self)
self.ent_answer.grid(column=17, row=6, columnspan=10)
# Submit Button
self.btn_submit = Button(self, text="Submit", command=self.check_answer)
self.btn_submit.grid(column=13, row=7, pady=10, columnspan=6, rowspan=3)
# Instructions Label
self.lbl_instructs = Label(self, text="Type your answer in the box and click \"Submit\"\nYour progress will be displayed below")
self.lbl_instructs.grid(column=1, row=11, padx=20, columnspan=30, rowspan=2)
# Total Correct Label
self.lbl_totalCorrect = Label(self, text="Correct: " + str(self.i_totalCorrect))
self.lbl_totalCorrect.grid(column=4, row=15, padx=0, pady=10, columnspan=10, rowspan=2, sticky=W)
# Total Wrong Label
self.lbl_totalWrong = Label(self, text="Incorrect: " + str(self.i_totalWrong))
self.lbl_totalWrong.grid(column=20, row=15, padx=0, pady=10, columnspan=10, rowspan=2, sticky=W)
def check_answer(self):
""" Compare user's answer to correct answer """
self.s_userAnswer = self.ent_answer.get()
if self.s_userAnswer == self.s_answer:
# Correct Answer
self.i_totalCorrect += 1
# Update label of total correct
self.lbl_totalCorrect.config(text="Correct: " + str(self.i_totalCorrect))
else:
# Wrong Answer
self.i_totalWrong += 1
# Update label of total wrong
self.lbl_totalWrong.config(text="Incorrect: " + str(self.i_totalWrong))
# Get a new problem
self.new_problem()
def new_problem(self):
""" Reset all for a new problem """
i_old_number1 = self.i_number1
i_old_number2 = self.i_number2
# Generate new numbers
while i_old_number1 == self.i_number1 and i_old_number2 == self.i_number2:
self.i_number1 = randint(0, 20)
self.i_number2 = randint(0, 20)
# Get the new answer
self.s_answer = str(self.i_number1 + self.i_number2)
# Reset the problem label
self.lbl_problem.config(text=str(self.i_number1) + " + " + str(self.i_number2))
# Reset the entry box
self.ent_answer.delete(0, END)
# Main
def main():
gui = Tk()
gui.title("Math Fun")
gui.geometry("300x200")
app = Application(gui)
gui.mainloop()
main()
|
faba524317f09830bbe0096d3a5bb5fa72887c33 | Xiaoke1982/StockPriceIndicator | /UserInterface/KNN.py | 1,346 | 4.15625 | 4 | import numpy as np
import pandas as pd
class KNNLearner(object):
"""
The class builds a KNN model object and provides a method
to make prediction on new input points.
"""
def __init__(self, k=3, verbose=False):
#initialize the k in KNN model.
self.k = k
def fit(self, dataX, dataY):
"""
This method stores the training X and Y respectively for the
use of the future prediction.
@param dataX: 2-d array
@param dataY: Series
"""
self.X = dataX
self.Y = dataY
def predict(self, points):
"""
The method takes a 2-d array as input and return a 1-d array
as the prediction based on the KNN algorithm.
@param points: must be 2d -array, if not reshape it
@return: 1d-array, predicted values
"""
#reshape points to 2-d array if points is 1-d array
if len(points.shape) == 1:
points = points.reshape(1, -1)
ans = np.array([])
for i in range(points.shape[0]):
xi = points[i]
dists = np.sqrt(((self.X - xi) ** 2).sum(axis=1))
idxes = dists.argsort()[:self.k]
pred_y = self.Y[idxes].mean()
ans = np.append(ans, [pred_y])
return ans |
f3aa43fe2ca55196597029d3fbc2b120642d4ed4 | gprender/challenges | /python/is_square.py | 622 | 4.15625 | 4 | # Library-less solution to check if an integer is a perfect square.
def is_square(n):
if (n < 0):
return False # real squares only
else:
return binary_search_is_square(0,n,n)
def binary_search_is_square(min,max,n):
# base case: [min,max] are adjacent integers
if max - min == 1:
return False
midpoint = (min + max) // 2
midpoint_squared = midpoint * midpoint
if midpoint_squared < n:
return binary_search_is_square(midpoint,max,n)
elif midpoint_squared > n:
return binary_search_is_square(min,midpoint,n)
else:
return True
|
00221c988d7320fdd7417a775f38c8967046de97 | julissel/Practice_with_Python | /venv/include/number_belongs_to_given_intervals.py | 267 | 4.1875 | 4 | """
There are given intervals {-10}and(-5, 3]and(8, 12)and[16, infinity).
The program returns 'True' if the number belongs to any of interval's part? and 'False' if it not.
"""
numb = int(input())
print((-10 == numb)or(-5 < numb <= 3)or(8 < numb < 12)or(numb >= 16))
|
144affbc9d46e349ee76697c0f3ef466faaa3b3f | AndreiBratkovski/CodeFights-Solutions | /Arcade/Intro/Island of Knowledge/isIPv4Address.py | 1,723 | 4.0625 | 4 | """
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
IPv4 addresses are represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1.
Given a string, find out if it satisfies the IPv4 address naming rules.
Example
For inputString = "172.16.254.1", the output should be
isIPv4Address(inputString) = true;
For inputString = "172.316.254.1", the output should be
isIPv4Address(inputString) = false.
316 is not in range [0, 255].
For inputString = ".254.255.0", the output should be
isIPv4Address(inputString) = false.
There is no first number.
"""
def isIPv4Address(inputString):
orderedNumList = []
if inputString[0] == ".":
return False
IPNum = ""
for i in inputString:
if i != ".":
IPNum += i
else:
if IPNum == "":
return False
else:
orderedNumList.append(IPNum)
IPNum = ""
try:
IPNum = int(IPNum)
orderedNumList.append(str(IPNum))
except ValueError:
return False
if len(orderedNumList) != 4:
return False
try:
orderedNumList = [int(x) for x in orderedNumList]
except ValueError:
return False
for i in orderedNumList:
if 0 <= i <= 255:
continue
else:
return False
return True
|
0d343da9ceffc69544e330c68dd54325fb3ecc23 | yyzhu0817/leetcode- | /链表/160.找出两个链表的交点.py | 1,226 | 3.703125 | 4 | '''
执行结果:
通过
显示详情
执行用时 :
164 ms
, 在所有 Python3 提交中击败了
84.53%
的用户
内存消耗 :
28.3 MB
, 在所有 Python3 提交中击败了
31.27%
的用户
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA, headB):
p1 = headA
p2 = headB
# 加入判空
if not p1 or not p2:
return None
while p1 != p2:
p1, p2 = p1.next, p2.next
# 如果没有交点,则p1,p2同时指向None
if not p1 and not p2:
return p1
if p1 is None: p1 = headB
if p2 is None: p2 = headA
return p1
# 建立节点A
a4 = ListNode(4)
a1 = ListNode(1)
a8 = ListNode(8)
a4_2 = ListNode(4)
a5_2 = ListNode(5)
# 建立节点B
a5 = ListNode(5)
a0 = ListNode(0)
a1_2 = ListNode(1)
# 将A和B节点连接,形成有交叉节点的链表
a4.next = a1
a1.next = a8
a8.next = a4_2
a4_2.next = a5_2
a5.next = a0
a0.next = a1_2
a1_2.next = a8
# 运行
headA = a4
headB = a5
s = Solution()
node = s.getIntersectionNode(headA, headB)
print(node.val)
|
5a126da44167cb3a08871d65a91f74dba1eedf13 | roboGOD/Python-Programs | /chaoticBribes.py | 2,220 | 4.03125 | 4 | #!/bin/python
'''
It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride!
There are a number of people queued up, and each person wears a sticker indicating their
initial position in the queue. Initial positions increment by 1 from 1 at the front of the line to n at the back.
Any person in the queue can bribe the person directly in front of them to swap positions.
If two people swap positions, they still wear the same sticker denoting their original
places in line. One person can bribe at most two others.
For example, if n=8 and 5 bribes 4, the queue will look like this: 1,2,3,5,4,6,7,8.
Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place
to get the queue into its current state!
'''
# Complete the minimumBribes function below.
def recursiveBribe(i,q):
inc = 0
j = q[i]
diff = j-i-1
if diff > 2:
return -1, q
elif diff > 0:
if q[i] > q[i+1]:
inc += 1
q[i] = q[i+1]
q[i+1] = j
else:
tInc, q = recursiveBribe(i+1,q)
if tInc == -1:
return -1,q
inc += tInc
if diff == 2:
if q[i+1] > q[i+2]:
inc += 1
temp = q[i+1]
q[i+1] = q[i+2]
q[i+2] = temp
else:
tInc, q = recursiveBribe(i+2,q)
if tInc == -1:
return -1,q
inc += tInc
elif diff == 0:
pass
return inc,q
def minimumBribes(q):
minB = 0
i = 0
while i < len(q):
j = q[i]
diff = j-i-1
if diff > 2:
print "Too chaotic"
break
elif diff == 0:
pass
else:
inc,q = recursiveBribe(i,q)
if inc == -1:
print "Too chaotic"
break
minB += inc
i -= 1
i += 1
if i == len(q):
print minB
if __name__ == '__main__':
t = int(raw_input())
for t_itr in xrange(t):
n = int(raw_input())
q = map(int, raw_input().rstrip().split())
minimumBribes(q)
|
2b1c22439248ac18ea315f80bb63424376c74c8d | hoodielive/python_automated_testing | /automated_software_testing/blog/app.py | 452 | 4.28125 | 4 | MENU_PROMPT = 'Enter "c" to create a blog, "l" to list a blog, "r" to read one, "p" to create a post and "q" to quit.'
blogs = dict() # mapping blog_name to blog_object
def menu():
# Show the user the available blogs
# Let the user make a choice
# Do something with that choice
# Eventually
print_blogs()
selection = input(MENU_PROMPT)
def print_blogs():
for key, blog in blogs.items():
print('- {}'.format(blog)) |
71cb6300f8d026e2f002fd6f904f8cfe602f4af4 | ani03sha/Python-Language | /06_itertools/05_compress_the_strings.py | 400 | 4.03125 | 4 | # You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these
# consecutive occurrences of the character 'c' with (X,c) in the string.
from itertools import groupby
# Using list comprehensions, we are getting the length of occurrence of character c. x is the key i.e. character
# itself
print(*[(len(list(c)), int(x)) for x, c in groupby(input())])
|
ea0967e72eee3ca951c1a52eab1170aa52eaba96 | yglj/learngit | /PythonPractice/廖雪峰Python/14.sqlite.py | 2,439 | 3.78125 | 4 | # SQLite 一种嵌入式数据库
# 一个数据库连接称为Connection
# 通过 游标Cursor 执行sql语句
# Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。
import sqlite3 #导入驱动
'''
try:
conn = sqlite3.connect('s.db') #创建连接对象
cursor = conn.cursor() #创建游标对象
#cursor.execute('create table stu (name varchar(10),id int primary key)')
#cursor.execute('insert into stu (name,id) values ("pp","9")')
#print(cursor.rowcount) #获取插入的行数
conn.commit() #提交事务
cursor.execute('select * from stu where id like ?',('_',))
print(cursor.rowcount)
cursor.execute('delete from stu where id = ?',('4',))
print(cursor.rowcount)
cursor.execute('update stu set name=? where id=?',('dd','5'))
print(cursor.rowcount)
conn.commit()
cursor.execute('select * from stu')
value = cursor.fetchall() #拿取结果集 list(tuple)
print(value)
cursor.close()
finally:
conn.close()
'''
##
##练习
##请编写函数,在Sqlite中根据分数段查找指定的名字:
# -*- coding: utf-8 -*-
import os, sqlite3
db_file = os.path.join(os.path.dirname(__file__), 'test.db')
if os.path.isfile(db_file):
os.remove(db_file)
# 初始数据:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')
cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")
cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
cursor.close()
conn.commit()
conn.close()
def get_score_in(low, high):
#' 返回指定分数区间的名字,按分数从低到高排序 '
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute('select name from user where score between ? and ? order by score asc',(low,high))
names = cursor.fetchall()
cursor.close()
conn.close()
names = [''.join(name) for name in names]
return names
# 测试:
assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)
print('Pass')
|
47d17b25cfc1a40c5fad46cead9740882a80dfaa | Brunocfelix/Exercicios_Guanabara_Python | /Desafio 042.py | 924 | 4.34375 | 4 | """Desafio 042: Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo
será formado:
Equilátero: todos os lados iguais
Isósceles: dois lados iguais
Escaleno: todos os lados diferentes"""
# Desafio 035: Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não
# formar um triângulo.
print('-*=*-' * 20)
print('\033[34mAnalisador de Triângulos\033[m')
print('-*=*-' * 20)
p1 = float(input('Primeiro Segmento: '))
p2 = float(input('Segundo Segmento: '))
p3 = float(input('Terceiro Segmento: '))
if p1 < p2 + p3 and p2 < p1 + p3 and p3 < p1 + p2:
print('Os segmentos acima PODEM formar um Triângulo', end=' ')
if p1 == p2 == p3:
print('EQUILÁTERO!')
elif p1 != p2 != p3 != p1:
print('ESCALENO!')
else:
print('ISÓSCELES!')
else:
print('Os segmentos acima NÃO PODEM formar um Triângulo.')
|
fb013e1ec44efb1fc590ee03e5aff0a2dbe078de | generic-user1/restaurant-selector | /output_formatting.py | 1,776 | 4.15625 | 4 |
#output formatting
#functions to print information in defined,
#human readable formats
#given a place id (from the Maps API),
#return a URL that points to that location
#on the Google Maps website.
#note that this DOES NOT require an API call;
#this is simply creating a URL that the user
#can put into their browser
def getPlaceLink(placeId):
placeLink = f"https://www.google.com/maps/place/?q=place_id:{placeId}"
return placeLink
#generates and prints a Google Maps link to a place, given a place id
#surrounds it with space using newlines so it's easier to copy+paste
def printPlaceLink(placeId):
placeLink = getPlaceLink(placeId)
print(f"\n\n{placeLink}\n\n")
#given a Place object (as returned by the pickRestaurant function),
#print Place information that is relevant to the user to the console
#(this includes the name, full address, rating, price level, and Google Maps URL)
def printInfoForUser(selectedPlace):
#print the place name
print(f"*** {selectedPlace['name']} ***")
#print the place address
print(f"{selectedPlace['formatted_address']}")
#print the place's price level, if it exists
try:
print(f"Price level: {selectedPlace['price_level']} out of 3")
except KeyError:
print("Price level unknown")
try:
#print the place's rating along with the number of reviews
print(f"Rated {selectedPlace['rating']} out of 5 stars (from {selectedPlace['user_ratings_total']} reviews)")
except KeyError:
print("Rating unknown")
#indicate that this place is closed if appropriate
if not selectedPlace['opening_hours']['open_now']:
print ('### Currently Closed ###')
#print an empty line to signify the end of info
print()
|
04324d7b50ce291897aa243aaad36001d8a431ab | lizhihui16/aaa | /pbase/day15/shili/myzip.py | 1,187 | 3.78125 | 4 |
# numbers=[10086, 10000, 10010, 95588]
# names = ['中国移动', '中国电信', '中国联通']
# # def myzip(*args)
# def myzip(iter1,iter2):
# #先拿到两个对象的迭代器
# it1=iter(iter1)
# it2=iter(iter2)
# while True:
# try:
# a=next(it1)
# b=next(it2)
# yield(a,b)
# except StopIteration:
# return #此生成器函数结束
# # yield(next(it1),next(it2))
# for t in myzip(numbers, names):
# print(t)
# d = dict(myzip(numbers, names)) # ???
# print(d)
# 练习:
# 写一个程序,读入任意行文字,当输入空行时结束输入
# 打印带有行号的输入结果
# 如:
# 请输入:hello
# 请输入:world
# 请输入:python
# 请输入:<回车>
# 输入如下:
# 第1行: hello
# 第2行: world
# 第3行: python
def get_input_text():
L=[]
while True:
s=input("请输入:")
if not s:
return L
L.append(s)
def print_text_with_number(L):
for t in enumerate(L,1):
print("第%d行: %s" % t)
L=get_input_text()
print_text_with_number(L) |
e3afacc8652b61bc007a586e4d2de7ed3165647a | rj-aj/my-coding-assignments | /Python/Python_I/PythonFundamentals/funWithFunctions.py | 1,861 | 4.46875 | 4 | """
Assignment: Fun with Functions
Create a series of functions based on the below descriptions.
Odd/Even:
Create a function called odd_even that counts from 1 to 2000.
As your loop executes have your program print the number of that iteration
and specify whether it's an odd or even number.
Your program output should look like below:
Number is 1. This is an odd number.
Number is 2. This is an even number.
Number is 3. This is an odd number.
...
Number is 2000. This is an even number.
"""
def odd_even():
for number in range(1, 2001):
if ((number%2)!=0):
print "Number is", number,"."," ", "This is odd number"
else:
print "Number is", number,"."," ", "This is even number"
odd_even()
"""
Multiply:
Create a function called 'multiply' that iterates through each value in a list
(e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5.
The function should multiply each value in the list by the second argument. For example, let's say:
a = [2,4,10,16]
Then:
b = multiply(a, 5)
print b
Should print [10, 20, 50, 80 ].
"""
"""
Hacker Challenge:
Write a function that takes the multiply function call as an argument.
Your new function should return the multiplied list as a two-dimensional list.
Each internal list should contain the 1's times the number in the original list.
"""
def multiply(my_list, multiple):
new_list=[]
for i in my_list:
new_list.append(i*multiple)
return new_list
arr1=[10, 20, 50, 80 ]
arr2=multiply(arr1, 5)
print "New List : ", arr2
def layered_multiples(arr):
print arr
new_array = []
for num in arr:
temp_arr = []
for index in range(0,num):
temp_arr.append(1)
new_array.append(temp_arr)
return new_array
new_arr = layered_multiples(multiply([2,4,5],3))
print new_arr
|
7df2b180ce9ad97c5347764f5d8e5f0319a1ddaf | priyanka-cse/python | /program 1a.py | 145 | 3.609375 | 4 | a=[]
b=[]
size=int(input("enter the size"))
for i in range(size):
a.append(int(input()));
if(a[i]%2==0):
b.append(a[i])
print(b)
|
91e589d184294d6a273fcf367f0baeb9c1e18349 | ddarkclay/programming-cookbook | /Harry_Python/Multilevel Inheritance.py | 593 | 3.9375 | 4 | class Person:
def printpersondata(self,name,age):
self.name = name
self.age = age
print(f"Name is : {self.name} and Age is : {self.age}")
class Player(Person):
def printplays(self,plays):
self.plays = plays
print(f"Player Plays : {self.plays}")
class Employee(Player):
def printdata(self):
print(f"Name is : {self.name} and Age is : {self.age} and Player Plays {self.plays}")
raj = Employee()
raj.printpersondata("Raj",19)
raj.printplays("Cricket")
raj.printdata()
# Example like electronic device -> poketdevice -> Mobile phone |
7797f056b2156665874ec42dc1cd6e83c098f13d | pepelamah/MesRevisions | /TP_GE.py | 522 | 4.1875 | 4 | moy_int=0
while moy_int==0:
moy_str=input("Saisir votre note: ")
try:
moy_int=int(moy_str)
except:
print("Veuillez saisir une valeur numérique!!")
else:
if(20>=moy_int>=18):
print("Excellent!")
elif(18>moy_int>=14):
print("Très bien!!")
elif(14>moy_int>=10):
print("Assez bien!!")
elif(10>moy_int<=5):
print("Insuffisant!!")
elif(moy_int<5):
print("catastrophique!!")
|
7889281eab4f558940016a4e78cf3c30b1ff7a06 | rheehot/Algorithm-53 | /Programmers/Level2/124 나라의 숫자.py | 621 | 3.71875 | 4 | def solution(n):
answer = ''
# 몫과 나머지
quotient = 1
remainder = 1
# 나머지에따라 값 바꿔주기 위한 dictionary
country = {1: "1", 2: "2", 0: "4"}
# 몫이 0일때까지 반복
while quotient != 0:
quotient = n // 3
remainder = n % 3
# 나머지가 0일 경우에는 몫에서 1을 빼준다
if remainder == 0:
quotient -= 1
# 숫자 갱신
n = quotient
# 앞부분에 숫자를 붙여가며 만든다
answer = country[remainder] + answer
return answer
n = 10
print(solution(n)) |
f906f2d144132316f48474911e157e0389926dd0 | crizzy9/Algos | /data_structures/queue.py | 611 | 3.921875 | 4 | class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return not bool(self.items)
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[-1]
def __repr__(self):
return "{}".format(self.items)
if __name__ == "__main__":
q = Queue()
q.enqueue(5)
q.enqueue(7)
q.enqueue(25)
q.enqueue(3)
q.enqueue(15)
print(q)
q.dequeue()
print(q)
q.dequeue()
print(q) |
2a7127f9b901619456b56e83155ca7a84936f5a4 | Max143/Python_programs | /String manipulation.py | 424 | 4.09375 | 4 | # String Manipulation
# Find the length of string
print("Find the length of string.")
Fucking_style =(input("Which style you choose to fuck Mansi ? "))
def string_length(style):
return(len(style))
print(string_length('Anal'))
def string_length(my_string):
count = 0
for letter in my_string:
count += 1
return count
print(string_length(input("Please Input something: ")))
|
b467891803f375578a7ec512b5cf7687f7e1973c | PhilippeOC/p7 | /optimized.py | 2,412 | 3.515625 | 4 | import argparse
import csv
import time
def get_data_actions(file_name: str) -> list:
""" retourne la liste des données des actions : nom, prix, profit, rentabilité """
actions = []
with open(file_name, newline='', encoding='utf-8') as csvfile:
datas = csv.reader(csvfile, delimiter=',', quotechar="'")
for data_action in list(datas)[1:]:
if not check_valid_data(data_action):
continue
else:
valid_data = get_valid_data(data_action)
actions.append(valid_data)
return actions
def check_valid_data(data_action: list) -> bool:
""" retourne faux s'il manque une donnée ou si le prix de l'action est <=0 """
valid_data = True
if not data_action[0] or not data_action[1] or not data_action[2]:
return not valid_data
elif float(data_action[1]) <= 0:
return not valid_data
return valid_data
def get_valid_data(data_action: list) -> dict:
""" retourne les données des actions valides """
data_dict = {}
data_dict['name'] = data_action[0]
data_dict['price'] = float(data_action[1])
data_dict['profit'] = float(data_action[1])*float(data_action[2])/100
data_dict['efficiency'] = data_dict['profit']/data_dict['price']
return data_dict
def main():
parser = argparse.ArgumentParser(description='Execute le programme optimized.py')
parser.add_argument('file_name',
help="Entrez le nom du fichier csv contenant les données des actions",
type=str)
start_time = time.time()
budget_max = 500
total_price = 0
total_profit = 0
best_combination = []
actions = get_data_actions(parser.parse_args().file_name)
actions = sorted(actions, key=lambda k: k['efficiency'], reverse=True)
for action in actions:
if action['efficiency'] <= 0:
continue
elif total_price + action['price'] <= budget_max:
total_price = total_price + action['price']
total_profit = total_profit + action['profit']
else:
continue
best_combination.append(action['name'])
print(f"Total cost: {round(total_price, 2)}")
print(f"Profit: {round(total_profit, 2)}")
print(f"Combination: {best_combination}")
print(f"Execution time: {(time.time() - start_time)} seconds")
if __name__ == "__main__":
main()
|
8121250f8a1d25babbac135460110cb9bfced48f | execion/wordlist | /py/functionality.py | 3,640 | 3.578125 | 4 | from random import randint
def verifyRepeate(word, table, cursor):
sql = "SELECT * FROM {} WHERE word=\"{}\";".format(table, word)
cursor.execute(sql)
result = cursor.fetchall()
if len(result) > 0:
return True
else:
return False
def addWord(word, meaning, table, cursor):
sql = "INSERT INTO {}(word,meaning) VALUES(\"{}\",\"{}\");".format(table, word, meaning)
cursor.execute(sql)
def fetchWords(table, cursor):
sql = "SELECT * FROM {};".format(table)
cursor.execute(sql)
return cursor.fetchall()
def question(connection):
with connection.cursor() as cursor:
selectTable = input("All or Table: ")
if selectTable == "all":
tables = ["adjective", "noun", "adverb", "verb"]
else:
tables = selectTable.split(" ")
AllTables = []
for table in tables:
wordsRows = fetchWords(table, cursor)
AllTables.append(wordsRows)
adjective = []
adverb = []
verb = []
noun = []
corrects = 0
cont = 1
totalWords = 0
for i in AllTables:
totalWords += len(i)
while True:
if cont == totalWords:
print("\tFinish: {} / {}".format(corrects, totalWords))
break
randomTables = randint(0,len(tables)-1) # Elige una Tabla
randomRows = randint(0, len(AllTables[randomTables])-1) # Elige un indice de la tabla elegida
if randomTables == 0:
if randomRows in adjective:
continue
else:
adjective.append(randomRows)
elif randomTables == 1:
if randomRows in adverb:
continue
else:
adverb.append(randomRows)
elif randomTables == 2:
if randomRows in verb:
continue
else:
verb.append(randomRows)
elif randomTables == 3:
if randomRows in noun:
continue
else:
noun.append(randomRows)
listMeaning = AllTables[randomTables][randomRows]["meaning"].split(", ")
print("\n\tTable: {}".format(tables[randomTables].capitalize()))
question = input("{} - What does {} mean?: ".format(cont, AllTables[randomTables][randomRows]["word"].upper()))
if question == "-quit":
print("\tTotal: {} / {}".format(corrects, totalWords))
break
elif question in listMeaning:
print("\tCorrect")
corrects += 1
else:
print("Incorrect")
print(AllTables[randomTables][randomRows]["meaning"])
cont += 1
def addWordsInTable(connection):
continueLoop = True
table = input("Table: ")
while continueLoop:
print("\nTable: {}".format(table.capitalize()))
with connection.cursor() as cursor:
word = input("Insert your word: ")
if verifyRepeate(word, table, cursor) == True:
print("The word is repeat")
continue
elif (word == ""):
continue
elif (word == "-quit"):
break
meaning = input("Insert your meaning: ")
if meaning == "-quit":
break
if meaning == "":
continue
addWord(word, meaning, table, cursor)
connection.commit() |
40399459d51dfe5d9c394ac385b57be6eaf34325 | mctopherganesh/diabetes_data | /dis_helper.py | 1,462 | 3.53125 | 4 | import sqlite3
import datetime
import pandas as pd
def db_and_table_name_setter(name_of_db, name_of_table):
return name_of_db, name_of_table
def create_table_for_bs(name_of_db, name_of_table):
# function for testing and creating bs data table
conn = sqlite3.connect(name_of_db) # previously 'bs.db'
c = conn.cursor()
c.execute('create table if not exists {}(date_measure_taken text, bs_measure real)'.format(name_of_table))
c.close()
conn.close()
def create_table_for_food(name_of_db, name_of_table):
# function for testing and creating bs data table
conn = sqlite3.connect(name_of_db) # previously 'bs.db'
c = conn.cursor()
c.execute('create table if not exists {}(date_measure_taken text, consumed text)'.format(name_of_table))
c.close()
conn.close()
def data_entry(new_data_row, name_of_db, name_of_table):
conn = sqlite3.connect(name_of_db)
c = conn.cursor()
c.execute('insert into {} values {}'.format(name_of_table, new_data_row))
conn.commit() # have to run this after changing the table
c.close() # closes the connection to the cursor
conn.close()
def return_date():
x = datetime.datetime.now()
return x.strftime("%Y-%m-%d %H:%M:%S")
def reads_in_time_and_data(data):
dtstmp = return_date()
return "('{}',{})".format(dtstmp, data)
def reads_in_time_and_data_for_food(data):
dtstmp = return_date()
return "('{}','{}')".format(dtstmp, data)
|
e7d438416515a8f1f68e864b353b01c30672e592 | corey-miles/Python-Projects | /word_count_gen/word_count_gen.py | 1,569 | 3.984375 | 4 | '''
Script using a text file, reads each word into a
dictionary, then output an HTML file in a Tag Cloud
format.
** Project based on a course project **
CSS file created by dept.
'''
import os
from utils import FileParser
from web import MarkupParser
#################
## MAIN SCRIPT ##
#################
# Get .txt path
text = input('Enter file to read: ')
while not os.path.exists(text):
print('ERROR: File does not exist...')
text = input('Enter file to read: ')
# Utilize FileParser
f_parser = FileParser(text)
f_parser.parse_file()
main_dict = f_parser.words_dict
# Sort words by value
main_dict = sorted(main_dict.items(), key=lambda x: x[1], reverse=True)
# Get length
LENGTH = -1
while LENGTH < 0:
try:
LENGTH = int(input('Enter number of words: '))
if LENGTH < 0:
print('ERROR: Value cannot be negative...')
except ValueError:
print('ERROR: Cannot convert to int...')
# Grab requested words and sort by key
sub_dict = main_dict[:LENGTH]
maximum = sub_dict[0][1]
minimum = sub_dict[LENGTH-1][1]
sub_dict = sorted(sub_dict)
# Get .html path
html = input('Enter file [.html] to create: ')
while not html.endswith('.html'):
print('ERROR: Missing .html extension...')
html = input('Enter file [.html] to create: ')
# Utilize MarkupParser
m_parser = MarkupParser(html, text, sub_dict, maximum, minimum, LENGTH)
m_parser.create_html()
# Inform of new file
print("New File: " + html)
|
82315198e104b24b1612134a8400cfedadfe4e4c | elenalb/geekbrains_python | /lesson2/set.py | 519 | 3.640625 | 4 | # множества
my_set_1 = set('simple')
my_set_2 = frozenset('simple')
print(my_set_1)
print(my_set_2)
my_set_1.add(1)
print(my_set_1)
my_set_1.remove('s')
print(my_set_1)
my_set_1.pop()
print(my_set_1)
my_set_3 = {1, 3}
print(my_set_3)
my_set_3.clear()
print(my_set_3)
print(my_set_1)
print(my_set_2)
# вычитание
print(my_set_2 - my_set_1)
# объединение
print(my_set_1 | my_set_2)
my_set_1 = set('simple')
my_set_2 = frozenset('simple')
my_set_4 = set('and')
print(my_set_1 - my_set_4)
|
a275a21c9ac895db4817418a1fc330875a594388 | rvcjavaboy/eitra | /MIT python course/Assignment 1/Exercise_1_8.py | 602 | 3.84375 | 4 | #1
for i in range(1, 11):
print ("1/" + str(i) + " is " + str(1.0/i))
#2
n = int(input("Enter no. for countdown: "))
if n>0:
while n!=0:
n-=1
print(n)
else:
print("You've entered wrong or negative number")
#3
base = int(input("Enter base: "))
exp = int(input("Enter exponential: "))
res = base**exp
print(res)
#4
while True:
n = int(input("Enter number: "))
if n%2!=0:
print("Please enter number which is divisible by 2 only")
continue
else:
print("Number is divisible by 2")
break
|
a8473a3f04a04525e09aa06f52f5d3fda397029a | aditisinghq/IRobotics-assignments | /a2.py | 337 | 3.5 | 4 | import numpy as np
import math
def main():
p=[[2],[3],[0]]
#for rotation about x axis twice by 30 degrees
r1=np.array([[1,0,0],[0, 0.5, -0.866],[0, 8.66, 0.5]])
#for rotation about y axis by 30 degrees
r2=np.array([[0.866,0,0.5],[0,1,0],[-0.5,0,0.866]])
r=np.matmul(r2,r1)
rr=r.transpose()
res=np.matmul(rr,p)
print(res)
main()
|
dac765fb91cb2541d79cb9bb7e57ba9f1944c0dc | nikolaikk/First_try | /python try/surface3d_demo2.py | 2,051 | 4.15625 | 4 | '''
========================
3D surface (solid color)
========================
Demonstrates a very basic plot of a 3D surface using a solid color.
'''
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
#ax = fig.add_subplot(111, projection='3d')
# Make data
u = np.linspace(0, np.pi, 100)
v = np.linspace(0, 0.5*np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
# Plot the surface
fig.add_subplot(111, projection='3d').plot_surface(x, y, z, color='b')
plt.show()
#=========================================================================
#import numpy as np
##from mpl_toolkits.mplot3d import Axes3Ds
#import matplotlib.pyplot as plt
#
#
#def fun(x, y):
# return x**2 + y
#
#fig = plt.figure()S
#ax = fig.add_subplot(111, projection='3d')
#x = y = np.arange(-3.0, 3.0, 0.05)
#X, Y = np.meshgrid(x, y)
#zs1 = fun(x,y)
#zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
#Z = zs.reshape(X.shape)
#
#ax.plot_surface(X, Y, Z)
#
#ax.set_xlabel('X Label')
#ax.set_ylabel('Y Label')
#ax.set_zlabel('Z Label')
#
#plt.show()
#=========================================================================
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
plt.show() |
3a4872723eb8bbc8b256618586c427543eed20f9 | heinthu12/Python | /MyPython/Exercise/and.py | 83 | 3.53125 | 4 | x = 9
y = 3
# use and logic
print(x >= 5 and x <= 10 )
print(y >=5 and y <=10)
|
476cd1cdcbf8dc422e4dffdc7c81e66249db3493 | Aasthaengg/IBMdataset | /Python_codes/p00001/s630899474.py | 219 | 3.8125 | 4 | #coding:UTF-8
def LoT(List):
List2=sorted(List)
for i in range(3):
print(List2[len(List)-1-i])
if __name__=="__main__":
List=[]
for i in range(10):
List.append(int(input()))
LoT(List) |
405e9016b0b748ee1c757b98dd580977c1bef572 | xfhy/LearnPython | /廖雪峰老师的教程/7. 面向对象高级编程/使用__slots__.py | 1,555 | 3.796875 | 4 | # 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性
class Student(object):
pass
s = Student()
# 绑定属性
s.name = 'xfhy'
print(s.name)
# 绑定方法
def set_name(self,name):
self.name = name
from types import MethodType
s.set_name = MethodType(set_name,s) #给实例绑定一个方法
s.set_name('xfhy666')
print(s.name)
# 但是,给一个实例绑定的方法,对另一个实例是不起作用的:
s2 = Student()
print(hasattr(s2,'set_name')) #False
# 为了给所有实例都绑定方法,可以给class绑定方法:
# 给class绑定方法后,所有实例均可调用:
def set_score(self,score):
self.score= score
Student.set_score = set_score
s2.set_score(4)
print(s2.score)
# 但是,如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加name和age属性。
class Student2(object):
__slots__ = ('name','age') # 用tuple定义允许绑定的属性名称
s = Student2()
s.name = 'xfhy' #绑定一个属性
print(s.name)
s.age = 18
# s.score = 80 这里无法进行绑定 AttributeError
# 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
class GraduateStudent(Student2):
pass
g = GraduateStudent()
g.score = 100
print(g.score)
# 除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。 |
a9f8bdbb607ed16c977d70a78b494d74ed8adb9f | Anju-PT/pythonfilesproject | /exam/removeduplicate.py | 143 | 3.53125 | 4 | lst=[1,2,4,5,6,7,3,2,3,1,10]
s=[]
for i in lst:
if i not in s:
s.append(i)
print(s)
l=len(lst)
#output
#[1, 2, 4, 5, 6, 7, 3, 10]
|
e8878836d7646cdb4c2e1c73aa1d074812acd8a1 | github-hrithik/stringl1-py | /Q4level1.py | 160 | 3.6875 | 4 | #Count Number of vowels
st=input("Enter String-")
stf=st.upper()
ctr=0
for i in stf:
if i in ["A","E","I","O","U"]:
ctr+=1
print(ctr)
|
1fc36f89c90e0c2ba56b8f889a68a11664f1037a | yiming1012/MyLeetCode | /LeetCode/双指针(two points)/1423. 可获得的最大点数.py | 2,603 | 3.671875 | 4 | """
1423. 可获得的最大点数
几张卡牌 排成一行,每张卡牌都有一个对应的点数。点数由整数数组 cardPoints 给出。
每次行动,你可以从行的开头或者末尾拿一张卡牌,最终你必须正好拿 k 张卡牌。
你的点数就是你拿到手中的所有卡牌的点数之和。
给你一个整数数组 cardPoints 和整数 k,请你返回可以获得的最大点数。
示例 1:
输入:cardPoints = [1,2,3,4,5,6,1], k = 3
输出:12
解释:第一次行动,不管拿哪张牌,你的点数总是 1 。但是,先拿最右边的卡牌将会最大化你的可获得点数。最优策略是拿右边的三张牌,最终点数为 1 + 6 + 5 = 12 。
示例 2:
输入:cardPoints = [2,2,2], k = 2
输出:4
解释:无论你拿起哪两张卡牌,可获得的点数总是 4 。
示例 3:
输入:cardPoints = [9,7,7,9,7,7,9], k = 7
输出:55
解释:你必须拿起所有卡牌,可以获得的点数为所有卡牌的点数之和。
示例 4:
输入:cardPoints = [1,1000,1], k = 1
输出:1
解释:你无法拿到中间那张卡牌,所以可以获得的最大点数为 1 。
示例 5:
输入:cardPoints = [1,79,80,1,1,1,200,1], k = 3
输出:202
提示:
1 <= cardPoints.length <= 10^5
1 <= cardPoints[i] <= 10^4
1 <= k <= cardPoints.length
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def maxScore1(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
pre = [0] * (k + 1)
suf = [0] * (k + 1)
for i in range(1, k + 1):
pre[i] = pre[i - 1] + cardPoints[i - 1]
for i in range(n - 1, n - 1 - k, -1):
suf[k - n + i] = suf[k - n + i + 1] + cardPoints[i]
res = float('-inf')
for i in range(k + 1):
res = max(res, pre[i] + suf[i - k - 1])
return res
def maxScore2(self, cardPoints: List[int], k: int) -> int:
"""
滑动窗口
@param cardPoints:
@param k:
@return:
"""
res = cursum = sum(cardPoints[-k:])
for i in range(k):
cursum += cardPoints[i] - cardPoints[-k + i]
res = max(res, cursum)
return res
if __name__ == '__main__':
cardPoints = [1, 2, 3, 4, 5, 6, 1]
k = 3
print(Solution().maxScore1(cardPoints, k))
print(Solution().maxScore2(cardPoints, k))
|
fac9e42fc5d9ff5a7ea08cf78950ffa3efec1a70 | glavdev/SquareChallenge | /algorithms/hello.py | 2,322 | 3.625 | 4 | """Ознакомительная реализация
Пример поиска границ заказа
Автор: Alexandr Gorlov
"""
import cv2
def square(image) -> int:
"""Определим площадь, с помощью OpenCv.findContours"""
image = cv2.imread("./imgs/" + image)
# 0. вырежем центральную часть
#image = image[100:1700, 350:2050]
# 1. Переведем в градации серого
grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 2. Немного размажем границы
grayImage = cv2.GaussianBlur(grayImage, (51, 51), 0)
viewImage(grayImage, "Перевел в градации серого и размыл")
# 3. Переведем в черно-белое (если пиксель ярче 30 - считаем белым, если темнее - черным)
ret, bwImage = cv2.threshold(grayImage, 30, 255, 0)
viewImage(bwImage, "Перевел в черно-белое (без переходов)")
# 4. Поищем контуры с помощью OpenCV.findContours
_, contours, hierarchy = cv2.findContours( bwImage.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
maxConturArea = 0
# 5. Выберем самый большой из них
i = 0
for cnt in contours:
area = cv2.contourArea(cnt)
if area > maxConturArea:
maxConturArea = area
maxContur = i
i += 1
cv2.drawContours( image, contours, maxContur, (0,0,255), 3, cv2.LINE_AA, hierarchy, 1 )
viewImage(image, "Итоговый контур")
return maxConturArea
def viewImage(image, nameOfWindow):
"""Вывод картинки для наладки
ESC - закрывает окно
кнопка s - сохраняет в файле tmp.png
"""
# Чтобы выключить отладку, раскоментировать следующую строку:
# return
cv2.namedWindow(nameOfWindow, cv2.WINDOW_NORMAL)
cv2.imshow(nameOfWindow, image)
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('tmp.png', image)
cv2.destroyAllWindows() |
5e3277d2ded388beb5ae2c9d0cab84d03df20e7d | The-1999/Snake4d | /src/score.py | 7,058 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 25 22:01:56 2018
@author: Mauro
"""
#==============================================================================
# Score board
#==============================================================================
import datetime
import os
from tkinter import Label, Toplevel
#import visu, poly, vec #needed for the graph
#==============================================================================
# Class score
# small class to store a score and a date
#==============================================================================
class Score:
def __init__(self, date, score = None):
if type(date) == str:
self.read_from_line(date)
elif type(date) is datetime.datetime and type(score) is int:
self.date = date
self.score = score
else:
raise ValueError("wrong parameters: " + str(date) + ", " + str(score))
def read_from_line(self, line):
data = line.split(" ")
self.date = datetime.datetime.strptime(data[0], "%Y-%m-%dT%H:%M:%S.%f")
self.score = int(data[1])
def __str__(self):
s = self.date.isoformat() + " "
s += str(self.score)
return s
#==============================================================================
# A list of scores
# the class manages the reading and writing to file of the scores and the
# sorting of different scores
#==============================================================================
class Scores:
def __init__(self):
self.filename = "./score.txt"
self.scores = []
self.new_scores = []
# read in from the score file the scores
old_scores = []
if os.path.isfile(self.filename):
with open(self.filename, "r") as f:
old_scores = f.readlines()
# parse the line in scores
for line in old_scores:
s = Score(line)
self.scores.append(s)
print("Loaded", len(self.scores), "scores")
def add_score(self, score):
self.new_scores.append(score)
def write_scores(self):
# append the new scores in the file
with open(self.filename, "a") as f:
f.write("\n")
f.writelines([str(score) for score in self.new_scores])
self.scores = self.scores + self.new_scores
self.new_scores = []
# get the top ten scores in terms of score
def get_top_ten_scores(self):
all_scores = self.scores + self.new_scores
all_scores = sorted(all_scores, key=lambda x : x.score)
all_scores = all_scores[::-1]
return all_scores[:10]
# gets the last 20 scores in order of time
def get_last_scores(self):
all_scores = self.scores + self.new_scores
all_scores = sorted(all_scores, key=lambda x : x.date)
all_scores = all_scores[::-1]
return all_scores[:20]
#==============================================================================
# The GUI representation of the class scores
#==============================================================================
class ScoreBoard:
def __init__(self, parent):
self.parent = parent
self.scores = Scores()
def add_score(self, score):
self.scores.add_score(score)
self.scores.write_scores()
def render_scores(self):
board = Toplevel(self.parent)
# title lable
titlel = Label(board, text = "---- HIGH SCORE ----", font=("Arial", 20))
titlel.grid(row = 0, column = 0)
# get top ten
top_ten = self.scores.get_top_ten_scores()
# get last score
if self.scores.new_scores:
last_score = self.scores.new_scores[0]
elif self.scores.scores:
last_score = self.scores.scores[-1]
# create a list from the scores, if the last score is in the list
# split the list according to previous score - curr score - prev score
label_list = []
label_list.append([])
idx = 0
for score in top_ten:
if score.date == last_score.date and score.score == last_score.score:
label_list.append([])
idx += 1
label_list[idx].append(score)
label_list.append([])
idx += 1
else:
label_list[idx].append(score)
# score list
# take highest score
hscore = top_ten[0].score
# get the character width
cwidth_score = len(str(hscore))
# construct the format
format_score = "{: >" + str(cwidth_score) + "}"
# *BUG* if is first or last in the list magics happen...
for i, ss in enumerate(label_list):
s = ""
for score_line in ss:
# print the formatted score
fscore = format_score.format(score_line.score)
# assemble the formatted string with date and score
s += score_line.date.strftime("%d %b %y") + " - " + fscore + "\n"
s = s[:len(s)-1]
if (i == 1 and len(ss) == 3) or (i == 0 and len(ss) == 2):
color = "darkorange3"
rel = "groove"
else:
color = "green"
rel = "flat"
ltop_board = Label(board, text=s, font=("Fixedsys", 14), fg = color,
borderwidth=2, relief=rel, padx=1, pady=1)
ltop_board.grid(row=(i + 1), column = 0, padx=0, pady=0)
# in case needed is a graph of the scores
#
#
# row = len(label_list) + 1
#
# graph = visu.VisuArea(board, None, [250, 100], "Score Evolution")
# graph.fP.grid(row=row, column = 0)
#
# graph.c_center_w = 0
# graph.c_center_h = 0
#
# p = poly.Polygon()
#
# score_list = self.scores.get_last_scores()
# score_list = score_list[::-1]
#
# point_list = []
# for i, score in enumerate(score_list):
# print(score.score)
# v = vec.V2(i, score.score)
# point_list.append(v)
#
# p_max = max(point_list, key= lambda polygon : polygon.y())
# graph.area_h = p_max.y() + 2
# graph.area_w = len(score_list)
#
# e_list = []
# for i, p in enumerate(point_list[:-1]):
# e_list.append([i, i + 1])
#
# p.v_list = point_list
# p.e_list = e_list
# p.color = "red"
#
# graph.draw_poly(p)
# graph.draw_edge(vec.V2(0, graph.area_h), vec.V2(graph.area_w, graph.area_h), kwargs={"fill":"black"})
# graph.canvas.create_text(5, p_max.y(), text= str(p_max.y()), anchor= "w")
|
44efe9184d35af42951f7e8a3914475475e7ceec | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter5/q31.py | 498 | 4.0625 | 4 | """
recursion, sum the two dimensional list
"""
def sum_one_list(data):
total = 0
if not isinstance(data, list):
return data # for one value, just return the value for the addtion in total += sum_one_list(element)
else: # for a list, go deeper into each element
for element in data:
total += sum_one_list(element)
return total
if __name__ == '__main__':
data = [[1,2,3], [4,5,6], [7,8],[9], [10]]
print(sum_one_list(data)) |
df541f0524f189bbe1d8e8910678fb494e7b2be8 | ruizhiwang11/2001-lab | /Lab1/testcaseAutoGen.py | 1,117 | 3.5 | 4 | import random
import json
TestingCharlist=['A','C','G','T']
listGen={}
tmpgen={}
testinglist={}
#Parameter you need to set
LOWER_BOUND=7
HIGHER_BOUND=10
REPEAT_TIME=5
def readInPut():
LOWER_BOUND = input ("Enter LOWER_BOUND :")
HIGHER_BOUND = input ("Enter HIGHER_BOUND :")
REPEAT_TIME = input ("Enter REPEAT_TIME :")
return [LOWER_BOUND,HIGHER_BOUND,REPEAT_TIME]
"""Single String Generation"""
def singStringGen(charlist,lens=int):
temp=""
for i in range (0,lens):
temp += charlist[random.randint(0,3)]
#print (temp)
#print (len(temp))
return temp
"""list of string generation"""
def testCaseGen(start,end,numb):
for i in range (start,end+1):
tmpgen={i:[]}
for j in range(numb):
x=singStringGen(TestingCharlist,i)
tmpgen[i].append(x)
listGen.update(tmpgen)
#print (json.dumps(listGen, indent=4))
return listGen
"""call for the function"""
getinput=readInPut()
testinglist=testCaseGen(int(getinput[0]),int(getinput[1]),int(getinput[2]))
|
da0f3462591f4d70d1227d57215800395d463b6e | vin-nag/Sudoku-SAT | /Model/sudoku.py | 2,105 | 3.859375 | 4 | import numpy as np
class Sudoku:
"""
A class that represents a Sudoku board
The board is stored internally as a numpy array
Zeroes preresent blank spaces
"""
def __init__(self, degree, matrix=None):
self.degree = degree
if matrix is None:
self.matrix = np.zeros((degree, degree), dtype='int')
else:
self.matrix = matrix
@property
def rows(self):
n = 0
while n < self.degree:
yield self.matrix[n]
n += 1
@property
def columns(self):
n = 0
while n < self.degree:
yield self.matrix[:, n]
n += 1
@property
def squares(self):
square = int(np.sqrt(self.degree))
for i in range(square):
for j in range(square):
yield self.matrix[i * square:i * square + square, j * square:j * square + square]
def num_to_let(num):
return chr(ord('a') + num - 1)
def cnf_output(self):
output = ""
for i in range(self.degree):
for j in range(self.degree):
num = self.matrix[i][j]
if num == 0: continue
output += "{}{}{} 0".format(i, j, num)
output += '\n'
return output
def regular_output(self):
output = []
for i in range(self.degree):
for j in range(self.degree):
num = self.matrix[i][j]
if num == 0: continue
output.append([i,j,num])
return output
def randomize_board(self, num_cells):
for n in range(num_cells):
self._draw_random_number()
return
def _draw_random_number(self):
for n in range(10000): # in case of timeout
x = np.random.randint(0, self.degree) # high exclusive
y = np.random.randint(0, self.degree)
if self.matrix[x][y] != 0:
continue
self.matrix[x][y] = np.random.randint(1, self.degree + 1)
break
else:
raise Exception("Max exceeded") |
e8340d9cbb12043870fc2e8e80e225f6e788e3a4 | alexjohnlyman/Python-Exercises | /4-8-15.py | 275 | 3.65625 | 4 | """
weekday false, vacation false true
weekday true, vacation false false
weekday false, vacation true true
"""
def sleep_in(weekday, vacation):
return vacation or not weekday
print sleep_in(False, False)
print sleep_in(True, False)
print sleep_in(False, True) |
4aec6bd05dacc556b10906d3a5692c48ec0d70a1 | shivapri/Ai | /main.py | 9,606 | 3.59375 | 4 | import numpy as np
import random
#
p=[]
for i in range(0,3,1):
c=[]
for j in range(0,3,1):
c.append('_')
p.append(c)
for i in range(0,3,1):
for j in range(0,3,1):
print(p[i][j],end=" ")
print('\n')
def checkRows(board):
for row in board:
if len(set(row)) == 1:
return row[0]
return 0
def checkDiagonals(board):
if len(set([board[i][i] for i in range(len(board))])) == 1:
return board[0][0]
if len(set([board[i][len(board)-i-1] for i in range(len(board))])) == 1:
return board[0][len(board)-1]
return 0
def checkWin(board):
#transposition to check rows, then columns
for newBoard in [board, np.transpose(board)]:
result = checkRows(newBoard)
if result:
return result
return checkDiagonals(board)
row,col =input("The location where you want the 0")
# print(row," ",col)
p[int(row)][int(col)]='O'
row,col =input("The location where you want the 0")
# print(row," ",col)
p[int(row)][int(col)]='O'
row,col =input("The location where you want the 0")
# print(row," ",col)
p[int(row)][int(col)]='X'
for i in range(0,3,1):
for j in range(0,3,1):
print(p[i][j],end=" ")
print('\n')
# global eva
def utility(node):
cost = 0
goal = np.array(node)
row,col = np.where(goal=='X')
# print("row is ",row," and col is ",col)
for i in range(0, len(row), 1):
if row[i] + 1 in row and col[i] - 1 in col:
cost = cost + 1
continue
# return "Not same"
# break
if row[i] + 1 in row and col[i] + 1 in col:
cost = cost + 1
continue
if row[i] - 1 in row and col[i] + 1 in col:
cost = cost + 1
continue
if row[i] - 1 in row and col[i] - 1 in col:
cost = cost + 1
continue
if row[i] + 1 in row and col[i] in col:
cost = cost + 1
continue
if row[i] - 1 in row and col[i] in col:
cost = cost + 1
continue
if col[i] + 1 in col and row[i] in row:
cost = cost + 1
continue
if col[i] - 1 in col and row[i] in row:
cost = cost + 1
continue
if cost == 0:
cost = -1
return cost
return cost
# print(utility(p))
# def terminal(node):
def checkpos(node):
# self.state = state
arr = np.array(node)
# print(arr)
dim = np.where(arr == '_')
row,col =dim
# print(row)
str = []
pos = []
for i in range(0, len(row), 1):
if row[i] == 1 and col[i] == 1:
s ="centre"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif row[i] == 0 and col[i] == 0:
s = "extreme up left"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif row[i] == 0 and col[i] == 2:
s = "extreme up right"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif row[i] == 2 and col[i] == 0:
s= "extreme down left"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif row[i] == 2 and col[i] == 2:
s = "extreme down right"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif col[i] == 0:
s = "extreme left"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif col[i] == 2:
s = "extreme right"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif row[i] == 0:
s = "up"
str.append(s)
pos.append(row[i])
pos.append(col[i])
elif row[i] == 2:
s = "down"
str.append(s)
pos.append(row[i])
pos.append(col[i])
return str,pos
def checkstate(self,node):
self.node=node
arr =np.array(node)
row1, col1 = np.where(arr == '_')
if (len(row1) == 0):
state = 'terminal'
else:
state = 'non-terminal'
# @staticmethod
class Node(object):
def __init__(self,value,state):
self.value = value
self.state = state
self.left = None
self.right = None
self.middle = None
# return value
class BinaryTree(object):
def __init__(self,root,state):
self.root = Node(root,"non-terminal")
self.state = state
# return root
def Dfs_print(self,start,depth,traversal):
depth +=1
if depth<4:
traversal = start
traversal = self.Dfs_print(left(start),depth,traversal)
traversal = self.Dfs_print(mid(start),depth,traversal)
traversal = self.Dfs_print(right(start),depth,traversal)
return traversal
def left(node):
s,p = checkpos(node)
cond = ["extreme up left","extreme down left","extreme left"]
t = [word for word in s if word in cond]
if len(t)>0:
node[p[0]][p[1]] = 'X'
return node
def mid(node):
s, p = checkpos(node)
cond = ["up", "down", "center"]
t = [word for word in s if word in cond]
if len(t) > 0:
node[p[0]][p[1]] = 'X'
return node
def right (node):
s,p= checkpos(node)
cond = ["extreme up right", "extreme down right", "extreme right"]
t = [word for word in s if word in cond]
if len(t) > 0:
node[p[0]][p[1]] = 'X'
return node
p = np.array(p)
row1,col1= np.where(p=='_')
print(row1,"-",col1)
def minimax(node,depth,state,maximizing,acc):
node1 = np.array(node)
depth = depth+1
if depth>5:
return utility(node),acc
if len(np.where(node1=='_'))==0:
return utility(node),acc
if state == 'terminal':
return utility(node),acc
if maximizing:
maxeva = -99999
child=left(node)
if (node== child).all():
state = 'terminal'
evalef,temp= minimax(child,depth,state,False,acc)
maxeva = max(maxeva,evalef)
if (maxeva == evalef).all():
acc.append('left')
child = mid(node)
if (node == child).all():
state = 'terminal'
evamid,temp = minimax(child,depth, state, False,acc)
maxeva = max(maxeva,evamid)
if maxeva == evamid:
acc.append('mid')
child =right(node)
if (node == child).all():
state ='terminal'
evarig,temp = minimax(child,depth,state,False,acc)
maxeva=max(maxeva,evarig)
if maxeva == evarig:
acc.append('right')
return utility(node),acc
else:
mineva = 9999
child = left(node)
if (node == child).all():
state = 'terminal'
# if child == node:
# state = 'terminal'
evalef,temp= minimax(child,depth,state,True,acc)
mineva = min(mineva,evalef)
if mineva== evalef:
acc.append('left')
child = mid(node)
if (node == child).all():
state = 'terminal'
# if child == node:
# state = 'terminal'
evamid,temp= minimax(child, depth,state, True,acc)
mineva = min(mineva, evamid)
if mineva == evamid:
acc.append('mid')
child = right(node)
if (node == child).all():
state = 'terminal'
# if child == node:
# state = 'terminal'
evarig,temp = minimax(child, depth,state, True,acc)
mineva = min(mineva, evarig)
if mineva == evarig:
acc.append('right')
return utility(node),acc
# print(tree.Dfs_print(tree.root.value,0,""))
# print(tree.root.right)
# print(tree.root.right.state)
# tree.root.left = Node(2)
# tree.root.right = Node(3)
# tree.root.left.left = Node(4)
# tree.root.left.right = Node(5)
# print(tree.print_tree('yes'))
# acc = []
# depth = 0
# value,result = minimax(p,depth,'non-terminal',False,acc)
# print(result)
node = p
while(True):
node = np.array(node)
row, col = input("The location where you want the 0")
# print(row," ",col)
if node[int(row)][int(col)]=='_':
node[int(row)][int(col)] = 'O'
print(node)
else:
print("wrong choice")
if len(np.where(node=='_'))==0:
if checkWin(np.array(node)) == 0:
print('losecondition')
print(node)
break
if checkWin(np.array(node) )== 1:
print('wincondition')
print(node)
break
acc = []
score,dir = minimax(node,5,'non-terminal',False,acc)
if dir == 'left':
node = left(node)
print(node)
if dir=='mid':
node = mid(node)
print(node)
if dir == 'right':
node = right(node)
print(node)
# sh = states(p)
# print(sh.checkpos(p))
# print(sh.minimax(p,True))
|
b720ed6db5eb0842d0652ec4fe5e64bc874c8096 | nei1d0r/python | /helloworld.py | 884 | 4 | 4 | def main():
print("Name: {name}\nAge: int{age}\nFavourite Colour: {colour}\nPet name(s): {pet}\nHobbies: {hobby}".format(name = input("What is your name? "),age = int(input("How old are you? ")),colour = input("What is your favourite colour? "),pet = input("What is/are your pet's name(s)? "),hobby = input("What are your hobbies? ")))
'''
if name == 'Neil':
print("hello sir, and welcome!")
else:
print("Who the fuck is {name}!?")
if age >= 18:
print("you are old enough to be here.")
else:
print("you need to be 18 or over to enter.") #Have to define these individually, cannot associate with .format!
if colour == orange:
print("Orange, no way me too!!")
else:
print("I don't really relate to people with {colour} as colour choice!")
if hobby == code:
print("HelloWorld")
else:
print("GoodbyeWorld")
'''
main()
|
77e99a341c2f4ea0bb098a698317e724b59d6847 | ckidckidckid/leetcode | /LeetCodeSolutions/140.word-break-ii.python3.py | 1,900 | 3.609375 | 4 | #
# [140] Word Break II
#
# https://leetcode.com/problems/word-break-ii/description/
#
# algorithms
# Hard (24.68%)
# Total Accepted: 115.3K
# Total Submissions: 466.6K
# Testcase Example: '"catsanddog"\n["cat","cats","and","sand","dog"]'
#
# Given a non-empty string s and a dictionary wordDict containing a list of
# non-empty words, add spaces in s to construct a sentence where each word is a
# valid dictionary word. Return all such possible sentences.
#
# Note:
#
#
# The same word in the dictionary may be reused multiple times in the
# segmentation.
# You may assume the dictionary does not contain duplicate words.
#
#
# Example 1:
#
#
# Input:
# s = "catsanddog"
# wordDict = ["cat", "cats", "and", "sand", "dog"]
# Output:
# [
# "cats and dog",
# "cat sand dog"
# ]
#
#
# Example 2:
#
#
# Input:
# s = "pineapplepenapple"
# wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
# Output:
# [
# "pine apple pen apple",
# "pineapple pen apple",
# "pine applepen apple"
# ]
# Explanation: Note that you are allowed to reuse a dictionary word.
#
#
# Example 3:
#
#
# Input:
# s = "catsandog"
# wordDict = ["cats", "dog", "sand", "and", "cat"]
# Output:
# []
#
#
from functools import lru_cache
class Solution:
@lru_cache(maxsize = 10000)
def helper(self, s):
ans = []
if len(s) == 0:
ans.append([])
else:
n = len(s)
for i in range(n):
head = s[:i+1]
if head in self.wordSet:
subs = self.helper(s[i+1:])
for sub in subs:
ans.append([head] + sub)
return ans
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
self.wordSet = set(wordDict)
ans = self.helper(s)
return [' '.join(x) for x in ans]
|
5257a3610ac3e81812272932176bed7c284160a3 | didoman/prog101tasks | /week0/normal/iterationsofnanexpand.py | 605 | 3.859375 | 4 | #iterations of nan expand
def iterations_of_nan_expand(expanded):
if len(expanded) == 0:
print(0)
return 0
elif "Not a NaN" in expanded:
counter = expanded.count("Not a")
print (counter)
return counter
else:
print("False")
return False
iterations_of_nan_expand('Not a Not a Not a Not a Not a Not a Not a Not a Not a Not a NaN')
iterations_of_nan_expand("")
iterations_of_nan_expand("Not a NaN")
iterations_of_nan_expand('Not a Not a Not a Not a Not a Not a Not a Not a Not a Not a NaN')
iterations_of_nan_expand("Show these people!")
|
a39f2b66c43d1f59ff942e33741c9bc4e26a9b95 | toggled/NetTrees | /metric.py | 4,114 | 4.3125 | 4 | """
Defines classes to compute the distance between points in any general metric spaces.
"""
from abc import ABC, abstractmethod
import functools
from config import config
class Metric(ABC):
"""
An abstract base class for any arbitrary metric which delegates the distance
computation to its concrete subclasses.
Parameters
----------
cachedist : bool
Determines whether the computed distances should be stored in
a dictionary to avoid recalculations.
"""
def __init__(self, cachedist):
self.cachedist = cachedist
self.distdict = dict()
self.reset()
def reset(self):
"""
Resets the counter tracing the number of distance computations
and clears the dictionary storing the computed distances.
Parameters
----------
None
Returns:
-------
None
"""
self.counter = 0
self.distdict.clear()
def dist(self, first, *others):
"""
Computes the minimum distance of a point to other points.
Parameters
----------
first : Point
The first point.
others: variable length argument list of type Point
A collection of points.
Returns:
-------
float or Decimal
The minimum distance.
"""
if len(others) == 0:
raise TypeError("Metric.dist: this method should have at least two arguments")
return min(map(functools.partial(self.getdist, first), others))
def getdist(self, first, second):
"""
Computes the distance between two points.
Parameters
----------
first : Point
The first point.
second: Point
The second point.
Returns:
-------
float or Decimal
The distance between `first` and `second`.
"""
dist = (self.distdict.get((id(first), id(second)), None) or
self.distdict.get((id(second), id(first)), None)) if self.cachedist else None
if not dist:
dist = 0
if first != second:
dist = self.distance(first, second)
self.counter += 1
if self.cachedist:
self.distdict[(id(first), id(second))] = dist
return dist
@abstractmethod
def distance(self, first, second):
"""
Returns the distance between two points in a certain metric.
To be implemented by concerete metric subclasses.
Parameters:
----------
first : Point
The first point.
second : Point
The second point.
Returns:
-------
float or Decimal
The distance between the first and the second points.
"""
pass
def __str__(self):
"""
Creates a string representation for a metric object.
Parameters:
----------
None
Returns:
-------
str
The class name.
"""
return type(self).__name__
class Euclidean(Metric):
def __init__(self, cachedist=False):
Metric.__init__(self, cachedist)
def distance(self, first, second):
return config.arithmatic.sqrt(sum((first[i] - second[i]) ** 2 for i in range(len(first.coords))))
class Manhattan(Metric):
def __init__(self, cachedist=False):
Metric.__init__(self, cachedist)
def distance(self, first, second):
return sum([abs(first[i] - second[i]) for i in range(len(first.coords))])
class LInfinity(Metric):
def __init__(self, cachedist=False):
Metric.__init__(self, cachedist)
def distance(self, first, second):
return max([abs(first[i] - second[i]) for i in range(len(first.coords))])
|
15cec1129c5142f3f7a41ae119ff540df5130717 | SaudiWebDev2020/Sumiyah_Fallatah | /Weekly_Challenges/python/week5/week5day1.py | 3,255 | 4.21875 | 4 | # Node
# - Constructor
# -val
# - next
class StackNode:
def __init__(self, value=None, next=None):
self.value = value
self.next = None
# -Constructor
# - head
class Stack:
def __init__(self):
self.head = None
temp = self.head
# Stack Push
# ------------------------------------------------
# Create push(val) that adds val to our stack.
def push(self, val):
if self.head == None:
self.head = StackNode(val)
else:
print('pushing...')
new_val = StackNode(val)
new_val.next = self.head
self.head = new_val
# Stack Top
# ------------------------------------------------
# Return (not remove) the stack’s top value.
def top(self):
if self.head == None:
return None
else:
print('top is :')
print (self.head.value)
# Stack Is Empty
# ------------------------------------------------
# Return whether the stack is empty.
def isEmpty(self):
if self.head == None:
print ("this stack is empty")
else:
print ("this stack is not empty")
# Stack Pop
# ------------------------------------------------
# Create pop() to remove and return the top val.
def pop(self):
if self.head == None:
return None
else:
value = self.head.value
self.head = self.head.next
print('popping ...')
return f"the value {value} has been removed"
# Stack Contains
# ------------------------------------------------
# Return whether given val is within the stack.
def contain(self, value):
current = self.head
while current != None:
if current.value == value:
print(f"the value {value} exists!")
return True
current = current.next
# print(f"the value {value} does not exist")
return False
# Stack Size
# ------------------------------------------------
# Return the number of stacked values.
def size(self):
# if self.head == None:
# return None
# else:
temp = self.head
count = 0
while(temp):
count+=1
# print('value', temp.value)
temp = temp.next
print('size is :', count)
return count
def printstack(self):
head = self.head
while(head):
print(head.value)
head = head.next
def rListLength(self):
count =0
if self.head == None:
return None
else:
count+=1
self.head.next
return rListLength(self)
lifo = Stack()
lifo.isEmpty()
print('-'*30)
lifo.push(5)
lifo.push(9)
lifo.printstack()
print('-'*30)
lifo.pop()
lifo.printstack()
print('-'*30)
lifo.isEmpty()
print('-'*30)
lifo.size()
print('-'*30)
lifo.top()
print('-*'*30)
lifo.pop()
lifo.printstack()
print('-'*30)
lifo.isEmpty()
print('-'*30)
lifo.top()
lifo.push(5)
lifo.push(4)
lifo.push(7)
print(lifo.contain(5))
print(lifo.contain(9))
print('-'*30)
print('-'*30)
lifo.rListLength() |
f6172f74dedf06addccb87890613690ddadc2b75 | sahar-murrar/python_stack | /_python/python_fundamentals/Functions Intermediate II/Task3.py | 512 | 4.1875 | 4 | students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def iterateDictionary2(key_name, students):
for student in students:
for key,value in student.items():
if(key == key_name):
print(f"{student[key_name]}")
iterateDictionary2('last_name',students) |
368b3bd63d3a7c60fa192c6f95848bc971949b46 | ArmaniGiles/P | /com/fireboxtraining/box.py | 215 | 3.5 | 4 | '''
Created on Jun 11, 2017
@author: moni
'''
def square(x):
return x * x
def sta():
if __name__ == '__main__':
print ("test: square(42) ==", square(42))
print ("this is mygame.")
print (17*17) |
5414157e6935b057f7dcaecc9ff0ec752d47f960 | bansal19/PizzaParlour | /PizzaParlour.py | 6,666 | 3.578125 | 4 | from flask import Flask, request
from Classes.Menu import Menu
from Classes.Order import Order
from Classes.MenuItem import MenuItem
from Classes.Drink import Drink
from Classes.Pizza import Pizza
import json
menu_path = "Classes/Menu.json"
app = Flask("Assignment 2")
menu = Menu(menu_path)
# Store all the orders
all_orders = []
# Helper Functions:
def helper_add_to_order(order, json_data):
# Get all the Drinks from the POST request and add them to the order
try:
if len(json_data["Drinks"]) > 0:
for drink in json_data["Drinks"]:
order_drink = Drink(drink)
order.add_order_item(order_drink)
except KeyError:
pass
try:
# Get all the Pizzas from the POST request and add them to the order
if len(json_data["Pizzas"]) > 0:
for pizza in json_data["Pizzas"]:
pizza_name = pizza
pizza_size = json_data["Pizzas"][pizza_name]["size"]
pizza_toppings = json_data["Pizzas"][pizza_name]["toppings"]
order_pizza = Pizza(pizza_name, pizza_size, pizza_toppings)
order.add_order_item(order_pizza)
except KeyError:
pass
""" Menu APIs: """
@app.route('/pizza')
def welcome_pizza():
return 'Welcome to Pizza Planet!'
@app.route('/print_menu')
def print_menu():
return str(menu.get_menu())
@app.route("/get_item/<menu_item>", methods=['GET'])
def get_item(menu_item):
return str(menu_item) + ": " + str(menu.get_item_price(menu_item))
""" Order APIs: """
@app.route("/new_order", methods=['POST'])
def new_order():
"""
Input a new order into Pizza Parlour. It's a POST request with the body being a JSON
"""
if request.method == 'POST':
new_customer_order = Order()
helper_add_to_order(new_customer_order, request.get_json())
all_orders.append(new_customer_order)
return "Order was filled in successfully. Your orderID is: " + str(new_customer_order.order_number)
else:
return "Sorry, have to use POST request to fill in pizza order"
@app.route("/get_order_info/<order_id>", methods=['GET'])
def get_order_info(order_id):
if request.method == 'GET':
for order in all_orders:
if order.order_number == int(order_id):
return json.dumps(order.to_dict())
return "Sorry, the order with the order number " + order_id + " was not found."
@app.route("/order_distribution/<order_id>/<pickup_or_deliver>", methods=['PATCH'])
def set_order_distribution(order_id, pickup_or_deliver):
""" Provide information for if the order is for either pickup or delivery
possible values for pick_or_deliver: ["pickup", "in-house", 'uber', "foodora"] """
if request.method == 'PATCH':
for order in all_orders:
if order.order_number == int(order_id):
if pickup_or_deliver == "pickup":
order.set_order_distribution(pickup_or_deliver)
else:
json_data = request.get_json()
order.set_order_distribution(list(json_data.keys())[0], json_data[list(json_data.keys())[0]])
return json.dumps(order.to_dict())
return "Sorry, the order with the order number " + order_id + " was not found."
@app.route("/add_to_order/<order_id>", methods=['PATCH'])
def add_to_order(order_id):
"""Given a particular orderID, add to this specific order"""
if request.method == 'PATCH':
for order in all_orders:
if order.order_number == int(order_id):
json_data = request.get_json()
helper_add_to_order(order, json_data)
return json.dumps(order.to_dict())
return "Sorry, the order with the order number " + order_id + " was not found."
@app.route("/remove_from_order/<order_id>", methods=['PATCH'])
def remove_from_order(order_id):
""" Given particular orderID, remove specific items from the order"""
if request.method == 'PATCH':
for order in all_orders:
if order.order_number == int(order_id):
json_data = request.get_json()
try:
if len(json_data["Drinks"]) > 0:
for drink in json_data["Drinks"]:
drink_to_remove = Drink(drink)
order.remove_order_item(drink_to_remove)
except KeyError:
pass
try:
if len(json_data["Pizzas"]) > 0:
for pizza in json_data["Pizzas"]:
pizza_to_remove = Pizza(pizza)
order.remove_order_item(pizza_to_remove)
except KeyError:
pass
return json.dumps(order.to_dict())
return "Sorry, the order with the order number " + order_id + " was not found."
@app.route("/cancel_order/<order_id>", methods=['DELETE'])
def cancel_order(order_id):
"""Cancel the order with this orderID"""
if request.method == 'DELETE':
for order in all_orders:
if order.order_number == int(order_id):
order.cancel_order()
all_orders.remove(order)
return "Order: " + order_id + " cancelled successfully"
@app.route("/deliver_order/<order_id>", methods=['PATCH'])
def deliver_order(order_id):
if request.method == 'PATCH':
for order in all_orders:
if order.order_number == int(order_id):
if order.distribution == "pickup":
order.order_ready_for_pickup()
return "Order " + order_id + " ready for pickup"
elif order.distribution == "in-house":
order.order_out_for_delivery()
return "Order " + order_id + " is out for our in-house delivery to " + order.order_address
elif order.distribution == "uber":
order.order_out_for_delivery()
return json.dumps(order.to_dict())
elif order.distribution == "foodora":
order.order_out_for_delivery()
return json.dumps(order.to_dict())
return "Order was not delivered"
@app.route("/add_pizza/<new_pizza_type>/<price>", methods=['POST'])
def add_pizza_type(new_pizza_type, price):
if request.method == 'POST':
menu.create_pizza_type(new_pizza_type, float(price))
return new_pizza_type + ": " + str(menu.get_item_price(new_pizza_type))
if __name__ == "__main__":
app.run()
|
88f42e0e7fea00efdeb616293b9182c7b083a77b | J-Krisz/EDUBE-Labs | /PCAP/2.5.1.9 LAB: The Digit of Life.py | 868 | 4.5 | 4 | """
Some say that the Digit of Life is a digit evaluated using somebody's birthday. It's simple - you just need to sum
all the digits of the date. If the result contains more than one digit, you have to repeat the addition until you get
exactly one digit. For example:
1 January 2017 = 2017 01 01
2 + 0 + 1 + 7 + 0 + 1 + 0 + 1 = 12
1 + 2 = 3
3 is the digit we searched for and found.
Your task is to write a program which:
asks the user her/his birthday (in the format YYYYMMDD, or YYYYDDMM, or MMDDYYYY - actually, the order of the
digits doesn't matter) outputs the Digit of Life for the date.
"""
# input data
birth_date = int(input("Enter your date of birth :"))
try:
while birth_date > 9:
birth_date = sum([int(i) for i in str(birth_date)])
print(birth_date)
except ValueError:
print("Enter digits only please")
|
6da6d2660dd06466767f0fdf0d052d9fe350bee0 | tangmingyi/offer | /4.py | 638 | 3.75 | 4 | # -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target:int, array:list)->bool:
rows = len(array)
cols = len(array[0])
for col in range(cols-1,-1,-1):
for row in range(rows):
if(array[row][col]>target):
break
else:
if(array[row][col]==target):
return True
return False
# write code here
if __name__ == '__main__':
array = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
target = 7
sol = Solution()
result = sol.Find(target,array)
print(result)
|
1b8ad2897d1c89ea821aa7a779f522af57de8fc2 | devynchew/number-guessing-game | /noGuessGame.py | 1,286 | 3.90625 | 4 | max = int(input("Enter the range: ")) # Get max number
johnsNumber = int(input(f'Think of a random number between 1 and {max} and press enter once done: ')) # Get the number the program has to guess
numberHasBeenGuessed = False
noOfQuestions = 0
candidates = list(range(1,max+1))
# breakpoint = 1 # Initialize first oldbreakpoint
i = 0
while not numberHasBeenGuessed:
breakpointIndex = int(len(candidates)/2)
oldbreakpoint = breakpoint
breakpoint = candidates[breakpointIndex]
userinput = input(f'Is it smaller than {breakpoint}, \'y\' or \'n\'? ').lower()
if userinput == 'y':
if i == 0:
oldbreakpoint = 1
elif breakpoint < oldbreakpoint:
oldbreakpoint = candidates[0]
candidates = list(range(oldbreakpoint,breakpoint))
else:
if i == 0:
oldbreakpoint = max + 1
elif oldbreakpoint < breakpoint:
oldbreakpoint = candidates[-1] + 1
candidates = list(range(breakpoint,oldbreakpoint))
noOfQuestions += 1
if len(candidates) == 1: # number has been guessed when only one number is left in the list
numberHasBeenGuessed = True
i += 1
print(f'Wonderful it took me {noOfQuestions} questions to find out that you had the number {candidates[0]} in mind!') |
795f87bd4abdf66b13fbd17cf5ef3f68a6d3af0e | maria-zdr/softuni | /Python Fundamentals/Functions/4.Draw a Filled Square.py | 215 | 3.96875 | 4 | def print_dashes(n):
print('-' * 2 * n)
def print_middle(n):
for i in range(0, n - 2):
print('-' + '\\/' * (n - 1) + '-')
num = int(input())
print_dashes(num)
print_middle(num)
print_dashes(num)
|
30122f2f9bd8b4cc27a3643d974ad3b52113205f | hussainMansoor876/Python-Work | /Chapter 2 & 3/title 1.py | 108 | 3.53125 | 4 | name="Mansoor"
age=18
info=name+" "+str(age)
print(name)
print(age)
print(info)
print(name + " " + str(age)) |
f36b98a01be793430cfd49640364aaccddb44b1c | Bankole2000/pirple-training | /pirplePython/main.py | 1,373 | 3.703125 | 4 | """
FileName: main.py V1.0
Author: Bankole Esan
Description: Pirple.com Python Homework #1
Task: Variables for attributes of favorite Song
"""
SongTitle = "Wa Mpaleha" # Title of the song
Artist = "Lira" # Recording Artist
Genre = "R & B" # Genre or Category of the song
DurationInSeconds = 204 # Length of song in seconds
# Length of song in minutes
DurationInMinutes = f"{ int((DurationInSeconds / 60) - ((DurationInSeconds % 60) / 60)) }:{ DurationInSeconds % 60 }"
Album = "Soul in Mind" # Album where song first featured
TrackNumber = 1 # Song track number on album
CountryOfFirstRelease = "South Africa" # Any Featured artists
YearReleased = 2008 # Year released
RecordLabel = "Sony Music" # Record label song was released under
Mp3FileSizeInMB = 9.09 # Size of song on disk in MegaBytes
Mp3FileSizeInKB = Mp3FileSizeInMB * 1024 # Size of song on disk in KiloBytes
InStoresNow = True
# print(f"Title: {SongTitle}")
# print(f"Artist: {Artist}")
# print(f"Genre: {Genre}")
# print(f"Duration in Seconds: {DurationInSeconds}")
# print(f"Duration in Minutes: {DurationInMinutes}")
# print(f"Album name: {Album}")
# print(f"Track Number: {TrackNumber}")
# print(f"Country of Release: {CountryOfFirstRelease}")
# print(f"Year: {YearReleased}")
# print(f"Label: {RecordLabel}")
# print(f"Size in MB: {Mp3FileSizeInMB} MB")
# print(f"Size in KB: {Mp3FileSizeInKB} KB")
|
1e659720b23761566d50fc3313657a2e7759dbad | roryfortune/CP1404-Practicals | /prac_05/STATE_NAMES.py | 552 | 4.34375 | 4 | stateNames = {"QLD": "Queensland",
"ACT": "Australian Capital Territory",
"NT": "Northern Territory",
"VIC": "Victoria",
"WA": "Western Australia",
"TAS": "Tasmania",
"NSW": "New South Wales"}
states = input("Enter short state: ").upper()
while states != "":
if states in stateNames:
print(states, "=", stateNames[states])
else:
print("Error: Short state is invalid")
states = input("Enter a short state: ").upper()
|
55c8d53a7d054102429a24dc9f27ca7f2bb5680c | boyshen/leetcode_Algorithm_problem | /680.验证回文字符串Ⅱ/validPalindrome.py | 2,267 | 3.609375 | 4 | # -*- encoding: utf-8 -*-
"""
@file: validPalindrome.py
@time: 2020/11/18 下午2:24
@author: shenpinggang
@contact: [email protected]
@desc: 680. 验证回文字符串 Ⅱ
给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。
示例 1:
输入: "aba"
输出: True
示例 2:
输入: "abca"
输出: True
解释: 你可以删除c字符。
注意:
字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome-ii
"""
import unittest
def valid_palindrome1(s):
"""
贪心算法。 时间复杂度为 O(n), 空间复杂度为O(1)
1. 枚举左右指针。如果左右字符相等,则进入下一个。如果不相等,则进行删除左字符或右字符。
:param s: (str)
:return: (bool)
"""
def check_palindrome(low, height):
i, j = low, height
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
left, right = 0, len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
return check_palindrome(left + 1, right) or check_palindrome(left, right - 1)
return True
def valid_palindrome(s):
def valid(low, height):
while low < height:
if s[low] != s[height]:
return False
low += 1
height -= 1
return True
left, right = 0, len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
return valid(left + 1, right) or valid(left, right - 1)
def work(s, answer):
outputs = valid_palindrome(s)
print("Inputs:{}, Outputs:{}, Except:{}".format(s, answer, outputs))
return outputs
class TestValidPalindrome(unittest.TestCase):
def test_valid_palindrome(self):
s, answer = "aba", True
self.assertTrue(work(s, answer))
s, answer = "abca", True
self.assertTrue(work(s, answer))
s, answer = "abcaadba", False
self.assertFalse(work(s, answer))
if __name__ == '__main__':
unittest.main()
|
a1915e013cf9e1800bc457eb508495da4fb72917 | mengyujackson121/CodeEval | /split_the_number.py | 477 | 3.75 | 4 | import sys
import re
def split_plus_or_minus(integer_string):
if "+" in integer_string:
first, second = integer_string.split("+")
print int(first) + int(second)
else:
first, second = integer_string.split("-")
print int(first) - int(second)
f = open(sys.argv[-1],'r').readlines()
for line in f:
a = re.split('([- +])',line.strip())
# print a
n = len(a[2])
l = a[0]
split_plus_or_minus(l[:n] + a[3] + l[n:])
|
6f2957a258449386d7525f541ed076459bcc5175 | Squirrel-zc/Learn_share | /Try/guess_age_第一版.py | 2,205 | 3.578125 | 4 | # coding-utf-8:
import cent_screen
def guess_age(true=29,n=3,c=0): # true是正确年龄,n为可猜次数,c为已猜次数
range_begin=true-10
if range_begin<=0:
range_begin=1
range_over=true+10
if range_over<=10:
range_over=11
age_range=[range_begin,range_over]
print('我的年龄范围是:',range_begin,'~',range_over)
age_guess_over="年龄不是问题,重要的是我们有没有共同语言。" \
"不如见见我吧,见到我您一定会说,‘看起来好小啊!’,哈哈!!" \
" PS:快面试我吧!"
guesslist=[]
while True:
guess=int(input('猜一猜(请输入整数):')) #猜测值取整,如果输入非法还需处理
guesslist.append(guess)
x=guess-true #猜测值与真实值的差
if n==0:
n=''
if guess==true:
if c==0:
print('您快去买彩票吧,居然一次就猜中了,但我还是要说:',age_guess_over)
else:
print('恭喜您猜中了,但我还是要说:',age_guess_over)
break
if guess<true:
if abs(x)<=2:
print('我比您猜的年龄大一点点\n')
else:
print('我比您猜的要大一些\n')
n=n-1
c=c+1
print('您已经猜了{}次,您还有{}次机会。'.format(c,n))
else:
if abs(x)<=2:
print('我比您猜的年龄小一点点\n')
else:
print('我比您猜的年龄小得多\n')
n=n-1
c=c+1
print('您已经猜了{}次,您还有{}次机会。'.format(c,n))
if c==3:
print("非常抱歉,三次机会已经用完.")
print('您的三次猜测依次为:',guesslist)
print("'松果'虽然不能直接告诉您我的年龄,但是通过您的三次猜测,""'松果'帮您算出了我新的年龄范围:")
cent_screen.cent_screen(true,guesslist)
break
guess_age()
|
981330b014f914095451db154cd064adebb5209f | AlexandreVelloso/escola-de-ferias | /2018-1/Introdução a criptografia e segurança digital/Codigos/Desafio 1/Vigenere.py | 951 | 3.609375 | 4 | import sys
def criptografa( mensagem, senha ):
mensagemCriptografada = ''
pos = 0
for c in mensagem:
mensagemCriptografada += chr( ( ord(c) + ord(senha[pos]) ) % 256 )
pos = ( pos + 1 ) % len( senha )
return mensagemCriptografada
def descriptografa( mensagem, senha ):
mensagemCriptografada = ''
pos = 0
for c in mensagem:
mensagemCriptografada += chr( ( ord(c) - ord(senha[pos]) ) % 256 )
pos = ( pos + 1 ) % len( senha )
return mensagemCriptografada
if __name__ == "__main__":
mensagemOriginal = input("Digite uma mensagem\n")
senha = input("Digite a senha\n")
mensagemCriptografada = criptografa( mensagemOriginal, senha )
print( "\nMensagem original\n"+ mensagemOriginal )
print( "\nMensagem criptografada\n"+ criptografa( mensagemOriginal, senha ) )
print( "\nMensagem descriptografada\n"+ descriptografa( mensagemCriptografada, senha ) +"\n") |
2713d49761eb192a0fbf433f5dcf5526809dd906 | trigus00/python-challenge | /Pybank/main.py | 2,198 | 3.6875 | 4 | import os
import csv
from statistics import mean
budget_data_path = os.path.join('/Users/gmendoza/Documents/GitHub/python-challenge/Pybank/main.py','budget_data.csv')
total_month = 0
total_revenue = 0
change_in_revenue_list = []
previous_revenue = 0
percent_increase = [" " ,0]
percent_decrease = [" " ,0]
with open('budget_data.csv',newline='') as csvfile:
read =csv.DictReader(csvfile)
for row in read:
#Tracking Total Months and Revenue
total_month = total_month + 1
total_revenue = total_revenue + int(row["Profit/Losses"])
#Calculate the total revenue and changes
change_in_revenue = (int(row["Profit/Losses"]) - previous_revenue)
previous_revenue = (int(row["Profit/Losses"]))
change_in_revenue_list.append(change_in_revenue)
#calculate percent increase and decrease
if (change_in_revenue > percent_increase[1]):
percent_increase[0] = row["Date"]
percent_increase[1] = change_in_revenue
if change_in_revenue < percent_decrease[1]:
percent_decrease[0] = row["Date"]
percent_decrease[1] = change_in_revenue
#Change in revenue
average_change = (sum(change_in_revenue_list) - change_in_revenue_list[0] )/(len(change_in_revenue_list)-1)
print("--- Finacial Analysis----\n")
print (f"Total Months: {total_month}\n")
print (f"Total Revenue: (${total_revenue:,.2f})\n")
print(f"Greatest Increase in Revenue: {percent_increase[0]} (${percent_increase[1]:,.2f})\n")
print (f"Greatest Decrease in Revenue: {percent_decrease[0]} (${percent_decrease[1]:,.2f})\n")
print (f"Average Change: (${average_change:,.2f})\n",)
budget_data_output = "Budget_data.txt"
with open(budget_data_output, "w") as txt_file:
txt_file.write(
"--- Finacial Analysis----\n"
f"Total Months: {total_month}\n"
f"Total Revenue: (${total_revenue:,.2f})\n"
f"Greatest Increase in Revenue: {percent_increase[0]} (${percent_increase[1]:,.2f})\n"
f"Greatest Decrease in Revenue: {percent_decrease[0]} (${percent_decrease[1]:,.2f})\n"
f"Average Change: (${average_change:,.2f})\n")
|
696ade49a388256b3c1ed043c8ce6f3f74d108a6 | idahopotato1/learn-python | /09- Python Decorators/003-decorators.py | 1,102 | 4.28125 | 4 | # functions as Arguments
print('=============================================')
def hello():
return 'Hello'
def other_fun(fun):
print('other fun')
print(fun())
other_fun(hello) # other fun , Hello
print('=============================================')
def new_decorator(func):
def wrap_func():
print('code here, before executing the func')
func()
print('code here will execute after the func()')
return wrap_func
def func_needs_decorator():
print('This function needs a decorator !')
func_needs_decorator = new_decorator(func_needs_decorator)
func_needs_decorator()
# code here, before executing the func
# This function needs a decorator !
# code here will execute after the func()
print('=============================================')
@new_decorator
def func_needs_decorator_2():
print('This function needs a decorator !')
func_needs_decorator_2()
# code here, before executing the func
# This function needs a decorator !
# code here will execute after the func()
print('=============================================')
|
43d7c323bff218ec7ced79ddda28537e36dc05cd | kdockman96/CS0008-f2016 | /Ch3-Ex/ch3-ex11.py | 469 | 4.21875 | 4 | # Ask the user to enter the number of books purchased
books = int(input('Enter the number of books purchased: '))
# Write an IF-ELIF-ELSE statement, but an else statement \
# is not needed in this situation
if books == 0:
print('No points are awarded.')
elif books == 2:
print('5 points are awarded.')
elif books == 4:
print('15 points are awarded.')
elif books == 6:
print('30 points are awarded.')
elif books >= 8:
print('60 points are awarded.') |
d71e7905878eafacf189fce5f7df2a9e39c69e3a | EishaMazhar/Semester6-Resources | /IR/Batch15_Assignment/positional index/search.py | 2,949 | 3.6875 | 4 | import json
from nltk.stem import PorterStemmer as ps
import nltk
with open("index_without_stem.json", "r") as read_file:
index = json.load(read_file)
def intersection(a,b):
result = []
for item in a:
if item in b and not item in result:
result.append(item)
return result
def single_word(list):
counter = 0
newlist = []
while counter<len(list):
if not list[counter][0] in newlist:
newlist.append(list[counter][0])
counter = counter + 1
return newlist
def invert(list):
newlist = range(1, 51)
newlist2 = []
for element in newlist:
if not element in list:
newlist2.append(element)
return newlist2
string = input('Enter your query please: ')
query1 = string
query = nltk.word_tokenize(query1.lower())
if '/' in query1:
if len(query) == 3:
count = int(query[2][1:])
##print (count)
list = index[query[0]]
list2 = index[query[1]]
#print (list) uncomment to see the lists
#print(list2)
result = []
for element in list:
for element1 in list2:
ans = int(int(element[1])-int(element1[1]))
if ans<0:
ans = ans * -1
if (int(element[0]) == int(element1[0])) and (ans <= count) and (not element[0] in result):
result.append(element[0])
print(result)
else:
string = string.replace(' ','')
strint = string.split('or')
print(strint)
value = list(range(0,len(strint)))
counter = 0
for elem in strint:
value[counter] = elem.split('and')
counter = counter + 1
#print(value)
#print(len(value))
counter = 0
temp = []
result = []
for elem in value:
if len(elem) == 1:
for x in elem:
if 'not' in x:
var = invert(single_word(index[x[3:]]))
result.append(var)
else:
var = single_word(index[x])
result.append(var)
else:
#temp = list(range(0,len(value)))
for x in elem:
if 'not' in x:
var = invert(single_word(index[x[3:]]))
temp.append(var)
else:
var = single_word(index[x])
temp.append(var)
if len(temp) > 1:
counter = 1
result2 = temp[0]
while int(counter) <int(len(temp)):
result2 = intersection(result2,temp[counter])
counter = counter+1
result.append(result2)
result3 = []
for elem in result:
for elem1 in elem:
if not elem1 in result3:
result3.append(elem1)
var = len(result3)
print('There are ' + str(var) + ' results for your query')
print(result3)
|
158cce25a012104652c81075282f4e4fa1d27974 | climberhunt/wiring-x86 | /examples/fade.py | 1,814 | 4.0625 | 4 | # -*- coding: utf-8 -*-
#
# Copyright © 2014, Emutex Ltd.
# All rights reserved.
# http://www.emutex.com
#
# Author: Nicolás Pernas Maradei <[email protected]>
#
# See license in LICENSE.txt file.
#
# This example is inspired on Arduino Fade example.
# http://arduino.cc/en/Tutorial/Fade
#
# This example will work "out of the box" on an Intel® Edison board. If
# you are using a different board such as an Intel® Galileo Gen2, just change the
# import below. wiringx86 uses the same API for all the boards it supports.
# Import the time module enable sleeps between turning the led on and off.
import time
# Import the GPIOEdison class from the wiringx86 module.
from wiringx86 import GPIOEdison as GPIO
# Create a new instance of the GPIOEdison class.
# Setting debug=True gives information about the interaction with sysfs.
gpio = GPIO(debug=False)
pin = 3
brightness = 0
fadeAmount = 5
# Set pin 3 to be used as a PWM pin.
print 'Setting up pin %d' % pin
gpio.pinMode(pin, gpio.PWM)
print 'Fading pin %d now...' % pin
try:
while(True):
# Write brightness to the pin. The value must be between 0 and 255.
gpio.analogWrite(pin, brightness)
# Increment or decrement the brightness.
brightness = brightness + fadeAmount
# If the brightness has reached its maximum or minimum value swap
# fadeAmount sign so we can start fading the led on the other direction.
if brightness == 0 or brightness == 255:
fadeAmount = -fadeAmount
# Sleep for a while.
time.sleep(0.03)
# When you get tired of seeing the led fading kill the loop with Ctrl-C.
except KeyboardInterrupt:
# Leave the led turned off.
print '\nCleaning up...'
gpio.analogWrite(pin, 0)
# Do a general cleanup. Calling this function is not mandatory.
gpio.cleanup()
|
62c27d800f72b4521403a04c9cece0b778bd34a5 | lntutor/cp | /practice/python/time_conversion.py | 289 | 3.796875 | 4 | time = raw_input()
if 'AM' in time:
hh = (int) (time[:2])
if hh == 12:
hh = '00'
print hh + time[2:8]
else:
print time[:8]
else:
hh = (int) (time[:2])
if hh != 12:
hh += 12
print `hh` + time[2:8]
else:
print time[:8] |
83a57f785080067ca38aab040bd2c65fd7d9cc68 | kamit17/Python | /Think_Python/Chp11/Examples/primes_lessthan.py | 451 | 4.09375 | 4 | def is_prime(n):
if ( n ==1):
return False
elif (n ==2):
return True
else:
for x in range(2,n):
if(n %x ==0):
return False
return True
def primes_lessthan(n):
"""Returns a list of all prime numbers less than n."""
result = []
for i in range(2,n):
if is_prime(i):
result.append(i)
return result
#print(is_prime(15))
print(primes_lessthan(15)) |
3536a6f56204797b26c60818e7dad939d6b7f482 | saritaverma60/python-program | /recursion-factorial.py | 197 | 4.15625 | 4 | # Recursion Factorial of number
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
n=int(input("Enter the no. :"))
R=fact(n)
print("FACTORIAL of ",n," is ",R)
|
bada6cf0c7e88733ab8caa0881458d803e74c335 | Kabileshj/college-works | /Stacks and Queues/Sort Stack.py | 556 | 4.03125 | 4 | def sortedInsert(s , element):
if len(s) == 0 or element > s[-1]:
s.append(element)
return
else:
temp = s.pop()
sortedInsert(s, element)
s.append(temp)
def sortStack(s):
if len(s) != 0:
temp = s.pop()
sortStack(s)
sortedInsert(s , temp)
def printStack(s):
for i in s[::-1]:
print(i , end=" ")
print()
# Driver Code
if __name__=='__main__':
s = [ ]
for i in [int(i) for i in input().split()]:
s.append(i)
sortStack(s)
print("\nStack elements after sorting: ")
printStack(s) |
74c671655defa6123b02ec3d286f5e5518f181de | qiangzuangderen/My_code | /python_learn/py_test/mypro_base/gridPassing.py | 174 | 3.75 | 4 | #coding=UTF-8
grid0 = [[1,2],[3,4],[5,6]]
grid1 = []
print(grid0)
for i in range(3):
print(grid0[i])
for j in range(2):
print(grid0[i][j])
|
ee4268323ad177d7c25992105149d646ea764124 | eloghin/Python-courses | /HackerRank/pilingup.py | 1,362 | 4 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
"""
There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical
pile of cubes. The new pile should follow these directions: if cubei is on top of cubej then sideLengthj>=sideLengthi.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time.
Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks.
Input Format
The first line contains a single integer, T, the number of test cases.
For each test case, there are lines.
The first line of each test case contains , the number of cubes.
The second line contains space separated integers, denoting the sideLengths of each cube in that order.
"""
from collections import deque
T = int(input())
for _ in range(T):
n = int(input())
d = deque(map(int, input().split()))
top_of_pile = max(d[0],d[len(d)-1])
print(len(d))
while len(d) > 0 and top_of_pile >= max(d[0],d[len(d)-1]):
if d[0] >= d[len(d)-1]:
top_of_pile = d[0]
d.popleft()
print(f'd.popleft:{d}')
else:
top_of_pile = d[len(d)-1]
d.pop()
print(f'd.pop:{d}')
if len(d) == 0:
print("Yes")
else:
print("No")
|
a5874e39f6d28e5a4feaa396b7f0d3827570ba17 | rachel2011/Job | /CC150/chap01/is_unique.py | 396 | 3.828125 | 4 |
def isUniqueChars(input):
# O(n) time
if len(input) > 128:
return false
charSet = [False] * 128
for char in input:
index = ord(char)
if charSet[index]:
return False
charSet[index] = True
return True
# Test
input = 'a'
print isUniqueChars(input)
input = 'abc'
print isUniqueChars(input)
input = 'asdfa'
print isUniqueChars(input)
|
5de5aeebb607b47b54b82d97b766423c065dcda9 | sunnyhyo/Problem-Solving-and-SW-programming | /lab12-1.py | 439 | 3.65625 | 4 | #실습1
import turtle
def play():
t.forward(2)
screen.ontimer(play, 10)
t=turtle.Turtle()
t.up()
screen=t.getscreen()
screen.ontimer(play,10)
import turtle
stop=False
def moveStop():
global stop
stop=True
def play():
t.forward(2)
if stop ==False:
screen.ontimer(play, 10)
t=turtle.Turtle()
t.up()
screen = t.getscreen()
screen.ontimer(play,10)
screen.onkeypress(moveStop, "Up")
screen.listen()
|
259b05cab684c7866d4462099529706526580f24 | mwiens91/sfu_ec_2017_10_29 | /safetrain/train.py | 3,789 | 4.03125 | 4 | """Train class and related functions."""
from . import controller
from enum import Enum
class TrainState(Enum):
"""Simple enumerator which holds state of train."""
INMOTION = 1
IDLING = 2
OOS = 3
EMR = 4
class Train:
"""Represents a train on the transportation grid.
Attributes:
idnum: A five digit integer containing the trains identification number.
state: A TrainState instance which indicates whether the train
is in motion, idling, or out of service.
velocity: A float representing the velocity of the train. This
is a signed number; i.e., a negative sign means the train is
travelling west or south.
frontRed: A float representing the front red buffer of the
train. If this buffer contacts another train's rear blue buffer,
then an emergency stop will be performed.
frontYellow: A float representing the front yellow buffer of the
train. If this buffer contacts another train's rear blue
buffer, then the train will be slowed down.
backBlue: A float representing the rear blue buffer, which
interacts with frontRed and frontYellow above.
"""
def __init__(self, controller, idnum, road, position):
"""Initialize train variables."""
self.controller = controller
self.idnum = idnum
self.road = road
self.position = position
self.velocity = 0
self.acceleration = 9.8
self.state = TrainState.IDLING
self.maxSlowAmount = -9.8
self.position = position
self.length = 144
self.frontRed = 0
self.frontYellow = 0
self.backBlue = 0
def calculateBuffer(self):
if self.velocity >= 51:
self.frontRed = 121.4 + (((self.velocity-51)/37)*51.8)
self.frontYellow = 217.3 + (((self.velocity-51)/37)*85.1)
self.backBlue = 82.15 - (((self.velocity - 51)/37)*12.95)
elif self.velocity >= 31:
self.frontRed = 88.75 + (((self.velocity-31)/19)*23.75)
self.frontYellow = 162 + (((self.velocity-31)/19)*38)
self.backBlue = 89.15 - (((self.velocity - 31)/19)*(-6.65))
elif self.velocity >= 1:
self.frontRed = 51.1 + (((self.velocity-1)/30)*31.9)
self.frontYellow = 101.8 + (((self.velocity-1)/30)*52.2)
self.backBlue = 99.65 - (((self.velocity - 1)/30)*(-10.15))
else:
self.frontRed = 50
self.frontYellow = 100
self.backBlue = 100
def getTrainState(self):
return self.state
def bufferIsClear(self):
if self.yellowZoneIsEmpty() and self.redZoneIsEmpty():
return True
return False
def yellowZoneIsEmpty(self):
if self.controller.distanceToIntersection() <= self.frontYellow and self.controller.isIntersectionOpen():
return True
return False
def redZoneIsEmpty(self):
if self.controller.distanceToIntersection() <= self.frontRed and self.controller.isIntersectionOpen():
return True
return False
def eStop(self):
while self.redZoneIsEmpty():
self.changeSpeed(self.maxSlowAmount)
def eSlow(self):
while self.yellowZoneIsEmpty():
self.changeSpeed(self.maxSlowAmount)
def speedUp(self):
if self.velocity < 88.5:
self.changeSpeed(self.acceleration)
def changeSpeed(self, delta):
if self.velocity + delta > 88.5:
self.velocity = 88.5
elif self.velocity + delta < 0:
self.velocity = 0
else:
self.velocity += delta
if __name__ == "__main__":
# Self-test code
train1 = Train()
|
690e5cda620a8d2c8b5a6a1cd5657d4750a11eb0 | vit050587/Python-homework-GB | /lesson2.4.py | 1,177 | 3.8125 | 4 | # 4. Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
n_str = input("введите строку: ")
word = []
number = 1
el = 0
for el in range(n_str.count(' ') + 1):
word = n_str.split()
if len(str(word)) <= 10:
print(f" {number} {word[el]}")
number += 1
else:
print(f" {number} {word[el][:10]}")
number += 1
#--------------------------Решение GB----------------------------
string = input('Enter the number with space - ').split()
for n, i in enumerate(string, 1):
print(n, i) if len(i) <= 10 else print(n, i[:10])
#--------------------------------------------------------------
my_string = input('Введите строку из нескольких слов, разделенных пробелами: ').split()
for i, word in enumerate(my_string, 1):
print(f'{i}. {word[:10]}')
|
ba661bb30923b54847bb2ce9c967f4f8b5e54367 | Abdulrehmanvirus10/Automate_the_boring_stuff_with_Python | /tests/test_4.py | 129 | 3.78125 | 4 | def printMyName(myName):
print('My name is' + myName)
print('Who are you ?')
myName = input()
printMyName(myName)
|
77e644180f2598e302f357d888ca3363adde5f32 | woshihehao/Game | /game2.py | 1,357 | 3.5 | 4 | # -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name_, atk_, blood_, defense_):
self.name = name_
self.atk = atk_
self.blood = blood_
self.defense = defense_
def attack(self, b):
if b.defense <= self.atk:
real_damage = self.atk - b.defense
hurt = b.blood if real_damage > b.blood else real_damage
b.blood = b.blood - hurt
print '%s攻击%s,%s收到%d点伤害,%s剩余生命值:%d' % (self.name, b.name, b.name, hurt, b.name, b.blood)
else:
self.blood = 0
print '连防御都破不了,打个卵'
def Fight(a, b):
flag = True
while a.blood > 0 and b.blood > 0:
if flag:
a.attack(b)
else:
b.attack(a)
flag = not flag
if a.blood > 0:
print "%s获胜" % (a.name)
if b.blood > 0:
print "%s获胜" % (b.name)
def main():
per = []
for i in range(2):
name_ = raw_input('名字:')
atk_ = input('攻击力:')
blood_ = input('血量:')
defense_ = input('防御力:')
per.append(Student(name_, atk_, blood_, defense_))
'''zhang_san = Student('张三', 2, 6, 2)
li_si = Student('李四', 2, 7, 1)'''
Fight(per[0], per[1])
if __name__ == "__main__":
main() |
29f13cfa558c53cfca4391c394fc566f08e9cfe4 | sailakshmi-mk/pythonprogram1 | /venv/co1/10. Area of circle.py | 80 | 4.03125 | 4 | r=int(input("enter a radius"))
area=3.14*r*r
print("the area of circle is",area) |
ef0f6e9bb6e2412fdc6546b14705ecea522a11bb | Tdfrantz/DJST-AI | /src/card.py | 1,536 | 3.984375 | 4 | # classes and functions for cards and decks of cards
import random
cardNumbers = ["ace",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"jack",
"queen",
"king"]
cardSuits = ["spades","hearts","diamonds","clubs"]
blackjackValues = [11,2,3,4,5,6,7,8,9,10,10,10,10]
# represents a card in the blackjack game
class Card:
def __init__(self,number,suit,value):
self.number = number
self.suit = suit
self.value = value
def __str__(self):
return "<%s:%s:%d>" % (self.number,self.suit,self.value)
def __repl__(self):
return "<%s:%s:%d>" % (self.number,self.suit,self.value)
# a deck of cards that can be drawn from and shuffled
class Deck:
def __init__(self):
self.reset()
def __str__(self):
ret = "["
for card in self.cards:
ret += " %s " % card
ret += "]"
return ret
# reset the deck of cards
def reset(self):
self.cards = []
for suit in cardSuits:
for i in range(len(cardNumbers)):
self.cards.append(Card(cardNumbers[i],suit,blackjackValues[i]))
# shuffle the deck
def shuffle(self):
random.shuffle(self.cards)
# remove a card from top of deck and return it
def draw(self):
return self.cards.pop()
# test
if __name__ == "__main__":
deck = Deck()
print (deck)
print ("DRAWING")
print (deck.draw())
print ("DECK AFTER DRAW")
print (deck)
|
079d558de95f4650e766e308d04b68f86c1a62fc | ParisRohan/Python_Projects | /max_occurrence.py | 483 | 4.28125 | 4 | #Program to print maximum occurrence of a character in an input string along with its count
def most_occurrence(string_ip):
count={}
max_count=0
max_item=None
for i in string_ip:
if i not in count:
count[i]=1
else:
count[i]+=1
if count[i]>max_count:
max_count=count[i]
max_item=i
return max_item,max_count
string_ip=input("Enter a string")
print(most_occurrence(string_ip)) |
d2af354745db4ae3b8bb1846df55ecfd90623e4f | cboopen/algorithm004-04 | /Week 02/id_329/LeetCode_94_329.py | 1,881 | 4.0625 | 4 | # coding=utf-8
"""
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
"""
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 1. 递归法
# 前序遍历,中序遍历,后序遍历,只需要更改下代码顺序即可;维护很方便
# 时间复杂度: O(N)
# 空间复杂度: O(N)
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = []
self._inorder_traversal(root, result)
return result
def _inorder_traversal(self, root: TreeNode, _result: List[int]):
if not root:
return
if root.left:
self._inorder_traversal(root.left, _result)
_result.append(root.val)
if root.right:
self._inorder_traversal(root.right, _result)
# 2. 利用栈实现
# 本质还是递归,手动维护一个栈;递归是自动维护一个栈
# 时间复杂度: O(N)
# 空间复杂度: O(N)
def inorderTraversal2(self, root: TreeNode) -> List[int]:
result = []
if not root:
return result
stack = []
curr = root
while curr or len(stack) != 0:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
result.append(curr.val)
curr = curr.right
return result
if __name__ == '__main__':
# origin data
root_node = TreeNode(1)
root_node.right = TreeNode(2)
root_node.right.left = TreeNode(3)
so = Solution()
print(so.inorderTraversal2(root_node))
|
93dd9ffd97af04d2212ca02ee47493d36e6a1d49 | ds-ga-1007/assignment7 | /yz1349/assignment7.py | 1,183 | 3.90625 | 4 | import sys
from interval import interval,insert
if __name__=="__main__":
while True:
try:
inputstring = raw_input("List of intervals? ")
if inputstring == "quit":
sys.exit()
inputstring = inputstring.replace(" ","")
stringlist = inputstring.split(",")
intervallist=[]
for index in range(0,len(stringlist),2):
thisstring = stringlist[index]+","+stringlist[index+1]
intervallist.append(interval(thisstring))
break
except KeyboardInterrupt:
sys.exit()
except Exception:
print ('Invalid list input')
pass
while True:
try:
inputint = raw_input("Interval? ")
if inputint =="quit":
sys.exit()
inputint = interval(inputint)
intervallist = insert(intervallist,inputint)
for thisint in intervallist:
print(thisint),
print("")
except KeyboardInterrupt:
sys.exit()
except Exception:
print ("Invalid interval")
|
992199cd12ef1cd4b2fcb3369bb26068f9b5d614 | odilonjk/matematica | /limites/exemplo_1.py | 514 | 3.578125 | 4 | # %%
from sympy import Symbol, Limit, init_printing
init_printing(use_latex=True)
x = Symbol('x')
def f(x):
return (x**3 + x**2 + x)**101
def g(x):
return (x**2 - (2 * x)) / (x + 1)
print('Considerando a função f(x)')
display(f(x))
print('\ne a função g(x)')
display(g(x))
limite_fx = Limit(f(x), x, -1)
limite_gx = Limit(g(x), x, 3)
print('\nCalcule o valor do seguinte limite:')
display(limite_fx - 4 * limite_gx)
print('\nResultado: {}'.format(limite_fx.doit() - (4 * limite_gx.doit())))
|
fd52e8e4bd85af7a95234e8a2387bbf3fd8143a6 | seoyoungsoo/CodingTest-Python | /Programmers/Lv1/lv1_3진법뒤집기.py | 482 | 3.65625 | 4 | # 3진법 뒤집기
# 나의 풀이
THREE = 3
def solution(n):
question = []
answer = 0
decimal = n
while True:
if decimal > 0:
modular = decimal % THREE
question.append(modular)
decimal //= THREE
else:
break
sqrNum = 0
for x in range(len(question)-1, -1, -1):
answer += int(question[x]) * (3**sqrNum)
sqrNum += 1
return answer
# testcase 1
n = 45
print(solution(n)) |
c549b371e1c1a36905f24bd9e3344ff9ff64ab4a | pemedeiros/python-CeV | /pacote-download/CursoemVideo/ex088.py | 461 | 3.515625 | 4 | from random import randint
from time import sleep
jogo = []
lista = []
tot = 1
qtd = int(input('Quantos jogos você quer fazer? '))
while tot <= qtd:
cont = 0
while True:
n = randint(1, 60)
if n not in jogo:
jogo.append(n)
cont += 1
if cont >= 6:
break
lista.append(sorted(jogo[:]))
jogo.clear()
tot += 1
for i, l in enumerate(lista):
print(f'Jogo {i + 1}: {l}')
sleep(1)
|
c7d4e0f27975b82f6a192e059d2c89775296208a | surajkumar4aug/kec | /digitsum.py | 262 | 4.09375 | 4 | num=int(input("enter number"))
even=0
odd=0
while(num!=0):
rem=int(num%10)
if(rem%2==0):
even=even+rem
else:
odd=odd+rem
num=num/10
diff=even-odd
print("difference between even and odd digit "+str(diff)) |
5b6d523703aed591d503091a0ea95eed027c5b75 | SmileAK-47/webderviver | /python_rumendaoshijian/diliuzhang/HanShu/printing_models.py | 866 | 3.609375 | 4 | '''
unprinted_designs = ['iphone cas','robot pendant','dodecahedron']
completed_models = []
while unprinted_designs:
current_dision = unprinted_designs.pop()
print("model:"+ current_dision)
completed_models.append(current_dision)
print("-----")
for a in completed_models:
print(a)
'''
def print_models(unprinted_desions,conmpleted_models):
while unprinted_desions:
current_design = unprinted_desions.pop()
print("moder : "+current_design)
conmpleted_models.append(current_design)
def show_completed(completed_models):
print("The followingmodels have been printd:")
for i in completed_models:
print(i)
unprinted_designs = ['iphone cas','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs[:],completed_models)
show_completed(completed_models)
print(unprinted_designs) |
0ad14136fd0d4de88e3440313324c714ba6cb0b5 | cedelmaier/primeSieveProjects | /pythonPrimes/pythonPrimes.py | 4,669 | 4.1875 | 4 | #!/usr/bin/env python
import sys
import time
#Basic implementation
def eratosthenes(n):
multiples = set()
for i in range(2, n+1):
if i not in multiples:
yield i
multiples.update(range(i*i, n+1, i))
#A different take on the basic implementation thinking about it for a little bit
def eratosthenes2(limit):
is_prime = [False] * 2 + [True] * (limit - 1)
for n in xrange(int(limit**0.5 + 1.5)): #stop at ``sqrt(limit``
if is_prime[n]:
for i in xrange(n * n, limit + 1, n): #start at ``n`` squared
is_prime[i] = False
for i in xrange(limit + 1):
if is_prime[i]: yield i
#Odds only generator, basically a 2 wheel
def iprimes2(limit):
yield 2
if limit < 3: return
lmtbf = (limit - 3) // 2
#print "lmtbf: " + str(lmtbf)
buf = [True] * (lmtbf + 1)
for i in xrange((int(limit ** 0.5) - 3) // 2 + 1):
#print("outeri " + str(i))
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
#print("p: " + str(p) + ", s: " + str(s))
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
#print buf
for i in xrange(lmtbf + 1):
if buf[i]: yield(i + i + 3)
#23wheel
def primes23(limit):
nums = [True, False, True] * ((limit + 5) / 6)
nums[0] = False #1 is not prime.
nums[1] = True #3 is prime.
print(nums)
i = 5
#Strangely, there is no do-while loop in python
while True:
m = i * i
if m > limit:
break
print("i: " + str(i) + ", m: " + str(m))
if nums[i >> 1]:
i_times_2 = i << 1
i_times_4 = i << 2
while m <= limit:
nums[m >> 1] = False
m += i_times_2
nums[m >> 1] = False
m += i_times_4 #When i = 5, skip 45, 75, 105, ...
i += 2
if nums[i >> 1]:
m = i * i
i_times_2 = i << 1
i_times_4 = i << 2
while m <= limit:
nums[m >> 1] = False
m += i_times_4 #When i = 7, skip 63, 105, 147
nums[m >> 1] = False
m += i_times_2
i += 4
print(nums)
for j in xrange(len(nums)):
if nums[j]: yield(j * 2 + 1)
def primes235(limit):
yield 2; yield 3; yield 5
if limit < 7: return
modPrms = [7,11,13,17,19,23,29,31]
gaps = [4,2,4,2,4,6,2,6,4,2,4,2,4,6,2,6] # 2 loops for overflow
ndxs = [0,0,0,0,1,1,2,2,2,2,3,3,4,4,4,4,5,5,5,5,5,5,6,6,7,7,7,7,7,7]
lmtbf = (limit + 23) // 30 * 8 - 1 # integral number of wheels rounded up
lmtsqrt = (int(limit ** 0.5) - 7)
lmtsqrt = lmtsqrt // 30 * 8 + ndxs[lmtsqrt % 30] # round down on the wheel
buf = [True] * (lmtbf + 1)
for i in xrange(lmtsqrt + 1):
if buf[i]:
ci = i & 7; p = 30 * (i >> 3) + modPrms[ci]
s = p * p - 7; p8 = p << 3
for j in xrange(8):
c = s // 30 * 8 + ndxs[s % 30]
buf[c::p8] = [False] * ((lmtbf - c) // p8 + 1)
s += p * gaps[ci]; ci += 1
for i in xrange(lmtbf - 6 + (ndxs[(limit - 7) % 30])): # adjust for extras
if buf[i]: yield (30 * (i >> 3) + modPrms[i & 7])
def runSieve(name, limit):
lprimes = list()
starttime = time.time()
if name == "eratosthenes2":
lprimes = list(eratosthenes2(limit))
elif name == "iprimes2":
lprimes = list(iprimes2(limit))
elif name == "primes23":
lprimes = list(primes23(limit))
elif name == "primes235":
lprimes = list(primes235(limit))
endtime = time.time()
elapsed = float(endtime - starttime)
return(str(len(lprimes)), str(lprimes[-1]), elapsed)
def displayResults(name, count, maxprime, elapsedtime):
sys.stdout.write(name + "\n")
sys.stdout.write("\ttime: " + str(elapsedtime*1000) + "ms\n")
sys.stdout.write("\tPrimes Counted: " + count + "\n")
sys.stdout.write("\tMax Prime: " + maxprime + "\n")
def main(argv):
n2 = int(argv[0])
limit = 1 << n2
sys.stdout.write("Limit: " + str(limit) + "\n")
sys.stdout.flush()
(e2num, e2max, e2time) = runSieve("eratosthenes2", limit)
displayResults("Eratosthenes2", e2num, e2max, e2time)
(ip2num, ip2max, ip2time) = runSieve("iprimes2", limit)
displayResults("iprimes2", ip2num, ip2max, ip2time)
#(p23num, p23max, p23time) = runSieve("primes23", limit)
#displayResults("primes23", p23num, p23max, p23time)
(pnum, pmax, ptime) = runSieve("primes235", limit)
displayResults("primes235", pnum, pmax, ptime)
if __name__ == "__main__":
main(sys.argv[1:])
|
62f280a92b94bffbc06bf3d59c42b433fd1b6bfc | lujamaharjan/IWAssignmentPython1 | /DataType/Question1.py | 423 | 4.53125 | 5 |
'''
1. Write a Python program to count the number
of characters (character frequency) in a string.
Sample String : google.com'
Expected Result :
{'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}
'''
sample_string = 'google.com'
#filtering unique char
presented_char = set(sample_string)
result = dict()
for i in presented_char:
frequency = sample_string.count(i)
result[i] = frequency
print(result) |
441770cb1b866bfda831c3fe32f671899d288b6a | Danielgergely/intermediate_python | /intermediate_python/count.py | 624 | 3.84375 | 4 | import collections
import operator
def count_unique_words(filename):
with open(filename, 'r') as f:
content = f.read()
words = content.split()
lowercase_words = []
for word in words:
lowercase_words.append(word.lower())
cnt = collections.Counter(lowercase_words)
cnt = dict(sorted(cnt.items(), key=operator.itemgetter(1), reverse=True)[:10])
return cnt
if __name__ == '__main__':
top_lines = count_unique_words('hamlet.txt')
for index, (key, value) in enumerate(top_lines.items()):
print(f"{index +1}: '{key}' with {value} occurrences") |
9931342f8bb79101fbcdcff6b2f1eef8c75dc37f | David-Smith-Zhou/PythonLearn | /main/sort/my_sort.py | 8,936 | 3.59375 | 4 | # -*- coding: utf-8 -*- f
import math
class MySort:
def __init__(self):
pass
def bubble_sort(self, src: list) -> list:
dst = src.copy()
for i in range(len(dst)):
for j in range(len(dst)):
if dst[i] < dst[j]:
tmp = dst[j]
dst[j] = dst[i]
dst[i] = tmp
return dst
def select_sort(self, lst: list) -> list:
tmp = lst.copy()
rst = []
# tmp_min = tmp_max = 0
while len(tmp) != 0:
tmp_min = tmp_max = 0
for i in range(len(tmp)):
if tmp[i] > tmp[tmp_max]:
tmp_max = i
if tmp[i] < tmp[tmp_min]:
tmp_min = i
if len(rst) == 0:
rst.append(tmp[tmp_min])
rst.append(tmp[tmp_max])
print("rst len: " + str(len(rst)))
print("rst: " + str(rst))
else:
index = int(len(rst) / 2)
print("index: " + str(index))
rst.insert(index, tmp[tmp_min])
if tmp[tmp_min] is not tmp[tmp_max]:
rst.insert(index + 1, tmp[tmp_max])
print("rst len: " + str(len(rst)))
print("rst: " + str(rst))
print("tmp len: " + str(len(tmp)))
print("tmp_min: " + str(tmp_min))
tmp.pop(tmp_min)
print("tmp_max: " + str(tmp_max))
if tmp_min < tmp_max:
tmp.pop(tmp_max - 1)
else:
if len(tmp) is not 0:
tmp.pop(tmp_max)
return rst
def insert_sort(self, lst: list) -> list:
rst = []
rst.append(lst[0])
for i in range(1, len(lst)):
for j in range(0, len(rst)):
print("go into second for: i = %d, j = %d, lst size = %d, rst size = %d" % (i, j, len(lst), len(rst)))
if lst[i] > rst[len(rst) - 1]:
rst.append(lst[i])
if lst[i] < rst[0]:
rst.insert(0, lst[i])
if (rst[j - 1] < lst[i]) and (lst[i] < rst[j]):
rst.insert(j, lst[i])
return rst
def merge_sort(self, lst: list) -> list:
if len(lst) <= 1:
return lst
num = int(len(lst) / 2)
left = self.merge_sort(lst[:num])
right = self.merge_sort(lst[num:])
return self.__merge(left, right)
def __merge(self, left: int, right: int) -> list:
r, l = 0, 0
rst = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
rst.append(left[l])
l += 1
else:
rst.append(right[r])
r += 1
# 若一个列表优先取完,另一个列表内的值无需比较直接追加在后面
rst += right[r:]
rst += left[l:]
return rst
def debug_log(self, src: str):
with open("log.txt", "a") as file:
file.write(src + "\n")
def heap_sort(self, lst: list) -> list:
size = len(lst)
self.__heap_build(lst, size)
# 这个len(lst) - 1很重要,不减一就会排序出错,这是一个需要注意的坑
for i in range(len(lst) - 1, 0, -1):
lst[0], lst[i] = lst[i], lst[0]
self.__heap_max_heapify(lst, 0, i)
return lst
def __heap_build(self, lst: list, size: int):
for i in range(int(len(lst) / 2), -1, -1):
self.__heap_max_heapify(lst, i, size)
def __heap_max_heapify(self, lst: list, index: int, size: int):
left_index = 2 * index + 1
right_index = 2 * index + 2
largest = index
if index < int(size / 2):
if left_index < size and lst[left_index] > lst[largest]:
largest = left_index
if right_index < size and lst[right_index] > lst[largest]:
largest = right_index
if largest is not index:
lst[index], lst[largest] = lst[largest], lst[index]
self.__heap_max_heapify(lst, largest, size)
# =======================================================================================================================
# source code on the web
# def __adjust_heap(self, lists, i, size):
# lchild = 2 * i + 1
# rchild = 2 * i + 2
# max = i
# if i < size / 2:
# if lchild < size and lists[lchild] > lists[max]:
# max = lchild
# if rchild < size and lists[rchild] > lists[max]:
# max = rchild
# if max != i:
# lists[max], lists[i] = lists[i], lists[max]
# self.__adjust_heap(lists, max, size)
#
# def __build_heap(self, lists, size):
# for i in range(0, int((size / 2)))[::-1]:
# self.__adjust_heap(lists, i, size)
#
# def heap_sort(self, lists):
# size = len(lists)
# self.__build_heap(lists, size)
# for i in range(0, size)[::-1]:
# lists[0], lists[i] = lists[i], lists[0]
# self.__adjust_heap(lists, 0, i)
def quick_sort(self, lst: list) -> list:
self.__quick_sort(lst, 0, len(lst) - 1)
return lst
def __quick_sort(self, lst: list, p: int, r: int):
print("quick_sort: p = %d, r = %d" % (p, r))
if p < r:
# 根据选取的值确定第二次分治时的界限
q = self.__quick_sort_partition(lst, p, r)
self.__quick_sort(lst, p, q - 1)
self.__quick_sort(lst, q + 1, r)
def __quick_sort_partition(self, lst: list, p: int, r: int) -> int:
print("quick_sort_partition: p = %d, r = %d" % (p, r))
x = lst[r]
i = p - 1
for j in range(p, r):
if lst[j] <= x:
i = i + 1
print("cur x is %d, exchange: No.%d = %d and No.%d = %d" % (x, i, lst[i], j, lst[j]))
lst[i], lst[j] = lst[j], lst[i]
print("list: " + str(lst))
print("exchange: No.%d = %d and No.%d = %d" % (i + 1, lst[i + 1], r, lst[r]))
lst[i + 1], lst[r] = lst[r], lst[i + 1]
print("list: " + str(lst))
return i + 1
def counting_sort(self, src_list: list) -> list:
# content_length = 0
k = len(src_list)
dst_list = ([0] * k)
backup_list = ([0] * k)
for j in range(0, len(src_list)):
# print("#1 src_list[j] = %d" % (src_list[j]))
backup_list[src_list[j]] = backup_list[src_list[j]] + 1
# print("#1 backup_list: " + str(backup_list))
for i in range(1, len(backup_list)):
backup_list[i] = backup_list[i] + backup_list[i - 1]
# print("#2 backup_list: " + str(backup_list))
for m in range(len(src_list) - 1, -1, -1):
# print("m = %d, src_list[m] = %d, backup_list[src_list[m]] = %d"
# % (m, src_list[m], backup_list[src_list[m]]))
# 这个地方的减一,是通过debug发现的索引大了一,整体的数组往后移了一个单位,还不知道原因是什么
dst_list[backup_list[src_list[m]] - 1] = src_list[m]
backup_list[src_list[m]] = backup_list[src_list[m]] - 1
# print("#3 backup_list: " + str(backup_list))
# print("#3 dst_list: " + str(dst_list))
return dst_list
def radix_sort(self, src_list: list) -> list:
max = self.__radix_get_max(src_list)
loop_time = int(math.ceil(math.log(max, 10)))
# print("loop_time: ", loop_time)
dst_list = src_list.copy()
self.__radix_sort(dst_list, 10, loop_time)
return dst_list
def __radix_sort(self, dst_list: list, radix: int, loop_times: int):
for j in range(0, loop_times):
radixs = [[] for j in range(radix)]
for k in dst_list:
# print("k / (radix ** j) % radix = ", k / (radix ** j) % radix)
radixs[int(k / (radix ** j) % radix)].append(k)
# print("radix size = ", len(radixs))
# for i in range(0, 10):
# print("radix: " + str(radixs[i][:]))
del dst_list[:]
for m in range(0, len(radixs)):
dst_list.extend(radixs[:][m])
return dst_list
def __radix_get_max(self, src_list) -> int:
max = src_list[0]
for i in range(1, len(src_list)):
if src_list[i] > max:
max = src_list[i]
return max
def bucket_sort(self, src_list) -> list:
n = len(src_list)
buckets = [[] for _ in range(n)]
for a in src_list:
buckets[int(n * a)].append(a)
dst_list = []
for b in buckets:
dst_list.extend(self.insert_sort(b))
return dst_list
|
e00aaec2902b48f2b9b2c0fdca7092a4792c458b | juzh1998/CLRS_python_version | /chapter 2/insertion-sort.py | 602 | 3.8125 | 4 | """
-*- coding:utf-8 -*-
@time :2021.3.20
@IDE : pycharm
@autor :juzh
@email : [email protected]
暴力排序
"""
#生成随机list
import random
def random_int(length,a,b):
list=[]
count=0
while(count<length):
number=random.randint(a,b)
list.append(number)
count=count+1
return list
randomList=random_int(30,1,100)
print(randomList)
for i in range(1,len(randomList)):
element_now=randomList[i]
j=i-1
while j>=0 and randomList[j]>element_now:
randomList[j+1]=randomList[j]
j=j-1
randomList[j+1]=element_now
print(randomList)
|
773732ea4ad83fdb490571bfbdce62c604207c80 | thedreamer67/Simulating_Forest_Fire | /Task 1 Random Forest.py | 990 | 4.125 | 4 | # Task 1: create a random forest with stated width, height and density (num_of_trees/area)
# output: a 2D matrix of 0s and 1s to represent water and trees
def createForest(width, height, density):
from random import randint
forest = [] # Initialise empty list
trees = round(density * width * height) #Computes the total number of trees and rounds to nearest integer
randsum = sum(sum(e) for e in forest) #Sums the total amount of trees in each row
while randsum != trees: #Keep iterating until the random number of trees is correct. This ensures independent randomisation of each element.
for x in range(height):
templist = [] #Initialise an empty list at the start of each new row
for y in range(width): #Iterate through each element
templist.append(randint(0,1)) #Add an element to the temporary list
forest.append(templist) # Add the completed row as an element to forest
return forest
print(createForest(5,10,0.2))#Just to see the result
|
05a982ff7705d288fd01c1977e5566e7b61adab8 | CodingDojoDallas/python_july_2018 | /prajesh_gohel/Python/python_fundamentals/forloop_basic.py | 1,663 | 4.125 | 4 | # 1. Basic - Print all the numbers/integers from 0 to 150.
# for i in range(1, 151):
# print(i)
# 2. Multiples of Five - Print all the multiples of 5 from 5 to 1,000,000.
# for i in range(5, 1000000, 5):
# print(i)
# 3. Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If by 10, also print " Dojo".
# for i in range(1, 101):
# if(i % 5 == 0):
# print("Coding")
# if(i % 10 == 0):
# print("Dojo")
# else:
# print(i)
# 4. Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum.
# sum = 0
# for i in range(1, 500001, 2):
# sum = sum + i
# print(sum)
# 5. Countdown by Fours - Print positive numbers starting at 2018, counting down by fours (exclude 0).
# for i in range(2018, 0, -4):
# print(i)
# 6. Flexible Countdown - Based on earlier "Countdown by Fours", given lowNum, highNum, mult, print multiples of mult from lowNum to highNum, using a FOR loop. For (2,9,3), print 3 6 9 (on successive lines)
# def countdown(lowNum, highNum, mult):
# for i in range(lowNum, highNum):
# if(i % mult == 0):
# print(i)
# countdown(2, 10, 3)
# Predict the output for the following codes:
# list = [3,5,1,2]
# for i in list:
# print(i)
#Prediction: 3, 5, 1, 2
#Answer: 3, 5, 1, 2
# list = [3,5,1,2]
# for i in range(list):
# print(i)
#Prediction: 1, 2, 3, 5
#Answer: error object can't be interpreted as integer
# list = [3,5,1,2]
# for i in range(len(list)):
# print(i)
#Prediction: 0, 1, 2, 3
#Output: 0, 1, 2, 3
def a():
print(1)
b()
print(2)
def b():
print(3)
a()
|
7044506b6151f966fc2d90afdfeef00205890f4e | dharanidurairaj/codevita-practice-problems | /matrix.py | 249 | 3.75 | 4 | i/p:
1
2
3
4
o/p:
0 1
2 3
r=2
c=2
b=[[0 for i in range(r)]for i in range(c)]
for i in range(0,r):
for j in range(0,c):
b[i][j]=int(input())
for i in range(0,r):
for j in range(0,c):
print(b[i][j],end=" ")
print(" ")
|
8fdcb04662fc31c53d99a995e92dc6fbf37660c8 | Neeraj-kaushik/Geeksforgeeks | /Array/Union_of_two_sorted_array.py | 391 | 3.9375 | 4 | def union(n, li, m, li2):
li3 = []
for i in range(len(li)):
if li[i] not in li3:
li3.append(li[i])
for i in range(len(li2)):
if li2[i] not in li3:
li3.append(li2[i])
li3 = sorted(li3)
print(li3)
n = int(input())
li = [int(x) for x in input().split()]
m = int(input())
li2 = [int(y) for y in input().split()]
union(n, li, m, li2)
|
d24b4ae901739f5936fdf4fc73ea6139f0919880 | RyanIsCoding2021/RyanIsCoding2021 | /exercises/1.py | 925 | 3.703125 | 4 | import turtle as t
import random
s = t.Screen()
s.title("rect")
t.speed(0)
colorlist = ["black", "blue", "green", "red"]
def drawRect(width, height):
for i in range(2):
t.color(colorlist[random.randint(0, 3)])
t.fd(width)
t.lt(90)
t.fd(height)
t.lt(90)
# def drawRect(width, height):
# for i in range(4):
# if i == 0:
# t.fd(width)
# t.lt(90)
# elif i == 1:
# t.fd(height)
# t.lt(90)
# elif i == 2:
# t.fd(width)
# t.lt(90)
# elif i == 3:
# t.fd(height)
# t.lt(90)
# def drawRect(size):
# for i in range(4):
# t.fd(size)
# t.lt(90)
for i in range(40):
# drawRect(size=random.randint(20, 500))
drawRect(random.randint(100, 200), random.randint(100, 200))
s.mainloop() |
b0f4efae3c3430bb2039be71df90b3980a586c7b | karkonio/first_module | /vault77/week4/test.py | 351 | 3.890625 | 4 | string = 'Alise is 21 years old'
def no_digits(string):
result = []
#result = ''.join([i for i in string if not i.isdigit()])
for char in string:
if not char.isdigit():
result.append(char)
result = ''.join(result)
return result
print(no_digits(string))
assert no_digits(string) == 'Alise is years old' |
366d2d58a95e33ed438bec6d990e1834ef71bceb | sklucioni/crimtechcomp | /assignments/000/sarah-lucioni/assignment.py | 1,848 | 4.0625 | 4 | def say_hello():
print("Hello, world!")
# Color: blue
# TODO: implement
def echo_me(msg):
print(msg)
# TODO: understand and remove
def string_or_not(d):
exec(d)
# TODO: understand formatting - can you eliminate the redundancy here?
def append_msg(msg):
print("Your message should have been: {}!".format(msg))
# TODO: understanding classes (an introduction)
class QuickMaths():
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
return x / y
# TODO: implement - can you do this more efficiently?
# Instead of creating a new list and copying each element + 1 to the new list, simply add
# one to each element of the current list.
def increment_by_one(lst):
for x in range(len(lst)):
lst[x] = lst[x] + 1
return lst
# TODO: understand - do we need a return statement here? why?
# We don't need the return statement, but it helps us check in a REPL and make sure the function
# actually worked correctly.
def update_name(person, new_name):
person["name"] = new_name
return person
# TODO: implement - these are still required, but are combinations of learned skills + some
def challenge1(lst):
# loops through every element of a string list and reverses the string by using a slice with a step of -1
for x in range(len(lst)):
lst[x] = lst[x][::-1]
lst.reverse()
return lst
# TODO: implement
def challenge2(n):
# create an empty list
factors = []
# loop through the possible factors of n (only need to look at one half)
for i in range(1, int((n + 1) / 2)):
# if i is a factor of n, append the tuple (i, n/i) to the factors list
if n % i == 0:
factors.append((int(i), int(n/i)))
return factors
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.