blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
77c0c33393d0df7df1adfe9765feb07d4f0978d0 | whocaresustc/LeetCode-Solutions-Python | /1095. Find in Mountain Array.py | 2,201 | 3.9375 | 4 | # """
# This is MountainArray's API interface.
# You should not implement it, or speculate about its implementation
# """
#class MountainArray(object):
# def get(self, index):
# """
# :type index: int
# :rtype int
# """
#
# def length(self):
# """
# :rtype int
# """
"""
method 1: binary search
Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1],
or A[i-1] > A[i] > A[i+1], we are either at the left side, peak,
or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times
to find whether the value occurs on either side of the peak.
"""
class Solution(object):
def findInMountainArray(self, target, mountain_arr):
"""
:type target: integer
:type mountain_arr: MountainArray
:rtype: integer
"""
n = mountain_arr.length()
# search peak
left, right = 0, n-1
while left + 1 < right:
mid = left + (right-left)//2
pre = mountain_arr.get(mid-1)
cur = mountain_arr.get(mid)
if cur > pre:
left = mid
else:
right = mid
peak = left if mountain_arr.get(left) > mountain_arr.get(right) else right
i = self.search(target, mountain_arr, 0, peak, True)
if i != -1:
return i
return self.search(target, mountain_arr, peak, n-1, False)
def search(self, target, mountain_arr, left, right, flag=True):
# flag = True means the array mountain_arr[left:right+1]
# is increasing, else decreasing
while left + 1 < right:
mid = left + (right - left)//2
cur = mountain_arr.get(mid)
if cur == target:
return mid
elif (flag and cur > target) or (not flag and cur < target):
right = mid
else:
left = mid
if mountain_arr.get(left) == target:
return left
if mountain_arr.get(right) == target:
return right
return -1
|
8d8b7843ee181c0feddbf94b2d0b98da83552475 | YusefQuinlan/PythonTutorial | /Intermediate/2.3 BeautifulSoup/2.3.1_BeautifulSoup_Introduction.py | 2,385 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 12:47:42 2020
@author: Yusef Quinlan
"""
# We must import requests and BeautifulSoup in order to webscrape with
# BeautifulSoup.
import requests
from bs4 import BeautifulSoup
# First we need to request the url and get it contents etc with
# requests.get(url).
page = requests.get('http://quotes.toscrape.com/page/1/')
"""
Looking at the item gives us the response and so does the status code,
we want a 200 response as this shows that we can succesfully request
our intended url.
"""
print(page)
print(page.status_code)
# if we try to get non-existent urls, we will run into problems, always check
# that your url exists and that it is in string format.
page2 = requests.get('diufgerygfuerf')
page3 = requests.get('http://diufgerygfuerf')
# We can get the request headers with the gotten request variable property
# .headers
print(page.headers)
"""
We can also extract the page content with the .content property note that this
does not give us the webpage or its actual rendered content, rather the html
tag structure contents of that webpage.
"""
page_content = page.content
print(page_content)
"""
We must then make what is known as a soup object from the page content. This
Soup object can be further manipulated and specific information can be scraped
from it.
"""
soup = BeautifulSoup(page_content)
"""
We can find the first tag of a specific kind with the .find('tag') function
the function returns the first found tag if any exist. Printing this out will
give a full tag along with the tags content for example:
<a class="aclass"> I'm a link </a>, if we just want the text i.e. 'I'm a link'
we can get it with the .text attribute. Note that not all links have any text
but they will have a .text attribute that will return nothing.
"""
link_First = soup.find("a")
print(link_First)
print(link_First.text)
"""
One can also find all tags of a certain kind with the .find_all('tag')
function, however this returns an array of tags, and so if we want the text
of all tags we cannot simply use .text on an array, as the array does not
have the .text property. Instead we must use .text on every tag in the
array, as the individual tags do have the .text property.
"""
link_Anchors = soup.find_all("a")
print(link_Anchors)
print(link_Anchors.text)
for i in link_Anchors:
print(i.text) |
224737857b2b5ec072400a7b65c696ccdba0a28f | AlakiraRaven/ProjectEuler | /HelloWorld_and_SomeFun.py | 351 | 3.65625 | 4 | x = 'Hello World'
s = 'Sander'
m = 'Marta'
ListOfNames = [m, s]
l = []
print(x + ', ' + s + ' and ' + m)
for i in range(len(ListOfNames)):
print(x + ', ' + ListOfNames[i])
for name in ListOfNames:
print(x + ', ' + name)
for i in range(2, 20):
if i % 2 == 0:
print(i)
else:
print('Eh' + i*'eh' + ', ' 'STUPID')
|
a840e333d2e491409b7dcbf2dde1172d880083b1 | tarrlikh/Casimir-course | /old_stuff/test.py | 284 | 3.671875 | 4 | print('hello world')
print('bye world!')
print('Hi Yaroslav! I changed your code')
x=2+2
print(x==4)
'''This is Klara's first comment on this code, we want to merge comments from all of us here!'''
"""THERE ARE LLAMAS OUTSIDE OR ALPAKAS I AM NOT SURE SINCE THEY LOOK THE SAME"""
|
440e4d1194605237e34f37e8b5c81fb3d398ce79 | YujiaBonnieGuo/learn_python | /ex10条件判断.py | 922 | 4.15625 | 4 | # age=2
# print('your age is',age)
# if age>=18:
# print('adult')
# elif age>=6:
# print('tennager')
# else:
# print('kid')
hight=float(input('请输入身高(单位:米):'))
weight=float(input('请输入体重(单位:千克):'))
# BMI=weight/(hight*hight)
BMI=weight/(hight**2)
if BMI<18.5:
print('过轻')
elif BMI<25:
print('正常')
elif BMI<28:
print('过重')
elif BMI<32:
print('肥胖')
else:
print('严重肥胖')
H = float(input('请输入身高(单位:米):'))
W = float(input('请输入体重(单位:公斤):'))
bmi = W/(H**2)
if bmi >=32:
print('你的BMI指数%.1f,严重肥胖'% BMI)
elif bmi>=28:
print('你的BMI指数%.1f,肥胖'% BMI)
elif bmi>=25:
print('你的BMI指数%.1f,过重'% BMI)
elif bmi>=18.5:
print('你的BMI指数%.1f,正常'% BMI)
elif bmi>0:
print('你的BMI指数%.1f,过轻'% BMI)
else:
print('输入有误') |
75d9ab5215e9cd485bb81eb9bffedd19e76e6be2 | sti11wind/pythontutor | /calculations.py | 7,374 | 3.890625 | 4 |
# Задача «Последняя цифра числа»
# Условие
# Дано натуральное число. Выведите его последнюю цифру.
a = int(input('Введите число '))
print(a % 10)
# Задача «МКАД»
# Условие
# Длина Московской кольцевой автомобильной дороги —109 километров. Байкер Вася стартует с нулевого километра МКАД и едет со скоростью v километров в час. На какой отметке он остановится через t часов?
#
# Программа получает на вход значение v и t. Если v>0, то Вася движется в положительном направлении по МКАД, если же значение v<0, то в отрицательном.
#
# Программа должна вывести целое число от 0 до 108 — номер отметки, на которой остановится Вася.
#
# Условие
# Дано натуральное число. Выведите его последнюю цифру.
v = int(input('скорость '))
t = int(input('время '))
mkad_len = 109
print(abs( (v * t) % mkad_len))
# Задача «Дробная часть»
# Условие
# Дано положительное действительное число X. Выведите его дробную часть.
from decimal import Decimal
x = Decimal(input('Введите число '))
print(x - int(x))
# Задача «Первая цифра после точки»
# Условие
# Дано положительное действительное число X. Выведите его первую цифру после десятичной точки.
x = float(input('Введите число '))
print(int(x * 10)% 10)
# Задача «Конец уроков»
# Условие
# В некоторой школе занятия начинаются в 9:00. Продолжительность урока — 45 минут, после 1-го, 3-го, 5-го и т.д. уроков перемена 5 минут, а после 2-го, 4-го, 6-го и т.д. — 15 минут.
#
# Дан номер урока (число от 1 до 10). Определите, когда заканчивается указанный урок.
#
# Выведите два целых числа: время окончания урока в часах и минутах.
n=int(input())-1
x=n//2*15+(n+n%2)//2*5+(n+1)*45
h=9
m=0
h=h+x//60
x=x %60
m=x
print(h,m)
# Задача «Автопробег»
# Условие
# За день машина проезжает n километров. Сколько дней нужно, чтобы проехать маршрут длиной m километров? Программа получает на вход числа n и m.
import math
n = int(input('Введите N '))
m = int(input('Введите M '))
print(math.ceil(m / n))
# Задача «Стоимость покупки»
# Условие
# Пирожок в столовой стоит a рублей и b копеек. Определите, сколько рублей и копеек нужно заплатить за n пирожков. Программа получает на вход три числа: a, b, n, и должна вывести два числа: стоимость покупки в рублях и копейках.
from decimal import Decimal
a = int(input('Введите рубли '))
b = int(input('Введите копейки '))
n = int(input('Введите пирожки '))
result = ((a * 100 + b) * n / 100)
print(int(result), int(round(result - int(result), 2) * 100) )
# Задача «Разность времен»
# Условие
# Даны значения двух моментов времени, принадлежащих одним и тем же суткам: часы, минуты и секунды для каждого из моментов времени. Известно, что второй момент времени наступил не раньше первого. Определите, сколько секунд прошло между двумя моментами времени.
#
# Программа на вход получает три целых числа: часы, минуты, секунды, задающие первый момент времени и три целых числа, задающих второй момент времени.
#
# Выведите число секунд между этими моментами времени.
#
a = int(input())
b = int(input())
c = int(input())
a1 = int(input())
b1 = int(input())
c1 = int(input())
time1 = (a * 3600) + (b * 60) + c
time2 = (a1 * 3600) + (b1 * 60) + c1
result = time2 - time1
print(result)
# Задача «Улитка»
# Условие
# Улитка ползет по вертикальному шесту высотой h метров, поднимаясь за день на a метров, а за ночь спускаясь на b метров. На какой день улитка доползет до вершины шеста?
#
# Программа получает на вход натуральные числа h, a, b.
#
# Программа должна вывести одно натуральное число. Гарантируется, что a>b.
import math
h = int(input())
a = int(input())
b = int(input())
result = (h - a) / (a - b) + 1
print(int(math.ceil(result)))
# Занятие 3. Вычисления
# Задача «Число десятков»
# Условие
# Дано натуральное число. Найдите число десятков в его десятичной записи.
a = int(input())
b = a % 100
print(b // 10)
# Задача «Сумма цифр»
# Условие
# Дано трехзначное число. Найдите сумму его цифр.
a = str(input())
print(int(a[0]) + int(a[1]) + int(a[2]))
# Занятие 3. Вычисления
# Задача «Гипотенуза»
# Условие
# Дано два числа a и b. Выведите гипотенузу треугольника с заданными катетами.
import math
a = int(input())
b = int(input())
print(math.sqrt((a * a) + (b * b)))
# Занятие 3. Вычисления
# Задача «Проценты»
# Условие
# Процентная ставка по вкладу составляет P процентов годовых, которые прибавляются к сумме вклада. Вклад составляет X рублей Y копеек. Определите размер вклада через год.
# Программа получает на вход целые числа P, X, Y и должна вывести два числа: величину вклада через год в рублях и копейках. Дробная часть копеек отбрасывается.
p = int(input())
x = int(input())
y = int(input())
deposit = (x + y / 100) * (1+ p/100)
rub = int(deposit)
kop = int(100 * (float('%.2f' % (deposit - int(deposit)))))
print(rub, kop)
|
db072b1375c4f0ae9c411b89582e21e4ecfd15f7 | rafdanzi/git_lesson | /src/my_square.py | 155 | 3.65625 | 4 |
def my_square(x):
"""take a value and returns the square value
use the ** operator
"""
return(x **2)
print(my_square(4))
|
05c15d71a8ca22611288097ecd50f01daae69272 | pparonson/LPTHW | /review_notes.py | 1,710 | 4.15625 | 4 | # Assign "formatter" var to "%r %r %r %r"
formatter = "%r %r %r %r"
# print value of formatter var with hard values passed into parameter
print "This will print hard values.", formatter % (1, 2, 3, 4)
print "This will pass variables.", formatter % ("one", "two", "three", "four")
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing",
"That you could type up right.",
"But it didn\'t sing.",
"So I said goodnight."
)
# \r - Carriage return
# \n - linefeed
# \\ - Backslash
# input() versus raw_input() - input() will attempt to conversion;
# input() is recommended to avoid
# Example - y = raw_input("Name? ")
# Also see "pydoc raw_input"
# Module that accept arguments to pass variables
# The variable holds the arguments you pass to your python script
from sys import argv
# "Unpacks" argv so that, rather than holding all the arguments
# it gets assigned to multiple variables you can work with
script, user_name = argv
prompt = '>'
print "Hi {1}, I\'m the {0} script." .format (user_name, script)
# Module imports from filepath and return "True" if exists and "False" if not
from os.path import exists
# Various methods / functions "Commands"
# .close() - closes the file.
# .read() - reads the contents of the file. You can assign the result to a var
# .readline() - reads just one line of .txt file\
# .truncate - empties the file.
# write("stuff") - writes "stuff" to the file; remember that the .write method
# take a parameter of a string intended to write to the file.
# Command line terminal - "." (dot, period) calls / runs a function
"""
and
or
not
!" (not equal)
== (equal)
>= (greater-than-equal)
<= (less-than-equal)
True
False |
5fe95312c939d79334c79fecc72e93e3410cd071 | LuluOS/WorldDomination2 | /main.py | 6,564 | 3.71875 | 4 | from bs4 import BeautifulSoup #""" http://www.crummy.com/software/BeautifulSoup/bs4/doc/ """
import requests
#############################################################################################################
#""" Functions """
#""" function to check if a substring is part of a string """
def checkSubInStr(substring, string):
if (substring in string):
return True
else:
return False
#""" function to check if a given word is part of a phrase """
def checkWordInPhrase(givenWord, phrase):
words = phrase.split() #""" split the sentence into individual words """
for i in range(len(words)):
if (givenWord.lower() == words[i].lower()): #""" see if one of the words in the sentence is the word we want """
return True
return False
#""" function that returns the index of the position from the string in the phrase """
def indexStr(phrase, string):
#""" string = "href" #link starts after 2 more char """
index = 0
if (string in phrase):
letter = string[0]
#""" loop to navagate in the phrase """
for char in phrase:
#""" if char is a substring of letter """
if (char == letter):
#""" if the sublist from index to (index+len(string)) contains the string """
if (phrase[index : (index+len(string))] == string):
return index #""" return the index """
index += 1
return -1 #""" if the string is not in the phare """
#""" function that returns the link from the entire tag """
def getLink(tag, position):
char = tag[position] #""" char is the first character of the link """
link = []
#""" keep copying char by char to the link until find a quote """
while (char != "\""):
#print char
link.append(char)
position += 1
char = tag[position]
#""" transform link in a string and atribute it to href """
href = ''.join(link)
string = "http://"
#""" if is a link return it """
if (string in href):
return href
#""" if is not a link return -1 (error) """
else:
return -1
#""" function that returns the title from the entire tag """
def getTitle(tag):
index = 0
text = []
char = tag[index]
#""" find the position of '>' on the tag """
while (char != ">"):
index += 1
char = tag[index]
#""" pick the next char """
index += 1
char = tag[index]
#""" add each char in the text until find a '<' """
while (char != "<"):
text.append(char)
index += 1
char = tag[index]
#""" transform text in a string and atribute it to title """
title = ''.join(text)
return title
#""" function that returns the list b but without the elements that contained in a (difference between two lists) """
#""" http://stackoverflow.com/questions/3462143/get-difference-between-two-lists """
def listB_A(b, a):
return list(set(b) - set(a))
#############################################################################################################
#""" _Main_ """
if __name__ == '__main__':
givenWord = raw_input("What do you want to search for? ") #""" input given word (to search) """
webPages = [] #""" is a list of url that we want to check """
intersection = [] #""" is a list of the html tags (<a>) that contains the classes 'title may-blank' """
links = [] #""" is a list of links that contains the given word """
recommended = [] #""" is a list of links that contains similar words with the given word """
webPages.append(requests.get("http://" +"www.reddit.com"))
webPages.append(requests.get("http://" +"www.reddit.com/r/technology/"))
pagesNumbers = len(webPages) #""" number of webPages """
#""" loop to search into all pages """
for i in range(pagesNumbers):
data = webPages[i].text
soup = BeautifulSoup(data,"lxml")
#""" returns all tags that contains the class 'may-blank' to the list called mayblank """
mayblank = soup.findAll('a', attrs={'class':'may-blank'}) #""" returns a list with all class called 'may-blank' """
#""" size of the list mayblank """
sizeMB = len(mayblank)
#""" loop to check if in each mayblank[i] has the word 'title' to store the tags that contains 'title may-blank' """
for j in range(sizeMB):
if (checkSubInStr("title", str(mayblank[j])) == True): #""" if the tag contains the class 'title may-blank' """
intersection.append(str(mayblank[j])) #""" add the tag to the intersection list """
#print ("intersection: "),
#print intersection
sizeInter = len(intersection)
#""" loop to check if in each intersection[i] has the given word to store the links """
for i in range(sizeInter):
if (checkWordInPhrase(givenWord, str(intersection[i])) == True): #""" if the tag contains the given word """
links.append(str(intersection[i])) #""" add the tag to the links list """
if (checkSubInStr(givenWord, str(intersection[i])) == True): #""" if the tag contains a similar word """
recommended.append(str(intersection[i])) #""" add the tag to the links list """
href = [] #""" is a list of just the href of the links """
titleL = [] #""" is a list of the title of the links """
recom = [] #""" is a list of just the href of the recommended """
titleR = [] #""" is a list of the title of the recommended """
#""" because all the time is going to be with this pattern """
#""" [<a class="title may-blank " href="] the link start in """
#""" the position 33 of the tag """
if ((len(links) != 0) or (len(recommended) != 0)):
#""" if there is a link or more save the title(s) and the link(s) """
if (len(links) != 0):
for i in range(len(links)):
titleL.append(getTitle(links[i]))
if (getLink(links[i], 34) != -1):
href.append(getLink(links[i], 34))
#""" output: title and href """
if (len(href) != 0):
print ("Links: ")
for i in range(len(href)):
print ("> %s: \n\t%s\n" %(titleL[i],href[i]))
#""" if there is a recommended or more save the title(s) and the recommended(s) """
if (len(recommended) != 0):
for i in range(len(recommended)):
titleR.append(getTitle(recommended[i]))
if (getLink(recommended[i], 34) != -1):
recom.append(getLink(recommended[i], 34))
#""" take out the repeated links """
if (len(href) != 0):
recom = listB_A(recom, href)
#""" output: title and recom """
if (len(recom) != 0):
print ("Recommended: ")
for i in range(len(recom)):
print ("> %s: \n\t%s\n" %(titleR[i],recom[i]))
else:
print ("Sorry, but nothing on these pages match with your given word!")
############################################################################################################# |
d5460ce6c0f4829a773b94ceb08ac546bd5cc174 | vstarman/python_codes | /8day/06.生成器的使用.py | 1,129 | 4.125 | 4 |
'''# 生成器是特殊的迭代器可用next()获取下一个值
# 如果在函数里出现了yield这个关键字,它就是生成器
def fib(num):
a = 0
b = 1
current_index = 0
print("---------1---------")
while current_index < num:
result = a
a, b = b, a+b
current_index += 1
print("---------2---------")
# 如果函数里出现了yield表示生成器
yield result
print("---------3---------")
#return result
result = fib(5)
print(result)
print(next(result))
print(next(result))
print(next(result))
# yield 特点
# 程序执行到yield时会暂停返回值,下一次调用会继续一轮到下次yield返回值再停止
# return 只会返回一次值,但是yield可以多次返回值
def fib():
a, b = 0, 1
for i in range(5):
yield b
a, b = b, a+b
a = fib()
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())'''
def test():
i = 0
while i < 5:
temp = yield i
i += 1
a = test()
print(a.__next__())
|
85d66d3a20f79d265626067e460c91809f79d2df | nachande/PythonPrograms | /AssignmentOperator_10.py | 301 | 3.9375 | 4 | a,x=10,2
b=20
print("Addition of ",a,b,"is =",a+b)
print("Subtraction of ",a,b,"is =",a-b)
print("Multiplication of",a,b,"is =",a*b)
print("Division of ",a,b,"is =",a/b)
print("Modulus of ",a,b,"is=",a%b)
print(a,"to the power of ",x," is =",a**x)
print("Floor Division of",a,b,"is=",a//b)
|
a4d998be3c76fd5db9df580d84cf7699d6d02ba8 | HenryBalthier/Python-Learning | /Leetcode_easy/linkedlist/203.py | 1,160 | 3.640625 | 4 |
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head == None:
return head
while head.val == val:
head = head.next
if head == None:
return head
p = head
while p.next:
while p.next.val == val:
p.next = p.next.next
if p.next == None:
break
p = p.next
if p == None:
break
return head
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def printlist(head):
if head == None:
print('head is None!')
return
p = head
lst = []
lst.append(p.val)
while p.next:
p = p.next
lst.append(p.val)
print(lst)
if __name__ == '__main__':
s = Solution()
head = ListNode(1)
point = head
n = 5
for i in range(n):
p = ListNode(i + 2)
point.next = p
point = p
printlist(head)
printlist(s.removeElements(head, 6)) |
b411ac4668d81b05f86ae0789e34aaee41ed9efd | RoyHoffman/python-NEAT-implementation | /XOR_test.py | 921 | 3.5 | 4 | # -*- coding: utf-8 -*-
import globals
import math
def test_network(network,run,debug = False):
fitness = 16
fitness -= (abs(0-network.run(0,0,globals.BIAS)[0])*2)**2
fitness -= (abs(1-network.run(1,0,globals.BIAS)[0])*2)**2
fitness -= (abs(1-network.run(0,1,globals.BIAS)[0])*2)**2
fitness -= (abs(0-network.run(1,1,globals.BIAS)[0])*2)**2
if debug:
print "here"
a = 0
a= network.run(0,0,globals.BIAS)[0]
print str(a) + " expected: 0"
a= network.run(1,0,globals.BIAS)[0]
print str(a) + " expected: 1"
a= network.run(0,1,globals.BIAS)[0]
print str(a) + " expected: 1"
a= network.run(1,1,globals.BIAS)[0]
print str(a) + " expected: 0"
raw_input()
return fitness**2
def main():
"""
Add Documentation here
"""
pass # Add Your Code Here
if __name__ == '__main__':
main() |
ff96864b7bc73043721afd18a6c7645430590dec | vuminhph/randomCodes | /Techniques/DynamicProgramming/knapsack_problem.py | 1,460 | 3.609375 | 4 |
def main():
val = [10, 40, 30, 50]
wt = [5, 4, 6, 3]
items = dict(zip(wt, val))
weight = 10
lookup = [[-1 for i in range(weight + 1)] for j in range(len(items))]
print(solve_knapsack(len(items) - 1, items, weight, lookup)[0])
def solve_knapsack(index, items, capacity, lookup):
if index == 0:
first_item = list(items.keys())[0]
if capacity >= first_item:
return ( [first_item], items[first_item] )
else:
return ( [], 0 )
if lookup[index][capacity] == -1:
cur_item = list(items.keys())[index]
capacity_if_incl = capacity - cur_item
if capacity_if_incl >= 0:
last_incl = solve_knapsack(index - 1, items, capacity_if_incl, lookup)
incl_combination = last_incl[0]
incl_value = last_incl[1]
incl_combination.append(cur_item)
incl_value += items[cur_item]
else:
incl_combination = []
incl_value = 0
last_not_incl = solve_knapsack(index - 1, items, capacity, lookup)
not_incl_combination = last_not_incl[0]
not_incl_value = last_not_incl[1]
max_value = max(incl_value, not_incl_value)
opt_combination = incl_combination if max_value == incl_value else not_incl_combination
lookup[index][capacity] = (opt_combination, max_value)
return lookup[index][capacity]
if __name__ == '__main__':
main() |
cd4d11dac06e7a0453a9f133af3409190c76c29e | icodetohack/pythonProject | /codewars_replaceWithAlphabetPosition.py | 577 | 4.34375 | 4 | """
Welcome.
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)
"""
def alphabet_position(text):
text = text.lower()
s=""
for i in text:
if ord(i)>=97 and ord(i)<=122:
s=s+str((ord(i)-96))+" "
s= s.strip()
return s
|
f23aab913b77cae96e354e4285358191358a7b95 | kalyan-dev/Python_Projects_01 | /demo/oop/doctor.py | 1,940 | 3.890625 | 4 | from abc import ABC,abstractmethod
class Doctor:
def __init__(self, name, specialization, phone_no):
self.name = name
self.specialization = specialization
self.phone_no = phone_no
def print(self):
return self.name + "[" + self.specialization + ", Ph-" + str(self.phone_no) + "]"
@abstractmethod
def get_salary(self):
pass
class ResidentDoctor(Doctor):
def __init__(self, name, specialization, phone_no, salary):
super().__init__(name, specialization, phone_no)
self.salary = salary
def print(self):
return super().print() + " Total Salary = " + str(self.get_salary())
def get_salary(self):
return self.salary
class Consultant(Doctor):
def __init__(self, name, specialization, phone_no, no_of_visits, charge_per_visit):
super().__init__(name, specialization, phone_no)
self.no_of_visits = no_of_visits
self.charge_per_visit = charge_per_visit
def get_salary(self):
return self.no_of_visits * self.charge_per_visit
def print(self):
return super().print() + " Total Salary = " + str(self.get_salary())
@property
def salary(self):
return self.get_salary()
class Surgeon(Doctor):
def __init__(self, name, specialization, phone_no, total_surgery_amount, no_of_visits, charge_per_visit):
super().__init__(name, specialization, phone_no)
self.total_surgery_amount = total_surgery_amount
self.no_of_visits = no_of_visits
self.charge_per_visit = charge_per_visit
def get_salary(self):
return self.total_surgery_amount + self.no_of_visits * self.charge_per_visit
def print(self):
return super(Surgeon, self).print() + " Total Salary = " + str(self.get_salary())
@property
def salary(self):
return self.get_salary()
|
78a05b99b762de6027e43591d9127fda73550e36 | soonhyeok/Python_DataStructure_codeit | /Chap04/05_Linked_List.py | 1,077 | 4.25 | 4 | class Node:
"""링크드 리스트의 노드 클래스"""
def __init__(self,data):
self.data = data # 노드가 저장하는 데이터
self.next = None # 다음 노드에 대한 레퍼런스
class LinkedList:
"""링크드 리스트 클래스"""
def __init__(self):
self.head = None
self.tail = None
def append(self, data):
"""링크드 리스트 추가 연산 메소드"""
new_node = Node(data)
if self.head is None: # 링크드 리스트가 비어있는 경우
self.head = new_node
self.tail = new_node
else: # 링크드 리스트가 비어 있지 않은 경우
self.tail.next = new_node
self.tail = new_node
# 새로운 링크드 리스트 생성
my_list = LinkedList()
# 링크드 리스에 데이터 추가
my_list.append(2)
my_list.append(3)
my_list.append(5)
my_list.append(7)
my_list.append(11)
# 링크드 리스트 출력
iterator = my_list.head
while iterator is not None:
print(iterator.data)
iterator = iterator.next |
fba379fc20c4a387e22a96c7a191dd77da10f52a | ganqzz/sandbox_py | /examples/job_queue.py | 521 | 3.8125 | 4 | # Circular Queue demo
from collections import deque
import random
jq = deque()
for j in list('ABCD'):
jq.append({'label': j, 'completed': random.randint(5, 25)})
while len(jq) > 0:
current = jq[0]
current['completed'] -= 5
if current['completed'] > 0:
print('Job {0} has {1} remaining'.format(current['label'], current['completed']))
else:
print('Job {0} has completed'.format(current['label']))
jq.remove(current)
jq.rotate(1)
print('All jobs have been completed')
|
8404f41ae1485c6f07c517fb13d341d4ff1e8c86 | Xuu666/algorithm023 | /Week_07/#433 最小基因的变化.py | 750 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Solution(object):
def minMutation(self, start, end, bank):
"""
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
bank = set(bank)
if end not in bank: return -1
q = [(start,0)]
change = {'A':'CTG','C':'ATG','T':'ACG','G':'ACT'}
while q:
node, step = q.pop(0)
if node == end: return step
for i, v in enumerate(node):
for j in change[v]:
new = node[:i] + j + node[i+1:]
if new in bank:
q.append((new,step+1))
bank.remove(new)
return -1
|
23b0e689463443300974acc1f27388e93e66bf27 | kts1297/Leetcode | /443.py | 723 | 3.578125 | 4 | # https://leetcode.com/problems/string-compression/?envType=study-plan-v2&envId=leetcode-75
class Solution:
def compress(self, chars: List[str]) -> int:
res = ""
count = 1
c = chars[0]
for ndx in range(1, len(chars)):
if c == chars[ndx]:
count += 1
else:
if count == 1:
res = f"{res}{c}"
else:
res = f"{res}{c}{count}"
count = 1
c = chars[ndx]
if count == 1:
res = f"{res}{c}"
else:
res = f"{res}{c}{count}"
for ndx in range(len(res)):
chars[ndx] = res[ndx]
return len(res) |
7c104931288427d82cf99a0caf7dfc1439a6534c | tennyson-mccalla/PPaItCS | /lineSeg.py | 999 | 4.21875 | 4 | from graphics import *
def main():
# Create the window
win = GraphWin("Line Segment Information", 1000, 1000)
win.setCoords(0, 0, 1000, 1000)
# Explain to user what the app does
intro = Text(Point(250, 975), "This app will draw a line segment between two mouse clicks and show some info about it.")
intro.draw(win)
# Get points from mouse clicks
p0 = win.getMouse()
p0.draw(win)
p1 = win.getMouse()
p1.draw(win)
# Create line
l = Line(p0, p1)
l.draw(win)
# Find midpoint of line
mid = Point(((p0.getX() + p1.getX()) / 2),((p0.getY() + p1.getY()) / 2))
mid.setFill("cyan")
mid.draw(win)
print(mid.getX(), mid.getY())
# Getting the slope of the line
dx = p0.getX() - p1.getX()
dy = p0.getY() - p1.getY()
m = dy / dx
print("This line's slope is",m)
# Getting the line's length
s = (dx ** 2 + dy ** 2) ** 0.5
print("This line's length is", s)
win.getMouse()
win.close()
main()
|
8fccaecf919b896a13273999c4c8314b05f628c8 | UberBudderCow/L1-Python-Tasks | /Giftcard.py | 417 | 3.84375 | 4 | giftcard = 50
print("Giftcard balance: ${}".format(giftcard))
decision = input("Do you wish to purchase skins and weapons for your game?")
if decision == "Yes":
giftcard -= 35
print("You have purchased skins and weapons")
print("Your new balance is: ${}".format(giftcard))
elif decision == "No":
print("Your giftcard balance remains at ${}".format(giftcard))
else:
print("Thats not an answer...")
|
107461172a4a2d9597c2219f4848a4beb01385e2 | rishabhkashyap/pyCookbook | /com/algo/trie/trie.py | 1,448 | 3.953125 | 4 | from com.algo.trie.node import Node
class Trie:
def __init__(self):
self.root = Node('')
def add_word(self, word):
if (word is not None and isinstance(word, str)):
current_node = self.root
for char in word:
node = current_node.get_neighbour(char)
if (node is not None):
current_node = node
else:
new_node = Node(char)
current_node.add(new_node)
current_node = new_node
current_node.is_word = True
def search_word(self, word):
if (word is not None and isinstance(word, str)):
current_node = self.root
word_available = False
for char in word:
node = current_node.get_neighbour(char)
if (node is not None and node.label==char):
current_node = node
else:
current_node=node
break
if(current_node is not None and current_node.is_word):
word_available=True
return word_available
if __name__=='__main__':
trie=Trie()
trie.add_word('geek')
trie.add_word('geekforgeeks')
trie.add_word('geeky')
trie.add_word('geektrust')
trie.add_word('apple')
found=trie.search_word('geektrust')
print('geektrust found = {}'.format(found)) |
32ea461137c4352a5309cbf57356484858ace417 | Nischal47/Python_Exercise | /#13.py | 528 | 4.0625 | 4 | '''Question:
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3
'''
Letters_count=0
Digits_count=0
x=input("Enter a sentence:")
for i in range(len(x)):
if (x[i]>="A" and x[i]<="Z") or (x[i]>="a" and x[i]<="z"):
Letters_count+=1
elif(x[i]>="0" and x[i]<="9"):
Digits_count+=1
print("LETTERS "+str(Letters_count))
print("DIGITS "+str(Digits_count)) |
7d3dcac4e75c47e87299c8abf3572d7ffcf7de89 | harshitsoni01/codes | /kinter.py | 1,005 | 3.921875 | 4 | from tkinter import *
m = Tk()#initializing the tkinter window
m.title("Title of GUI")
m.geometry("600x600")#size of the window # its "x" not "*"
thelabel = Label(m, text = "Welcome to GUI!")
thelabel.pack(side = TOP)#pack method for placements of objects
b1 = Button(m, text = "Button1", fg="white", bg="black")
b1.pack(side=LEFT)# (side = top, bottom, )
b2 = Button(m, text = "button2", font="comicsans, 14", width=15, height=2)
b2.pack(side=RIGHT)
#b3 = Button(m, text = "Button3")
#b3.grid(row = 1, column = 0)# grid method for placement of objects
# you cannot mix grid and pack method
#the values of row=1,col=0 depend of the position of the other widget in your window
def close_window():
m.destroy()
b4 = Button(m, text= "Exit",command = close_window)
b4.place(relx=0.5, rely=0.5, anchor=CENTER)
#this is udes to get image in tkinter
#img = ImageTk.PhotoImage(Image.open("True1.gif"))
#panel = Label(root, image = img)
#panel.pack(side = "bottom", fill = "both", expand = "yes")
m.mainloop() |
9794530e59a070c7545bca1dce5c7fadc0f6c760 | jefinagilbert/problemSolving | /hr105_missingNumbers.py | 398 | 3.828125 | 4 | def missingNumbers(arr, brr):
arr1 = []
for i in brr:
if i in arr:
arr.remove(i)
else:
if i not in arr1:
arr1.append(i)
arr1.sort()
return arr1
arr = []
brr = []
k = input().split()
for i in k:
arr.append(int(i))
k = input().split()
for i in k:
brr.append(int(i))
print(missingNumbers(arr,brr)) |
9095ecdd33337bcd414c28728f0fc49a602c3ce0 | confar/simple-db-auth | /main.py | 1,101 | 4.03125 | 4 | import sqlite3
import getpass
conn = sqlite3.connect('firstbase.sqlite')
print "Connecting database ";
cursor1 = conn.execute("SELECT id, access, login, password from loginlist")
for row in cursor1:
print "id = ", row[0]
print "access = ", row[1]
print "login = ", row[2]
print "and the password is", row[3], "\n"
print "Operation was done successfully\n";
print "Now lets do the Authorization\n"
print "Enter login"
entered_login = raw_input("< ")
print "Enter password"
entered_password = getpass.getpass("< ")
cursor2 = conn.cursor()
x = cursor2.execute("SELECT * from loginlist WHERE login =:entered_login AND password =:entered_password", {"entered_login" : entered_login, "entered_password" : entered_password})
if cursor2.fetchall():
print "Authorization WAS A HUGE SUCCESS!!"
else:
print "You failed!"
cursor2.execute("SELECT * from loginlist WHERE login =:entered_login AND password =:entered_password", {"entered_login" : entered_login, "entered_password" : entered_password})
for row in cursor2:
print "This user has got access to the following files:\n", row[4]
conn.close()
|
71b5db48fc51dbd82b53663b6cb4cc08458c878d | justien/lpthw | /ex5.py | 1,017 | 4.03125 | 4 | # Describe Zed Shaw - the Hard Way!
# -*- coding: utf-8 -*-
# here we define our variables
my_name = "Zed Shaw"
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # pounds
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
# now we print out information about Zed, using the above defined variables
print
print
print " . . . . . . . . . . . . . . . . . "
print "Describe Zed Shaw - the Hard Way!"
print
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
# now Zed wants us to really concentrate on typing a tricky line
# that shows us we are adding similar types together.
# this probably wouldn't work if we used %d and %s together.
print "If I add %d, %d, and %d - I get %d." % (
my_age, my_height, my_weight, my_age + my_height + my_weight)
print
print
|
8ff8b85c5c9a82404db175a5883183d338b562b6 | petitblue/Python | /games/tictac.py | 8,220 | 4.4375 | 4 | # -----------------------------------------------------------------------------
# Name: tictac
# -----------------------------------------------------------------------------
'''
Module to implement a Tic-tac-toe game between human player and computer
player. The players take turns marking the spaces in a 3×3 grid. T
he player who succeeds in placing three marks in a horizontal, vertical,
or diagonal row wins the game.
'''
import tkinter
import random
class Game(object):
'''
GUI Game class to support a n * n board game
Argument:
parent:(tkinter.Tk) the root window object
Attribute:
canvas: (tkinter.Canvas) our drawing canvas
'''
# Add your class variables if needed here - square size, etc...)
# set square size
sq_size = 100
def __init__(self, parent):
parent.title('Tic Tac Toe')
# save the parent in the object
self.parent = parent
self.initialize_game()
self.draw_board()
def initialize_game(self):
"""
Initialize the game
Parameter: None
:return: None
"""
self.board = [None, None, None,
None, None, None,
None, None, None]
# map to self.board
self.map = {(0, 0): 0, (0, 1): 1, (0, 2): 2,
(1, 0): 3, (1, 1): 4, (1, 2): 5,
(2, 0): 6, (2, 1): 7, (2, 2): 8}
self.win_combo =((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6))
def draw_board(self):
"""
draw the game board
Parameter: None
Return: the updated object
"""
restart_frame = tkinter.Frame(self.parent)
# register it with a geometry manager
restart_frame.grid()
# Create the restart button widget
restart_button = tkinter.Button(self.parent, text='RESTART', width=10,
command=self.restart)
# register it with a geometry manager
restart_button.grid(column=0, row=0)
# Create a canvas widget
self.canvas = tkinter.Canvas(self.parent,
width=self.sq_size * 3,
height=self.sq_size * 3)
self.canvas.grid()
for row in range(3):
for column in range(3):
self.canvas.create_rectangle(self.sq_size * column,
self.sq_size * row,
self.sq_size * (column +1),
self.sq_size * (row + 1),
fill='white')
# register it with a geometry manager
self.canvas.grid()
# when the user clicks on the canvas, we invoke self.play
self.canvas.bind("<Button-1>", self.play)
# Create a label widget for the win/lose message
self.message = tkinter.Label(self.parent, text=None)
# register it with a geometry manager
self.message.grid()
return self
def board_full(self):
"""Check if the board is full or empty"
Parameter: None
Return: Boolean Value
"""
if None in self.board:
return False
else:
return True
def legal_move(self):
"""
Check if the move is possible
Parameter: None
Return: legal_move(list): a list of possible moves
"""
legal_move = []
for i in range(9):
# check if the square is taken
if self.board[i] is None:
# add the square number to the list
legal_move.append(i)
else:
pass # if the square is taken, don't append to the list
return legal_move
def pc_move(self):
"""
Computer player makes move, update the game board
Parameter: None
Return: the updated object
"""
pc_turn= True
while pc_turn:
pc_move = random.randint(0, 8) # random generate a number from 0 to 8
if pc_move in self.legal_move(): # if the number is a possible move
self.board[pc_move] = 'O' # mark O
self.canvas.itemconfigure(tagOrId=(pc_move+1),fill='cyan')
pc_turn = False # exit loop
else: # not a possible movie
continue # re-do
return self
def restart(self):
"""
invoked the method when the user clicks on the RESTART button
Return: the updated object
"""
self.message.destroy()
self.canvas.destroy()
self.initialize_game()
self.draw_board()
return self
def sq_num(self,event):
"""
when the player click a empty square,convert cursor into
square number
Parameter: event; click a square
Return: play_move (int) the square number was clicked
"""
# convert window coordinate to canvas coordinate
x = self.canvas.canvasx(event.x)
y = self.canvas.canvasy(event.y)
# map cursor
play_move = self.map[(y // self.sq_size, x // self.sq_size)]
return play_move
def play(self, event):
"""when the human player click on a un-taken square,
update game board and check game result based on condition
Parameter: Event: a click on a square
Return: the updated object
"""
play_move = self.sq_num(event)
# check if the square is empty
if self.board[play_move] is None:
# if the square is empty mark X for human player
self.board[play_move] = 'X'
# fill red color for human player
click_square = self.canvas.find_closest(event.x, event.y)
self.canvas.itemconfigure(click_square, fill='magenta')
else:
return None
# if the board is not full, play game
if not self.board_full():
self.pc_move()
self.check_result()
else: # if the board is full, check the result
self.check_result()
self.check_winner()
return self
def check_result(self):
"""check game result,win, lose or tie"""
for row in self.win_combo:
if self.board[row[0]] == self.board[row[1]]\
== self.board[row[2]]is not None:
winner = self.board[row[0]]
if winner == 'X':
self.message.configure(text='You Won!')
elif winner == 'O':
self.message.configure(text='You Lost!')
# unbind click so player cannot click on square
self.canvas.unbind("<Button-1>")
else:
if self.board_full():
self.message.configure(text="It's a Tie!")
self.canvas.unbind("<Button-1>")
def check_winner(self):
"""
Check if human or computer wins
:return: None
"""
for row in self.win_combo:
if self.board[row[0]] == self.board[row[1]]\
== self.board[row[2]]is not None:
winner = self.board[row[0]]
if winner == 'X':
self.message.configure(text='You Won!')
elif winner == 'O':
self.message.configure(text='You Lost!')
self.canvas.unbind("<Button-1>")
def main():
# Instantiate a root window
root = tkinter.Tk()
# Instantiate a Game object
my_game = Game(root)
# Enter the main event loop
root.mainloop()
if __name__ == '__main__':
main()
|
9aaaf68ad3259e6474020dd6ecc5f1f480a638df | anton-dovnar/CodeWars | /kyu6/decode_the_morse_code.py | 295 | 3.5 | 4 | def decodeMorse(morse_code):
translate = [MORSE_CODE[code] if code else '' for code in morse_code.split(' ')]
result = ""
for value in translate:
if value == '':
result += ' '
else:
result += value
return result.replace(' ', ' ').strip()
|
5fd557303d4a7628cb6b303b650622981fe33e06 | gautam417/Python-Files | /CIS41A/ICE_F.py | 1,521 | 3.84375 | 4 | """
Gautam Mehta
CIS 41A Fall 2017
ICE_F
"""
myInt=3
myList= [0,1,2]
def byVal(y):
print ("Original ID of parameter in byVal is:", id(y))
x= y+7
print ("ID of parameter in byVal after change is:", id(x))
def byRef(b):
print("Original ID of parameter in byRef is:",id(b))
w=len(b)-1
print("Original ID of parameter's last element in byRef is:",id(w))
b[len(b)-1]+=7
print("ID of parameter in byRef after change:", id(b))
def main():
print("Original ID of myInt in main is:",id(myInt))
print("Original ID of myList in main is:", id(myList))
print("ID of myList's last element in main is:", id(len(myList)-1))
byVal(myInt)
byRef(myList)
print("ID of parameter's last element in byRef after change:", id(myInt))
print ("ID of myList in main after call to byRef is:", id(myList))
print ("ID of myList's last element in main after call to byRef is:", id(len(myList)-1))
print("myInt is now:", myInt)
print("myList is now:", myList)
main()
'''
Part 2
Ragged Table
'''
def build_bell(num_rows):
rtable = [[1]]
for i in range(1, num_rows):
rtable.append([rtable[i - 1][-1]])
for j in rtable[i - 1]:
rtable[i].append(rtable[i][-1] + j)
return rtable
def print_bell(table):
for i in range(len(table)):
for j in range(len(table[i])):
num = str(table[i][j])
print(num.rjust(4), end = ' ')
print("")
def main():
print_bell(build_bell(6))
main()
|
126afe024cddd389bde6bfd97586b4257bd4f7f0 | redpanda-ai/ctci | /solutions/group_anagrams_2.py | 360 | 3.8125 | 4 | from collections import defaultdict
def group_anagrams(anas):
groups = defaultdict(list)
for word in anas:
x = "".join(sorted(word))
groups[x].append(word)
solution = []
for key in groups.keys():
solution.extend(groups[key])
print(solution)
test = ["ABC", "BAC", "DEF", "FED", "FFE", "FOO"]
group_anagrams(test) |
18020c4f50b78b0fe35baf22dc529ee9e07fd7a4 | citlalygonzale/TC1014 | /e.py | 208 | 3.71875 | 4 | def calculate_e(c):
x = c
ce = (1+1/x)**x
return float(ce)
r = int(input("Number of decimal points of accuracy: "))
resulte = calculate_e(r)
print("The estimate of the constant e is:",resulte)
|
a98bd51799efc96e2ed24bb96c1c785603d193d2 | Jiaweihu08/EPI | /16 - Dynamic Programming/16.3 - number_of_traversals_matrix.py | 814 | 3.953125 | 4 | """
Given a nxm grid starting at the top-left corner. Compute the number of
distinct paths to get to the bottom-right corner if we're only allowed
to go right or down.
"""
import functools
def number_of_traversals_matrix(n, m):
"""
O(nm) space and time complexity
"""
@functools.lru_cache(None)
def number_of_traversals_helper(i, j):
if i == 0 or j == 0:
return 1
return (number_of_traversals_helper(i - 1, j) +
number_of_traversals_helper(i, j - 1))
return number_of_traversals_helper(n - 1, m - 1)
def number_of_traversals_matrix_minab_space(n, m):
"""
O(nm) time complexity
O(min(a, b)) space complexity
"""
if m > n:
n, m = m, n
dp = [1] * m
for i in range(1, n):
for j in range(1, m):
dp[j] += dp[j - 1]
return dp[-1]
print(number_of_traversals_matrix_minab_space(5, 5)) |
3f033c2a5a58803eb8147ec612bd172dee24b318 | NAVEENMN/MyArchives | /avltree/bstnew.py | 4,410 | 3.875 | 4 | import random, math
#------------------------------------------------------------------------ BST Section start
class BstNode():
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BSTTree():
def __init__(self, *args):
self.node = None
self.height = -1
if len(args) == 1:
for i in args[0]:
self.insert(i)
def height(self):
if self.node:
return self.node.height
else:
return 0
def insert(self, key):
tree = self.node
newnode = BstNode(key)
if tree == None:
self.node = newnode
self.node.left = BSTTree()
self.node.right = BSTTree()
print "Inserted key [" + str(key) + "]"
elif key < tree.key:
self.node.left.insert(key)
elif key > tree.key:
self.node.right.insert(key)
else:
print "Key [" + str(key) + "] already in tree."
self.update_heights(False)
def update_heights(self, recurse=True):
if not self.node == None:
if recurse:
if self.node.left != None:
self.node.left.update_heights()
if self.node.right != None:
self.node.right.update_heights()
self.height = max(self.node.left.height,
self.node.right.height) + 1
else:
self.height = -1
def delete(self, key):
if self.node != None:
if self.node.key == key:
print "Deleting ... " + str(key)
if self.node.left.node == None and self.node.right.node == None:
self.node = None # leaves can be killed at will
# if only one subtree, take that
elif self.node.left.node == None:
self.node = self.node.right.node
elif self.node.right.node == None:
self.node = self.node.left.node
# worst-case: both children present. Find logical successor
else:
replacement = self.smallonrightsub(self.node)
if replacement != None: # sanity check
print "Found replacement for " + str(key) + " -> " + str(replacement.key)
self.node.key = replacement.key
# replaced. Now delete the key from right child
self.node.right.delete(replacement.key)
return
elif key < self.node.key:
self.node.left.delete(key)
elif key > self.node.key:
self.node.right.delete(key)
else:
return
def smallonrightsub(self, node):
'''
Find the smallese valued node in RIGHT child
'''
node = node.right.node
if node != None: # just a sanity check
while node.left != None:
print "LS: traversing: " + str(node.key)
if node.left.node == None:
return node
else:
node = node.left.node
return node
def inorder_traverse(self):
if self.node == None:
return []
inlist = []
l = self.node.left.inorder_traverse()
for i in l:
inlist.append(i)
inlist.append(self.node.key)
l = self.node.right.inorder_traverse()
for i in l:
inlist.append(i)
return inlist
def getheight(self):
return(self.height)
#----------------------------------------------------------------------------------------------------------- BST section end
# Usage example
if __name__ == "__main__":
a = BSTTree()
print "----- Inserting -------"
inlist = [0, 1, 2, 3, 4, 5, 6, 7]
for i in inlist:
a.insert(i)
a.delete(4)
print "Input :", inlist
print "Inorder traversal:", a.inorder_traverse()
print "height of tree: ", a.getheight()
|
6a655b9cec1a3a6d45eb047b82f5f186582db1f4 | sbeaumont/AoC | /2021/AoC-2021-1.py | 866 | 3.578125 | 4 | #!/usr/bin/env python3
"""Solution for Advent of Code challenge 2021 - Day 1"""
__author__ = "Serge Beaumont"
__date__ = "December 2021"
def part_1(entries):
raised = 0
for i in range(1, len(entries)):
if entries[i] > entries[i-1]:
raised += 1
return raised
def part_2(entries):
raised = 0
for i in range(4, len(entries) + 1):
slice1 = entries[i-3: i]
slice2 = entries[i-4: i-1]
if sum(slice1) > sum(slice2):
raised += 1
return raised
def read_puzzle_data(file_number):
with open(f"AoC-2021-{file_number}-input.txt") as infile:
return [int(line) for line in infile.readlines()]
test_result = part_2(read_puzzle_data("1-test"))
print("Test:", test_result)
assert test_result == 5
print("Part 1:", part_1(read_puzzle_data(1)))
print("Part 2:", part_2(read_puzzle_data(1)))
|
a392987a5b1455949ccc720689b5c585c383940f | wangjm12138/python_other_script | /sockets_server.py | 1,193 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#import sys
##reload(sys)
##sys.setdefaultencoding('utf8')
#import socket
## 建立一个服务端
#server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#server.bind(('127.0.0.1',1080)) #绑定要监听的端口
#server.listen(5) #开始监听 表示可以使用五个链接排队
##flag=1
##while True:# conn就是客户端链接过来而在服务端为期生成的一个链接实例
#conn,addr = server.accept() #等待链接,多个链接的时候就会出现问题,其实返回了两个值
#print(conn,addr)
#while True:
##flag=flag+1
# data = conn.recv(10) #接收数据
# print('recive:',data.decode()) #打印接收到的数据
# #print(flag) #打印接收到的数据
# if len(data) ==0:
# break
# conn.send(data.upper()) #然后再发送数据
#conn.close()
__author__ = 'nickchen121'
from socket import *
ip_port = ('127.0.0.1', 8080)
TCP_socket_server = socket(AF_INET, SOCK_STREAM)
TCP_socket_server.bind(ip_port)
TCP_socket_server.listen(5)
conn, addr = TCP_socket_server.accept()
data1 = conn.recv(10)
data2 = conn.recv(10)
print('----->', data1.decode('utf-8'))
print('----->', data2.decode('utf-8'))
|
0f140cdc0dbfbea690e8a9b843bee1fd6d655356 | madelinecodes/beginner-projects | /TurnBasedPokemon/pokemongame.py | 3,258 | 3.984375 | 4 | import random
import time
print('*' * 36)
print('''\nThis is a turn based Pokemon style game against the computer.
You both have 100 health to start. You cannot go above full health.
Option 1 deals between 18 and 25 damage, option 2 between 10 and 35.
Option 3 heals you by 18 to 25 health points. \n''')
print('*' * 36)
player_health = 100
comp_health = 100
turn = 0
while comp_health and player_health > 0:
if turn == 0:
move = int(input('Enter move 1, 2, or 3: '))
if move not in [1, 2, 3]:
print('I didnt recognize that number.')
elif move is 1:
number = random.randint(18, 25) # set here instead of inline below so that number can be called in print statement
comp_health -= number
comp_health = max(comp_health, 0) # makes sure that health never displays below 0
# affected, dmg_heal, and move_name are only for the sake of the printed message
affected = 'Computer'
dmg_heal = 'damaged'
move_name = 'STRIKE'
elif move is 2:
number = random.randint(10, 35)
comp_health -= number
comp_health = max(comp_health, 0)
affected = 'Computer'
dmg_heal = 'damaged'
move_name = 'FURY'
elif move is 3:
number = random.randint(18, 25)
player_health += number
player_health = min(player_health, 100) # makes sure that health doesnt go above 100
affected = 'Player'
dmg_heal = 'healed'
move_name = 'RECOVERY'
turn = 1 - turn # toggle turn between 0 and 1
else:
move = random.randint(1, 3)
time.sleep(1) # 'loading time'
if comp_health < 35: # increase probability of choosing 3 if comp_health is under 35 points
choices = [1, 2] + [3] * 2
move = random.choice(choices)
if move is 1:
number = random.randint(18, 25)
player_health -= number
player_health = max(player_health, 0)
affected = 'Player'
dmg_heal = 'damaged'
move_name = 'STRIKE'
elif move is 2:
number = random.randint(10, 35)
player_health -= number
player_health = max(player_health, 0)
affected = 'Player'
dmg_heal = 'damaged'
move_name = 'FURY'
elif move is 3:
number = random.randint(18, 25)
comp_health += number
comp_health = min(comp_health, 100)
affected = 'Computer'
dmg_heal = 'healed'
move_name = 'RECOVERY'
turn = 1 - turn
print('*' * 36)
print('\n!!!{}!!!\n'.format(move_name))
print('''{affected} has been {dmg_heal} by {number} points. \n
Player:{player_health}/Computer:{comp_health}
'''.format(affected=affected, dmg_heal=dmg_heal, number=number, player_health=player_health, comp_health=comp_health))
print('*' * 36)
# if either player has reached zero, end the game
if comp_health == 0 or player_health == 0:
print('GAME OVER! Player:{player_health}/Computer:{comp_health}'.format(
player_health=player_health, comp_health=comp_health))
|
cf9912fae71a8f01e96f87773edfc174aeef211a | kwngo/NYC_Subway_python | /plot_entries_per_hour.py | 716 | 3.671875 | 4 | from pandas import *
from ggplot import *
def plot_weather_data(turnstile_weather):
entries_per_hour = turnstile_weather.groupby(["hour"], as_index=False)["ENTRIESn_hourly"].sum()
# Plot with day of week relabeled as abreviation
plot = ggplot(entries_per_hour, aes('hour', 'ENTRIESn_hourly')) + \
geom_line(stat='identity') + \
ggtitle('Subway entries by hour of day (for the month of May)') + \
ylab('Total entries') + \
theme(text = element_text(size=25))
return plot
def main(filename):
turnstile_weather = pandas.read_csv(filename, parse_dates=True)
plot_weather_data(turnstile_weather)
if __name__ == "__main__":
main('turnstile_weather_v2.csv')
|
03184a2f469e1ce27641847dc30183d3a658359d | flogothetis/Technical-Coding-Interviews-Algorithms-LeetCode | /Grokking-Coding-Interview-Patterns/14. Top K Numbers/KpointsClosestTwoOrigin.py | 1,047 | 3.765625 | 4 | '''
Problem Statement #
Given an array of points in the a 2D2D2D plane, find ‘K’ closest points to the origin.
'''
from heapq import *
# Time Comp : O(NlogK)
# Space Comp : O(K)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
self.euclidean_dist() > other.euclidean_dist()
def print_point(self):
print("[" + str(self.x) + ", " + str(self.y) + "] ", end='')
def euclidean_dist (self):
return (self.x ** 2 + self.y **2) ** (1/2)
def find_closest_points(points, k):
result = []
max_heap = []
for i in range(k):
heappush(max_heap, points[i])
for i in range ( k, len(points)):
if (points[i].euclidean_dist() < max_heap[0].euclidean_dist()):
heappop(max_heap)
heappush(max_heap, points[i])
return list(max_heap)
def main():
result = find_closest_points([Point(1, 3), Point(3, 4), Point(2, -1)], 2)
print("Here are the k points closest the origin: ", end='')
for point in result:
point.print_point()
main()
|
c4d9084f7bafc58f473dcec142ddac37eac2b8cd | EshwaryForReasons/Python-Scripts | /Python Calculator/Calculator Multiplication.py | 946 | 4.09375 | 4 | import time
import clipboard
print("Welcome to the multiplication calculator")
p = input("Which profile would you like?")
pi = int(p)
#multiply two digit numbers
def calculator():
i1 = input("What is the first number?")
i2 = input("What is the second number?")
v = int(i1) * int(i2)
print(v)
clipboard.copy(v)
ri = input("reset?")
#multiply by 11
def clac_profile1():
i1 = input("What is the number?")
v = int(i1) * 11
print (v)
clipboard.copy(v)
#multiply by 111
def clac_profile2():
i1 = input("What is the number?")
v = int(i1) * 111
print (v)
clipboard.copy(v)
#multiply by 111
def clac_profile3():
i1 = input("What is the number?")
v = int(i1) ** 3
print (v)
clipboard.copy(v)
if pi == 0:
while True:
calculator()
elif pi == 1:
while True:
clac_profile1()
elif pi == 2:
while True:
clac_profile2()
elif pi == 3:
while True:
clac_profile3() |
a5db0f6958a3ee88727eefae105cf6ad98139f3a | chprabhu/earnings-trade-strategy | /compute_strategy.py | 2,892 | 3.515625 | 4 | import pandas as pd
import numpy as np
from constants import *
def get_pre_earnings_trading_returns(ticker):
'''
This function returns a list of return rates, assuming that we buy at the open 'num_days'
before the earnings announce date, and sell near the close of the earnings announce date
BTO = Before Trading Opens
DMT = During Market Trading
AMC = After Market Close
'''
return_rates = []
try:
price_data = pd.read_csv(stock_price_data_path + ticker + ".csv", parse_dates=['timestamp'])
earnings = earnings_dates[earnings_dates['ticker'] == ticker]
except:
print(ticker + " Error reading in price data")
error_tickers.append(ticker)
return return_rates
for row in earnings.itertuples():
earnings_date = row[2] # get back earnings date
announce_time = row[3] # get back announce time
try:
if (announce_time == "BTO" or announce_time == "DMT"):
# get data from num_days+1 trading days ago up to 1 trading day ago
begin_index = price_data[price_data['timestamp'] == earnings_date].index.values[0] + 1
elif (announce_time == "AMC"):
# get data from num_days trading days ago up to today
begin_index = price_data[price_data['timestamp'] == earnings_date].index.values[0]
else:
print('Invalid Announce Time Code: ' + ticker)
continue
end_index = begin_index + num_days
window = price_data[begin_index:end_index]
return_rate = (window['close'][begin_index] / window['open'][end_index-1]) - 1
return_rates.append(return_rate)
except (IndexError, ValueError) as error:
print(ticker + " Error pulling price data subset")
error_tickers.append(ticker)
break
return return_rates
def get_returns_table(tickers):
'''
This function returns a table that has the following columns:
Ticker - Ticker symbol
R1-R5 - Stock return for specified time period. R1 uses the most recent earnings date,
with each subsequent R going backwards in time
'''
returns_table = pd.DataFrame(columns=['R1', 'R2', 'R3', 'R4', 'R5'])
for i, ticker in enumerate(tickers):
get_returns = get_pre_earnings_trading_returns(ticker)
# Some stocks don't have 5 earnings dates. Append zeros until length equals 5
while len(get_returns) < 5:
get_returns.append(0)
get_returns = pd.Series(get_returns, index=['R1', 'R2', 'R3', 'R4', 'R5'])
returns_table = returns_table.append(get_returns, ignore_index=True)
print(str(i) + ": " + ticker + " - Complete")
returns_table.index = tickers
return returns_table
if __name__ == '__main__':
error_tickers = []
earnings_dates = pd.read_csv(earnings_dates_data_path + "earnings_dates.csv", parse_dates=["earnings_date"])
tickers = list(earnings_dates['ticker'].unique())
returns_table = get_returns_table(tickers)
print(returns_table)
print(error_tickers)
returns_table.to_csv(earnings_dates_data_path + "returns_table.csv", index_label = 'ticker')
|
4c973fa53432d84ac1b819869fee27d195a34b41 | fernandocampello/PythonClasses | /List_15.py | 363 | 3.5 | 4 | x = [5,2,3,10]
n = len(x)
sum = 0
for _x in x:
sum = sum + _x
'''sum + = _x'''
print(sum)
mean = sum/n
print(mean)
sse = 0
for _x in x:
sse = sse + (_x - mean)**2
print(sse)
ssen = sse/n
std = ssen**0.5
print(std)
ssen1 = sse/(n-1)
stds = ssen1**0.5
print(stds)
x = [5,2,3,10]
n = len(x)
sum = 0
for i in range(n):
sum += x[i]
print(sum)
|
c99809cb53127eb3e5c35be41268f2c6fd573e33 | BhagyaRB/python93 | /Activity_04.py | 486 | 3.984375 | 4 | Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> n=int(input("enter the value for n="))
enter the value for n=4
>>> m=int(input("enter the value for m="))
enter the value for m=8
>>> p=n+m
>>> print(P)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(P)
NameError: name 'P' is not defined
>>> print(p)
12
>>>
|
3ee4d84864be39ec52aeb986e4c79cb23b4d6e79 | JohanEddeland/AdventOfCode | /2018/05/aoc_05.py | 2,433 | 3.625 | 4 | """ aoc_05.py
Solution for Advent of Code 2018
"""
import aoc_05_input
def replace_all_polymer(aoc_input):
aoc_input = aoc_input.replace('\n', '')
# Start counting at the second letter
current_letter_index = 1
result = [aoc_input[0]]
while current_letter_index < len(aoc_input):
if result:
previous_letter = result[-1]
else:
previous_letter = '\x00'
this_letter = aoc_input[current_letter_index]
if same_type_different_polarity(this_letter, previous_letter):
result.pop()
else:
result.append(this_letter)
current_letter_index += 1
return ''.join(result)
def same_type_different_polarity(letter1, letter2):
letter_difference = ord(letter1) - ord(letter2)
if abs(letter_difference) == 32:
return True
else:
return False
def replace_one_substring(string_to_replace, letter_index):
if letter_index == len(string_to_replace):
new_string = string_to_replace[0:letter_index - 1]
else:
new_string = string_to_replace[0:letter_index - 1] + string_to_replace[letter_index + 1:]
return new_string
def is_this_letter(lowercase_letter, letter):
if lowercase_letter == letter:
return True
elif ord(letter) - ord(lowercase_letter) == -32:
return True
else:
return False
def solve_task2(aoc_input):
shortest_result = float('inf')
shortest_letter = '\x00'
for letter_counter in range(65, 91):
input_with_removed_letter = aoc_input.replace(chr(letter_counter), '')
input_with_removed_letter = input_with_removed_letter.replace(chr(letter_counter + 32), '')
final_result = replace_all_polymer(input_with_removed_letter)
if len(final_result) < shortest_result:
shortest_result = len(final_result)
shortest_letter = chr(letter_counter)
return shortest_result, shortest_letter
def main():
""" main()
Main function that use the input from Advent of Code and print the
answer to the problems for day one.
"""
aoc_input = aoc_05_input.get_input()
answer1 = replace_all_polymer(aoc_input)
(shortest_result, shortest_letter) = solve_task2(aoc_input)
print('Part 1: {}'.format(len(answer1)))
print('Part 2: {}'.format(shortest_result))
print(shortest_letter)
if __name__ == '__main__':
main()
|
17d8eda143520015721cc5adf206e46293dc5cfc | yui-chouchou/AMECOBA_PROJECTS | /AMECOBA_SEMESTER1/ADRIAN_PROJECTS/AMECOBA_PROJECT/SECTION_1/python/part1/amecoba-answer.py | 3,980 | 4 | 4 | #端末で初めてのHELLOWORLDを出力してみよう
print("hello world")
print(10-1)
#文字列や数字を合わせて表示する
print("NUMBER", 10 + 2)
print("WELCOME" + "to" + "AMECOBA")
#モジュール(部品)を使って簡単なおみくじプログラムを作ってみよう
import random #シャフルするので、Randomという部品を使います。
kujibiki = ["VERY LUCKY", "LUCKY", "GOOD", "NOT BAD", "BAD", "VERY BARD"]
#変数 = [要素0, 要素1, 要素2, 要素3, 要素4, 要素5]
print(random.choice(kujibiki))
#出力(モジュール.選ぶ(変数))
#BMI直計算プログラムの身長と体重の総合を測ってみよう
HEIGHT = float(input("身長何センチですか?"))
#身長 = 浮動小数点(入力("身長何センチですか?"))
WEIGHT = float(input("体重何キロですか?"))
#体重 = 浮動小数点(入力("体重何キロですか?"))
BMI = WEIGHT / (HEIGHT * HEIGHT)
#BMI = 体重 / (身長 ✖️ 身長)
print("あなたのBMI値:", BMI, "ですね!")
#出力("あなたのBMI値", BMI(変数), "ですね!")
#様々なデータの種類を理解しよう
#変数に入れることができるデータには、「数値」、「文字」などいろいろな種類がある = データ型
number = 100
float_number = 13.2
string_word = "hello"
b = True #反対はFalse
print(type(number)) #個数や順番に使う
print(type(float_number)) #一般的な計算に使う
print(type(string_word)) #文字数を扱う時に使う
print(type(b)) #true か false かの二択の時に使う
#文字列の操作を覚えよう
write = "hello" + "my name is amecoba"
print(write)
print(len(write)) #文字数を調べる lenメソッド
print(write[0]) #出力(変数[要素番号])
print(write[6:12]) #出力(変数[開始要素番号:最後の要素番号から一つ前])
print(write[-3:]) ##出力(変数[逆の要素番号])
print("hello \n world.") #文字列を改行
print("hello wo\trld.") #タブ文字
#データ型を変換する
a = "100"
print(a + 23) # TypeError なぜかというと 100という数字ではなく、文字列として扱われているから
print(int(a) + 23) #123
#変換できない時はエラーになる
b = "hello"
print(int(b) + 23) #Type Error
#isdigitメソッドを用いて数値に変換できるのか
a = "100"
b = "hello"
print(a.isdigit())
print(b.isdigit())
#データをまとめるためのリストを使ってみよう
fruits = ["apple", "banana", "cherry", "blueberry"]
print(fruits[2])
#===========================================================================
#if文を使ってみよう
#if 条件式:
#条件式が正しい時にする処理
tennsu = 100
if tennsu >= 80: #もしも
#>=とは 比較演算子
print("Good job!")
elif tennsu >= 60: #そうでないけれど、もしも
print("good")
else: #そうでないとき
print("Don't worry about tennsu")
#for文を使ってみよう
#for カウント変数 in range(回数):
#繰り返す処理
for i in range(10):
print(i)
#for文を使ってリストを取り出しみる
#for 要素をいれる変数 in リスト:
#繰り返す処理
score = [64, 100, 78, 80, 72]
for i in score:
print(i)
#for文によるネスト化(入れ子)
#for カウント変数 in range(回数):
#for カウント変数 in range(回数):
# 繰り返す処理
for i in range(10):
for j in range(10):
print(j * i)
#def関数を使って簡単に一つ
#def 関数名():
# 関数で行う処理
def hello():
print("hello")
hello()
# return を使う
# def 関数名(引数1, 引数2):
# 関数で行う処理
# return 戻り値
def postTaxPrice():
ans = 100 * 1.08
return ans
# print("hello") #呼び出されることはない, returnがあるので
print(postTaxPrice()) |
d36df4cd5c9559fd808fc7df7527d68db7724da2 | Xenever/pavlov | /WithoutKeys.py | 930 | 3.734375 | 4 | #Extended Euclidean algorithm
def egcd(a, b):
x, lastX = 0, 1
y, lastY = 1, 0
while (b != 0):
q = a // b
a, b = b, a % b
x, lastX = lastX - q * x, x
y, lastY = lastY - q * y, y
return (lastX, lastY)
#дробь по модулю(num-числитель,denom-знаменатель)
def Exponent(num,denom,mod):
a,b=egcd(denom,mod)
a=a*num
while a>mod:
a=a-mod
return a
#WrongKeys
def WKey(y1,e1,y2,e2,N):
a,b=egcd(e1,e2)
if a<b:
c=a
a=b
b=c
c=y1
y1=y2
y2=c
b=-b
result=pow(int(int(pow(y1,a)//pow(y2,b))+Exponent(pow(y1,a)%pow(y2,b),pow(y2,b),N)),1,N)
return result
"""
x=int(input("начальный текст:"))
e1=int(input("первый ключ:"))
e2=int(input("второй ключ:"))
N=int(input("модуль:"))
y1=pow(x,e1,N)
y2=pow(x,e2,N)
print(WKey(y1,e1,y2,e2,N))
"""
|
0a85876b84a26926f7bea8593e86ff15105867bb | chizom/python-tutorial | /guessing_game_v1.py | 319 | 3.859375 | 4 | # This is a guessing game that can be inproved on. Just gettnig version one on
the_mind = 10
users_guess = 0
chances = 1
end_game = False
while chances <= 3:
users_guess = input('Guess: ')
chances += 1
if users_guess == the_mind:
print('You win')
break
else:
print('Sorry you failed')
|
7185fa4a9ec0703f6a61c37884a34dfd0b2b6707 | BufteacEcaterina03/Rezolvare-problemelor-IF-WHILE-FOR | /1pr.py | 343 | 3.921875 | 4 | n=int(input('Introduceti numarul de zile:'))
if (n>=28 and n<=31):
if (n==28 or n==29):
print('Februarie')
elif n==30:
print('Aprilie,Iunie,Septembrie,Noiembrie')
else:
print('Ianuarie,Martie,Mai,Iulie,August,Octombrie,Decembrie')
else:
print('Nu exista luna cu asa numar de zile') |
8cf9b52617ed8eb6b6588a7033ec081ac885f0d3 | mtbutler93/pythonprojects | /buffets.py | 327 | 3.765625 | 4 | # playing with lists, creating tuples
# mtb 03.20.2018
buffets = ('eegs','bacon','waffles','omlette','sausage')
print ('Original buffet items:')
for buffet in buffets:
print(buffet)
buffets = ('pizza','toast','waffles','omlette','sausage')
print ('\nUpdated buffet items:')
for buffet in buffets:
print(buffet)
|
9c84cd16cfdbfbd5bf925fbb560892e0752681b1 | Abrar-04/DSA-Practice | /02.LinkedLists/4.ReversedLL.py | 829 | 4.03125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
# insert at beginning
def Push(self,key):
new_node=Node(key)
new_node.next=self.head
self.head=new_node
def ReversedLL(self):
p1=None
p2=self.head
while p2:
p3=p2.next
p2.next=p1
p1=p2
p2=p3
self.head=p1
# print LL
def PrintLL(self):
t=self.head
while t:
print(t.data)
t=t.next
if __name__=='__main__':
ll=LinkedList()
ll.Push(5)
ll.Push(4)
ll.Push(3)
ll.Push(2)
ll.Push(1)
ll.Push(0)
ll.PrintLL()
print("*"*10)
print("reversed")
ll.ReversedLL()
ll.PrintLL() |
74f6a7f39d6173fe523f5c4d57d4c457feb0331a | meloncloud/python-calc | /Class_Persona2.py | 601 | 4.03125 | 4 | class Persona:
def __init__(self,name, age):
self.name = name
self.age = age
def show (self):
print('your name is : ',self.name, ', and your age is :', self.age, 'years old' )
class Persona2(Persona):
def __init__(self,name, age,height):
self.name = name
self.age = age
self.height = height
def show (self):
print('your name is : ',self.name, ', and your age is :', self.age, 'years old' )
persona1=Persona("Pedro", "32")
persona1.show()
persona2=Persona2("Pedro", "32",23)
persona2.show()
|
1653a4d478cbae57fd5a72159fb8354cad7ddc09 | green-fox-academy/Angela93-Shi | /week-02/day-8/write_multiple_lines.py | 935 | 4.21875 | 4 | # Create a function that takes 3 parameters: a path, a word and a number
# and is able to write into a file.
# The path parameter should be a string that describes the location of the file you wish
# to modify
# The word parameter should also be a string that will be written to the file as individual
# The number parameter should describe how many lines the file should have.
# If the word is "apple" and the number is 5, it should write 5 lines
# into the file and each line should read "apple"
# The function should not raise any errors if it could not write the file.
def write_multiple_lines(path,word,number):
f=open(path,'w')
try:
for i in range(number):
f.write(word+'\n')
f.close()
except IOError:
print("can't write the file")
finally:
("completed")
write_multiple_lines(r"C:\Users\Angela_Shi\Desktop\angela\week2\day8\multiple_lines.txt","apple",5)
|
eb792677600bf534dccd8b0e928174c2653cfa87 | nishitpatel01/Data-Science-Toolbox | /algorithm/Array/755_Pour_Water.py | 1,566 | 3.515625 | 4 | class Solution:
def pourWater1(self, heights, V, K):
"""
:type heights: List[int]
:type V: int
:type K: int
:rtype: List[int]
"""
# W
# | # |
# |######|
for _ in range(V):
for d in (-1, 1):
i = low = K
# less or equal so water can travel
while 0 <= i + d < len(heights) and heights[i + d] <= heights[i]:
# strictly less so water stops traveling
if heights[i + d] < heights[i]:
low = i + d
i += d
if low != K:
heights[low] += 1
break
if low == K:
heights[K] += 1
return heights
def pourWater2(self, heights, V, K):
"""
:type heights: List[int]
:type V: int
:type K: int
:rtype: List[int]
"""
for _ in range(V):
index = K
for i in range(K - 1, -1, -1):
if heights[i] > heights[i + 1]:
break
elif heights[i] < heights[i + 1]:
index = i
if index != K:
heights[index] += 1
continue
for i in range(K + 1, len(heights)):
if heights[i] > heights[i - 1]:
break
elif heights[i] < heights[i - 1]:
index = i
heights[index] += 1
return heights |
abb6b549a2f4ce4842747b38cd544f4ea6e633e6 | ssf-czh/paper_system | /tools/random_pick.py | 297 | 3.53125 | 4 | import random
def random_pick(probabilities):
x = random.uniform(0, 1)
cumulative_probability = 0.0
for item_probability in probabilities:
cumulative_probability += item_probability
if x < cumulative_probability:
return probabilities.index(item_probability) |
a6c1cda5a52bce28900f7e9ed5bac297f59d53f7 | OmarLahzy/Python-scripts | /Function.py | 2,039 | 3.578125 | 4 | def pig_latin (word):
first_letter = word[0]
if first_letter in 'aeiou':
return word+'ay'
else:
return word[1:]+first_letter+'ay'
def Sumnumbers (*args):
return sum(args) * 0.05
def Vegtiable(**kwargs):
if 'fruit' in kwargs:
print('My fruite choice is {}'.format(kwargs['fruit']))
else:
print('i didnt find any fruit')
def lesser_of_two_evens (a,b):
if a%2 == 0 and b%2==0:
if a>b:
return b
else:
return a
else:
if a>b:
return a
else:
return b
def animal_crackers(str):
strlist = str.split()
return strlist[0][0] == strlist[1][0]
def returntwenty(a,b):
return a==20 or b==20 or a+b==20
def old_macdonald(str):
str[0].upper()+str[1:3]+str[4].upper()+str[4:]
def reverse(str):
#I am Home
strlist = str.split()
return " ".join(strlist[::-1])
def Almostthere(n):
return (abs(200-n) <= 10) or (abs(100-n) <=10)
def has_33 (nums):
for i in range(0,len(nums)):
if (nums[i] == 3) and (nums[i] == nums[i+1]):
return True
return False
def paper_doll (text):
str = ''
for i in range(0,len(text)):
str = str+text[i]*3
return str
def blackjack(a,b,c):
sum = a+b+c
if sum <= 21:
return sum
elif (sum >21) and (a==11 or b==11 or c==11):
return sum-10
elif sum>21:
return 'Bust'
def SummerOf69(arr):
sum = 0
for i in range(0,len(arr)):
sum = sum+arr[i]
print(sum)
if __name__ == '__main__':
answer = pig_latin("Omar")
print(answer)
print(Sumnumbers(40,40,50,60,80))
print(Vegtiable(fruit='apple',veggie='lettuce'))
print(lesser_of_two_evens(2,5))
print(animal_crackers("Levelheaded blama"))
print(returntwenty(5,10))
old_macdonald("omarr")
print(reverse("I am Home"))
print(Almostthere(190))
print(has_33 ([1,1,3,3,1]))
print(paper_doll ('Hello'))
print(blackjack(9,9,9))
SummerOf69([1,2,3,6,8,8,9])
|
388dacbe23bf519a8a4505d82fd8fb417b33bb36 | vadsimus/Python | /HackerRank/Python Challenge/MergeTheTools!.py | 476 | 3.609375 | 4 | # https://www.hackerrank.com/challenges/merge-the-tools/problem
def merge_the_tools(string, k):
for i in range(int(len(string) / k)):
line_str = string[i * k:i * k + k]
line = list(line_str)
j = len(line) - 1
while j > -1:
if line.count(line[j]) >= 2:
del line[j]
j -= 1
print(''.join(line))
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
|
fd42d88656031d97048692f32ffa162a52eeb1e0 | idobleicher/pythonexamples | /examples/functional-programming/itertools_examples/itertools_compress.py | 508 | 4.34375 | 4 | # compress(iter, selector) :- This iterator selectively picks the values to print from the passed container according
# to the boolean list value passed as other argument.
# The arguments corresponding to boolean true are printed else all are skipped.
import itertools
# using compress() selectively print data values
print ("The compressed values in string are : ",end="")
print (list(itertools.compress('GEEKSFORGEEKS',[1,0,0,0,0,1,0,0,1,0,0,0,0])))
# The compressed values in string are : ['G', 'F', 'G'] |
ade7d89656382c39b72c08bf1c6c2b6e9311c097 | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/check_triange_solution.py | 794 | 4.03125 | 4 | # # To add a new cell, type '# %%'
# # To add a new markdown cell, type '# %% [markdown]'
# # %%
# # ---------------------------------------------------------------
# # python best courses https://courses.tanpham.org/
# # ---------------------------------------------------------------
# # Write a Python program to check a triangle is valid or not
#
# ___ triangle_check l1 l2 l3
# __ (l1>l2+l3) o. (l2>l1+l3) o. (l3>l1+l2
# print('No, the lengths wont form a triangle')
# ____ (l1__l2+l3) o. (l2__l1+l3) o. (l3__l1+l2):
# print('yes, it can form a degenerated triangle')
# ____
# print('Yes, a triangle can be formed out of it')
#
# length1 _ in. i.. 'enter side 1\n'
# length2 _ in. i.. 'enter side 2\n'
# length3 _ in. i.. 'enter side 3\n'
#
# ? ? ? ?
#
|
69794166935dfc48225128ed5ad48a6c6882ca8f | William-Mou/Coding365-Practice | /week_1/41.py | 1,078 | 3.890625 | 4 | tree = {"first":['null']}
roots = []
not_root = []
global first
first = "first"
def printf(root = first):
#print(root)
tree[root] = sorted(tree[root])
if root == "first":
pass
elif root == first:
print(root,end = "")
for j in tree[root]:
print(j,end ="")
if j in tree:
printf(j)
def insert(leaf):
for i in range(len(leaf)):
if i == 0:
root = leaf[i]
#roots.append(root)
if root in tree:
for j in range(1,len(leaf)):
tree[root].append(leaf[j])
break
else:
tree[root] = []
else:
tree[root].append(leaf[i])
#not_root.append(i)
return 0
flag = True
while True:
#print(tree)
n = input()
if n == 'p':
printf(first)
print()
elif n == 'i':
leaf = input()
if flag == True:
first = leaf[0]
flag = False
#print(first)
insert(leaf)
else :
break |
f8dc19c96a106c79df790bf93ea0c950e9eb8686 | peiss/ant-learn-python-100P | /p008_remove_elements_from_list.py | 395 | 3.984375 | 4 | def remove_elements_from_list(lista, listb):
for item in listb:
lista.remove(item)
return lista
lista = [3, 5, 7, 9, 11, 13]
listb = [7, 11]
print(f"from {lista} remove {listb}, result : ", remove_elements_from_list(lista, listb))
lista = [3, 5, 7, 9, 11, 13]
listb = [7, 11]
data = [item for item in lista if item not in listb]
print(f"from {lista} remove {listb}, result : ", data)
|
cab2a3884a184839d61196ce7eff3f3df32ef7ff | syedmeesamali/Python | /5_Homeworks/Previous/py funcs.py | 1,712 | 4 | 4 | #Simple function to add numbers
def add(a,b):
mysum = a + b
return mysum
#Function to find intersection of two lists
def intersect(s1,s2):
#res is empty list to store numbers
res = []
for x in s1:
if x in s2:
res.append(x)
return res
#Function to create random password from a given length and characters saved
import random
def password(length):
#pw is empty string to later store password
pw = str()
chars = "abcdefghijklmn"
for i in range(length):
pw = pw + random.choice(chars)
return pw
#Below function calculates factorial of a number
def factorial(n):
if n == 0:
return 1
else:
N = 1
for i in range(1, n+1):
N = N * i
return(N)
#Below function counts the characters in a word
def count_letters(word, char):
count = 0
while count <= len(word):
for char in word:
if char == word[count]:
count += 1
return count
#Count the number for each character occurence in string and save in dictionary
def counter(input_string):
dict1={}
for x in input_string:
dict1[x] = dict1.setdefault(x,0)+1
return dict1
#Function to count most frequent letter in dictionary
def most_frequent_letter(input_dict):
maximum = 0
letter_maximum = ""
for letter in input_dict:
if input_dict[letter] > maximum:
maximum = input_dict[letter]
letter_maximum = letter
return letter_maximum
#Below function can be used to calculate distance between two points x,y
import math
def distance(x, y):
distance = math.sqrt( ((x[0]-y[0])**2)+((x[1]-y[1])**2) )
return distance
x=(0,0)
y=(1,1)
print(distance(x,y))
|
b99422ffb2d756fd5739524abcb8cd535ceb0da0 | onerbs/w2 | /structures/linked_list.py | 3,366 | 4.09375 | 4 | from structures.node import Node
from typing import Iterable
class LinkedList:
"""Unordered linked list."""
def __init__(self, values: Iterable = None):
self._head = None
for value in (values or [])[::-1]: # O(k)
self.unshift(value)
def push(self, value): # O(n)
"""Adds one node to the end of the list."""
if not (last_node := self._head):
return self.unshift(value)
while last_node.next_node:
last_node = last_node.next_node
last_node.next_node = Node(value)
def pop(self): # O(n)
""" Removes the last node from the list.
:returns: The value of the removed node.
"""
if not (penultimate_node := self._head):
return
if not penultimate_node.next_node:
value = self._head.value
self._head = None
return value
while penultimate_node.next_node.next_node:
penultimate_node = penultimate_node.next_node
value = penultimate_node.next_node.value
penultimate_node.next_node = None
return value
def unshift(self, value): # O(1)
"""Adds one node to the beginning of the list."""
self._head = Node(value, self._head)
def shift(self): # O(1)
"""Removes the first node from the list.
:returns: The value of the removed node.
"""
value = self._head.value
self._head = self._head.next_node
return value
def find(self, value): # O(n)
"""Find a node by value.
:returns: The first node with the given value or None.
"""
if (current_node := self._head).value == value:
return self._head
while current_node := current_node.next_node:
if current_node.value == value:
return current_node
def remove(self, value): # O(n)
"""Removes the first node with the given value."""
current_node = self._head
previous_node = self._head
while current_node.next_node:
if current_node.value == value:
previous_node.next_node = current_node.next_node
return
previous_node = current_node
current_node = current_node.next_node
def replace(self, value, new_value) -> None: # O(n)
"""
Replaces the value of the first node
with the given value by another value.
"""
if node := self.find(value):
node.value = new_value
def is_empty(self):
return self._head is None
def __contains__(self, value):
return self.find(value) is not None
def __iter__(self):
class Iterator:
def __init__(self, node):
self._node = node
def __next__(self):
if not self._node:
raise StopIteration
value = self._node.value
self._node = self._node.next_node
return value
return Iterator(self._head)
def __len__(self): # O(n)
current_node, count = self._head, 0
while current_node is not None:
count += 1
current_node = current_node.next_node
return count
def __str__(self):
return ' -> '.join([str(it) for it in self])
|
b5bd5b6b996c1b19db36a4d9a7b347be6c1c0188 | vardanohanyan/homework | /VardanOhanyanHomeWork6/VardanOhanyanHomeWork6.py | 2,576 | 3.96875 | 4 | #Problem 1
#Create a file manually with some text in it like "My favourite fruits are:".
#Then write a program to append the file with the fruits that you love.
import os
#f = open(r"C:\Users\ASUS\Desktop\problem1.txt", "a")
#f.write("banana, apple, mango, qiwi, orange")
#f.close()
#Problem 2
#Create a file that has 5 or more lines of text.
#Write a program to store each line in a variable
#with open(r"C:\Users\ASUS\Desktop\problem2.txt") as f:
# line1 = f.readline()
# line2 = f.readline()
# line3 = f.readline()
# line4 = f.readline()
# line5 = f.readline()
#print(line1, line2, line3, line4, line5)
#uzeca listovel sarqel
#ls = []
#with open(r"C:\Users\ASUS\Desktop\problem2.txt") as f:
# for line in f:
# ls.append(line.rstrip("\n"))
#print(ls)
#Problem 3
#Find the longest word in the file pr3.txt.
#f = open(r"C:\Users\ASUS\Desktop\problem3.txt")
#s = f.read().split()
#print(max(s,key=len))
#Problem 4
#Create a list of names of all our group members.
#Loop over the list and create files (filename = name).
#Each file should contain the name of a person repeated as many times as the characters of the name.
#l = ["Vardan","Abraham","Alik","Ani","Aren","Armen","Ars","Arthur","Mark","Mary"]
#for x in l:
# f = open(rf"C:\Users\ASUS\Desktop\{x}.txt","x")
# f.write((x + "\n") * len(x))
#Problem 5
#After writing Problem 4 write a function that gets this list and checks if files with these names exist.
#If a file exists return True, otherwise False.
#new_names = ['Ani', 'Armen', 'Aren', 'Argishti', 'Arsen', 'Alik', 'Anahit', 'Anna']
#for x in new_names:
# if os.path.exists(rf"C:\Users\ASUS\Desktop\{x}.txt"):
# new_names = True
# else:
# new_names = False
#Problem 6
#Write a function that gets a file path and calculates how many upper case letters are in the text.
#Hint: use isupper() method.
#def count_letter():
# file = open(r"C:\Users\ASUS\Desktop\problem3.txt")
# data = file.read()
# count = 0
# for letter in data:
# if letter.isupper():
# count+=1
# print(count)
# file.close()
#count_letter()
#Problem 7 (OPTIONAL)
#Write a program to show the frequency(how many times a word appears in the text) of each word.
#Hint: set()
from collections import Counter
def word_count(fname):
with open(r"C:\Users\ASUS\Desktop\problem7.txt") as f:
return Counter(f.read().split())
print("Number of words in the file :", word_count(r"C:\Users\ASUS\Desktop\problem7.txt"))
|
95b9ceae2d2103c971cf84fe74d7ec924d11f218 | HieuChuoi/nguyenminhhieu-fundamental-c4e25 | /session3/BTVN S3/sheep_4.py | 437 | 3.84375 | 4 | sheep = [5, 7, 300, 90, 24, 50, 75]
print("Hello, my name is Hieu and this are my ship size ",end='')
print(sheep)
print()
biggest_sheep = max(sheep)
print("Now my biggest sheep has size ",biggest_sheep," let's shear it")
print()
sheep[2] = 8
print("After shearing, here is my flock ",sheep)
print()
z = int(len(sheep))
for i in range(z):
sheep[i] += 50
print("One month has passed, now here is my flock: ",end='')
print(sheep) |
845ddda7fab5ab148bb377a3cb317c84e97f033e | lamtharnhantrakul/coding-interview-bootcamp | /elements_of_programming/rotateMatrix.py | 272 | 3.984375 | 4 | a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
def rotateImageC(a):
a = zip(*reversed(a))
a = [list(item) for item in a]
return a
def rotateImageCC(a):
a = zip(*a)
a = [list(item) for item in a]
a.reverse()
return a
print(rotateImageCC(a))
|
2e3e259848e37aec019a69927d267565a86fa8ed | nirmalnishant645/Python-Programming | /Competitive-Programming/Formatted-Number.py | 1,086 | 4.3125 | 4 | '''
Have the function FormattedNumber(strArr) take the strArr parameter being passed,
which will only contain a single element,
and return the string true if it is a valid number that contains only digits with properly placed decimals and commas,
otherwise return the string false.
For example: if strArr is ["1,093,222.04"] then your program should return the string true,
but if the input were ["1,093,22.04"] then your program should return the string false.
The input may contain characters other than digits.
Examples
Input: ["0.232567"]
Output: true
Input: ["2,567.00.2"]
Output: false
'''
# Efficiency to be checked
def addCommas(x):
if x < 1000:
return str(x)
else:
return addCommas(x // 1000) + ',' + '%03d' % (x % 1000)
def FormattedNumber(strArr):
s = strArr.split('.')
if len(s) > 2:
return False
temp = s[0]
temp = temp.replace(',', '')
temp = int(temp)
temp = addCommas(temp)
if temp != s[0]:
return False
for num in s:
if num < '0' or num > '9':
return False
return True |
c0dc478236e9965fbd0c08c5381b6839aeb61a7c | SpielerNogard/SecuredSocket | /send_mail.py | 1,395 | 3.515625 | 4 | import socket
server_info = ("192.168.10.45", 25)
socket = socket.socket()
socket.connect(server_info)
def send_message(data):
arr = bytes(data, 'utf-8')
socket.send(arr)
username = input("Enter your username: ")
password = input("Enter your password: ")
recipient = input("Recipient: ")
data = input("Your message: ")
auth = username + "" + password
#auth = auth.encode("base64").replace("\n", "")
send_message("HELO\r\n")
print ("EHLO Response: " + str(socket.recv(1024)))
#socket.send("AUTH PLAIN "+auth+"\r\n")
#print ("AUTH Response: " + socket.recv(1024))
#socket.send("MAIL FROM:<"+username+">\r\n")
send_message("MAIL FROM:<"+username+">\r\n")
print ("MAIL FROM Response: " + str(socket.recv(1024)))
send_message("RCPT TO:"+recipient+"\r\n")
#socket.send("RCPT TO:"+recipient+"\r\n")
print ("RCPT TO Response: " + str(socket.recv(1024)))
send_message("RCPT TO:"+recipient+"\r\n")
#socket.send("RCPT TO:"+recipient+"\r\n")
print ("RCPT TO Response: " + str(socket.recv(1024)))
#socket.send("DATA\r\n")
send_message("DATA\r\n")
print ("DATA Response: " + str(socket.recv(1024)))
#socket.send(data + "\r\n.\r\n")
send_message(data + "\r\n.\r\n")
print ("RAW DATA Response: " + str(socket.recv(1024)))
#socket.send("QUIT\r\n")
send_message("QUIT\r\n")
print ("QUIT Response: " + str(socket.recv(1024)))
print ("Done.")
socket.close()
|
dfac81b97868421a0e73b8485634fba6908db9ce | Suprit5/synerzip_training | /Bank-Management-System/account_section.py | 5,852 | 3.625 | 4 | from database import *
import prettytable
def savings_account():
bank_db=accessing_db()
bank=bank_db.cursor()
print('--------Enter the following details--------')
name=input('Enter Full Name :- ')
address=input('Enter The Address:- ')
p_number=int(input('Enter Phone Number:- '))
email=input('Enter email:- ')
aadhar_no=int(input('Enter Aadhar Number:- '))
bank.execute(f'''INSERT INTO savings_account
(name, address, phone_no, email, aadhar_no)
VALUES ("{name}","{address}",{p_number},"{email}",{aadhar_no})
''')
bank_db.commit()
def salary_account():
bank_db=accessing_db()
bank=bank_db.cursor()
'''
acno int not null auto_increment primary key,
company_id varchar(20),
name char(30),
address varchar(100),
phone_no int not null unique,
email varchar(80) unique,
aadhar_no int not null unique,
acc_type char(30) DEFAULT "Salary Account",
status varchar(10),
balance int not null)
'''
print('--------Enter the following details--------')
company_id=input('Enter Company ID:- ')
name=input('Enter Full Name :- ')
address=input('Enter The Address:- ')
p_number=int(input('Enter Phone Number:- '))
email=input('Enter email:- ')
aadhar_no=int(input('Enter Aadhar Number:- '))
bank.execute(f'''INSERT INTO salary_account
(company_id, name, address, phone_no, email, aadhar_no)
VALUES ("{company_id}","{name}","{address}",{p_number},"{email}",{aadhar_no})
''')
bank_db.commit()
def account_type():
print('''
----------Account Type-----------
------------Options--------------
1. Savings Account.
2. Salary Account.
''')
choice=int(input('Enter the option number:- '))
if choice == 1:
savings_account()
elif choice == 2:
salary_account()
def search_account(table_name):
bank_db=accessing_db()
bank=bank_db.cursor()
while True:
print('''
--------Search By--------
1. Account Number.
2. Name.
3. Aadhar Number.
4. Phone Number.
''')
choice=int(input('Enter The Number:- '))
if choice == 1:
attribute='acno'
account_no = int(input('Enter Account Number:- '))
bank.execute(f'''
SELECT * FROM {table_name}
WHERE {attribute} = {account_no}
''')
print(prettytable.from_db_cursor(bank))
return account_no,attribute
elif choice == 2:
attribute='name'
name = input('Enter Name:- ')
bank.execute(f'''
SELECT * FROM {table_name}
WHERE {attribute} = '{name}'
''')
print(prettytable.from_db_cursor(bank))
return name,attribute
elif choice == 3:
attribute='aadhar_no'
aadhar_no = int(input('Enter Aadhar Number:- '))
bank.execute(f'''
SELECT * FROM {table_name}
WHERE {attribute} = {aadhar_no}
''')
print(prettytable.from_db_cursor(bank))
return aadhar_no,attribute
elif choice == 4:
attribute='phone_no'
phone_no = int(input('Enter phone number:- '))
bank.execute(f'''
SELECT * FROM {table_name}
WHERE {attribute} = {phone_no}
''')
print(prettytable.from_db_cursor(bank))
return phone_no,attribute
def delete_account():
bank_db=accessing_db()
bank=bank_db.cursor()
while True:
print('''
--------Select Option--------
1. Delete A Account From Savings Account.
2. Delete A Account From Salary Account.
''')
choice=int(input('Enter The Number:- '))
if choice == 1:
value, attribute = search_account('savings_account')
print('''
--------Do You Want To Delete This Account?--------
1. Yes.
2. No.
''')
choice = int(input('Enter The Number'))
if choice == 1:
if type(value)== int:
bank.execute(f'''
DELETE FROM savings_account
WHERE {attribute} = {value}
''')
bank_db.commit()
else:
bank.execute(f'''
DELETE FROM savings_account
WHERE {attribute} = '{value}'
''')
bank_db.commit()
else:
accounts()
elif choice == 2:
value, attribute = search_account('salary_account')
print('''
--------Do You Want To Delete This Account?--------
1. Yes.
2. No.
''')
choice = int(input('Enter The Number'))
if choice == 1:
if type(value)== int:
bank.execute(f'''
DELETE FROM salary_account
WHERE {attribute} = {value}
''')
bank_db.commit()
else:
bank.execute(f'''
DELETE FROM salary_account
WHERE {attribute} = '{value}'
''')
bank_db.commit()
else:
accounts()
def accounts():
while True:
print('''
------------Options--------------
1. Create A New Account.
2. Delete Account.
''')
choice=int(input('Enter the option number:- '))
if choice == 1:
account_type()
elif choice == 2:
delete_account()
if __name__ == '__main__':
search_account('savings_account') |
4477911c7d80a3f414731925051acff1817b15b8 | Candace-Beall/python_kata | /talk_python_to_me/02_guess_that_number_game/program.py | 355 | 3.625 | 4 | import random
from talk_python_to_me.helpers.header import print_header
print_header('GUESS THAT NUMBER GAME', 65)
the_number = random.randint(0, 100)
guess_text = input('Guess a number between 0 and 100: ')
guess = int(guess_text)
if the_number > guess:
print('too low')
elif the_number < guess:
print('too high')
else:
print('you win')
|
fcea9ef0d1bb2489fb5cfd511ef2f85eef1acd0f | samruddhi221/Python_DS_Algo | /CodingQuestions/Google1.py | 1,730 | 3.640625 | 4 | """
Question: In a nxn chessboard, the position of king and queen is specied as K->(kx, ky) and Q->(qx, qy).
Other pieces are denoted by '1's and blank spaces are denoted by '0'. The king can move one step in any
direction. There are j jumps, i.e. the king can share the space with a piece j times.
Write an algorithm to calculate the shorted distance the king has to travel to reach the queen.
chessboard = [[K, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0 ,0, 0, 1],
[1, 0, 0, 1, Q]]
kx=ky=0, qx=qy=4, j=1
answer = 4 (K->(1,1)->(2,2)->(3,3)->Q)
"""
import collections
def shortestDistance(chessboard, kx, ky, qx, qy):
pass
def bfs(chessboard, kx, ky, qx, qy):
n = len(chessboard)
queue = collections.deque([])
queue.append((kx, ky, 0)) #x, y, distance
# next move = {up, up_right_diag, right, down_right_diag, down, down_left, left, up_left}
nextRow = [-1,-1,0,1,1,1,0,-1]
nextCol = [0,1,1,1,0,-1,-1,-1]
visited = [[0 for i in range(n)] for j in range(n)]
while queue:
node_x, node_y, distance = queue.popleft()
if node_x==qx and node_y==qy:
return distance
for i in range(8):
nextX = node_x+nextRow[i]
nextY = node_y+nextCol[i]
if 0 <= nextX <= n and 0 <= nextY <= n:
if chessboard[nextX][nextY] == 0:
if visited[nextX][nextY] == 0:
queue.append((nextX, nextY, distance+1))
visited[nextX][nextY] = distance
else:
visited[nextX][nextY] = min(visited[nextX][nextY], distance+1)
pass
if __name__ == '__main__':
|
3a8d4317313e40a7bff3a18d7f97ab0b8b4b30d9 | gowthamrajceg/python | /pythoncode/stringmethod3.py | 309 | 4.09375 | 4 |
quote = 'Let it be, let it be, let it be'
result = quote.find('let it')
print("Substring 'let it':", result)
result = quote.find('small')
print("Substring 'small ':", result)
# How to use find()
if (quote.find('be,') != -1):
print("Contains substring 'be,'")
else:
print("Doesn't contain substring")
|
8d9b15cf0add58beed7dca83ebbd5f84a0f248b8 | joedeller/pymine | /mandel.py | 2,074 | 4.21875 | 4 | #!/usr/bin/python
# Joe Deller 2014
# A very simplified version of the Mandelbrot set
# Level : Intermediate
# Uses : Libraries, variables, lists
# I have taken some example code for how to draw the Mandelbrot set from Wikipedia
# and made it compatible with the Pi.
# This isn't a true fractal program as we can't zoom in
# This is another example of where it isn't necessary to understand the code completely
# to be able to use it.
# If you know that fractals draw patterns in different colors, then
# it's just a question of converting the fractal code to draw blocks instead.
import mcpi.minecraft as minecraft
import mcpi.block as block
blockList = [block.STONE, block.DIRT, block.GRASS, block.SAND,
block.WOOD, block.WOOD_PLANKS, block.LAPIS_LAZULI_BLOCK,
block.COAL_ORE, block.IRON_ORE, block.WOOL, block.GLASS,
block.WATER]
def chooseBlock(iterations):
if (iterations > 10 ):
return block.WATER
else:
return (blockList[iterations])
def drawMandelbrot(xPos, yPos, zPos, imgx, imgy, maxIt, xa, ya, xb, yb):
for y in range(imgy):
zy = y * (yb - ya) / (imgy - 1) + ya
for x in range(imgx):
zx = x * (xb - xa) / (imgx - 1) + xa
# The next line uses something called a complex, or imaginary number
# This is from a fairly advanced set of mathematics
z = zx + zy * 1j
c = z
for i in range(maxIt):
if abs(z) > 2.0: break
z = z * z + c
mc.setBlock(xPos + x, yPos, zPos + y, chooseBlock(i))
mc = minecraft.Minecraft.create()
x, y, z = mc.player.getTilePos()
mc.setBlocks(x -10, y, z, x + 40, y + 40, z + 50, block.AIR.id)
mc.setBlocks(x -10, y - 2, z, x + 40, y + -1, z + 50, block.GRASS.id)
# You can try different numbers and see what happens to the shape that is drawn
# Try changing by small amounts first.
# It's never going to be super detailed in Minecraft, but it does work, sort of
drawMandelbrot(x - 10, y - 1, z - 10, 60, 60, 554, -2.0, -1.5, 1.0, 1.5)
|
c51aca1b16e6fd05d1f43514c99e9c94e3579be9 | vetiveria/pollutants | /pollutants/io/directories.py | 1,469 | 3.6875 | 4 | """Module directories"""
import os
class Directories:
"""
Class Directories
"""
def __init__(self):
"""
Constructor
"""
@staticmethod
def cleanup(directories_: list):
"""
Deletes a directory, after deleting its contents
:param directories_: A list of directories
:return:
"""
for path in directories_:
if not os.path.exists(path):
continue
files_ = [os.remove(os.path.join(base, file))
for base, directories, files in os.walk(path) for file in files]
if any(files_):
raise Exception('Unable to delete all files within path {}'.format(path))
paths_ = [os.removedirs(os.path.join(base, directory))
for base, directories, files in os.walk(path, topdown=False)
for directory in directories if os.path.exists(os.path.join(base, directory))]
if any(paths_):
raise Exception('Unable to delete all directories within path {}'.format(path))
if os.path.exists(path):
os.rmdir(path)
@staticmethod
def create(directories_: list):
"""
For creating directories
:param directories_: A list of directories
:return:
"""
for path in directories_:
if not os.path.exists(path):
os.makedirs(path)
|
310b8833f6f2c7f54707764b6f2f4b3c9a35437a | eddyD45/CSC321PythonAssignment | /part3/logic/logic.py | 180 | 3.765625 | 4 | def is_even(integer):
return integer % 2 == 0
def in_an_interval(number):
return (2 <= number < 9) or (47 < number < 92) or (12 < number <= 19) or (101 <= number <= 103)
|
7f837173bad966ae54b48ffbc996515f462db51f | Ming-H/Code_more | /python_test.py | 6,133 | 3.90625 | 4 | 1、对list去重
l1 = [1,1,2,3,2]
print(list(set(l1)))
l2 = {}.fromkeys(l1).keys()
print(l2)
l1 = ['b','c','d','b','c','a','a']
l2 = []
[l2.append(item) for item in l1 if not item in l2]
2、创建字典
dict1 = {}.fromkeys(('x','y'),-1)
print(dict1)
dict2 = {}.fromkeys(('a','b','c'))
print(dict2)
3、合并两个有序list
#遍历两个list,选择小的加入到新list
def func(L1,L2):
L = []
while len(L1)>0 and len(L2)>0:
if L1[0] < L2[0]:
L.append(L1[0])
del L1[0]
else:
L.append(L2[0])
del L2[0]
L.extend(L1)
L.extend(L2)
print(L)
#******pop方法******
def func(L1,L2):
L= []
while L1 and L2:
if L1[0] >= L2[0]:
L.append(L2.pop(0))
else:
L.append(L1.pop(0))
while L1:
L.append(L1.pop(0))
while L2:
L.append(L2.pop(0))
print(L)
#******尾递归方法*******
def _recursion_merge_sort2(l1, l2, tmp):
if len(l1) == 0 or len(l2) == 0:
tmp.extend(l1)
tmp.extend(l2)
return tmp
else:
if l1[0] < l2[0]:
tmp.append(l1[0])
del l1[0]
else:
tmp.append(l2[0])
del l2[0]
return _recursion_merge_sort2(l1, l2, tmp)
def recursion_merge_sort2(l1, l2):
result = _recursion_merge_sort2(l1, l2, [])
return result
4、交叉链表求交点
#******如果两个链表交叉,则从交叉点开始,后面的元素均相同******
a = [1,2,3,7,8,9,1,5]
b = [4,5,7,9,1,5]
for i in range(1,min(len(a),len(b))):
if i==1 and (a[-1] != b[-1]):
print("No")
break
else:
if a[-i] != b[-i]:
print("交叉节点:",a[-i+1])
break
else:
pass
5、字典排序
d = {'a':5, 'b':4, 'e':83, 'z':42, 'h':33}
#根据key排序
d_sort_key = sorted(d.items(), key=lambda k: k[0])
[(k,d[k]) for k in sorted(d.keys())]
#根据value排序
d_sort_value = sorted(d.items(), key = lambda k: k[1])
#通过公共键对字典列表进行排序
l = [{'x':1, 'y':2}, {'x':2, 'y':3}, {'x':3, 'y':4}]
L_new = sorted(l, key=lambda k: k['x'], reverse = True)
6、替换字符串指定字符
#subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量
import re
p = re.compile('blue|white|red')
print(p.subn('color','blue socks and red shoes'))
>>('color socks and color shoes', 2)
7、match()和search()的区别
re模块中match(pattern,string[,flags]),是从字符串首字母处匹配
re模块中research(pattern,string[,flags]),是遍历整个字符串匹配
import re
print(re.match('super', 'superstition').span())
>>(0, 5)
print(re.search('super', 'insuperable').span())
>>(2, 7)
8、正则表达式里<.*>和<.*?>的区别
( <.*> ) 贪婪匹配
(<.*?> ) 非贪婪匹配
9、函数传值还是传引用
说传值或者传引用都不准确,非要安一个确切的叫法的话,叫传对象
错误:
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
正确:
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
10、函数参数类型
必选参数、默认参数、可选参数、关键字参数
def func(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
11、浮点数比较
浮点数相等比较不能通过==,应该是一个范围,可以使用 x <= 1.0
x = 0.5
while x != 1.0
print(x)
x += 0.1
>>SyntaxError: invalid syntax
12、copy.copy和copy.deepcopy的区别
#1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
#2. copy.deepcopy 深拷贝 拷贝对象及其子对象
import copy
lista = [1,2,3,['a','b']]
listb = copy.copy(lista)
listc = copy.deepcopy(lista)
lista.append(5)
lista[3].append('c')
print(lista)
[1, 2, 3, ['a', 'b', 'c'], 5]
print(listb)
[1, 2, 3, ['a', 'b', 'c']]
print(listc)
[1, 2, 3, ['a', 'b']]
13、什么是装饰器,如何使用装饰器
def log(level):
def dec(func):
def wrapper(*kargc,**kwargs):
print("before func was called")
func(*kargc,**kwargs)
print("after func was called")
return wrapper
return dec
@log(2)
def funcLog():
print("funcLog was called")
funcLog()
>>before func was called
>>funcLog was called
>>after func was called
14、交换字典的键和值
d = {'A' : 1, 'B' : 2, 'C' : 3}
(1) 字典推导式
d1 = {v:k for k,v in d.items()}
生成器表达式 + dict()
(2) d2 = dict((v,k) for k,v in d.items())
zip() + dict()
(3) d3 = dict(zip(d.values(), d.keys()))
15、求斐波那契数列的第n项
def Fibonacci(n):
prev, curr = 0, 1
for _ in range(n):
prev, curr = curr, prev+curr
return prev
16、python面向对象
python单下划线、双下划线、头尾双下划线说明:
__foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。
_foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *
__foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
Python内置类属性
__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
参考文献:
https://github.com/taizilongxu/interview_python#29-super-init
http://www.cnblogs.com/ChenxofHit/archive/2011/03/18/1988431.html
https://www.cnblogs.com/shizhengwen/p/6972183.html
http://blog.csdn.net/u013679490/article/details/54948759
http://www.codingonway.com/python-get-fibonacci-n-number.html
http://www.runoob.com/python/python-object.html
|
4d1172ad0f9a35d17d3bd5a2d5740583e5f8b535 | teohklun/imdc2020_DHL_Google | /project DHL/class/hello.py | 338 | 3.890625 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student:
def __init__(self, name, course):
self.course = course
self.name = name
def get_student_details(self):
print("Your name is " + self.name + ".")
print("You are studying " + self.course) |
62d4809fa51155b55dd1f77f5b55bd99ffff2924 | pxu/LeetCode-1 | /Maximum Difference Between Node and Ancestor/Maximum Difference Between Node and Ancestor.py | 1,490 | 3.796875 | 4 | '''
Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B
where V = |A.val - B.val| and A is an ancestor of B.
(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)
Example 1:
Input: [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation:
We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Note:
1. The number of nodes in the tree is between 2 and 5000.
2. Each node will have value between 0 and 100000.
'''
# Appraoch: Divide and Conquer (Top-Down DFS)
# 解法详解参考同名 java 文件 Approach 2
# 介于 python 的特性,我们能重写函数名,避免创建新的 dfs函数
# 并且可以把这些内容比较 geek 地写到一行中。但是算法上和 java 的做法是相同的
#
# 时间复杂度:O(n)
# 空间复杂度:O(logn)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxAncestorDiff(self, root: TreeNode, mini = 0x3f3f3f3f, maxi = 0) -> int:
return max(self.maxAncestorDiff(root.left, min(mini, root.val), max(maxi, root.val)), self.maxAncestorDiff(root.right, min(mini, root.val), max(maxi, root.val))) if root else maxi - mini |
4d066e23610ef5224be97ccc1005134e4beb0025 | Fullmoon8507/PythonPracticeProject | /apply/class_variable_test2.py | 831 | 4.03125 | 4 | ###################################################################
# インスタンス変数が存在しない場合、「インスタンス.変数名」は
# クラス変数を参照する。
# 「インスタンス変数.変数名」に値を代入した時点で
# インスタンス変数が生成され、以降はインスタンス変数が参照される。
###################################################################
class MyClass:
PI = 3.14
if __name__ == "__main__":
a1 = MyClass()
a2 = MyClass()
print(a1.PI) # クラス変数 MyClass.PI(3.14)が参照される
a1.PI = 3.141593 # インスタンス変数a1.PIが生成される
print(a1.PI) # インスタンス変数a1.PI(3.141593)
print(a2.PI) # クラス変数 MyClass.PI(3.14)が参照される
|
c78eb7cabe947aad80c1ae46c99a59e5d521a074 | syurskyi/Python_3_Deep_Dive_Part_3 | /Section 3 Dictionaries/71. Counter - Coding.py | 7,993 | 3.984375 | 4 | print('#' * 52 + ' ')
from collections import defaultdict, Counter
sentence = 'the quick brown fox jumps over the lazy dog'
counter = defaultdict(int)
for c in sentence:
counter[c] += 1
print('#' * 52 + ' We can do the same thing using a `Counter` - unlike the `defaultdict`'
' we dont specify a default factory - its always zero (its a counter after all): ')
counter = Counter()
for c in sentence:
counter[c] += 1
print(counter)
print('#' * 52 + ' #### Constructor ')
print('#' * 52 + ' It is so common to create a frequency distribution of elements in an iterable,'
' that this is supported automatically: ')
c1 = Counter('able was I ere I saw elba')
print(c1)
print('#' * 52 + ' Of course this works for iterables in general, not just strings: ')
import random
random.seed(0)
my_list = [random.randint(0, 10) for _ in range(1_000)]
c2 = Counter(my_list)
print(c)
print('#' * 52 + ' We can also initialize a `Counter` object by passing in keyword arguments, or even a dictionary: ')
c2 = Counter(a=1, b=10)
print(c2)
c3 = Counter({'a': 1, 'b': 10})
print(c3)
print('#' * 52 + ' #### Finding the n most Common Elements ')
import re
sentence = '''
his module implements pseudo-random number generators for various distributions.
For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element,
a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma,
and beta distributions. For generating distributions of angles, the von Mises distribution is available.
Almost all module functions depend on the basic function random(), which generates a random float uniformly in
the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision
floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe.
The Mersenne Twister is one of the most extensively tested random number generators in existence.
However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable
for cryptographic purposes.'''
words = re.split('\W', sentence)
print(words)
print('#' * 52 + ' But what are the frequencies of each word, and what are the 5 most frequent words? ')
word_count = Counter(words)
print(word_count)
print(word_count.most_common(5))
print('#' * 52 + ' #### Using Repeated Iteration ')
c1 = Counter('abba')
print(c1)
for c in c1:
print(c)
print('#' * 52 + ' However, we can have an iteration'
' that repeats the counter keys as many times as the indicated frequency: ')
for c in c1.elements():
print(c)
print('#' * 52 + ' ')
l = []
for i in range(1, 11):
for _ in range(i):
l.append(i)
print(l)
print('#' * 52 + ' But we could use a `Counter` object as well: ')
c1 = Counter()
for i in range(1, 11):
c1[i] = i
print(c1)
print(c1.elements())
print('#' * 52 + ' And we can iterate through that `chain` quite easily: ')
for i in c1.elements():
print(i, end=', ')
print('#' * 52 + ' Just for fun, how could we reproduce this functionality using a plain dictionary? ')
class RepeatIterable:
def __init__(self, **kwargs):
self.d = kwargs
def __setitem__(self, key, value):
self.d[key] = value
def __getitem__(self, key):
self.d[key] = self.d.get(key, 0)
return self.d[key]
r = RepeatIterable(x=10, y=20)
print(r.d)
r['a'] = 100
print(r['a'])
print(r['b'])
print(r.d)
print('#' * 52 + ' Now we have to implement that `elements` iterator: ')
class RepeatIterable:
def __init__(self, **kwargs):
self.d = kwargs
def __setitem__(self, key, value):
self.d[key] = value
def __getitem__(self, key):
self.d[key] = self.d.get(key, 0)
return self.d[key]
def elements(self):
for k, frequency in self.d.items():
for i in range(frequency):
yield k
r = RepeatIterable(a=2, b=3, c=1)
for e in r.elements():
print(e, end=', ')
print('#' * 52 + ' Lastly lets see how we can update a `Counter` object using another `Counter` object. ')
print('#' * 52 + ' When both objects have the same key, we have a choice - do we add the count of one'
' to the count of the other, or do we subtract them? ')
print('#' * 52 + ' We can do either, by using the `update` (additive) or `subtract` methods. ')
c1 = Counter(a=1, b=2, c=3)
c2 = Counter(b=1, c=2, d=3)
c1.update(c2)
print(c1)
print('#' * 52 + ' On the other hand we can subtract instead of add counters: ')
c1 = Counter(a=1, b=2, c=3)
c2 = Counter(b=1, c=2, d=3)
c1.subtract(c2)
print(c1)
print('#' * 52 + ' Just as the constructor for a `Counter` can take different arguments, so too can the `update` and'
' `subtract` methods. ')
c1 = Counter('aabbccddee')
print(c1)
c1.update('abcdef')
print(c1)
print('#' * 52 + ' #### Mathematical Operations ')
c1 = Counter('aabbcc')
c2 = Counter('abc')
c1 + c2
print(c1 - c2)
c1 = Counter(a=5, b=1)
c2 = Counter(a=1, b=10)
print(c1 & c2)
print(c1 | c2)
print('#' * 52 + ' The **unary** `+` can also be used to remove any non-positive count from the Counter: ')
c1 = Counter(a=10, b=-10)
print(+c1)
print('#' * 52 + ' The **unary** `-` changes the sign of each counter, and removes any non-positive result: ')
print(-c1)
print('#' * 52 + ' ##### Example ')
import random
random.seed(0)
widgets = ['battery', 'charger', 'cable', 'case', 'keyboard', 'mouse']
orders = [(random.choice(widgets), random.randint(1, 5)) for _ in range(100)]
refunds = [(random.choice(widgets), random.randint(1, 3)) for _ in range(20)]
print(orders)
print(refunds)
print('#' * 52 + ' Lets first load these up into counter objects. ')
print('#' * 52 + ' To do this we are going to iterate through the various lists and update our counters: ')
sold_counter = Counter()
refund_counter = Counter()
for order in orders:
sold_counter[order[0]] += order[1]
for refund in refunds:
refund_counter[refund[0]] += refund[1]
print(sold_counter)
print(refund_counter)
net_counter = sold_counter - refund_counter
print(net_counter)
print(net_counter.most_common(3))
print('#' * 52 + ' We could actually do this a little differently, not using loops to populate our initial counters. ')
print('#' * 52 + ' Recall the `repeat()` function in `itertools`: ')
from itertools import repeat
print(list(repeat('battery', 5)))
print(orders[0])
print(list(repeat(*orders[0])))
print('#' * 52 + ' So we could use the `repeat()` method to essentially repeat each widget for each item of `orders`. ')
print('#' * 52 + ' We need to chain this up for each element of `orders` - this will give us a single iterable'
' that we can then use in the constructor for a `Counter` object. ')
print('#' * 52 + ' We can do this using a generator expression for example: ')
from itertools import chain
print(list(chain.from_iterable(repeat(*order) for order in orders)))
order_counter = Counter(chain.from_iterable(repeat(*order) for order in orders))
print(order_counter)
print('#' * 52 + ' What if we dont want to use a `Counter` object. We can still do it (relatively easily) as follows: ')
net_sales = {}
for order in orders:
key = order[0]
cnt = order[1]
net_sales[key] = net_sales.get(key, 0) + cnt
for refund in refunds:
key = refund[0]
cnt = refund[1]
net_sales[key] = net_sales.get(key, 0) - cnt
# eliminate non-positive values (to mimic what - does for Counters)
net_sales = {k: v for k, v in net_sales.items() if v > 0}
# we now have to sort the dictionary
# this means sorting the keys based on the values
sorted_net_sales = sorted(net_sales.items(), key=lambda t: t[1], reverse=True)
# Top three
print(sorted_net_sales[:3])
|
bb0beadea13777bd963e5e7557e2bf8bbadfbeee | shivamnegi1705/Competitive-Programming | /Atcoder/AtCoder Beginner Contest 179/A - Plural Form.py | 137 | 3.859375 | 4 | # Question Link:- https://atcoder.jp/contests/abc179/tasks/abc179_a
s = input()
if s[-1]!='s':
print(s+'s')
else:
print(s+'es')
|
9224003f9e5b1d473f5133d0e1d448ca78ab84c5 | learnwithaman/data-structure-and-algorithm | /python/product_sum.py | 343 | 3.921875 | 4 | # O(n) time | O(d) space
def product_sum(array, multiplier=1):
total_sum = 0
for element in array:
if type(element) is list:
total_sum += product_sum(element, multiplier + 1)
else:
total_sum += element
return total_sum * multiplier
print(product_sum([5, 2, [7, -1], 3, [6, [-13, 8], 4]]))
|
2baa2b6d9cfd6365af7653627fc696382de416ab | yongxing-zou/hello-world | /Class-1.py | 794 | 3.890625 | 4 | class Student():
# __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性
def __init__(self, name, age):
self.name = name
self.age = age
def study(self, course_name):
print('%s正在学习%s.' % (self.name, course_name))
# PEP 8要求标识符的名字用全小写多个单词用下划线连接
# 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)
def watch_movie(self):
if self.age < 18:
print('%s只能观看《熊出没》.' % self.name)
else:
print('%s正在观看岛国爱情大电影.' % self.name)
stu1=Student('yongxing',23)
stu1.studys('Python')
stu1.watch_movie() |
dace61374c704342e525c4cf70b1b9e0e76c6d36 | Do-code-ing/Python_Built-ins | /Methods_Set/copy.py | 410 | 3.875 | 4 | # set.copy()
# set의 얕은 복사본을 반환한다.
# = 을 사용해서 복사하면 set의 내용이 바뀌게 되는 경우, 원본과 복사본 모두 바뀌게 된다.
# copy()를 사용해서 복사하면 원본의 내용을 건드려도, 복사본의 내용은 바뀌지 않는다.
a = {1,2,3,4}
b = a # 그냥 복제
c = a.copy() # copy로 복제
a.clear()
print(b)
# set()
print(c)
# {1, 2, 3, 4} |
04621d57ad9a50740d97371b4853902c2bbe14f8 | canselkyo/Patika.dev-Python | /Temel-Python-Proje1.2.py | 592 | 3.921875 | 4 | # Verilen listenin içindeki elemanları tersine döndüren bir fonksiyon yazın. Eğer listenin içindeki elemanlar da liste içeriyorsa onların elemanlarını da tersine döndürün.
l = []
print("Listede kaç eleman olacağını girin:")
n = int(input())
i=1
for _ in range(n):
m = []
print("Listenin", i , ". elemanında kaç eleman olacağını girin:")
nn = int(input())
print("Elemanları girin:")
for _ in range(nn):
t = int(input())
m.append(t)
if type(m) == list:
m.reverse()
l.append(m)
i += 1
l.reverse()
print(l)
|
6b3153d2686b3f271354acce5cd2432257c5a6c1 | washie254/udacity-Intro | /LESSON 5 SCRIPTING/l02 Scripting with raw input/001introinput.py | 410 | 4.3125 | 4 | # using input() -> takes user input as a string
name = input("Enter Your Name: ")
print("Hello , "+name.title())
# changing to other datatypes"
age = int(input("Age ?: "))
age+=10
print("You'll be {} years old in 10 years".format(age))
#Eval -> evaluates a string as a line of python
x = eval(input('enter an expresion: '))
print(x)
# you can even include variables
num = 30
x = eval('num + 40')
print(x)
|
9069dc333f1a21e3226ff85dc18671ff07c20960 | talktobrent/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 235 | 3.859375 | 4 | #!/usr/bin/python3
""" MyList module
"""
class MyList(list):
""" custom list class inherits from list class
"""
def print_sorted(self):
""" prints list in ascending order
"""
print(sorted(self))
|
c08fd2fa4a5175df373c3481205740f63621a9f5 | LynneWest/PythonPractice | /pandas_csv.py | 425 | 3.515625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
cars = pd.read_csv("vehicletest.csv")
#print(cars)
x = cars['29'] #city mpg
y = cars['37'] #hwy mpg
print(np.corrcoef(x,y))
plt.scatter(x,y, s=1)
plt.xlabel('City mpg')
plt.ylabel('Highway mpg')
plt.title("Correlation of a vehicle's highway and city mpg")
plt.yticks([5,10,15,20,25,30,35,40,45,50])
plt.xticks([5,10,15,20,25,30,35,40,45,50])
plt.show() |
f58d9f2bcb291784e2c6903308883c6fd42aa8b3 | Malika939/PreHakaton2 | /Problem6.py | 99 | 3.875 | 4 | b = input()
if b != b[::-1]:
print('it s not palindrome')
else:
print('It s palindrome')
input() |
235df04db19f74b8f31cb31accc44558e1a80177 | Deser12/DataScienceFundamentals- | /word-checker.py | 453 | 3.921875 | 4 | wrong_words = ["worsd", "wlong", "si", "plogram", "displai"]
good_words = ["words", "wrong", "is", "program", "display"]
input_words = input("Write down a sentence")
check_words = input_words.split(" ")
index = 0
for word in check_words:
# if check_words in wrong_words
if word in wrong_words:
index = wrong_words.index(word)
check = good_words[index]
print("Hmm, " + word + " is spelled wrong! I think you mean " + check)
index += 1
|
0747c3d897cb13c78e9e2d7e710406fdd8d56a14 | snowlance7/Python-Projects | /week2/even_or_odd_checker.py | 279 | 4.09375 | 4 | print("Even or Odd Checker\n")
def main():
num = int(input("Enter an integer: "))
print("This is an " + str(calc(num)) + " number.")
def calc(n):
if n % 2 == 0:
return "even"
else:
return "odd"
if __name__ == "__main__":
main() |
0a50bf094eaa16099e109a6e3028a32a6ce1bc1d | hamza-yusuff/Python_prac | /python projects/alif.py | 527 | 3.640625 | 4 | def make_sin(number):
string_num=str(number)
total_odd=0
total_even=0
for i in range(8):
if i%2!=0:
if 2*(int(string_num[i]))>10:
num=2*(int(string_num[i]))
num=int(str(num)[0])+int(str(num)[1])
else:
num=2*(int(string_num[i]))
total_even=total_even+num
else:
total_odd=total_odd+int(string_num[i])
total=10-int(str(total_even+total_odd)[1])
return int(string_num+str(total))
|
99f64e39bfa99671e289698b7003e58b24da5e3f | sn3ak1/GraphTheoryProject | /main.py | 5,531 | 3.515625 | 4 | class Graph:
class Edge:
def __init__(self, capacity):
self.capacity = capacity
self.remaining = capacity
class Node:
def __init__(self, label):
self.label = label
self.predecessors = {}
self.successors = {}
def __getitem__(self, item):
return self.successors[item] if item in self.successors else self.predecessors[item]
def __init__(self, import_from=None):
self.nodes = {}
if import_from is not None:
self.from_file(import_from)
def add_node(self, label):
if not self.nodes.__contains__(label):
self.nodes[label] = self.Node(label)
def add_edge(self, start, end, capacity):
edge = self.Edge(capacity)
self.add_node(start)
self.add_node(end)
self.nodes[start].successors[end] = edge
self.nodes[end].predecessors[start] = edge
def __getitem__(self, item):
return self.nodes[item]
def is_directed(self, matrix):
for i, _ in enumerate(matrix):
for j, _ in enumerate(matrix[0]):
if matrix[i][j] != matrix[j][i]:
return True
return False
def from_file(self, name):
matrix = []
with open(name, 'r') as reader:
for line in reader.readlines():
matrix.append((line.strip()[:-1]).split(', '))
if not self.is_directed(matrix):
raise Exception('Graph is undirected!')
for i, row in enumerate(matrix):
for j, element in enumerate(row):
if int(element) != 0:
self.add_edge(i, j, int(element))
class Solver:
def __init__(self, g):
self.G = g
self.max_flow = 0
self.paths_taken = []
def shortest_path(self, source, sink):
parent = {}
queue = [source]
while queue:
node = queue.pop()
for pred in self.G[node].predecessors.keys():
if pred != source and pred not in parent and self.G[pred][node].capacity - self.G[pred][node].remaining >= 0:
parent[pred] = node
queue.append(pred)
for successor in self.G[node].successors.keys():
if successor not in parent and self.G[node][successor].remaining > 0:
parent[successor] = node
if successor == sink:
queue = []
break
queue.append(successor)
if sink not in parent:
return None
node = sink
path = []
while parent[node] != source:
path.append([parent[node], node])
node = parent[node]
path.append([source, node])
path.reverse()
return path
def flow_path(self, path):
min_val = min(self.G[edge[0]][edge[1]].remaining for edge in path if self.G[edge[0]][edge[1]].remaining > 0)
self.max_flow += min_val
for i, edge in enumerate(path):
self.G[edge[0]][edge[1]].remaining += -min_val if edge[0] < edge[1] else min_val
path[i].append(str(self.G[edge[0]][edge[1]].capacity - self.G[edge[0]][edge[1]].remaining)
+ '/' + str(self.G[edge[0]][edge[1]].capacity))
def solve(self, source, sink):
if sink == -1:
sink = len(self.G.nodes) - 1
if not self.G.nodes.__contains__(source) or not self.G.nodes.__contains__(sink):
raise Exception('Graph doesn\'t contain node with specified index.')
self.paths_taken.append(self.shortest_path(source, sink))
while self.paths_taken[-1] is not None:
self.flow_path(self.paths_taken[-1])
self.paths_taken.append(self.shortest_path(source, sink))
del self.paths_taken[-1]
for p_index, path in enumerate(self.paths_taken):
for e_index, edge in enumerate(path):
if edge[2][0] == '0':
for m_p_index, matching_path in enumerate(self.paths_taken):
for m_e_index, matching_edge in enumerate(matching_path):
if matching_edge[0] == path[e_index][1] and matching_edge[1] == path[e_index][0]:
self.paths_taken.append(path[:e_index])
self.paths_taken[-1] += matching_path[(m_e_index+1):]
self.paths_taken.append(matching_path[:m_e_index])
self.paths_taken[-1] += path[(e_index+1):]
del self.paths_taken[p_index]
del self.paths_taken[m_p_index]
break
else:
continue
break
try:
source_input = input('Specify source node index (leave blank for 0): ')
except SyntaxError:
source_input = ''
try:
sink_input = input('Specify sink node index (leave blank for last node index): ')
except SyntaxError:
sink_input = ''
solver = Solver(Graph('data.txt'))
solver.solve(int(source_input) if source_input != '' else 0, int(sink_input) if sink_input != '' else -1)
print('Maximum flow: ' + str(solver.max_flow))
print('Paths taken: ')
for path in solver.paths_taken:
print(path)
|
4f81d626d75b7a334e1cc60ac9ed48688dddda3a | yunusemregunduz/Python101-Course | /convert_function_F_to_C.py | 302 | 3.6875 | 4 | def converti(fahrenheit):
return (fahrenheit - 32) * 5 /9
print(converti(76))
#interesting because it is working :D
def quadratic(a,b,c,x):
f = a + x **9
s = b * c
t = c * x
return f + s + t
print(quadratic(2,5,4,8))
print(quadratic(4,5,4,78))
#it is really working "yep mann =D"
|
6af55cb01fb9139afa6043c8cf38d9847e68e3d9 | SupersonicCoder18/Class-109 | /Dist.py | 2,770 | 3.5 | 4 | import pandas as pd
import plotly.express as px
import plotly.figure_factory as ff
import statistics
import csv
df = pd.read_csv("Student.csv")
Height = df["Height(Inches)"].to_list()
Weight = df["Weight(Pounds)"].to_list()
HeightMean = statistics.mean(Height)
WeightMean = statistics.mean(Weight)
HeightMedian = statistics.median(Height)
WeightMedian = statistics.median(Weight)
HeightMode = statistics.mode(Height)
WeightMode = statistics.mode(Weight)
print("Mean, median, and mode of Height is {}, {}, {} respectively".format(HeightMean, HeightMedian, HeightMode))
print("Mean, median, and mode of Weight is {}, {}, {} respectively".format(WeightMean, WeightMedian, WeightMode))
fig = ff.create_distplot([Height], ["Height"], show_hist = False)
fig2 = ff.create_distplot([Weight], ["Weight"], show_hist = False)
fig.show()
fig2.show()
HeightStd = statistics.stdev(Height)
WeightStd = statistics.stdev(Weight)
print("Standard deviation of Height and Weight are {} and {} respectively".format(HeightStd, WeightStd))
HeightStd1Start, HeightStd1End = HeightMean - HeightStd, HeightMean + HeightStd
HeightStd2Start, HeightStd2End = HeightMean - ( 2* HeightStd), HeightMean + (2 * HeightStd)
HeightStd3Start, HeightStd3End = HeightMean - (3* HeightStd), HeightMean + (3* HeightStd)
WeightStd1Start, WeightStd1End = WeightMean - WeightStd, WeightMean + WeightStd
WeightStd2Start, WeightStd2End = WeightMean - ( 2* WeightStd), WeightMean + (2 * WeightStd)
WeightStd3Start, WeightStd3End = WeightMean - (3* WeightStd), WeightMean + (3* WeightStd)
WeightFirstStd = [result for result in Weight if result > WeightStd1Start and result < WeightStd1End]
WeightSecondStd = [result for result in Weight if result > WeightStd2Start and result < WeightStd2End]
WeightThirdStd = [result for result in Weight if result > WeightStd3Start and result < WeightStd3End]
HeightFirstStd = [result for result in Height if result > HeightStd1Start and result < HeightStd1End]
HeightSecondStd = [result for result in Height if result > HeightStd2Start and result < HeightStd2End]
HeightThirdStd = [result for result in Height if result > HeightStd3Start and result < HeightStd3End]
print("{} % of HeightData lies with FirstStd".format(len(HeightFirstStd)*100/len(Height)))
print("{} % of HeightData lies with SecondStd".format(len(HeightSecondStd)*100/len(Height)))
print("{} % of HeightData lies with ThirdStd".format(len(HeightThirdStd)*100/len(Height)))
print("{} % of WeightData lies with FirstStd".format(len(WeightFirstStd)*100/len(Weight)))
print("{} % of WeightData lies with SecondStd".format(len(WeightSecondStd)*100/len(Weight)))
print("{} % of WeightData lies with ThirdStd".format(len(WeightThirdStd)*100/len(Weight))) |
8734eb117bdf957bcd9648c3c39da563df530de8 | linshiyi/test | /yeah.py | 569 | 4.125 | 4 | #!/bin/env python
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
ending = ['st','nd','rd'] + 17 * ['th'] \
+ ['st','nd','rd'] + 7 * ['th'] \
+ ['st']
yeah = raw_input('Yeah: ')
month = raw_input('Month (1-12): ')
day = raw_input('Day (1-31): ')
month_number = int(month)
day_number = int(day)
month_name = months[month_number-1]
day_name = day + ending[day_number-1]
print month_name + ' ' + day_name + ' ' + yeah
|
cdaf5133a81cbd8dfc88a2bc1ef2071e120ae603 | MohamedFawzy/python-datastructure | /week1/while-loop.py | 144 | 3.53125 | 4 | __author__ = 'Mohamed fawzy'
fruit = 'banana'
index=0
while index < len(fruit):
letter = fruit[index]
print index, letter
index= index+1
|
11e95605df00a24cdb27a1bc196ab32c1aecc074 | ImSahilShaikh/LearnOpenCV | /shapes.py | 901 | 3.71875 | 4 | #Functions to draw geometric shapes on images
import cv2
img = cv2.imread('face.png',-1)
#line| arrowedLine(image, start_pts, end_pts, colorBGR,thickness)
img = cv2.line(img,(0,0),(255,255),(0,0,255), 3)
img = cv2.arrowedLine(img,(255,100),(255,255),(0,255,255), 2)
#rectangle(image,x1y1,x2y2,colorBGR,thickness)
#thickness if given -1 then shape fills with given color
img = cv2.rectangle(img, (300,100), (500,300), (255,0,0), 3)
#circle(image,center,radius,colorBGR,thicknes)
#thickness if given -1 then shape fills with given color
img = cv2.circle(img, (400,200), 50, (255,255,0), 2)
#set fontface in simple words font style
font = cv2.FONT_HERSHEY_SIMPLEX
#putText(image,texttobeprinted,start_pts,fontface,fontsize,color,thickness,linetype)
img = cv2.putText(img, "SAHIL LEARNING OpenCV", (0,700), font, 3,(15,55,255),7, cv2.LINE_AA)
cv2.imshow("image",img)
k=cv2.waitKey(0)
|
8dcc1bdad13c2a37c6edf738ef3813b8c823aa94 | gk12happy/Subgraph-Classifier | /src/bipartition.py | 2,510 | 3.6875 | 4 | class Node:
def __init__(self, x, n):
self.childs = []
self.data = x
self.lvl = n
def __repr__(self):
return self.data
def addToChilds(self, x):
nodex = Node(x, n+1)
self.childs.append(nodex)
def addToList(t,a,b):
if t == None:
return
else:
if t.lvl % 2 == 0:
if(len(a) > t.lvl//2):
print( "adding to a lvl: " + str(t.lvl) + " added: " + t.data )
a[t.lvl//2].append(t)
for i in range(len(t.childs)):
addToList(t.childs[i], a, b)
else:
newlvl = []
newlvl.append(t)
print( "adding to a lvl: " + str(t.lvl) + " added: " + t.data )
a.append(newlvl)
for i in range(len(t.childs)):
addToList(t.childs[i], a, b)
else:
if(len(b) > t.lvl//2):
print( "adding to b lvl: " + str(t.lvl) + " added: " + t.data )
b[t.lvl//2].append(t)
for i in range(len(t.childs)):
addToList(t.childs[i], a, b)
else:
newlvl = []
newlvl.append(t)
print( "adding to b lvl: " + str(t.lvl) + " added: " + t.data )
b.append(newlvl)
for i in range(len(t.childs)):
addToList(t.childs[i], a, b)
def bipartition(t):
a = []
b = []
addToList(t,a,b)
#node lvl even sa a ya lvl listine ekle
#node lvl odd sa b ya lvl listine ekle
bipart = []
bipart.append(a)
bipart.append(b)
return bipart
t = Node('a', 0)
t.childs.append(Node('b',1))
t.childs[0].childs.append(Node('c',2))
t.childs[0].childs.append(Node('d',2))
t.childs[0].childs.append(Node('e',2))
t.childs[0].childs[0].childs.append(Node('f',3))
t.childs[0].childs[1].childs.append(Node('g',3))
t.childs[0].childs[1].childs.append(Node('z',3))
t.childs[0].childs[1].childs.append(Node('j',3))
t.childs[0].childs[2].childs.append(Node('l',3))
t.childs[0].childs[0].childs[0].childs.append(Node('i',4))
t.childs[0].childs[0].childs[0].childs.append(Node('g',4))
t.childs[0].childs[0].childs[0].childs.append(Node('h',4))
retval = bipartition(t)
print(retval[0])
print()
print(retval[1])
|
283edaa26b111f1488412c90c50b0ff719eee530 | thunderbump/euler | /017/017.py | 1,303 | 4.0625 | 4 | #!/usr/bin/python
"""Computes the number of letters in all numbers below a given X"""
import sys
argc = len(sys.argv)
X = 1000
usage = """017.py [X]
Computes the number of letters in all numbers below a given X. If no X given,
1000 is used."""
raw_number = {0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3, 11:6,
12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8}#below 20 irregular
prefixes = {0:0, 1:4, 2:6, 3:6, 4:5, 5:5, 6:5, 7:7, 8:6, 9:6, 100:7, 1000:8}
len_and = 3
if argc > 2:
print(usage)
sys.exit(1)
if argc == 2:
try:
X = int(sys.argv[1])
except ValueError:
print(usage)
print("X must be a number")
sys.exit(1)
def number_to_len_word(number):
size = 0
#thousands
if number // 1000 != 0:
size += raw_number[number // 1000] + prefixes[1000]
number %= 1000
#hundreds
if number // 100 != 0:
size += raw_number[number // 100] + prefixes[100]
if number % 100 != 0:
size += len_and
number %= 100
#tens/ones
if number < 20:
size += raw_number[number]
else:
size += prefixes[number // 10] + raw_number[number % 10]
return size
print(sum(number_to_len_word(number)for number in range(1, X + 1)))
#print number_to_len_word(X)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.