blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
d89e6bf1069b6c5e7071c04a70221caaf3612bd8 | kaiqinhuang/Python_hw | /geometry.py | 261 | 4.0625 | 4 | print("The area of a rectangle with sides of length 51 and 84 is:")
print(51 * 84)
print("The area of a circle of radius 2.6 is:")
import math
print(round(math.pi * 2.6 * 2.6))
print("The perimeter a square whose area is 15 is:")
print(round(math.sqrt(15) * 4)) |
f988c49fc9308167f9b5e711a2ad96aec0722c72 | weiguangjiayou/LeetCode | /LeetCode/LeetCode257binary-tree-paths.py | 1,063 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/16 2:09 PM
# @Author : Slade
# @File : LeetCode257binary-tree-paths.py
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.ans = []
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def dfs(root, s):
if not root:
return
if not root.left and not root.right:
if s == "":
self.ans.append(str(root.val))
else:
self.ans.append(s + "->" + str(root.val))
if root.left:
dfs(root.left, s + "->" + str(root.val) if s != "" else str(root.val))
if root.right:
dfs(root.right, s + "->" + str(root.val) if s != "" else str(root.val))
dfs(root, "")
return self.ans
|
a8f07b61bc518ccd45525d5a736a34d3aaea381f | niuyaning/PythonProctice | /06/07/python_init_01.py | 551 | 4.34375 | 4 | #情况2:子类不需要自动调用父类的方法:子类重写__init__()方法,实例化子类后,将不会自动调用父类的__init__()的方法
class Father():
def __init__(self,name):
self.name = name
print("name %s" % (self.name))
def getName(self):
return "Father" + self.name
class Son(Father):
def __init__(self,name):
print("hi")
self.name = name
def getName(self):
return "Father" + self.name
if __name__ == "__main__":
son = Son("张三")
son.getName()
|
ebbeb50ca4fa1f1903dd3ce7b5c6f852e4d3f2b4 | roshnipriya/python-programming | /beginner level 1/rever.py | 74 | 3.734375 | 4 | c=raw_input()
char=c[::-1]
if(c==char):
print 'yes'
else:
print 'no'
|
6a1b2792905f4a2077b9bdd3db33c4b25f5e0511 | pavithra181/p | /leap.py | 89 | 3.734375 | 4 | x=int(input())
if x%4==0 and x%100!=0:
if x%400==0:
print("leap")
else:
print("not")
|
8b9610c2d6af0535ab3ad9127f69670b50835d24 | ScenTree/ScenTree | /python_script/from_pro_csv_to_updated_jsons.py | 2,683 | 3.84375 | 4 | #!/usr/bin/python
# coding: utf8
import os, sys
import csv
import json
# reading json files, adding the csv content, output = json files updated
print("Usage = a .csv then a .json file in argument then a string that represents the key to be created inside the .json file, usually 'csv_PRO.csv' or 'csv_IFRA.csv' then 'TreeFeaturesNEW_EN_and_FR.json', then 'PRO' or 'IFRA'", file=sys.stderr)
PLEASE_QUIT = False
if len(sys.argv) == 4:
THE_PATH_OF_THE_CSV_FILE = sys.argv[1]
THE_PATH_OF_THE_JSONFILE = sys.argv[2]
THE_DICT_KEY = sys.argv[3]
else:
print("/!\ There should be 3 arguments, but only %s argument(s) detected" % (len(sys.argv) -1), file=sys.stderr)
PLEASE_QUIT = True
if not PLEASE_QUIT:
if not os.path.isfile(THE_PATH_OF_THE_CSV_FILE):
print("THE_PATH_OF_THE_CSV_FILE", THE_PATH_OF_THE_CSV_FILE, "does not exists or is not a file", file=sys.stderr)
PLEASE_QUIT = True
if not os.path.isfile(THE_PATH_OF_THE_JSONFILE):
print("THE_PATH_OF_THE_JSONFILE", THE_PATH_OF_THE_JSONFILE, "does not exists or is not a file", file=sys.stderr)
PLEASE_QUIT = True
if PLEASE_QUIT:
print("Usage incorrect -> Stop", file=sys.stderr)
sys.exit(1)
else:
print("Usage : correct :-)", file=sys.stderr)
# reading the CSV
the_csv_file = open(THE_PATH_OF_THE_CSV_FILE, 'r')
the_pros = [d for d in csv.DictReader(the_csv_file, delimiter=';')] # list of dicts with the keys = the header of the csv
the_csv_file.close()
# remove 'empty line' from the csv (=empty value inside the resulting dict)
the_pros = [{a_key : a_value for a_key, a_value in a_pro.items() if bool(a_value)} for a_pro in the_pros]
# reading the JSON
the_json_file = open(THE_PATH_OF_THE_JSONFILE, 'r')
the_ingredients = json.load(the_json_file)
the_json_file.close()
try:
the_length_of_the_input_JSON_file = len(the_ingredients)
except:
the_length_of_the_input_JSON_file = 0
# updating the JSON ingredients with CSV infos
for an_ingredient in the_ingredients:
for a_pro in the_pros:
if int(a_pro["id"]) == int(an_ingredient["from_csv EN id"]):
try:
an_ingredient[THE_DICT_KEY].append(json.dumps(a_pro))
except KeyError:
an_ingredient[THE_DICT_KEY] = [json.dumps(a_pro)]
# echoing a JSON
the_length_of_the_output_JSON_file = len(the_ingredients)
print(json.dumps(the_ingredients, sort_keys=False, indent=4))
sys.stderr.write("\nChecking the length of the input JSON file : %s ; " % the_length_of_the_input_JSON_file)
sys.stderr.flush()
sys.stderr.write("Checking the length of the OUTput JSON file : %s\n" % the_length_of_the_output_JSON_file)
sys.stderr.flush()
|
8fdcab306204fc837c15a1cffbd91ccd4cf3e14b | surgicaI/computer-vision | /assignment-1/src/solution-1.py | 1,643 | 3.5 | 4 | from scipy import misc
from matplotlib import pyplot as plt
def convolve(image):
# kernel = [1 2 1]/4
rows, cols = image.shape
# assuming valid boundary conditions
# convolution of [1 2 1] / 4 kernel with the image
row_convolution = 2*image[:, 1:cols-1]
row_convolution = row_convolution + 1*image[:, :cols-2] + 1*image[:, 2:]
image = 0.25 * row_convolution
# the output of row convolution is convoluted again
# with ([1 2 1]/4)transpose
rows, cols = image.shape
col_convolution = 2*image[1:rows-1, :]
col_convolution = col_convolution + 1*image[:rows-2, :] + 1*image[2:, :]
image = 0.25 * col_convolution
# final size of the image is [image.rows - 2, image_cols -2]
return image
if __name__ == '__main__':
image_name = input('please input image path:')
try:
image = misc.imread(image_name, flatten=True)
except:
print('invalid image path')
quit()
kernel_width = 2
while kernel_width % 2 == 0 or kernel_width < 3:
kernel_width = int(input('please input kernel width(odd natural number >= 3):'))
# Applying multiple, successive Gaussian blurs to an image has the same effect as applying a single, larger Gaussian blur, whose radius is the square root of the sum of the squares of the blur radii that were actually applied.
print('input-image-shape:', image.shape)
num_iterations = ((kernel_width - 1) / 2)
num_iterations = int(num_iterations)
for _ in range(num_iterations):
image = convolve(image)
print('output-image-shape:', image.shape)
plt.imshow(image, cmap='Greys_r')
plt.show()
|
01c067729de040a30a6955a238bb6776748d7abc | kirankalsi/python-exercises | /programs/times_tables.py | 238 | 3.546875 | 4 | def times_tables():
tt=""
for first_num in range(1,11):
for second_num in range(1,11):
num = first_num*second_num
tt = tt + str(num) + " "
tt = tt + "\n"
return tt
print(times_tables()) |
2b47a769209b0e03d0af2ab0e6bb5e969829bab6 | khannasarthak/codingPrep | /Basics/BST.py | 1,093 | 3.875 | 4 | class Node:
def __init__(self, val):
self.value = val
self.leftChild = None
self.rightChild = None
class Tree:
def __init__(self):
self.root = None
def insert(self,value):
if self.root==None:
self.root = Node(value)
else:
# Private functions _, python doesn't have private functions inherently
self._insert(value, self.root)
def _insert(self, value, currentNode):
# Case 1: vaue to insert is smaller than current node
if value<currentNode.value:
if currentNode.leftChild ==None:
currentNode.leftChild = Node(value)
else:
self._insert(value, currentNode.leftChild)
elif value>currentNode.value:
if current.rightChild == None:
currentNode.rightChild = Node(value)
else:
self._insert(value, currentNode.rightChild)
else:
# same value
print ('Tree already has the value stored.')
def print
|
d559a4ed5a4dfc738c1dabc72a78e5493751f939 | albertojr/estudospython | /ex028.py | 377 | 3.96875 | 4 | import random
numero = random.randint(0, 5) #aqui ele pensa em um número ...
print('-=-'*20)
print('Estou pensando em um pensando em um número de 0 a 5 ... AGUARDE!')
print('-=-'*20)
numeroDigitado = int(input('Tente adivinhar meu número, digite abaixo: '))
if numero == numeroDigitado:
print('Parabéns, vc adivinhou, tu é FODA!!')
else:
print('ERROOOOOOOOU!!!!')
|
ef52c4a6e992fa3bb681c6397b02e543294b1a1d | umangSharmacs/InterviewBit-Python-Solutions | /Backtracking/Subsets II.py | 585 | 3.53125 | 4 | #https://www.interviewbit.com/problems/subsets-ii/
class Solution:
# @param A : list of integers
# @return a list of list of integers
def subsetsWithDup(self, A):
A=sorted(A)
answer=[]
n=len(A)
def findAllSubsets(idx,currentSet):
if(idx==n):
answer.append(currentSet)
else:
findAllSubsets(idx+1,currentSet)
findAllSubsets(idx+1,currentSet+[A[idx]])
findAllSubsets(0,[])
answer=set([tuple(x) for x in answer])
return sorted(answer)
|
9900b288df602118c18f99206422d1186fe44087 | Aasthaengg/IBMdataset | /Python_codes/p03294/s767795360.py | 390 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
import math
from functools import reduce
# In[19]:
N = int(input())
a = list(map(int, input().split()))
# In[20]:
def lcm_base(x, y):
return (x * y) // math.gcd(x, y)
def lcm_list(numbers):
return reduce(lcm_base, numbers, 1)
# In[21]:
f = 0
m = lcm_list(a)-1
for i in range(N):
f += m%a[i]
print(f)
# In[ ]:
|
32bf5a20d2b4907b4708b74458eacd85f4ab242e | aandr26/Learning_Python | /Coursera/Week4/Week4a/Exercises/list_reference.py | 281 | 3.671875 | 4 | # List reference problem
###################################################
# Student should enter code below
a = [5, 3, 1, -1, -3, 5]
b = a
b[0] = 0
print(a)
print(b)
###################################################
# Explanation
# They both reference the same object now? |
bd5f7fa14923d63014d65cb574df6bbdfabee59f | abdujalilHamidullayev/python_core | /Lesoon_14.py | 1,037 | 3.8125 | 4 | #bu son 3 ta sonnig kattasin belgilab beradi
'''def katta_son(a,b,c):
if a>b:
if a>c:
return(a)
else:
return(c)
else:
if b>c:
return(b)
else:
return(c)
son=katta_son(13,7,50)
print(son)
sonlar=[2,4,5,3,1,6,7,8,9,7,0,100]
#katta_son=max(sonlar)
#print(katta_son)
def MaX(lists):
katta_son=0
for son in sonlar:
if katta_son<son:
katta_son=son
return(katta_son)
print(MaX(sonlar))
sonlar=[2,3,4,5,1,5,6,10,70]
#def MiN(lists):
# katta_son=lists[0]
# for son in sonlar:
# if katta_son>son:
# katta_son=son
#return(katta_son)
#print(MiN(sonlar))
print(len(sonlar))
def uzunlik(lists):
t=0
for i in lists:
t+=1
return t
print(uzunlik(sonlar)
def ekranga_chiqar(xabar):
print(xabar)
#kvadrat
ekranga_chiqar(7**2)'''
|
2658f41c0a571b2177c7dc422ee2c8cfa55a5d3c | ZhiCheng0326/LeetCode-Practices | /solutions/283.Move Zeroes.py | 1,176 | 3.96875 | 4 | # Method 1: Double pointer
"""
Exchange nums[left] and nums[right] if nums[right] != 0
Time complexity: O(n)
Space complexity: O(1)
"""
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
left = 0
n = len(nums)
for right in range(n):
if nums[right] != 0:
# small optimization, avoid exchanging at same index
if right > left:
nums[left], nums[right] = nums[right], nums[left]
left += 1
# print(nums)
# # Method 2: Similar to method 1, replace instead of exchange
# """
# Consider test case: [0,0,0,0,12]
# M2 has to modify nums[i] to 0 from i=1 to i=n-1
# M1 exchange only once, no extra loop required
# Therefore, M1 is more efficient
# """
# class Solution:
# def moveZeroes(self, nums: List[int]) -> None:
# left = 0
# n = len(nums)
# for right in range(n):
# if nums[right] != 0:
# nums[left] = nums[right]
# left += 1
# for i in range(left, n):
# nums[i] = 0
|
897663a9c96293f09701c60401980cf39ec79f67 | kylefinter/old_programs | /CSC130/proj3.py | 4,034 | 4.09375 | 4 | '''
Kyle Finter
proj3.py
'''
string=input("Enter a phrase to be translated to Morse code: ")
string=string.upper()
liststr=list(string)
lengthlist=len(liststr)
count=0
while count<=lengthlist:
for letter in liststr:
count+=1
if letter==',':
liststr.insert(count,'--..--')
liststr.remove(',')
if letter=='.':
liststr.insert(count,'.-.-.-')
liststr.remove('.')
if letter=='?':
liststr.insert(count,'..--..')
liststr.remove('?')
if letter=='0':
liststr.insert(count,'-----')
liststr.remove('0')
if letter=='1':
liststr.insert(count,'.----')
liststr.remove('1')
if letter=='2':
liststr.insert(count,'..---')
liststr.remove('2')
if letter=='3':
liststr.insert(count,'...--')
liststr.remove('3')
if letter=='4':
liststr.insert(count,'....-')
liststr.remove('4')
if letter=='5':
liststr.insert(count,'.....')
liststr.remove('5')
if letter=='6':
liststr.insert(count,'-....')
liststr.remove('6')
if letter=='7':
liststr.insert(count,'--...')
liststr.remove('7')
if letter=='8':
liststr.insert(count,'---..')
liststr.remove('8')
if letter=='9':
liststr.insert(count,'----.')
liststr.remove('9')
if letter=='A':
liststr.insert(count,'.-')
liststr.remove('A')
if letter=='B':
liststr.insert(count,'-...')
liststr.remove('B')
if letter=='C':
liststr.insert(count,'-.-.')
liststr.remove('C')
if letter=='D':
liststr.insert(count,'-..')
liststr.remove('D')
if letter=='E':
liststr.insert(count,'.')
liststr.remove('E')
if letter=='F':
liststr.insert(count,'..-.')
liststr.remove('F')
if letter=='G':
liststr.insert(count,'--.')
liststr.remove('G')
if letter=='H':
liststr.insert(count,'....')
liststr.remove('H')
if letter=='I':
liststr.insert(count,'..')
liststr.remove('I')
if letter=='J':
liststr.insert(count,'.---')
liststr.remove('J')
if letter=='K':
liststr.insert(count,'-.-')
liststr.remove('K')
if letter=='L':
liststr.insert(count,'.-..')
liststr.remove('L')
if letter=='M':
liststr.insert(count,'--')
liststr.remove('M')
if letter=='N':
liststr.insert(count,'-.')
liststr.remove('N')
if letter=='O':
liststr.insert(count,'---')
liststr.remove('O')
if letter=='P':
liststr.insert(count,'.--.')
liststr.remove('P')
if letter=='Q':
liststr.insert(count,'--.-')
liststr.remove('Q')
if letter=='R':
liststr.insert(count,'.-.')
liststr.remove('R')
if letter=='S':
liststr.insert(count,'...')
liststr.remove('S')
if letter=='T':
liststr.insert(count,'-')
liststr.remove('T')
if letter=='U':
liststr.insert(count,'..-')
liststr.remove('U')
if letter=='V':
liststr.insert(count,'...-')
liststr.remove('V')
if letter=='W':
liststr.insert(count,'.--')
liststr.remove('W')
if letter=='X':
liststr.insert(count,'-..-')
liststr.remove('X')
if letter=='Y':
liststr.insert(count,'-.--')
liststr.remove('Y')
if letter=='Z':
liststr.insert(count,'--..')
liststr.remove('Z')
print(' '.join(liststr))
|
3e09aaf28d3e4f103bd10e30443074317f893459 | Derling/algorithms | /python_200_problems/class/convert_to_roman.py | 1,845 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 14 18:08:01 2017
@author: DerlingB
"""
# Write a Python program to convert an integer to a roman numeral.
# Input 1, 4000
# Output I, MMMM
values = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
class Int_Converter():
def convert_to_roman(self,integer):
roman = ''
for n, numeral in values:
'''
take each roman numeral value and find how many times
it would appear in the roman numeral presentation
by subtracting away the nth place value based on the
roman numeral
'''
while integer >= n:
roman = roman + numeral
integer = integer - n
return roman
class py_solution:
# course solution
def int_to_Roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i = 0
while num > 0:
print(num, i)
for _ in range(num // val[i]):
roman_num += syb[i]
print(roman_num, i, num)
num -= val[i]
i += 1
return roman_num
if __name__ == '__main__':
class_ = Int_Converter()
inputs = [
1,
4000,
21311,
982,
544
]
for i in inputs:
print(class_.convert_to_roman(i)) |
e83d7beec0fdb6a3185731cf8ce3b1b1dd178705 | atulzh7/IW-Academy-Python-Assignment | /python assignment ii/question_no_9.py | 717 | 3.890625 | 4 | """Binary search function
"""
def binary_search(sequence, item):
#initialization yo avoid garbage value in variable
high = len(sequence) - 1
low = 0
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < item:
low = mid + 1
elif arr[mid] > item:
high = mid - 1
else:
return mid
else:
return -1
# Sample test array
arr = [ 2, 3, 4, 10, 40 ]
user_input = int(input("Enter an integer value to see if it exits: "))
result = binary_search(arr, user_input)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array") |
108d37b53de91995f3a3f1d4a9465784d867de1b | debakarr/eternal-learning | /Python OOP/Searching/1_16_medianOfList.py | 433 | 4.15625 | 4 | # Find the median of an array
def medianUsingSort(arr):
arr.sort()
if len(arr) % 2:
return arr[len(arr) // 2]
else:
return (arr[len(arr) // 2] + arr[len(arr) // 2 - 1]) / 2.0
if __name__ == '__main__':
arr = [1, 3, 6, 9, 2, 4, 5, 7, 8]
print 'Median of', arr, 'is:', medianUsingSort(arr[:])
arr = [1, 3, 6, 9, 2, 4, 5, 7, 8, 10]
print 'Median of', arr, 'is:', medianUsingSort(arr[:])
|
04890c636e097a33fdad2ff75e9c00be0da9ee06 | Oluyosola/micropilot-entry-challenge | /oluyosola/count_zeros.py | 544 | 4.15625 | 4 | # Write a function CountZeros(A) that takes in an array of integers A, and returns the number of 0's in that array.
# For example, given [1, 0, 5, 6, 0, 2], the function/method should return 2.
def countZeros(array):
# count declared to be zero
count=0
# loop through array length and count the number of zeros
for m in range(0,len(array)):
if array[m] == 0:
count=count+1
return count
# testing the function
A = [1, 0, 5, 6, 0, 2]
zeros_count=countZeros(A)
print("Number of zeros is", zeros_count)
|
c5cdd848428769043401d4e891cd9c30f818da65 | manavpatel1021/Rock-Paper-Scissors-using-tkinter | /game.py | 3,452 | 3.953125 | 4 | from tkinter import *
import random
screen = Tk()
l1= ["Rock", "Paper" , "Seissor"]
userchoice_var = StringVar()
compchoice_var = StringVar()
result_var = StringVar()
u_score = IntVar()
c_score = IntVar()
user_score = 0
comp_score = 0
def mylogic(userchoice):
global user_score , comp_score , result_var
computer_choice = random.choice(l1)
userchoice_var.set(userchoice)
compchoice_var.set(computer_choice)
if computer_choice == userchoice:
result_var.set("tie")
elif computer_choice=="Rock" and userchoice == "Paper":
result_var.set('user won')
user_score+=1
elif computer_choice=="Rock" and userchoice == "Seissor":
result_var.set("computer won")
comp_score+=1
elif computer_choice=="Paper" and userchoice == "Rock":
result_var.set("computer won")
comp_score+=1
elif computer_choice=="Paper" and userchoice == "Seissor":
result_var.set("user won")
user_score+=1
elif computer_choice=="Seissor" and userchoice == "Rock":
result_var.set("user won")
user_score+=1
elif computer_choice=="Seissor" and userchoice == "Paper":
result_var.set("computer won")
comp_score+=1
print(userchoice)
print(computer_choice)
u_score.set(user_score)
c_score.set(comp_score)
screen.title("Rock Paper Seissor")
screen.geometry("520x500")
#---------------------> tkinter design
lbl_tittle = Label(screen,text="ROCK PAPER SEISSOR" , fg="red" , font=('arial',20,'bold') )
lbl_tittle.place(x=100 ,y = 30)
btn_rock = Button(screen, text="Rock" , bg = "black" , fg="white", font=('arial',12,'bold') , activebackground="red" , activeforeground="white", command=lambda : mylogic("Rock"))
btn_rock.place(x = 50, y = 120)
btn_paper = Button(screen, text="Paper" , bg = "black" , fg="white", font=('arial',12,'bold'), activebackground="red" , activeforeground="white",command=lambda : mylogic("Paper"))
btn_paper.place(x = 190, y = 120)
btn_seissor = Button(screen, text="Seissor" , bg = "black" , fg="white", font=('arial',12,'bold'), activebackground="red", activeforeground="white",command=lambda : mylogic("Seissor"))
btn_seissor.place(x = 340, y = 120)
#---------------->begin: user section
lbl_userdisplay = Label(screen, text="USER : " , font=('arial', 12 , 'bold'))
lbl_userdisplay.place(x = 50 , y = 280)
lbl_userdisplaychoice = Label(screen,textvariable=userchoice_var , font=('arial', 12 , 'bold'))
lbl_userdisplaychoice.place(x = 200 , y = 280)
lbl_userscoredisplay = Label(screen, textvariable=u_score , font=('arial', 12 , 'bold'))
lbl_userscoredisplay.place(x = 350 , y = 280)
#-------->end : user section
#----------->begin:computer section
lbl_computerdisplay = Label(screen, text="COMPUTER : " , font=('arial', 12 , 'bold'))
lbl_computerdisplay.place(x = 50 , y = 350)
lbl_computerdisplaychoice = Label(screen, textvariable=compchoice_var , font=('arial', 12 , 'bold'))
lbl_computerdisplaychoice.place(x = 200 , y = 350)
lbl_computerscoredisplay = Label(screen, textvariable=c_score , font=('arial', 12 , 'bold'))
lbl_computerscoredisplay.place(x = 350 , y = 350)
#------------> end :user section
btn_result = Button(screen, textvariable=result_var , font=('arial',12 , 'bold'),width=48,fg="blue")
btn_result.place(x=10 , y = 390)
screen.mainloop() |
dc19473781da1bdc5a47f5357eabeefd8da347ea | mtjones1115/100days | /tip_calculator.py | 435 | 3.734375 | 4 | # one hundred days of code day two
sub_total = float(input("What was the total bill? \n"))
tip_percentage = int(input("What percentage tip would you like to give? \n"))
bill_split = int(input("How many poeple to split the bill? \n"))
bill_total = sub_total*(1+tip_percentage/100)/bill_split
tidy_total = round(bill_total, 2)
tidy_total = "{:.2f}".format(tidy_total)
message = f"Each person should pay: {tidy_total}"
print(message)
|
8215371e357bd7cee7c447e49c31dbb10d2f22cb | debo2696/Python | /myfcn.py | 125 | 3.765625 | 4 | def adds(n1,n2):
add=n1+n2
print(n1,"+",n2,"=",add)
def mul(n1,n2):
mul=n1*n2
print(n1,"x",n2,"=",mul)
|
1912d13e2d219bb764ad92af06d085fa385a8bad | mattduan/proof | /pk/DateKey.py | 1,713 | 3.5625 | 4 | """
This class can be used as an ObjectKey to uniquely identify an
object within an application where the id consists
of a single entity such a GUID or the value of a db row's primary key.
"""
__version__= '$Revision: 3194 $'[11:-2]
__author__ = "Duan Guoqiang (mattgduan@gmail.com)"
import datetime
import time
import proof.pk.ObjectKey as ObjectKey
class DateKey(ObjectKey.ObjectKey):
def __init__(self, value, column_name=None, table_name=None):
""" Creates a DateKey whose internal representation is a Date.
"""
ObjectKey.ObjectKey.__init__(self, value, column_name, table_name)
def setKey(self, key):
""" Sets the internal representation to a Date
@param key the key value
"""
# A DateKey
if isinstance(key, self.__class__):
key = key.getKey()
# A timestamp
elif isinstance(key, types.IntType) or \
isinstance(key, types.LongType):
key = datetime.date.fromtimestamp(key)
# A date string with iso format
elif isinstance(key, types.StringType):
t_data = time.strptime(key, '%Y-%m-%d')
key = datetime.date(t_data[0], t_data[1], t_data[2])
assert isinstance(key, datetime.date)
ObjectKey.ObjectKey.setKey(self, key)
setValue = setKey
def __str__(self):
""" String representation of the key.
Each Key is represented by [type D][full_column]|[value].
"""
return "%s%s%s%s" % ( ObjectKey.DATE_KEY_TYPE,
self.getFullyQualifiedName(),
ObjectKey.COL_SEPARATOR,
self.__key.__str__() )
|
d9a1dfe75e9444874cbc0dbce696ad95bb42a9d1 | ohjho/ftds_oct_2018 | /Foundation/03-python-intro/exercises/solutions/encrypt.py | 259 | 3.796875 | 4 | def encrypt(text,key):
char2num = {k:i for i,k in enumerate(string.ascii_lowercase)}
num2char = {k:i for k,i in enumerate(string.ascii_lowercase)}
return "".join([ num2char[(char2num[c] + key) % 26 ] if c.isalpha() else c for c in text]) |
e9af6b4b1e5ac662f516a0efe407e3048357a6e0 | bdjackson/ProjectEuler | /primes.py | 6,890 | 4.34375 | 4 | #!/usr/bin/env python
# ============================================================================
import math
import collections
import operator
# ====================================================
# = Helper functiones for working with prime numbers =
# ====================================================
# ----------------------------------------------------------------------------
def isPrime(num):
"""
Is this number prime?
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Special case for 0, 1
if num == 0 or num == 1:
return False
# variables used in checking for primes
is_prime = True
max_possible = int(math.sqrt(num)+1)
test = 2
# check if num is factorable
while test < max_possible and is_prime:
if num % test == 0:
is_prime = False
test += 1
return is_prime
# ----------------------------------------------------------------------------
def isPrime_dumb(num):
"""
Is this number prime?
TODO optimize isPrime function!
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
is_prime = True
# check if num is divisible by all numbers less than it
i = 2
while i < num and is_prime:
if num % i == 0:
is_prime = False
i+=1
return is_prime
# ----------------------------------------------------------------------------
def getNextPrime(last_prime):
"""
Given last_prime, find the next prime
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
found_next_prime = False
next_prime = last_prime
while not found_next_prime:
next_prime += 1
if isPrime(next_prime):
found_next_prime = True
return next_prime
# ----------------------------------------------------------------------------
def getPrimeSeive(max):
"""
Get actual prime seive of number less than max
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
primes = [1]*int(max)
prime_list = []
for i in xrange(int(max)):
if i == 0 or i == 1:
primes[i] = 0
if primes[i] == 0:
continue
prime_list.append(i)
mults = 2*i
while mults < max:
primes[mults] = 0
mults += i
return primes
# ----------------------------------------------------------------------------
def primeSeive(max):
"""
Get list of all primes less than max
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
primes = [1]*int(max)
prime_list = []
for i in xrange(int(max)):
if i == 0 or i == 1:
primes[i] = 0
if primes[i] == 0:
continue
prime_list.append(i)
mults = 2*i
while mults < max:
primes[mults] = 0
mults += i
return prime_list
# ----------------------------------------------------------------------------
def getFirstNPrimes(n):
"""
Returns a list of the first n prime numbers
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
test = 0
primes = [2]
while len(primes) < n:
primes.append(getNextPrime(primes[-1]))
return primes
# ----------------------------------------------------------------------------
def getPrimesBelowN(max):
"""
Returns a list of all primes less than and including max
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
primes = []
for i in xrange(max+1):
if isPrime(i):
primes.append(i)
return primes
# ----------------------------------------------------------------------------
def getPrimeFactors(num):
"""
Returns a list of primes factors of num
"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if num == 0 or num == 1:
return []
# If num is prime, you are done! Return right away.
if isPrime(num):
return [num]
factors = []
found_factor = False
max_possible = math.sqrt(num)
prime = 0
# Loop through possible primes
while not found_factor and prime < max_possible:
# get next prime
prime = getNextPrime(prime)
# if num is divisible by this prime, set found_factor and look for more
if num%prime == 0:
factors.append(prime)
factors.extend(getPrimeFactors(num/prime))
found_factor = True
# if no prime factors found, this should have been prime! something is wrong
assert(found_factor == True)
return factors
# ----------------------------------------------------------------------------
def getPrimeFactorsWithSeive(num):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if num == 0 or num == 1:
return []
if isPrime(num):
return [num]
primes_factors = []
# get all primes up to num
primes = primeSeive(num)
for p in primes:
if num%p == 0:
primes_factors.append(p)
return primes_factors
# ----------------------------------------------------------------------------
def getPrimeFactors(num, primes_list):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if num == 0 or num == 1:
return []
test_num = num
prime_factors = []
for p in primes_list:
while test_num % p == 0:
prime_factors.append(p)
test_num /= p
if test_num == 1:
break
return prime_factors
# ----------------------------------------------------------------------------
def getNumDivisorsFromPrimes(prime_factors):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
num_primes = len(prime_factors)
num_divisors = 1
prime_counter = collections.Counter(prime_factors)
for elt,count in prime_counter.most_common():
num_divisors *= (count+1)
return num_divisors
# ----------------------------------------------------------------------------
def getDivisorsFromPrimes(prime_factors, master = True):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
divisors = []
if len(prime_factors) > 1:
divisors.append(reduce(operator.mul, prime_factors))
for i in xrange(len(prime_factors)):
tmp_list = prime_factors[:i]+prime_factors[i+1:]
divisors.extend(getDivisorsFromPrimes( prime_factors[:i]
+ prime_factors[i+1:]
, False
)
)
if master and len(prime_factors) > 0:
divisors.append(1)
divisors.extend(prime_factors)
divisors = list(set(divisors))
divisors.sort()
return divisors
# ----------------------------------------------------------------------------
def getDivisors(num, primes_list):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if num == 0:
return []
if num == 1:
return [1]
prime_factors = getPrimeFactors(num, primes_list)
return getDivisorsFromPrimes(prime_factors)
|
2b48bbbc9611328514189dfcfa38acc3b90b0a70 | akeeme/python | /QQ.py | 585 | 4.28125 | 4 | weight=int(input("Enter a weight in pounds "))
height=int(input("Enter a height in inches "))
kg=0.45359237
meter=0.0254
weightKg=weight*kg
print(weightKg)
heightMeter=height*meter
print(heightMeter)
heightSquare=heightMeter*heightMeter
print(heightSquare)
BM=weightKg/heightSquare
print(BM)
BMI=round(BM,1)
if BMI>18.5:
print("You are underweight, your BMI is",BMI)
if BMI<=18.5 and BMI>=24.9:
print("You are normal weight, your BMI is",BMI)
if BMI<=25.0 and BMI>=29.0:
print("You are overweight, your BMI is",BMI)
if BMI<30.0:
print("You are OBESE, your BMI is",BMI)
|
ac5b30e8d07ab10d27c3a8f2343534fb6e5574c4 | Neronjust2017/DL-TSC | /models/regression/LSTM.py | 2,836 | 3.5 | 4 | # 这里需要使用tensorflow.keras,否则可能会出现一个奇怪的错误:
# AttributeError: 'TFOptimizer' object has no attribute 'learning_rate'
import tensorflow.keras as keras
class LSTM:
def __init__(self, input_shape, output_shape):
self.model = self.build_model(input_shape, output_shape)
def build_model(self, input_shape, output_shape):
'''
1. 理解LSTM的输出,以及参数return_sequences 和 return_state
https://huhuhang.com/post/machine-learning/lstm-return-sequences-state
keras中默认return_sequences=False 和 return_state=False
默认状态下输出为最后时刻的隐藏状态ht, 格式为(samples, output_dim)
如果return_sequences=True, 则输出每一个时刻的隐藏状态h, 格式为(samples, timesteps, output_dim)
如果return_state=True, 则输出3个值,0和1都是最后时刻的隐藏状态ht,2是最后时刻的细胞状态ct
如果二者都为True,则输出3个值:
0 - 所有时刻的隐藏状态h
1 - 最后时刻的隐藏状态ht
2 - 最后时刻的细胞状态ct
如果是多层LSTM,需要将前N-1层return_sequence=True, 最后一层为False
2. dropout 与 recurrent_dropout
https://segmentfault.com/a/1190000017318397
3. batchNormal怎么用
“BN层放在每一个全连接层和激励函数之间”
LSTM可以使用该层,但GRU有时会出现loss为nan
'''
input_layer = keras.layers.Input(shape=(input_shape[0], input_shape[1]))
lstm1 = keras.layers.LSTM(32,
return_sequences=True,
dropout=0.4,
recurrent_dropout=0.4)(input_layer)
bn1 = keras.layers.BatchNormalization()(lstm1)
relu1 = keras.layers.Activation('relu')(bn1)
lstm2 = keras.layers.LSTM(64,
dropout=0.4,
recurrent_dropout=0.4,
return_state=True)(relu1)
lstm2 = lstm2[1]
bn2 = keras.layers.BatchNormalization()(lstm2)
relu2 = keras.layers.Activation('relu')(bn2)
#dense = keras.layers.Dense(output_shape, activation='sigmoid')(relu2)
dense = keras.layers.Dense(output_shape, activation='softmax')(relu2)
model = keras.models.Model(inputs=input_layer, outputs=dense)
return model
if __name__ == '__main__':
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
model =LSTM(input_shape=(18000,12), output_shape=9).model
model.summary() |
e4c65ba9bf4fe7caf23f2b88f933817fbc3a0b6f | arkaanashadi/Assignment-1-Driving-Simulation | /Arkaan CupsNBall.py | 366 | 3.640625 | 4 | user = input('Input must be the letters "A", "B", or "C"\n').upper()
ball = [1,0,0]
for i in range(len(user)):
if user[i] == "A":
x = ball[0]
ball[0] = ball[1]
ball[1] = x
elif user[i] == "B":
x = ball[1]
ball[1] = ball[2]
ball[2] = x
elif user[i] == "C":
x = ball[0]
ball[0] = ball[2]
ball[2] = x
for i in range(3):
if ball[i]==1:
print(i+1) |
0116d11b745364cebd41b340bab0915bebf803d4 | artorious/track_coach_data | /track_coach.py | 3,210 | 4.25 | 4 | #!/usr/bin/env python3
""" Track Coach Data
A play on files and working the data files,
text files holding athletes track records.
* Read from file, transform the data and process into sorted lists
* Display top three fastest times for each athlete
"""
# TODO: Write changes to file (add/delete etc)
class AthleteList(list):
"""
Class routines process Athelete Track information
Inherits from the built-in list class
"""
def __init__(self, a_name, a_dob=0, a_times=[]):
"""Initialize and assign class attributes"""
list.__init__([]) # Init sub-class
self.name = a_name
self.dob = a_dob
self.extend(a_times)
def top3_records(self):
""" Return Athelete's 3 Best recorded times """
return sorted(set([sanitize(t) for t in self]))[0:3]
def avg_record_time(self):
""" Return Athelete's Average recorded time """
summed_time = 0
for time_rec in self:
try:
summed_time += float(sanitize(time_rec))
except Exception as err:
return err
return summed_time / len(self)
def get_athlete_data(filename):# Process each file
""" (file) -> Athlete object instance
Takes <filename>, the file with the athletes' track records.
Processes each file, creating and returning an Athlete class object
for each athlete’s data.
"""
try:
with open(filename) as file_obj: # Open the file
file_data = file_obj.readline() # read the data
temp_list = file_data.strip().split(',') # hold gross data in list
return AthleteList(temp_list.pop(0), temp_list.pop(0), temp_list)
except IOError as ioerr:
print('File Error...', ioerr)
return None
def sanitize(time_string): # Fix non-uniformity in the athletes data to enable sorting
"""(str) -> str
Takes as input <time_string>, a string from each of the athletes's lists.
Processes the string to replace any dashes or colons found with a period.
Returns the sanitized string
"""
if '-' in time_string:
splitter = '-'
(mins, secs) = time_string.split(splitter)
elif ':' in time_string:
splitter = ':'
(mins, secs) = time_string.split(splitter)
else:
return time_string
return '{0}.{1}'.format(mins, secs)
if __name__ == '__main__':
# Init Athlete object instaces
sarah = get_athlete_data('text/sarah2.txt') # Gross Info
james = get_athlete_data('text/james2.txt') # Gross Info
mikey = get_athlete_data('text/mikey2.txt') # Gross Info
julie = get_athlete_data('text/julie2.txt') # Gross Info
vera = AthleteList('Vera Vi')
vera.append('1.31')
vera.extend(['2.22', '1-21', '2:22'])
# Display Athlete Info
for record in (sarah, james, mikey, julie, vera):
print(format(' ATHLETE INFO - {0} ', '*^45').format(record.name))
print('DOB : {0}'.format(record.dob))
print('Top 3 fastest times are : {0}'.format(record.top3_records()))
print('Average Time: {0:.2f}'.format(record.avg_record_time()))
print('Timing Data: {0}'.format(record))
print()
|
7557b0434ab8bfd6c19de6b4fceafe3198b4fec5 | douglasaxel/python | /GuessMyNumber.py | 762 | 3.796875 | 4 | import random
import sys
class funcionario():
def __init__(self, nome, sobre):
self.nome = nome
self.sobre = sobre
@property
def junta(self):
return f'{self.nome} {self.sobre}'
print("I'm thinking in a number between 1 and 20.")
secretNumber = random.randint(1, 20)
guessesTaken = 0
while guessesTaken < 6:
print('Type in a guess and press enter.')
guess = int(input())
guessesTaken = guessesTaken + 1
if guess < secretNumber:
print('Too low!')
if guess > secretNumber:
print('Too high!')
if guess == secretNumber:
print('You have guessed my number in ' +
str(guessesTaken) + ' guesses!')
sys.exit()
print('Nope! My number was ' + str(secretNumber))
|
fddd8fa61044ba8e951c0c25a3219bdd8260db0b | sambapython/batch44_1 | /compre.py | 260 | 3.53125 | 4 | l1=[1,2,"r1",3,4,"r2"]
res=[i+10 if isinstance(i,(int,float)) else i for i in l1]
print(res)
for i in res:
print(i)
print ("*"*50)
l1=[1,2,"r1",3,4,"r2"]
res = (i+10 if isinstance(i,(int,float)) else i for i in l1)
print (res)
for i in res:
print (i) |
92c03c19d4e5cfacac8091e10fc432921654e680 | rbusquet/advent-of-code | /aoc_2018/day5.py | 1,587 | 3.546875 | 4 | from string import ascii_lowercase
from typing import TypeVar
print("--- DAY 5: part 1 ---")
T = TypeVar("T")
def destroy(letter: str, next_letter: str) -> bool:
same_letter = letter.lower() == next_letter.lower()
opposite_sign = letter != next_letter
return opposite_sign and same_letter
def break_array(array: list[T], index: int) -> tuple[list[T], T, T, list[T]]:
return array[:index], array[index], array[index + 1], array[index + 2 :]
buffer = ""
with open("input5.txt") as f:
buffer = f.read(1)
while True:
letter = buffer[-1:]
next_letter = f.read(1)
if not next_letter:
break
should_destroy = destroy(letter, next_letter)
if should_destroy:
buffer = buffer[:-1]
else:
buffer += next_letter
# print(buffer[:50])
print(f"Processed polymer has length={len(buffer)}")
print("--- DAY 5: part 2 ---")
for unit in ascii_lowercase:
with open("input5.txt") as f:
buffer = f.read(1)
while buffer.lower() == unit:
buffer = f.read(1)
while True:
letter = buffer[-1:]
next_letter = f.read(1)
if next_letter.lower() == unit:
continue
if not next_letter:
break
should_destroy = destroy(letter, next_letter)
if should_destroy:
buffer = buffer[:-1]
else:
buffer += next_letter
# print(buffer[:50])
print(f"Removing units {unit} length of polymer is {len(buffer)}")
|
8d1d4dbad09e500c8c4b682d4534ae892f268aa0 | Naby-cmr/GeneticAlgorithm | /AbstractClasses.py | 4,069 | 3.65625 | 4 | from abc import ABC, abstractmethod
import random
__all__ = ['AbstractDNA', 'AbstractIndividual', 'AbstractPopulation']
class AbstractDNA(ABC):
"""Classe abstraite d'ADN."""
def __init__(self):
"""Constructeur."""
self._genes = None
def __str__(self):
"""Pretty-print."""
return str(self._genes)
def get_genes(self):
"""Getter."""
return self._genes
@abstractmethod
def make_genes(self, *args):
"""Fonction de création des gènes."""
pass
@abstractmethod
def mutate(self, rate):
"""Fonction de mutation."""
pass
@abstractmethod
def crossover(self, mate):
"""Fonction de reproduction."""
pass
class AbstractIndividual(ABC):
"""Classe abstraite d'individu."""
def __init__(self):
"""Constructeur."""
self._fitness = 0
self._DNA = None
def __lt__(self, other):
"""Surcharge opérateur de comparaison."""
return self._fitness < other.get_fitness()
def __str__(self):
"""Pretty-print."""
return f"""
Fitness : {self._fitness}
DNA : {self.get_DNA()}
"""
def get_DNA(self):
"""Getter."""
return self._DNA
@abstractmethod
def computeFitness(self, *args):
"""Fonction de fitness."""
pass
def get_fitness(self):
"""Getter."""
return self._fitness
class AbstractPopulation(ABC):
"""Classe abstraite de population."""
def __init__(self):
"""Constructeur."""
self.individuals = list()
self.size = 0
self.max_fitness = 0
def __str__(self):
"""Pretty-print."""
for ind in self.individuals:
print(f"Individual {self.individuals.index(ind)}")
print(ind)
return f"""
Size of population : {len(self.individuals)}
Maximum fitness : {self.max_fitness}
"""
@abstractmethod
def createDNA(self, *args):
"""Retourne un objet DNA."""
pass
@abstractmethod
def createIndividual(self, *args):
"""Retourne un objet individu."""
pass
def computeFitness(self, *args):
"""Fonction de fitness."""
for ind in self.individuals:
max_fitness = ind.computeFitness(*args)
if max_fitness > self.max_fitness:
self.max_fitness = max_fitness
def select(self, rate):
"""Fonction de sélection des meilleurs individus."""
self.individuals.sort(reverse=True)
self.individuals = self.individuals[0:int((rate)*self.size)]
return self.individuals[0]
def reproduce(self, m):
"""Fonction de reproduction."""
# print('caca')
childrens = []
random.shuffle(self.individuals)
while self.size != len(childrens):
for i in range(0, len(self.individuals)-1, 2):
dna1 = self.individuals[i].get_DNA()
dna2 = self.individuals[i+1].get_DNA()
childDNA = self.createDNA(dna1.crossover(dna2))
# childDNA = DNA(mate1.crossover(mate2))
childDNA.mutate(m)
ind = self.createIndividual(childDNA)
childrens.append(ind)
# childrens.append(Individual(childDNA))
if len(childrens) == self.size:
break
self.individuals = childrens
def stopIteration(self, n):
"""Critere d'arrêt de l'évolution."""
pass
def trackingProcess(self, best, n):
"""Suivi du process d'évolution."""
pass
def evolve(self, selection, mutation, target=None):
"""Suivi du process d'évolution."""
n = 0
while True:
self.computeFitness(target)
best = self.select(selection)
self.trackingProcess(best, n)
if self.stopIteration(n):
print()
break
self.reproduce(mutation)
n = n + 1
|
c0317c42c9aae214c187c4f7429fda084537714b | blixt/py-base | /__init__.py | 1,742 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# base - convert numbers between arbitrary bases.
# Copyright © 2011 Andreas Blixt
# MIT license
"""A module for converting between bases.
"""
BASE2 = BINARY = '01'
BASE8 = OCTAL = '01234567'
BASE10 = DECIMAL = '0123456789'
BASE16 = HEX = '0123456789ABCDEF'
BASE62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
def rebase(number, from_base, to_base):
"""Changes the base of a number. Takes the base to convert from and the
base to convert to. A base is defined as a string of digits that make up
the base.
Examples:
>>> rebase('80', HEX, DECIMAL)
'128'
>>> rebase(-255, DECIMAL, HEX)
'-FF'
>>> rebase('1111', BINARY, DECIMAL)
'15'
"""
# Assumes that numbers can be negative, and that they are so when they
# start with the dash character.
number = str(number)
if number[0] == '-':
number = number[1:]
negative = True
else:
negative = False
# Get the radii (number of possible digits) of the bases.
from_radix = len(from_base)
to_radix = len(to_base)
# Convert the input number to a normal integer so that arithmetics can be
# performed.
x = 0
for digit in number:
x = x * from_radix + from_base.index(digit)
# Build the final string that will be the number in the target base.
result = ''
while x:
result = to_base[x % to_radix] + result
x //= to_radix
# Return the result. If the input was negative, also return the result as
# negative.
return '-' + result if negative else result
if __name__ == '__main__':
import doctest
doctest.testmod()
|
db0d625c80b12e7c7f4299dd0c4cb21c5c819a68 | nhatsmrt/AlgorithmPractice | /LeetCode/420. Strong Password Checker/Solution.py | 3,567 | 4 | 4 | INSERT_CHAR = "<INSERT>"
def is_digit(character):
return ord('0') <= ord(character) <= ord('9')
def is_lowercase(character):
return ord('a') <= ord(character) <= ord('z')
def is_uppercase(character):
return ord('A') <= ord(character) <= ord('Z')
def is_alphabetical(character):
return is_lowercase(character) and is_uppercase(character)
class Solution:
def strongPasswordChecker(self, s: str) -> int:
# Time and Space Complexity: O(N)
self.dp = {}
return self.minChange(s, 0, 0, "", False, False, False, False)
def minChange(
self, s: str, i: int, num_letter: int, last: str, same: bool,
has_lowercase: bool, has_uppercase: bool, has_digit: bool
):
key = (i, num_letter, last, same, has_lowercase, has_uppercase, has_digit)
if key in self.dp:
return self.dp[key]
if num_letter > 20:
ret = -1
elif i == len(s):
ret = 0
if not has_lowercase:
ret += 1
if not has_uppercase:
ret += 1
if not has_digit:
ret += 1
num_letter += ret
if num_letter > 20:
ret = -1
elif num_letter < 6:
ret += 6 - num_letter
elif num_letter == 20:
if has_lowercase and has_uppercase and has_digit:
ret = len(s) - i
else:
ret = -1
else:
candidates = []
# Delete current character
candidates.append(
self.minChange(s, i + 1, num_letter, last, same, has_lowercase, has_uppercase, has_digit))
# Add a character:
candidates.append(
self.minChange(s, i, num_letter + 1, INSERT_CHAR, False, True, has_uppercase, has_digit)) # insert a lowercase character
candidates.append(
self.minChange(s, i, num_letter + 1, INSERT_CHAR, False, has_lowercase, True, has_digit)) # insert an uppercase character
candidates.append(
self.minChange(s, i, num_letter + 1, INSERT_CHAR, False, has_lowercase, has_uppercase, True)) # insert a digit
# Replace current character:
candidates.append(
self.minChange(s, i + 1, num_letter + 1, INSERT_CHAR, False, True, has_uppercase, has_digit)) # replace wwith a lowercase character
candidates.append(
self.minChange(s, i + 1, num_letter + 1, INSERT_CHAR, False, has_lowercase, True, has_digit)) # replace with an uppercase character
candidates.append(
self.minChange(s, i + 1, num_letter + 1, INSERT_CHAR, False, has_lowercase, has_uppercase, True)) # replace with a digit
filtered_candidates = list(filter(lambda val: val != -1, candidates))
ret = (1 + min(filtered_candidates)) if len(filtered_candidates) > 0 else -1
# Keep current character:
if not same or last != s[i]:
new_same = s[i] == last
new_last = s[i]
new_lower = has_lowercase or is_lowercase(s[i])
new_upper = has_uppercase or is_uppercase(s[i])
new_dig = has_digit or is_digit(s[i])
candidate = self.minChange(s, i + 1, num_letter + 1, new_last, new_same, new_lower, new_upper, new_dig)
if candidate != -1:
ret = min(ret, candidate) if ret != -1 else candidate
self.dp[key] = ret
return ret
|
39577b5fd85567767525474ce099cacee3025288 | AAAKgold/My-test | /if/16-判断白富美-高富帅.py | 458 | 3.5625 | 4 |
sex = input('请输入你的性别:')
#如果当前用户是男性的话,那么就输入判断女性的要求
if sex == '男':
color = input("你白么?")
money = int(input("请输入你的财产总和:"))
beautiful = input("你美么?")
if color == '白' and money>100000000 and beautiful == '美':
print('白富美……')
else:
print('矮穷矬……')
else:
print('判断高富帅的信息在下面')
|
2a7e504729b94d9f2dc6e41c843115b04cc014f3 | ElijahDR/adventofcode-2018 | /day2.py | 1,888 | 3.5625 | 4 | def part1(inputData = "input/input2.txt"):
twos = 0
threes = 0
with open(inputData) as f:
for line in f:
added2 = False
added3 = False
line = line.strip()
arr = list(line)
for item1 in arr:
count = 0
for item2 in arr:
if item1 == item2:
count += 1
if count == 2 and added2 == False:
added2 = True
twos += 1
if count == 3 and added3 == False:
added3 = True
threes += 1
print("day 2, part 1: " + str(twos * threes))
def part2(inputData = "input/input2.txt"):
with open(inputData) as f:
lines = f.readlines()
best = 0
bestX = 0
bestY = 0
x = 0
for line in lines:
y = 0
line = line.strip()
arr = list(line)
for line2 in lines:
if y == x:
y +=1
continue
line2 = line2.strip()
arr2 = list(line2)
count = 0
for i in range(0, len(arr)):
if arr[i] == arr2[i]:
count += 1
if count > best:
bestX = x
bestY = y
best = count
y += 1
x += 1
word1 = lines[bestX]
word2 = lines[bestY]
arr1 = list(word1)
arr2 = list(word2)
new = []
for i in range(0, len(arr1)):
if arr1[i] == arr2[i]:
new.append(arr1[i])
print("day 2, part 2: " + "".join(new).rstrip())
def main(inputData = "input/input2.txt"):
part1(inputData)
part2(inputData)
if __name__ == "__main__":
main()
|
7303d9b7fcfe2ab275788b0d1d46ffb20d3e41d2 | mingweihe/leetcode | /_0103_Binary_Tree_Zigzag_Level_Order_Traversal.py | 1,023 | 3.921875 | 4 | from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
use a queue to hold values and their order
remember this simple deque is from collections package
"""
if not root: return []
res, queue = [], deque([root])
to_right = True
while queue:
layer = []
for i in xrange(len(queue)):
node = queue.popleft()
if to_right:
layer.append(node.val)
else:
layer.insert(0, node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
to_right = False if to_right else True
res.append(layer)
return res
|
0a0d84d6d993909fbb049e6ff19203e4778efd17 | marcinpgit/Python_exercises | /Exercises_2/loops/l2.py | 679 | 4.28125 | 4 | # Write a Python program to convert temperatures to and from celsius, fahrenheit.
# [ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ]
# Expected Output :
# 60°C is 140 in Fahrenheit
# 45°F is 7 in Celsius
temp = input("Podaj temp w C lub F: ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
rezultat = int(round((9 * degree) / 5 + 32))
skala = "Farenheit"
elif i_convention.upper() == "F":
rezultat = int(round((degree - 32) * 5 / 9))
skala = "Celsius"
else:
print("Nieprawidłowowprowadzona temp!!")
print("Temperatura w {} wynosi {} stopni.".format(skala, rezultat))
|
8a34273a8bb7c0f611bd5232803b912f021c5469 | udoy382/IntermediateAdPy | /iap_5.py | 952 | 4.46875 | 4 | # List Comprehension, Dictionary Comprehension, and Generator Comprehension
'''
List Comprehension
Dictionary Comprehension
Set Comprehension
Generator Comprehension
'''
list_1 = [1, 2, 5, 4, 8, 5, 3, 6, 9, 76, 56, 3, 54, 24, 24, 75, 86, 356, 35, 75]
divide_by_3 = []
for item in list_1:
if item%3==0:
divide_by_3.append(item)
print("Without using list Comprehension:", divide_by_3)
# List Comprehension
print("Using list Comprehension: ", [item for item in list_1 if item%3==0])
# Dictionary Comprehension
dict1 = {'a':45, 'b':65, 'A':5}
print({k.lower():dict1.get(k.lower(), 0) + dict1.get(k.upper(), 0) for k in dict1.keys()})
# Set Comprehension
squared = {x**2 for x in [1, 3, 5, 2, 4, 3, 4, 4, 3, 4, 3, 2, 6, 5, 4, 3,2]}
print(squared)
# Generator Comprehension
gen = (i for i in range(56) if i%3==0)
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
for item in gen:
print(item) |
009c817b850e09e8460b47ab6e3f3e7570206619 | zjg540066169/Bioinformatics_learning | /UCSD/Genome Sequencing (Bioinformatics II)/Week 1/Eulerian_Cycle_Problem.py | 6,456 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 07:47:11 2019
Input: The adjacency list of an Eulerian directed graph.
Output: An Eulerian cycle in this graph.
Randomly select a starting point S, randomly search for a path from S to S,
which forms a cycle.
while True:
If there is no node has unused edges, then print the cycle.
Else
randomly select a searched point T that has unused edges, use searched path
to form a cycle first, from T to T. Then search from T by using another unused
edge. To form a new cycle.
Optimization: When searched in a new point D, read all neghbors of D, choose the
point that has the most neighbors that has not searched as the next point.
O(n), n is the number of edge, since we can simply change the position of path array
@author: jungangzou
"""
from Hamiltonian_Graph import node
class debruijn_graph_eulerian_cycle(object):
def __init__(self):
self.node_list = []
self.node_num = 0
self.ID_to_Index = {}
self.Index_to_ID = {}
def add_node(self, ID):
if ID in self.ID_to_Index:
raise Exception("there is the node with this ID")
self.ID_to_Index[ID] = self.node_num
self.Index_to_ID[self.node_num] = ID
new_node = node(ID)
self.node_list.append(new_node)
self.node_num += 1
#self.fit_prefix(ID, k, self.direct)
#self.fit_suffix(ID, k, self.direct)
def add_direct_edge(self, start_ID, end_ID):
# =============================================================================
# start_ID = edge_ID[:k]
# end_ID = edge_ID[-k:]
# =============================================================================
if start_ID not in self.ID_to_Index:
self.add_node(start_ID)
if end_ID not in self.ID_to_Index:
self.add_node(end_ID)
start_index = self.ID_to_Index[start_ID]
self.node_list[start_index].add_new_edge(end_ID)
def get_node_by_id(self, node_id):
index = self.ID_to_Index[node_id]
return self.node_list[index]
def get_edge_by_node(self, node_id):
index = self.ID_to_Index[node_id]
return self.node_list[index].get_edge()
def get_all_nodes_ID(self):
ID = []
for i in self.node_list:
ID.append(i.get_ID())
return ID
def get_all_edges(self):
edge_dict = {}
ID_list = self.get_all_nodes_ID()
for ID in ID_list:
edge_dict[ID] = self.get_edge_by_node(ID).copy()
return edge_dict
def eulerian_cycle_search(self, start_id):
remain_edges = self.get_all_edges()
path_nodes_list = []
start_point = start_id
while True:
#use old path to generate the beginning of the new path
if len(path_nodes_list) != 0:
path_nodes_list = path_nodes_list[:-1]
for i in range(len(path_nodes_list)):
if path_nodes_list[i] == start_point:
path_nodes_list = path_nodes_list[i:] + path_nodes_list[:i]
path_nodes_list.append(start_point)
while len(remain_edges[start_point]) != 0:
next_point_select_point_set = remain_edges[start_point]
#max_neighbor_node_id = next_point_select_point_set[0]
# =============================================================================
# next_point_select_index_set = []
# for ID in next_point_select_point_set:
# next_point_select_index_set.append(self.ID_to_Index[ID])
#
# =============================================================================
max_neighbor = 0
max_neighbor_node_id = remain_edges[start_point][0]
for neighbor_index in range(len(next_point_select_point_set)):
if len(remain_edges[next_point_select_point_set[neighbor_index]]) > max_neighbor:
max_neighbor_node_id = next_point_select_point_set[neighbor_index]
max_neighbor = len(remain_edges[next_point_select_point_set[neighbor_index]])
#print(start_point, max_neighbor_node_id, remain_edges[start_point])
#max_neighbor_node_id = random.choice(next_point_select_point_set)
remain_edges[start_point].remove(max_neighbor_node_id)
path_nodes_list.append(max_neighbor_node_id)
start_point = max_neighbor_node_id
for node_id in path_nodes_list:
if len(remain_edges[node_id]) != 0:
start_point = node_id
break
else:
return path_nodes_list
if __name__ == "__main__":
# =============================================================================
# with open("dataset_200_8.txt", "r") as f:
# string = f.readlines()
# for i in range(len(string)):
# string[i] = string[i][:-1]
# =============================================================================
path_num = 0
with open('dataset_203_2 09.26.00.txt', 'r') as file:
graph = dict((line.strip().split(' -> ') for line in file))
for key in graph:
graph[key] = graph[key].split(',')
g = debruijn_graph_eulerian_cycle()
for i in graph:
for j in graph[i]:
path_num += 1
g.add_direct_edge(i,j)
path = g.eulerian_cycle_search(list(graph.keys())[3])
# =============================================================================
# for i in range(len(path)):
# if path[i] == "1140":
# path = path[i:] + path[:i+1]
# break
# =============================================================================
a = "->".join(path)
print(a)
# =============================================================================
# with open("dataset_200_8_result.txt", "w") as w:
# for pattern, adjacencies in g.get_all_edges().items():
# if len(adjacencies) > 0:
# w.write(pattern + ' -> ' + str(', '.join(adjacencies)) + "\n")
#
# =============================================================================
|
bf156c52559b23195d7513e61e7daace80e87154 | Nyuhnyash/lab | /oop/lab2/1.py | 175 | 3.640625 | 4 | from math import sqrt, pi as PI
def solve(s1: float, s2: float):
return sqrt((s1 + s2) / PI)
for s1, s2 in [(108.25, 139.93)]:
print(format(solve(s1, s2), '.3f'))
|
13dd50d11b2c5a54c1b0f0acfc86c8113eebc256 | stephfz/taller-python-set18 | /stephanie/bloque_integracion_1/5_reemplazar_vocales_por_numeros.py | 338 | 3.6875 | 4 | reemplazo = {'a': 1, 'e': 2, 'i':3,'o':4, 'u':5}
palabra = input("Ingrese una palabra: ")
longitud = len(palabra)
nueva_palabra = ''
for contador in range(longitud):
letra = palabra[contador]
if letra in reemplazo.keys():
letra = str(reemplazo[letra])
nueva_palabra = nueva_palabra + letra
print(nueva_palabra)
|
714804ab0c7c8edb713a57b63daf939d27e26133 | zerolive/python_koans | /fizzbuzz/code/fizzbuzz.py | 577 | 3.625 | 4 |
class FizzBuzz():
FIZZ_NUMBER = 3
BUZZ_NUMBER = 5
BUZZ = 'Buzz'
FIZZ = 'Fizz'
def __init__(self, number):
self._number = number
def evaluate(self):
if self._is_fizzbuzz():
return self.FIZZ + self.BUZZ
if self._is_fizz():
return self.FIZZ
if self._is_buzz():
return self.BUZZ
return str(self._number)
def _is_fizz(self):
return (self._number % self.FIZZ_NUMBER == 0)
def _is_buzz(self):
return (self._number % self.BUZZ_NUMBER == 0)
def _is_fizzbuzz(self):
return self._is_buzz() and self._is_fizz()
|
359361d72fcd68ccfe5a6387aff9b3df730ececb | VadimKudryavcev/QuickSortPython | /main.py | 260 | 3.5625 | 4 | import time
from quicksort import *
array = [10, 16, 8, 8, 12, 15, 6, 3, 9, 5]
time0 = time.time()
quicksort(array, 0, len(array) - 1)
time1 = time.time()
print('Sorted')
print(array)
print('Время расчета {} секунд'.format(time1 - time0)) |
1bc0d7aa84d17d5cd50b470cd5dd6edd3d5c2528 | priyareena/helo | /ban.py | 67 | 3.84375 | 4 | a="string"
b="banana"
if(a==b):
print("yes")
else:
print("no")
|
ca5423a620d079fcbba058179dc9c1627edba2ce | hyccc/myPython | /7 字符串和数据结构/练习6:打印杨辉三角。.py | 1,582 | 4.15625 | 4 | '''
杨辉三角,是二项式系数在三角形中的一种几何排列
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
思路:
利用坐标来计算杨辉三角! 行(row)列(col)
(0,x)都等于1 , (x,x)也都等于1,
每一个元素都等于,上一行的两个元素相加:yh[row][col] = yh[row-1][col] + yh[row-1][col-1]
pyton中没有数组,就用双列表来代替。!
反思:
刚开始一直遇到错误,‘IndexError: list index out of range’
list一直为空,数传入不进去。
最后参考答案,发现原答案 传入了一个 None 来保证 list 为空
'''
def main():
num = int(input("想要计算列数:"))
yh = [[]] * num
for row in range(len(yh)):
yh[row] = [None]*(row+1)
for col in range(len(yh[row])):
if col == 0 or col == row:
yh[row][col] = 1
else:
yh[row][col] = yh[row-1][col] + yh[row-1][col-1]
print(yh[row][col], end=' ')
print()
if __name__ == '__main__':
main()
# def main():
# num = int(input('Number of rows: '))
# yh = [[]] * num
# for row in range(len(yh)):
# yh[row] = [None] * (row + 1)
# for col in range(len(yh[row])):
# if col == 0 or col == row:
# yh[row][col] = 1
# else:
# yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
# print(yh[row][col], end='\t')
# print()
#
#
# if __name__ == '__main__':
# main() |
229fea196eb969181e3a6f69d476bd5301f5237e | infinity-milesman/Python | /text_generator/text_generator.py | 1,091 | 3.875 | 4 | import random, string
vovels="aeiou"
consonents="bcdfghjklmnpqrstvwxyz"
any=string.ascii_lowercase
letter_input_1=input("Enter a letter?for vovels enter 'v',for consonents enter 'c',for any letter enter 'l':")
letter_input_2=input("Enter a letter?for vovels enter 'v',for consonents enter 'c',for any letter enter 'l':")
letter_input_3=input("Enter a letter?for vovels enter 'v',for consonents enter 'c',for any letter enter 'l':")
def generator():
if letter_input_1=="v":
let1=random.choice(vovels)
elif letter_input_1=="c":
let1=random.choice(consonents)
elif letter_input_1=="l":
let1=random.choice(any)
else:
let2=letter_input_2
if letter_input_2=="v":
let2=random.choice(vovels)
elif letter_input_2=="c":
let2=random.choice(consonents)
elif letter_input_2=="l":
let2=random.choice(any)
else:
let3=letter_input_3
if letter_input_3=="v":
let3=random.choice(vovels)
elif letter_input_3=="c":
let3=random.choice(consonents)
elif letter_input_3=="l":
let3=random.choice(any)
name=let1+let2+let3
return(name)
for i in range(20):
print(generator())
|
0c4f9e904084a688e8cdc612e16da932a36f97f4 | Baqirh/automate-boring-stuff-with-python-projects | /TicTacToe(multiplayer).py | 3,478 | 4.28125 | 4 | '''
A code for multiplayer TicTacToe game.
Last Edited: Jun 13, 2021
Creator: Nishkant
'''
import sys
#creating a dictionary for an empty game board.
theBoard = {(1,1): ' ', (1,2): ' ', (1,3): ' ',
(2,1): ' ', (2,2): ' ', (2,3): ' ',
(3,1): ' ', (3,2): ' ', (3,3): ' '}
def printBoard(board):
''' For printing the game board '''
print()
print(board[(1,1)] + ' | ' + board[(1,2)] + ' | ' + board[(1,3)])
print('--$---$--')
print(board[(2,1)] + ' | ' + board[(2,2)] + ' | ' + board[(2,3)])
print('--$---$--')
print(board[(3,1)] + ' | ' + board[(3,2)] + ' | ' + board[(3,3)])
print()
def WinCheck(board):
''' For cheking if any player has won in the TicTacToe game '''
g = 0 # initiallizing a switch which will turn to 1 if any player wins.
# will be helpful for performing actions after the win in any condition.
# Checking for rows....
for P in ("O", "X"):
for i in range(1,4): #checking each row one by one.
if board[(i,1)] == board[(i,2)] == board[(i,3)] == P:
g = 1
break
# checking for columns....
for i in range(1,4):
if board[(1,i)] == board[(2,i)] == board[(3,i)] == P:
g = 1
break
# checking for diagonas....
if board[(1,1)] == board[(2,2)] == board[(3,3)] == P:
g = 1
break
elif board[(3,1)] == board[(2,2)] == board[(1,3)] == P:
g = 1
break
#printing the winning message, game board and exiting the game if a player wins.
if g == 1:
print("****************************************************")
printBoard(board)
print(P," won." + " Tum to bade heavy player nikle.")
print("****************************************************")
sys.exit()
#starting the game.....
print('''
New game started...
Enter the position in the format (a,b) where a is row no. and b is column no.
Starting from top left i.e. (1,1).
Enjoy the game :)''')
turn = 'X'
for i in range(9): #running the loop for all 9 spaces.
printBoard(theBoard)
while True: #used for compensating errors by the user while giving inputs.
print('Turn for ' + turn + '. Move on which space?')
try:
a, b = input().split(",")
a = int(a)
b = int(b)
except:
print("Please enter a valid position.")
continue
if (a,b) not in theBoard.keys(): #if the format entered is correct but the position is not available.
print("Please enter a valid position.")
elif theBoard[(a,b)] != " ": #if already occupied space is entered.
print("This position is already occupied , choose a different one.")
else:
theBoard[(a,b)] = turn
break
# changing the turns.
if turn == 'X':
turn = 'O'
else:
turn = 'X'
#checking if someone won...
WinCheck(theBoard)
#using for-else statement and printing in case of a draw.
else:
print("****************************************************")
printBoard(theBoard)
print("Its a draw ,tired of your old tricks, try somethin different.")
print("****************************************************")
|
1762b42dfa32d729bbbc816346fb8d3526255881 | graying/PY3 | /tk/tk3_grid.py | 796 | 3.578125 | 4 | import tkinter as tk
import sys
counter = 0
conti = True
def counter_label(label):
def count():
global counter
global conti
if (conti):
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()
def set_continue():
global conti
global button
conti = not conti
if conti:
button.config(text='Stop!')
else:
button.config(text='Continue...')
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.grid(row=0, column=0, sticky=tk.E)
counter_label(label)
button = tk.Button(root, text='Stop!', width=15, command=set_continue)
button.grid(row=0, column=1, sticky=tk.E)
exit_button = tk.Button(root, text='Exit', command=sys.exit)
exit_button.grid(row=1, column=1, sticky=tk.E)
root.mainloop()
|
a6a6b897f174efecc7b082c046f943f79fa82844 | Zabdielsoto/Curso-Profesional-Python | /4.- Unidad/Ejercicio2.py | 284 | 4 | 4 | '''Ejercicio 2: Funciones
2.- Tomando 3.14 como valor de PI, escriba
una función que reciba el valor del radio
de un círculo y retorne el valor de su área:
'''
PI = 3.14
radio = 2
def area(r):
a = PI * (r ** 2)
return a
resultado = area(radio)
print(resultado) |
feaf1d04883fb9e0b7404fb760f96bf1f5b791bf | zhyordanova/Python-Basics | /Exam-Preparation/energy_booster.py | 813 | 3.796875 | 4 | fruit = input()
size = input()
set_count = int(input())
pack = 0
price_pack=0
if size == "small":
pack = 2
if fruit == "Watermelon":
price_pack = pack * 56
elif fruit == "Mango":
price_pack = pack * 36.66
elif fruit == "Pineapple":
price_pack = pack * 42.10
elif fruit == "Raspberry":
price_pack = pack * 20
else:
pack = 5
if fruit == "Watermelon":
price_pack = pack * 28.70
elif fruit == "Mango":
price_pack = pack * 19.60
elif fruit == "Pineapple":
price_pack = pack * 24.80
elif fruit == "Raspberry":
price_pack = pack * 15.20
total_price = price_pack * set_count
if 400 <= total_price <= 1000:
total_price *= 0.85
elif total_price >1000:
total_price *= 0.50
print(f'{total_price:.2f} lv.')
|
da122e3071bef8c1defed533df9342c12648bac9 | yatengLG/leetcode-python | /question_bank/intersection-of-two-arrays/intersection-of-two-arrays.py | 505 | 3.875 | 4 | # -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:56 ms, 在所有 Python3 提交中击败了85.56% 的用户
内存消耗:13.8 MB, 在所有 Python3 提交中击败了5.23% 的用户
解题思路:
集合 去重
"""
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1 = set(nums1)
nums2 = set(nums2)
if len(nums1) > len(nums2):
nums2, nums1 = nums1, nums2
return [i for i in nums1 if i in nums2] |
7b6ec6a50e7f71b43904ac4f05a26dd080c604d2 | dan-santos/python | /mundo1/exercicios/ex024.py | 116 | 4 | 4 | cidade = str(input("Digite o nome da sua cidade: "))
dividido = cidade.split()
print(dividido[0].upper() == "SANTO") |
6a563dbae7b8cf7a46621ba9013275c2856ffc95 | pratikmallya/interview_questions | /sorting/insertion_sort.py | 1,011 | 4.34375 | 4 | """
Insertion Sort
Pick lowest element, push it to the front of the list
This will be an in-place sort. Why? Because that's a little
more complicated.
"""
import unittest
from random import sample
from copy import deepcopy
class TestAlg(unittest.TestCase):
def test_case_1(self):
v = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
insertion_sort(v)
self.assertEqual(v, list(range(1,11)))
maxlen = 10000
v1 = sample(range(maxlen), maxlen)
v2 = deepcopy(v1)
self.assertEqual(
v1.sort(), insertion_sort(v2))
def insertion_sort(v):
for i in range(1, len(v)):
ind = find_ind(v[:i], v[i])
insert_elem(v, i, ind)
def find_ind(v, elem):
for i,item in enumerate(v):
if elem < item:
return i
return i
def insert_elem(v, from_ind, to_ind):
elem = v[from_ind]
for i in reversed(range(to_ind+1, from_ind+1)):
v[i] = v[i-1]
v[to_ind] = elem
if __name__ == "__main__":
unittest.main()
|
f3bd0efb053cca0be4fbf3454d6ffde63a323d00 | mkoryor/Python | /arrays & strings/rotateMatrixby90.py | 608 | 3.96875 | 4 |
def rotate(mat, start, end):
curr = 0
while curr + start < end:
temp = mat[start][start + curr] # save top
mat[start][start + curr] = mat[end - curr][start] # left to top
mat[end - curr][start] = mat[end][end - curr] # bottom to top
mat[end][end - curr] = mat[start + curr][end] # right to bottom
mat[start + curr][end] = temp # top to right
curr += 1
def rotateMatrixBy90(mat):
for layer in range(len(mat) // 2):
rotate(mat, layer, len(mat) - 1 - layer)
return mat
print(rotateMatrixBy90([[1,2,3], [4,5,6], [7,8,9]]))
|
a744c089e47da679a2bff17c298bf5ca3eec1532 | Commonists/MassUploadLibrary | /uploadlibrary/UnicodeCSV.py | 634 | 3.734375 | 4 | # -*- coding: latin-1 -*-
"""Managing CSV in Unicode."""
import csv
def unicode_csv_dictreader(unicode_csv_data, dialect=csv.excel, **kwargs):
"""Behave like a csv.DictReader but with Unicode support."""
csv_reader = csv.DictReader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
for key, value in row.items():
row[key] = unicode(value, 'utf-8')
yield row
def utf_8_encoder(unicode_csv_data):
"""Encode a given csv as UTF-8 and yield each line."""
for line in unicode_csv_data:
yield line.encode('utf-8')
|
f54f1b13f9ae5baaaa3e0c643f2a37afbf144ef9 | adibisht41/Machine-Learning-A-Z | /Part-1-Data-Preprocessing/template_ml_model.py | 671 | 3.640625 | 4 | """ Template for Machine learning model """
#importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#importing dataset
dataset=pd.read_csv('Data.csv')
X=dataset.iloc[:, :-1].values #excluding the last column and including only independent variables(first 3 col)
y=dataset.iloc[:, 3].values
#splitting data : training and test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test=train_test_split(X,y, test_size=0.2, random_state=0);
#feature scalling
from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler();
X_train=sc_X.fit_transform(X_train);
X_test=sc_X.transform(X_test);
|
3373b955f6088a08a1f838dc7ad3cc1bb197ceef | tomnt/leet_code | /others/codility/shortest-compressed-length.py | 1,842 | 4.0625 | 4 | """
The shortest possible length of the compressed representation of a string
http://prochal.com/2020/05/the-shortest-possible-length-of-the-compressed-representation-of-a-string/
https://app.codility.com/c/run/DA5DTY-KEN/
Test 1
Test 2: def solution(A):
Test 3: def solution(A):
"""
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(S: str, K: int) -> int:
"""
:param str S:
:param int K:
:return int:
"""
# write your code in Python 3.6
# print(S, K)
# if len(S) < K:
# raise Exception('len(S=' + str(len(S)) + ') should be longer than K=' + str(K))
list_length = []
for i in range(0, len(S) - K + 1):
trimmed = S[0:i] + S[i + K:len(S)]
compressed = get_compressed(trimmed)
list_length.append(len(compressed))
return min(list_length)
def get_compressed(target: str) -> str:
"""
Compress given string.
:param str target: Target string to compress.
:return str: Compressed string.
"""
c_tmp = None
count = 1
position = 0
dict_char = {}
for c in list(target):
if c is c_tmp:
count += 1
else:
if c_tmp is not None:
dict_char[c_tmp + str(position)] = count
c_tmp = c
count = 1
position += 1
if c_tmp is not None:
dict_char[c_tmp + str(position)] = count
compressed = ''
for k in dict_char:
if dict_char[k] == 1:
compressed += k[0]
else:
compressed += str(dict_char[k]) + k[0]
return compressed
print("Example 1: Expected: 5, Actual:", solution("ABBBCCDDCCC", 3))
print("Example 2: Expected: 3, Actual:", solution("AAAAAAAAAAABXXAAAAAAAAAA", 3))
print("Example 3: Expected: 6, Actual:", solution("ABCDDDEFG", 2))
|
31ad3bf72125b9f68ba55f57146c50f941f1ba41 | quantbruce/leetcode_test | /算法思想/动态规划/887. 鸡蛋掉落.py | 2,238 | 3.671875 | 4 | ### 方法1. 朴素动态规划
inspired by 小抄
"""
超时
"""
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
memo = dict()
def dp(K, N):
if K==1: return N
if N==0: return 0
if (K, N) in memo:
return memo[(K, N)]
res = float('INF')
for i in range(1, N+1):
res = min(res, max(dp(K-1, i-1), dp(K, N-i))+1 )
memo[(K, N)] = res
return res
return dp(K, N)
# 时间复杂度:O(KN^2)
# 空间复杂度:O(KN)
### 方法2 二分搜索+动态规划 inspired by 小抄
"""
执行用时:3004 ms, 在所有 Python3 提交中击败了7.47%的用户
内存消耗:43.4 MB, 在所有 Python3 提交中击败了16.42%的用户
"""
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
memo = dict()
def dp(K, N):
if K==1: return N
if N==0: return 0
if (K, N) in memo:
return memo[(K, N)]
res = float('INF')
lo, hi = 1, N
while lo <= hi:
mid = (lo+hi)//2
broken = dp(K-1, mid-1)
not_broken = dp(K, N-mid)
if broken > not_broken:
hi = mid - 1
res = min(res, broken+1)
else:
lo = mid + 1
res = min(res, not_broken+1)
memo[(K,N)] = res
return res
return dp(K, N)
# 时间复杂度:O(KNlogN)
# 空间复杂度:O(KN)
### 方法3 动态规划他法定义: inspired by 小抄
"""
执行用时:68 ms, 在所有 Python3 提交中击败了85.66%的用户
内存消耗:21 MB, 在所有 Python3 提交中击败了69.92%的用户
"""
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
dp = [[0]*(N+1) for i in range(K+1)] # 行列坐标别弄反了, 体会
m = 0
while dp[K][m] < N: # 还可以进一步压缩成1维空间,日后细究!
m += 1
for k in range(1, K+1):
dp[k][m] = dp[k][m-1] + dp[k-1][m-1] + 1
return m
# 时间复杂度:O(KN)
# 空间复杂度:O(KN)
|
6f80d1b996dced39d1a99d2cc9e93c54b446b5b9 | milshbrn/Latihan-Module-1 | /fundamental1.py | 1,326 | 4.40625 | 4 | print('Hello apa kabar');
print('Bro');
nama = 'Mila';
print(nama);
usia = 22;
usia = 32;
print(usia);
jomblo = True;
print(jomblo);
nama = 'Abi';
usia = 22;
jomblo = 'True';
print(type(nama));
print(type(usia));
print(type(jomblo));
# Latihan Intro to Python
nama = input("nama kamu? : ");
print("Nama : " + nama);
umur = input("umur kamu? : ");
print("Umur : " + umur);
kelamin = input("kelamin kamu? : ");
print("Kelamin : " + kelamin);
pekerjaan = input("pekerjaan kamu? : ");
print("Pekerjaan : " + pekerjaan);
#Cara buat function
def test(angka1):
hasil = angka1 + angka1;
return hasil;
num1 = 5;
jawaban = test(num1);
print(jawaban);
def mumet(angka2):
hasil = angka2 + angka2;
print(hasil);
mumet(12);
usiaAndi = 40;
usiaAndi = usiaAndi + 3;
print(usiaAndi);
usiaAndi = 40;
hasil = usiaAndi + 3;
print(usiaAndi);
# Number Aritmatics and Operator
usiaAndi = 40;
usiaBudi = 20;
print(usiaAndi * usiaBudi);
print(usiaAndi / usiaBudi);
print(usiaAndi + usiaBudi);
print(usiaAndi - usiaBudi);
print(usiaAndi % usiaBudi);
print(usiaBudi ** 2);
import math
print(math.pi);
print(math.fabs(-4.7));
print(math.pow(8, 2));
print(math.sqrt(64))
x = 'Halo Dunia';
print(len(x));
print(x.index('Dunia'));
print(x.split(' '));
print(x.lower());
print(x.upper());
print(x.capitalize());
|
3ff7532b0af8d090a58fb56306114088863598ab | Superbeet/LeetCode | /Non-leetcode/Collatz_Sequence.py | 536 | 3.78125 | 4 | cache = {1: 1}
def collatz_cache(n):
path = [n]
while n not in cache:
if n % 2:
n = 3 * n + 1
else:
n = n / 2
path.append(n)
for i, m in enumerate(reversed(path)):
cache[m] = cache[n] + i
def collatz_calculate(n):
path = [n]
while n not in cache:
if n % 2 == 0:
n /= 2
else:
n = 3*n + 1
path.append(n)
for i, m in enumerate(reversed(path))
cache[m] = cache[n] + i
return cache[path[0]] |
ecd3bc442b13dde0b80fd11ca5f2156e014a9447 | niuyaning/PythonProctice | /06/07/Serialization_xuliehua3.py | 307 | 3.640625 | 4 | import pickle
class Record:
def __init__(self,name,phone_number):
self.name = name
self.phone_number = phone_number
record = Record("牛亚宁",'15010561875')
with open("d:/2.txt","wb") as f:
print(pickle.dump(Record,f))
with open("d:/2.txt","rb") as f:
print(pickle.load(f))
|
a02381485e51a4008840a254bbdb79295a368038 | shesha4572/12 | /Assignment1_2.py | 477 | 4.09375 | 4 | def PrimeCheck(num):
if num == 2:
return True
elif num == 1:
return False
else:
for i in range(2 , num):
if num % i == 0:
return False
else:
return True
num_user = int(input("Enter a number to be checked : "))
print("Entered number is :" , num_user)
check = PrimeCheck(num_user)
if check:
print("Entered number is a prime number")
else:
print("Entered number is not a prime number")
|
47ad44c3913b2765c5e8ce0d112a467d4fcc099e | gabriellaec/desoft-analise-exercicios | /backup/user_212/ch23_2020_06_18_15_30_06_205153.py | 259 | 3.875 | 4 | velo = float(input("Qual a velocidade do carro?"))
if velo > 80:
km = velo-80
multa = km*5
retorno = "o usuário foi multado. Multa: R${2:.f}".format(multa)
elif velo <= 80:
retorno = 'Não foi multado'
print(retorno)
|
43c316353a153a89dd8e984dfe6682c6696d6045 | anuj69984/Python | /prac.py | 2,175 | 4.125 | 4 | # i am going to print my name.
''' multiline
comment '''
'''
print("Started learning python on 02-08-2018")
name="Anuj"
print(name)
print("***************")
print("Arithmetic operation")
print("power : ",2**5)
print(" checking 5//3 operator : ",5//3)
print(" checking 7//2 operator : ",7//2)
print("1-2+3*4 = ",1-2+3*4)
string1="I am not unique"
string2=" because we all are humans"
print(string1+string2)
print("%s %s %s" %('Always remember ',string1,string2))
print("I don't want newline", end="")
print(" : ok")
print("Now I want 5 new line", '\n' *5)
print("I got 5 newline")
'''
'''
print("********** *LIST* **************")
to_purchase1=['phone','charger','data cable']
print("To purchase : ",to_purchase1)
print('\n')
to_purchase2=['book','pen','copy']
print("To purchase : ",to_purchase2)
print('\n')
print("******************")
print("length of list1 : ",len(to_purchase1),'\n')
print("max of list1 : ",max(to_purchase1),'\n')
print("min of list1 : ",min(to_purchase1),'\n')
print("******************")
print("New purchase List: ")
print(to_purchase1,to_purchase2)
print('\n')
print("See the difference of () and []")
new_to_purchse=(to_purchase1,to_purchase2)
print(new_to_purchse)
print('\n')
new_to_purchse1=[to_purchase1,to_purchase2]
print(new_to_purchse1)
print('\n')
print("after Appending ",end="")
to_purchase1.append('speaker')
print("To purchase : ",to_purchase1)
print('\n')
print("inserting elements at particular index")
to_purchase1.insert(3,'laptop')
print(to_purchase1,'\n')
print("sorting ")
to_purchase1.sort()
print(to_purchase1,'\n')
print("reverse sort : ",to_purchase1.reverse())
print(to_purchase1,'\n')
print("removing speaker")
to_purchase1.remove('speaker');
print(to_purchase1,'\n')
print("removing from particular index")
del to_purchase1[1]
print(to_purchase1,'\n')
'''
print("********** *TUPLE* **************")
my_tuple=(2,3,4,5,6,7,8)
print(my_tuple)
print("converting tuple to list")
new_list=list(my_tuple);
print(new_list)
print("converting list to tuple")
new_tuple=tuple(new_list)
print(new_tuple)
print("length of tuple : ",len(new_tuple))
print("max of tuple : ",max(new_tuple))
print("min of tuple : ",min(new_tuple)) |
e0da43558fc62b910ff3af452918dada59e02c4e | alee023/IntroCS2-PYTHON | /Alison.Lee_HW31.py | 1,243 | 4.34375 | 4 | # Alison Lee
# IntroCS2 pd8
# # HW31 -- Stat-tastic
# 2016-04-14
# 1
def meanList( nums ) :
sumL = 0
for n in nums :
# using for because you are finding the sum of EVERY element in the list
sumL += n
# an element is added to the sum of the previous ones
return sumL / len( nums )
# an arithmetic mean is the sum of numbers / # of numbers provided
print meanList( [ 1 , 2 , 3 ] ) # 2
print meanList( [ 3 , 5 , 2 , 1 , 4 ] ) # 3
# 2
def medList( nums ) :
nums = sorted( nums )
if len( nums ) % 2 == 0 :
return ( nums[ len( nums ) / 2 - 1 ] + nums[ len( nums ) / 2 ] ) / 2.0
# nums[ len( nums ) / 2 - 1 ] is the last number in the first half
# nums[ len( nums ) / 2 ] is the first number in the last half
else :
return nums[ len( nums ) / 2 ]
print medList( [ 4 , 2 , 1 , 3 ] ) # 2.5
print medList( [ 3 , 2 , 5 , 1 , 4 ] ) # 3
# 3
def barGraphify( nums ) :
result = ""
for n in nums :
result += str( nums.index( n )) + ": " + ( n * "=" ) + "\n"
print result
barGraphify( [ 0 , 1 , 2 , 3 ] )
# 0:
# 1: =
# 2: ==
# 3: ===
barGraphify( [ 1 , 0 , 3 , 2 ] )
# 0: =
# 1:
# 2: ===
# 3: ==
|
d8715e45729166f32bc0639dd8ea7915052a6813 | rodrigocruz13/holbertonschool-machine_learning | /unsupervised_learning/0x00-dimensionality_reduction/1-pca.py | 1,332 | 4.125 | 4 | #!/usr/bin/env python3
"""
PCA: principal components analysis
"""
import numpy as np
def pca(X, ndim):
"""
Function that performs PCA on a dataset:
Args:
- X numpy.ndarray Array of shape (n, d) where:
- n (int) number of data points
- d (int) number of dims in each point
Note: All dims have a mean of 0 across all data points
- ndim (int) New dimensionality of the transformed X
Returns: (The weights matrix that maintains var fraction of X‘s
original variance)
T: numpy.ndarray of shape (d, ndim) containing the
transformed version of X
"""
# https://bit.ly/2zH844p
# 1. Normalize
normal = np.mean(X, axis=0)
X_normal = X - normal
# 2. calculate the single value decomposition
# - vh { (…, N, N), (…, K, N) } array
# Unitary array(s). The first a.ndim - 2 dimensions have the same size as
# those of the input a. The size of the last two dimensions depends on the
# value of full_matrices. Only returned when compute_uv is True.
vh = np.linalg.svd(X_normal)[2]
# 3. filter according ndim
Weights_r = vh[: ndim].T
# line 20 of 0-main.py
T = np.matmul(X_normal, Weights_r)
return T
|
1e75ae4cfede74dea1762b30e773243e173d9da2 | 824zzy/Leetcode | /I_Searching/DFS/Tree/404_Sum_of_Left_Leaves.py | 451 | 3.6875 | 4 | """ L0: https://leetcode.com/problems/sum-of-left-leaves/
traverse tree with label that marks left tree
"""
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
def dfs(node, l):
if not node: return 0
if not node.left and not node.right and l:
return node.val
return dfs(node.left, True)+dfs(node.right, False)
return dfs(root, False) |
ae60a6b09d842ce2e02062996367a716f2712234 | 0xVector/AdventOfCode2020 | /day13.py | 874 | 3.578125 | 4 | with open("inputs/day13.txt") as file:
data = [line.strip() for line in file]
def find(ans, bus_value, bus_offset):
while True:
if (ans + bus_offset) % bus_value == 0:
return ans
ans += increment
# Part 1 ===
depart_time = int(data[0])
buses = [int(number) for number in data[1].split(",") if number != "x"]
best_time = 0
for bus in buses:
time_to_wait = abs(depart_time - ((depart_time // bus + 1) * bus))
if time_to_wait < best_time or not best_time:
best_time = time_to_wait
best_bus = bus
part1 = best_bus * best_time
# Part 2 ===
buses = [(int(value), offset) for offset, value in enumerate(data[1].split(",")) if value.isnumeric()]
part2 = buses[0][0]
increment = 1
for bus in buses:
part2 = find(part2, bus[0], bus[1])
increment *= bus[0]
print("Part 1:", part1)
print("Part 2:", part2)
|
bc124e821fbcd8fa585bda7d23ec0d7eb6fd658f | dekaghub/folioprojects | /python-concepts/pretty-python.py | 2,231 | 4.15625 | 4 | # Borrowed from Raymond Hettinger's talk
# https://www.youtube.com/watch?v=OSGv2VnC0go
# Every list is iterable
# simple reverse iteration of for loop
colors = ['red', 'green', 'blue', 'yellow']
for color in reversed(colors):
print(color)
# keep track of indices
for i, color in enumerate(colors):
print(i, '-->', color)
# print multiple lists together
names = ['Jon', 'Kate', 'Defie']
foods = ['cheese', 'sauce', 'chips', 'guac']
# behaves like an inner join i.e. smallest of all the lists
for name, color, food in zip(names, colors, foods):
print(name, ' - ', color, ' - ', food)
# general find function
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
print(find(colors, 'purple'))
print(find(colors, 'yellow'))
# lambda functions
g = lambda x: x**2
print(g(2))
# dictionary
# create dictionary from lists
d = dict(zip(names, colors))
for k,v in d.items():
print(k, ' - ', v)
# Be Explicit with function calls for good readability
# Name the parameters to avoid bouncy reading
def favoriteFood(name, food):
favorite = name + ' ' + food
return favorite
import random
print(favoriteFood(name = names[random.randint(0, len(names)-1)], food = foods[random.randint(0,len(foods)-1)]))
import collections
def test(a,b):
tupleResult = collections.namedtuple('testResult', ['a','b'])
testResult = tupleResult(a,b)
return testResult
t = test(a='first', b='second')
print(t)
# One Line variable inits
a,b,c, = 1,2,3
print('a : ', a,' b : ', b, ' c : ', c)
x = [5,6,7]
a,b,c = x
print('a : ', a,' b : ', b, ' c : ', c)
a,b,c = (a + 10,
b + 20,
c + 30)
print('a : ', a,' b : ', b, ' c : ', c)
# Concatenate strings in linear time
# Avoid quadratic time with + operator
words = ['Combine','this','into','a','sentence']
s = ' '.join(words)
print(s)
s = words[1].join(' ').join(words[4]) # cool single space transform
print(s)
# Use decorators to differentiate Library/User code
def admincode(func):
s = [1,2,3]
def wrapper(a):
print('This is admin level.')
func(a)
return wrapper
@admincode
def usercode(a):
print('this is ', a)
usercode('test') |
dba59ab283f7044f31fea00cac17fec21f3b3559 | adaluong/miscellaneous | /bad_code/names-to-scrabble-value.py | 695 | 3.765625 | 4 | # Calculates the scrabble value associated with a name, given a list of names
# prints names sorted from smallest to largest scrabble value
score = {'E':1,'A':1,'I':1,'O':1,'N':1,'R':1,'T':1,'L':1,'S':1,'U':1,
'D':2,'G':2,
'B':3,'C':3,'M':3,'P':3,
'F':4,'H':4,'V':4,'W':4,'Y':4,
'K':5,'J':8,'X':8,'Q':10,'Z':10,
',':0,' ':0,'-':0}
names = {}
with open('2019_names.txt') as f:
for name in f:
name = name.strip()
total = 0
for letter in name:
total += score[letter]
names[name] = total
sorted_names = sorted(names.items(), key = lambda x: x[1])
for name, value in sorted_names:
print(value, name)
|
d6ea54c8789a9e9e9a3c42e67d81dca1b6cd6544 | Wangzhipeng777/file | /day4/demo01.py | 165 | 3.625 | 4 | if __name__ == '__main__':
num=input("请输入出生日期:")
num1=input("请在输入一个出生日期:")
if num>num1:
print("第一个 ") |
f8b11b382d77f294374cb9da70bcb50825acc34f | snblake/PythonChallenges_HW3 | /Pybank/Pybank.py | 2,784 | 3.71875 | 4 | import csv
import os
all_months = []
profit_loss_change = []
file_path = os.path.join("Resources", "budget_data.csv")
of= open("PybankHW3.txt","w+")
with open(file_path, "r") as f:
reader = csv.reader(f)
next(reader) # skips the header row
first_row = next(reader)
prev_row_value = first_row[1]
ctr = int(prev_row_value) #declare counter variables, list for
month_ctr = 1 #report calculations
all_months.append(first_row[0])
greatest_dec = 0
greatest_dec_mon = first_row[0]
greatest_inc = 0
greatest_inc_mon = first_row[0]
for row in (reader): #read first row, store values for
mon_yr = row[0] #comparison, store PL change for
all_months.append(mon_yr) #calculating change avg
ctr += int(row[1])
month_ctr = month_ctr +1
month_change_val = int(row[1]) - int(prev_row_value)
profit_loss_change.append(int(month_change_val))
if greatest_dec > month_change_val:
greatest_dec = month_change_val
greatest_dec_mon = row[0]
elif greatest_inc < month_change_val:
greatest_inc = month_change_val
greatest_inc_mon = row[0]
#print(f"int({row[1]}) - int({prev_row_value})") - test
prev_row_value = row[1]
avg_rev_change = "{:.2f}".format(sum(profit_loss_change)/len(profit_loss_change))
print(f" ") #print results
print(f"Financial Analysis")
print(f"_" * 25)
print(f" ")
print(f"Total Months: {month_ctr}")
print(f"Total: ${ctr}")
print(f"Average Change: ${avg_rev_change}")
print(f"Greatest Increase In Profits: {greatest_inc_mon} (${greatest_inc})")
print(f"Greatest Decrease in Profits: {greatest_dec_mon} (${greatest_dec})")
of.write("Financial Analysis\n") #write report to file
of.write("_" * 25 + "\n\n")
of.write("Total Months: " + str(month_ctr) + "\n")
of.write("Total: $" + str(ctr) + "\n")
of.write("Average Change: $" + str(avg_rev_change) + "\n")
of.write("Greatest Increase In Profits: " + str(greatest_inc_mon) + " " + "($" + str(greatest_inc) + ")" + "\n")
of.write("Greatest Decrease in Profits: " + str(greatest_dec_mon) + " " + "($" + str(greatest_dec) + ")" + "\n")
of.close
|
6d700a71bf0a4a294ca98e382fb6229f615284fc | a20170117/vechilecontrol | /Vechile.py | 2,002 | 3.53125 | 4 | from Events import *
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif isinstance(self.value, args): # changed for v1.5, see below
self.fall = True
return True
else:
return False
class Vechile:
"""
用于执行控制指令,控制硬件。
不同硬件设备继承本类分别实现。
"""
def event(self, e: Event):
for case in switch(e):
if case(Stop):
self.stop(e)
break
if case(MoveForward):
self.move_forward(e)
break
if case(MoveRight):
self.move_right(e)
break
if case(Turn):
self.turn(e)
break
if case(LookUp):
self.look_up(e)
break
if case(TurnRate):
self.turn_rate(e)
break
if case(LookUpRate):
self.look_up_rate(e)
break
if case():
break
def stop(self, e: Stop):
print("stop: ", e.value)
def move_forward(self, e: MoveForward):
print("move forward: ", e.value)
def move_right(self, e: MoveRight):
print("move right: ", e.value)
def turn(self, e: Turn):
print("turn: ", e.value)
def look_up(self, e: Turn):
print("look up: ", e.value)
def turn_rate(self, e: Turn):
print("turn_rate: ", e.value)
def look_up_rate(self, e: Turn):
print("look up rate: ", e.value)
if __name__ == '__main__':
v = Vechile()
v.event(Stop(0.0))
|
449037799de0c718c4263d4dd9495f0ed345e84d | rishabhranawat/challenge | /leetcode/longest_pre.py | 700 | 3.546875 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
counter = {}
for s in strs:
if(s == ""): return ""
for i in range(0, len(s)+1, 1):
sg = str(s[0:i])
if(sg in counter):
counter[sg] += 1
else:
counter[sg] = 1
m = ""
for pre, count in counter.items():
if(len(pre) > len(m) and counter[pre] == len(strs)):
m = pre
return m
a = Solution()
print(a.longestCommonPrefix(["abv", "ab", "abcd"]))
print(a.longestCommonPrefix(["a"])) |
54bc02075c0136709cec92a93b0743f0d7777579 | langzippkk/msds621 | /projects/linreg/linreg.py | 2,710 | 3.609375 | 4 | import numpy as np
import pandas as pd
from pandas.api.types import is_numeric_dtype
def normalize(X): # creating standard variables here (u-x)/sigma
if isinstance(X, pd.DataFrame):
for c in X.columns:
if is_numeric_dtype(X[c]):
u = np.mean(X[c])
s = np.std(X[c])
X[c] = (X[c] - u) / s
return
for j in range(X.shape[1]):
u = np.mean(X[:,j])
s = np.std(X[:,j])
X[:,j] = (X[:,j] - u) / s
def MSE(X,y,B,lmbda):
pass
def loss_gradient(X, y, B, lmbda):
pass
def loss_ridge(X, y, B, lmbda):
pass
def loss_gradient_ridge(X, y, B, lmbda):
pass
def sigmoid(z):
pass
def log_likelihood(X, y, B,lmbda):
pass
def log_likelihood_gradient(X, y, B, lmbda):
pass
# NOT REQUIRED but to try to implement for fun
def L1_log_likelihood(X, y, B, lmbda):
pass
# NOT REQUIRED but to try to implement for fun
def L1_log_likelihood_gradient(X, y, B, lmbda):
"""
Must compute \beta_0 differently from \beta_i for i=1..p.
\beta_0 is just the usual log-likelihood gradient
# See https://aimotion.blogspot.com/2011/11/machine-learning-with-python-logistic.html
# See https://stackoverflow.com/questions/38853370/matlab-regularized-logistic-regression-how-to-compute-gradient
"""
pass
def minimizer(X, y, loss, loss_gradient,
eta=0.00001, lmbda=0.0,
max_iter=1000, addB0=True,
precision=0.00000001):
"Here are various bits and pieces you might want"
if X.ndim != 2:
raise ValueError("X must be n x p for p features")
n, p = X.shape
if y.shape != (n, 1):
raise ValueError(f"y must be n={n} x 1 not {y.shape}")
if addB0:
pass # add column of 1s to X
B = np.random.random_sample(size=(p, 1)) * 2 - 1 # make between [-1,1)
prev_B = B
cost = 9e99
step = 0
eps = 1e-5 # prevent division by 0
class LinearRegression621:
def __init__(self,
eta=0.00001, lmbda=0.0,
max_iter=1000):
self.eta = eta
self.lmbda = lmbda
self.max_iter = max_iter
def predict(self, X):
n = X.shape[0]
B0 = np.ones(shape=(n, 1))
X = np.hstack([B0, X])
return np.dot(X, self.B)
def fit(self, X, y):
self.B = minimizer(X, y,
MSE,
loss_gradient,
self.eta,
self.lmbda,
self.max_iter)
class RidgeRegression621:
pass
class LogisticRegression621:
pass
# NOT REQUIRED but to try to implement for fun
class LassoLogistic621:
pass
|
aa069327a0e6189997eec002de62bf804200ec2b | lukaspacalon/LIVREDEV | /personnage.py | 1,543 | 3.640625 | 4 | # Bienvenue dans le Livre programmé dont vous êtes le Héro Développeur
# coding:utf-8
# https://trello.com/b/4L1gpwt1/chroniques
# Procédural
class Personnage:
personnages_crees = 0
def __init__(self, c_prenom, c_age, c_race):
self.prenom = c_prenom
self.age = c_age
self.race = c_race
Personnage.personnages_crees +=1
print("Decouverte d'un personnage", self)
def se_deplacer(self, vitesse):
print("{} se déplace {}".format(self.prenom, vitesse))
def parler(self, message):
print("{} a dit : {}".format(self.prenom, message))
class Humain(Personnage):
""" Les humains constituent la race la plus courante du Vieux Monde
et restent les fondateurs de l’Empire. """
class Nain(Personnage):
""" Les humains constituent la race la plus courante du Vieux Monde
et restent les fondateurs de l’Empire. """
class Elfe(Personnage):
""" Les humains constituent la race la plus courante du Vieux Monde
et restent les fondateurs de l’Empire. """
p1 = Personnage("Jojo", 27, "humain")
#print ("prenom de p1 -> {}".format(p1.prenom))
#print ("age de {} -> {} ans".format(p1.prenom, p1.age))
p2 = Personnage("Albert", 32, "nain")
#print ("prenom de p2 -> {}".format(p2.prenom))
#print ("age de {} -> {} ans".format(p2.prenom, p2.age))
p3 = Personnage("Camille", 18, "elfe")
#print ("prenom de p2 -> {}".format(p3.prenom))
#print ("age de {} -> {} ans".format(p3.prenom, p3.age))
#print("Personnage existant : {}".format(Personnage.personnages_crees))
|
e48dc0b29820317e1242be86fd60ea88e5f13355 | Keith-Njagi/python_intro | /functions.py | 2,572 | 4.0625 | 4 | """
Function is a block of coded or statements that perform a certain task and returns a result
"""
def addtwonumbers(x,y): # x,y are parameters, basically variables used in a function
sum = x + y
return sum
s1 = addtwonumbers(2,3) # 2,3 are arguments, basically the values used in place of the parameters
#print(s1)
# create a function that prints out the largest number in a list containing a random range of values: basically sort the list in ascending order then print out the largest number
# create a function that takes a list of numbers. Return the largest number
#hackarack....... website for challenges
# A > 79 , B - 60 to 78, C - 59 to 49, D - 48 to 40, E - less 40
# Task 1
def inputselector():
myinput = input("Please enter a Yes or No: ")
if myinput == "Yes" or myinput == "yes" or myinput == "YES":
return "yes"
elif myinput == "No" or myinput == "no" or myinput == "NO":
return "No"
else:
return "Please ensure your input is a Yes or No"
var_a = inputselector()
print(var_a)
# Task 2
def maxnumber(a, b, c):
if a > b and a >c:
val = a
elif b > a and b > c:
val = b
elif c > a and c > b:
val = c
else:
val = "Please check for two or more equal values"
return val
x = maxnumber(10,10,111)
print(x)
# Task 3
def getfirstandlast(mylist):
if len(mylist)== 1:
new_list = [mylist[0]] # fl = [x[0],x[n-1]]
else:
new_list = [mylist[0], mylist[len(mylist) - 1]]# fl = [x[0],x[n-1]]
return new_list
a = [5, 10, 15, 20, 25]
ret = getfirstandlast(a)
print(ret)
#Task 4
def oddevennumber():
myno = int(input("Please enter a Number: "))
if myno > 0:
if myno%2 == 0 and myno%4 !=0:
result = "This is an even number"
elif myno%2 == 0 and myno%4 ==0:
result = "This is an even number and divisible by 4"
else:
result = "This is an odd number"
else:
result = "You are trying to divide by zero"
return result
a = oddevennumber()
print(a)
#task 5
tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11)
def splitter(mytup):
if mytup == tuple:
ln = int((len(mytup)) / 2)
part_a = (mytup[(0):ln]) # list = [x[0:(length)/2]]
part_b = (mytup[ln:]) # list = [x[(length)/2: ]]
return str(part_a) + '\n' + str(part_b)
else:
return "Please ensure you input more than one number"
print(splitter(tup))
###### OR #####
ln = int((len(tup))/2)
part_a = (tup[(0):ln])
part_b = (tup[ln:])
print(part_a)
print(part_b) |
421b705991802782b78942f88b3dc0169f2fc8c3 | Mrwhitefox/psychic-nemesis | /murinput.py | 315 | 3.96875 | 4 | # -*- coding: utf-8 -*-
import os
from murfinder import *
### USER INPUT
def select_from_list(choices):
if len(choices) == 0:
return None
for i, choice in enumerate(choices):
print(i, choice)
nb = 0-1
while not (0 <= nb < len(choices)):
nb = input("Please choose: ")
nb = int(nb)
return choices[nb] |
ee1de9b2997e20f688d6157c0d02075a5c50661a | PhillippKoch/coursera-py4e | /week4/convertingUserInput.py | 204 | 4 | 4 | # Floor 0 in europe is Floor 1 in US
# Program to convert user input Europe Floor number to US Floor number
euroFloor = input('Europe floor?\n')
usFloor = int(euroFloor) + 1
print('US floor:', usFloor)
|
4f6d45e060d6a317cccf08f7905067fb806e681a | j3r3miah/InterviewPractice | /game_of_life.py | 1,787 | 3.859375 | 4 | from pprint import pprint
def gameOfLife(board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
# 0: dead
# 1: live
# 2: dead->live
# 3: live->dead
def is_live(v):
return v == 1 or v == 3
def count_neighbors(board, i, j):
count = 0
for x in range(i-1, i+2):
for y in range(j-1, j+2):
if x == i and y == j:
continue
if x >= 0 and x < len(board) and y >= 0 and y < len(board[0]):
if is_live(board[x][y]):
count += 1
return count
for i in range(len(board)):
for j in range(len(board[i])):
live_neighbors = count_neighbors(board, i, j)
if is_live(board[i][j]):
if live_neighbors != 2 and live_neighbors != 3:
board[i][j] = 3
else:
if live_neighbors == 3:
board[i][j] = 2
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 2:
board[i][j] = 1
elif board[i][j] == 3:
board[i][j] = 0
if __name__ == '__main__':
N,M = 46,26
board = []
for i in range(N):
board.append([0]*M)
for i in range(0, N, 3):
for j in range(0, M, 3):
board[i][j] = 1
for i in range(5):
for j in range(3):
board[i][j] = 1
print('--- Iteration 0 ------------------------------------------')
pprint(board)
for i in range(100):
gameOfLife(board)
print()
print(f'--- Iteration {i} ------------------------------------------')
pprint(board)
|
cc411a771afa6029d33e289317b1b0e9108bcafa | gitdog01/AlgoPratice | /levels/level_20/4949/main.py | 736 | 3.671875 | 4 | answers = []
while True :
buf = str(input())
if buf == '.' :
break
stack = []
for char in buf :
if char == '(' or char == '[' :
stack.append(char)
elif char == ')' or char == ']' :
if char == ')' :
if len(stack) > 0 and stack[-1] == '(' :
stack.pop()
else :
stack.append(char)
elif char == ']' :
if len(stack) > 0 and stack[-1] == '[' :
stack.pop()
else :
stack.append(char)
if len(stack) == 0 :
answers.append("yes")
else :
answers.append("no")
for answer in answers :
print(answer) |
829d085f43fb5f0a8c7f1067eaca33bdc33709a4 | lobhaum/python | /py2zumbis/vetorInverso.py | 192 | 3.890625 | 4 | i = 0
vetor = []
while i <= 9:
r = int(input('Digite um numero: '))
vetor.append(r)
i += 1
## print('Vetor contem', vetor[::-1])
i = 9
while i >= 0:
print(vetor[i])
i -= 1
|
cbc34284e44cbf39a96b5e4c2c1a1c4d42c64a12 | brockinit/bradfield-algos | /dataStructureImplementation/stackQueue.py | 916 | 4.0625 | 4 | '''
Didn't do anything meaningful here, just followed the walkthrough video.
'''
class Stack:
def __init__(self):
self._items = []
def is_empty(self):
return not bool(self._items)
def push(self, item):
self._items.insert(0, item)
def pop(self):
return self._items.pop(0)
def peek(self):
return self._items[0]
def size(self):
return len(self._items)
class Queue:
def __init__(self):
self._s1 = Stack()
self._s2 = Stack()
def is_empty(self):
return self._s1.is_empty() and self._s2.is_empty()
def size(self):
return self._s1.size() + self._s2.size()
def enqueue(self, item):
self._s1.push(item)
def dequeue(self, item):
if self._s2.is_empty():
while not self._s1.is_empty():
self._s2.push(self._s1.pop())
return self._s2.pop()
|
bef34f4a94299a1e16ad38ce836c1f1c46c91cc8 | Lyndm4200/CTI110 | /P5T2_FeetToInches_MarcLynd.py | 461 | 4.28125 | 4 | # Create a function to be used in a program
# October 11, 2018
# CTI-110 P5T2_FeetToInches
# Marc Anthony Lynd
#
def main():
# Ask user to input feet to be converted
feet = float(input("Please enter the amount of feet you wish to be converted to inches: "))
# Call, format, and print function out to user
print(format(feet_to_inches(feet),",.2f"))
# Function created for conversion
def feet_to_inches(feet):
return feet * 12
main()
|
7416803408200f8398136375fdd157e01ca7f4a4 | victor1ahermn/HerramientasComputacionales | /problema2.py | 372 | 3.640625 | 4 |
#Problema 2
def triangulo(a,b,c):
ptriangulo=(a+b+c)
print(ptriangulo)
return ptriangulo
def cuadrado(x):
pcuadrado=x*4
print(pcuadrado)
return pcuadrado
def rectangulo(a,b):
prectangulo=2*(a+b)
print(prectangulo)
return prectangulo
def circulo(r):
pcirculo=pi*2*r
print(pcirculo)
return pcirculo
|
dced2ff8f7638b7126d6bf035e71d44f564e116a | EchoLLLiu/OtherCodes | /剑指offer/maxInWindows.py | 960 | 3.59375 | 4 | # coding=utf-8
__author__ = 'LY'
__time__ = '2018/7/15'
# 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
# 例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}
class Solution:
def maxInWindows(self, num, size):
if not num or not size or len(num) < size:
return []
# 滑动窗口起始点与终点
start = 0
end = size - 1
res = []
# Max_idx 当前滑动窗口内的最大值下标
Max_idx = 0
while end < len(num):
if start == 0 or Max_idx < start:
Max = max(num[start:end+1])
res.append(Max)
Max_idx = num.index(Max)
elif num[Max_idx] > num[end]:
res.append(Max)
else:
Max = num[end]
res.append(Max)
Max_idx = end
start += 1
end += 1
return res
if __name__ == '__main__':
lst = [2,3,4,2,6,2,5,1]
s = Solution()
print(s.maxInWindows(lst, 3)) |
69f180ea846a26c8de2accc142156033b74a90bc | bearpython/Educational_administration_system | /core/BasicLogic.py | 2,834 | 3.796875 | 4 | #!/usr/bin/env python
#_*_ coding:utf-8 _*_
# Author:bear
import os,sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
class School(object):
'''
基础的学校类,学校信息
提供学员注册、老师入职等功能
'''
def __init__(self,name,addr):
self.name = name
self.addr = addr
self.students = []
self.staffs = []
self.courses = []
self.grades = []
def creat_course(self,course_obj):
self.courses.append(course_obj)
print("您创建了新的课程:%s" %course_obj.name)
def creat_grade(self,grade_obj):
self.grades.append(grade_obj)
print("您创建了新的班级:%s" %grade_obj.name)
def enroll(self,stu_obj):
print("为%s学员办理注册手续" % stu_obj.name)
self.students.append(stu_obj)
def hire(self,staff_obj):
print("雇佣了%s新员工" % staff_obj.name)
self.staffs.append(staff_obj)
class SchoolMember(object):
'''学校里的人,包括老师、学生'''
def __init__(self,name,age,sex,sch_name):
self.name = name
self.age = age
self.sex = sex
self.sch_name = sch_name
def tell(self,name,age,sex,school_id):
pass
class Teacher(SchoolMember):
def __init__(self, name, age, sex,sch_name,salary, course):
super(Teacher, self).__init__(name, age, sex,sch_name)
self.salary = salary
self.course = course
def tell(self):
print("""
---------info of Teacher:%s ---------
Nmae:%s
Age:%s
Sex:%s
School_id:%s
Salary:%s
Course:%s
"""%(self.name,self.name,self.age,self.sex,self.sch_name,self.salary,self.course))
def teach_grade(self,grade):
pass
def students_list(self):
pass
class Students(SchoolMember):
def __init__(self,name,age,sex,sch_name,stu_id,grade,pay_status):
super(Students,self).__init__(name,age,sex,sch_name)
self.stu_id = stu_id
self.grade = grade
self.pay_status = pay_status
def pay_tuition(self,amount):
pass
class Grade(object):
'''班级类,包括班级名称,老师,课程,通过学校进行创建'''
def __init__(self,name,teacher,course):
self.name = name
self.teacher = teacher
self.course = course
class Course(object):
'''课程类,包括学期,价格,通过学校进行创建'''
def __init__(self,name,semester,price,sh_id):
self.name = name
self.semester = semester
self.price = price
self.sh_id = sh_id
# 实例化两个学校对象
school_bj = School("北京教育培训学校","沙河")
school_sh = School("上海教育培训学校","陆家嘴")
|
43531db0c5a54338b829c20b409506fbf978a638 | simdani/Algorithms | /epi/arrays/random_permutation.py | 335 | 3.65625 | 4 | import random
def random_sampling(k, A):
for i in range(k):
r = random.randint(i, len(A) - 1)
A[i], A[r] = A[r], A[i]
def compute_random_permutation(n):
permutation = list(range(n))
random_sampling(n, permutation)
return permutation
if __name__ == "__main__":
print(compute_random_permutation(5)) |
8510d003d5da6cf2e4b8f9bfa3b473ce59f14ade | josefondrej/medical-ide-poc | /dev_utils/parse_drg_catalogue.py | 477 | 3.53125 | 4 | from pandas import read_excel, set_option
set_option("display.max_columns", 20)
set_option("display.width", 500)
catalogue_path = "SwissDRG-Version_10_0_Fallpauschalenkatalog_AV_2021_2021.xlsx"
df = read_excel(catalogue_path, sheet_name="Akutspitäler", skiprows=7)
df = df.iloc[:, [0, 2]]
df.columns = ["code", "text"]
df.set_index("code", inplace=True)
code_to_text = df["text"].to_dict()
code_text = [[key, value] for key, value in code_to_text.items()]
print(code_text)
|
c5db0d00c544f06f0ee8e1b97d12bf29f0b484f0 | Jiezhi/myleetcode | /src/1752-CheckIfArrayIsSortedAndRotated.py | 957 | 3.875 | 4 | #!/usr/bin/env python3
"""
CREATED AT: 2022-11-27
URL: https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/
GITHUB: https://github.com/Jiezhi/myleetcode
FileName: 1752-CheckIfArrayIsSortedAndRotated
Difficulty: Easy
Desc:
Tag:
See:
"""
from tool import *
class Solution:
def check(self, nums: List[int]) -> bool:
"""
Runtime: 77 ms, faster than 14.32%
Memory Usage: 13.9 MB, less than 14.05%
1 <= nums.length <= 100
1 <= nums[i] <= 100
"""
rotated = False
for i, num in enumerate(nums[1:], 1):
if num < nums[i - 1]:
if rotated or nums[0] < nums[-1]:
return False
rotated = True
return True
def test():
assert Solution().check(nums=[3, 4, 5, 1, 2])
assert not Solution().check(nums=[2, 1, 3, 4])
assert Solution().check(nums=[1, 2, 3])
if __name__ == '__main__':
test()
|
929babdf4471add2ee373ef47efd34db744cf6bd | siriwatmoontonglee/folderbeta | /week4.py | 1,101 | 4.03125 | 4 | '''
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are qeual")
else:
print("a is greater than b")
'''
'''x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")'''
price = float(input("ราคาสินค้า : "))
vat = price*7/100
pricevat = vat+price
print("ภาษี 7% = ", vat,"บาท")
print("ราคารวมภาษี = ", pricevat,"บาท")
threeper = pricevat*3/100
fiveper = pricevat*5/100
sevenper = pricevat*7/100
tenper = pricevat*10/100
#--------------------
if price < 1000:
print("ราคาสินค้า : ",pricevat)
elif price < 2000:
print("ราคาสินค้า : ",(pricevat-threeper),"บาท")
elif price < 3000:
print("ราคาสินค้า : ",(pricevat-fiveper),"บาท")
elif price < 5000:
print("ราคาสินค้า : ",(pricevat-sevenper),"บาท")
else:
print("ราคารวมส่วนลดสุทธิ : ",(pricevat-tenper),"บาท") |
994708ea551821304305d9ca4e7f8ac553c3d9eb | dzyounger/python | /iowa/Iowa08printTriangles.py | 2,308 | 3.953125 | 4 | #Programmer: Zhaoyang Dai
#Section: 22C:016:A06
#ID: 00719596
# Two words are neighbors if they differ in exactly on letter.
# This function returns True if a given pair of words are neighbors
def areNeighbors(w1, w2):
count = 0
for i in range(len(w1)):
if w1[i] != w2[i]:
count = count + 1
return count == 1
# The function reads from the file "words.dat" and inserts the words that are read
# into a list. The words are also inserted into a dictionary as keys, with each key
# initialized to have [] as its value.
def readWords(wordList, D):
fin = open("homework8words.dat", "r")
# Loop to read words from the and to insert them in a list
# and in a dictionary
for word in fin:
newWord = word.strip("\n")
wordList.append(newWord)
D[newWord] = []
fin.close()
# Builds the network of words using a dictionary. Two words are connected by an edge in this
# network if they are neighbors of each other, i.e., if they differ from each
# other in exactly one letter.
def buildDictionary(wordList, D):
numPairs = 0
# Nested for loop to generate pairs of words
for i in range(len(wordList)):
for j in range(i+1, len(wordList)):
# Check if the two generated words are neighbors
# if so append word2 to word1's neighbor list and word1 to word2's neighbor list
if areNeighbors(wordList[i], wordList[j]):
D[wordList[i]].append(wordList[j])
D[wordList[j]].append(wordList[i])
# Main program
wordList = []
D = {}
G=[]
readWords(wordList, D)
buildDictionary(wordList, D)
# Open a file "triangle" to write outputs
fout=open("homework8triangle.txt","w")
K=D.items()
# To test if all two-word pairs in the list of the values in dictionary "D" are neighbors
for i in range(len(K)):
for j in range(len(K[i][1])):
for l in range(len(K[i][1])):
if areNeighbors(K[i][1][j],K[i][1][l]):
L=[K[i][0],K[i][1][j],K[i][1][l]]
L.sort()
if L not in G:
G.append(L)
for i in range(len(G)):
# Write outputs
fout.write(G[i][0]+" "+G[i][1]+" "+G[i][2]+"\n")
fout.close()
|
2ea2425f80c2cf1cbdfbc30780b977911dae140f | kayaei/pands-problem-set | /datetime-1.py | 850 | 4.375 | 4 | # Etem Kaya 15-Mar-2019
# Solution to Problem-8.
# File name: "datetime.py".
# Problem-8: Write a program that outputs today’s date and time in the format
# ”Monday, January 10th 2019 at 1:15pm”.
# import datetime module to check the current date.
import datetime as dt
# read the today's full date and time
t_day = dt.datetime.today()
# 'day of month' variable to read day of the month only as integer
d_month = int(t_day.strftime("%d"))
# setup the suffix for the day depending of the day of the month
if d_month in (1, 21, 31):
d_suffix = 'st'
elif d_month in (2, 22):
d_suffix = 'nd'
elif d_month in (3, 23):
d_suffix = 'rd'
else:
d_suffix = 'th'
# print current date and time in the format of "Monday, January 10th 2019 at 1:15pm".
print((t_day.strftime("%A, %B %d"))+d_suffix,(t_day.today().strftime("%Y at %I:%M%p"))) |
bdace17f65f39ae19172a62933b55c29ab0e967a | Dualvic/Python | /Ejercicios navidad/tableroAjedrez.py | 924 | 4.15625 | 4 | '''6. Crea un tablero de ajedrez (matriz 8 x 8).
Los escaques de color negro se representan por un 1 y los de color blanco con un 0.
Muestra por pantalla el contenido de la matriz simulando un tablero de ajedrez.'''
matrix = []
def createMatrix(matrix):
while len(matrix) < 8:
matrix.append(addElement(matrix))
def addElement(matrix):
element = []
position = 0
while len(element) < 9:
if position <= 1:
element.append(1)
position = position + 1
elif position >= 2 and position <= 6:
element.append ("x")
position = position + 1
elif position >= 7:
element.append(0)
position = position + 1
else:
pass
return element
def printMatrix(matrix):
for element in matrix:
print (element)
createMatrix(matrix)
addElement(matrix)
printMatrix(matrix)
|
50b5cc31b0d28ee406c493fd0de9b1e8c867d243 | vikasjoshis001/Python-Course | /13_while_names.py | 196 | 3.859375 | 4 | #while loop
import random
names=[]
x=0
while x<8:
person=input("Enter a Name: ")
names.append(person)
x += 1
any=random.randint(0,7)
print("Random name among you entered is ",names[any])
|
92437dce132544ad4c5e18ae8913282e1566ccb9 | PauloBacelarAndrade/fibonacci | /fibonacci.py | 1,617 | 4.5625 | 5 | """
User type a positive integer number
The script shows the nth-position of that number on the Fibonacci Sequence
e.g. Input '3' returns '2', because the third number in the Fibonacci Sequence is '2'
"""
def ask_for_number():
""" Return the user input """
return input("Type nth number to be searched: ")
def check_number(num_str):
"""
Return True if user input is valid. Otherwise, returns False
User's input is invalid when is not a integer or is negative
"""
try:
return int(num_str) > 0
except ValueError:
return False
def show_error_message():
""" Prints an error message """
print("Invalid input! Try again\n")
def generate_fibonacci_list(nth_number):
""" Generates fibonacci list until the nth-number"""
fibonacci_list = [1, 1]
for _ in range(0, nth_number - 2):
fibonacci_list.append(fibonacci_list[-1] + fibonacci_list[-2])
return fibonacci_list
def get_nth_number(fibonacci_list, nth_number):
""" Get the nth-number from the Fibonacci Sequence """
return fibonacci_list[nth_number - 1]
def show_nth_number(nth, nth_number):
""" Show the Fibonacci Number """
print(f"\n{nth}th position in Fibonacci Sequence is the number {nth_number}\n")
def main():
""" Main function: execute the other functions"""
nth_str = ask_for_number()
if not check_number(nth_str):
show_error_message()
main()
nth = int(nth_str)
fibonacci_list = generate_fibonacci_list(nth)
nth_number = get_nth_number(fibonacci_list, nth)
show_nth_number(nth, nth_number)
# Main
main()
|
1ad1f1c894fc12254a2a0f08529ea6c5b1385a46 | seanszy/GeneFinder | /gene_finder.py | 10,949 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
YOUR HEADER COMMENT HERE
@author: YOUR NAME HERE
"""
import random
from amino_acids import aa, codons, aa_table # you may find these useful
from load import load_seq
dna_earliest = load_seq("./data/X73525.fa") #import DNA
print("Disclaimer: This takes a few minutes to run")
def shuffle_string(s):
"""Shuffles the characters in the input string
NOTE: this is a helper function, you do not
have to modify this in any way """
return ''.join(random.sample(s, len(s)))
# YOU WILL START YOUR IMPLEMENTATION FROM HERE DOWN ###
def get_complement(nucleotide):
""" Returns the complementary nucleotide
nucleotide: a nucleotide (A, C, G, or T) represented as a string
returns: the complementary nucleotide
>>> get_complement('A')
'T'
>>> get_complement('C')
'G'
This creates a test to make sure T is converted to A
>>> get_complement('T')
'A'
This test makes sure that G is converted to C
>>> get_complement('G')
'C'
"""
# TODO: implement this
#switches every character, C to G, G to C, A to T, and T to A
#Each if statement converts a letter to its pair.
if nucleotide == "C":
return("G") #return statements return the opposite dna pair
if nucleotide == "G":
return("C")
if nucleotide == "A":
return("T")
if nucleotide == "T":
return ("A")
def get_reverse_complement(dna):
""" Computes the reverse complementary sequence of DNA for the specfied DNA
sequence
dna: a DNA sequence represented as a string
returns: the reverse complementary DNA sequence represented as a string
>>> get_reverse_complement("ATGCCCGCTTT")
'AAAGCGGGCAT'
>>> get_reverse_complement("CCGCGTTCA")
'TGAACGCGG'
"""
# TODO: implement this
dna_list = list(dna) #converts dna to a list
dna_length = len(dna) #length integer to calculate how long to run while
repetition = len(dna)
reverse = "" #initialize blank string
while (repetition > 0):
dna_index = repetition-1 #takes index starting from end moving backwards
current_letter = dna_list[dna_index] #the letter at the curren index
reverse_letter = get_complement(current_letter) #finds the pair
reverse = reverse + reverse_letter #add current letter to string
repetition = repetition-1 #used as a count to end the loop
return reverse
def rest_of_ORF(dna):
""" Takes a DNA sequence that is assumed to begin with a start
codon and returns the sequence up to but not including the
first in frame stop codon. If there is no in frame stop codon,
returns the whole string.
dna: a DNA sequence
returns: the open reading frame represented as a string
>>> rest_of_ORF("ATGTGAA")
'ATG'
>>> rest_of_ORF("ATGAGATAGG")
'ATGAGA'
This function should return the whole string if there is no stop codon.
The other tests don't include this.
This test checks to make sure this is the case.
>>> rest_of_ORF("ATGATATTCG")
'ATGATATTCG'
"""
# TODO: implement this
length = len(dna) #number of characters in the dna string
dna_list = list(dna)
reach_end = False #boolea which is used to tell the loop to stop
current_index = 0 #keeps track of where in the string it is
while reach_end == False: #while loop used to search for end codons
current_index = current_index + 3
current_dna = dna_list [current_index-3:current_index] #this finds the current codon
#loops exit if stop codon or end of list is reached
if current_dna == ['T', 'A', 'G'] or current_dna == ['T','A','A'] or current_dna == ['T','G','A']:
reach_end = True
if current_index > len(dna):
return (dna)
reach_end = True
rejoin_string = ''.join(dna_list[0:current_index-3]) #converts list of characters into string
return rejoin_string
def find_all_ORFs_oneframe(dna):
""" Finds all non-nested open reading frames in the given DNA
sequence and returns them as a list. This function should
only find ORFs that are in the default frame of the sequence
(i.e. they start on indices that are multiples of 3).
By non-nested we mean that if an ORF occurs entirely within
another ORF, it should not be included in the returned list of ORFs.
dna: a DNA sequence
returns: a list of non-nested ORFs
>>> find_all_ORFs_oneframe("ATGCATGAATGTAGATAGATGTGCCC")
['ATGCATGAATGTAGA', 'ATGTGCCC']
#This test makes sure that if function starts with something other than a start codon, it still works
>>> find_all_ORFs_oneframe("CCCATGTAG")
['ATG']
"""
# TODO: implement this
dna_frames = [] #initialize variable that stores ORFs
length = len(dna)
dna_list = list(dna)
start = False #boolean used to run inner while loop. Changes if the whole strand is searched
current_index = -3
full_dna_boolean = 1
while full_dna_boolean < len(dna): #out while loop which finds multiple ORFs
start = False
input_boolean = False
full_dna_boolean = full_dna_boolean + 1
if len(dna_list[:]) == 0:
full_dna_boolean = len(dna) + 3
while start == False: #inner while loop takes an ORF and adds it dna_frames
current_index = current_index+3 #moves one codon at a time
current_dna = dna_list [current_index:current_index+3]
if current_dna == ['A', 'T', 'G']: #if an ORF is starting it changes a boolean to send that string through rest_of_orf
start = True
input_boolean = True
if current_index > len(dna_list[:])-1: #escapes if no more start codon
return (dna_frames) #returns the ORFs
full_dna_boolean = full_dna_boolean + 10
start = True
rejoin_string = ''.join(dna_list[current_index:])
if input_boolean == True:
newest_dna_frame = rest_of_ORF(rejoin_string) #adds an ORF
else:
break
dna_list = dna_list[current_index+len(newest_dna_frame):] #calculates new dna string without current ORF
dna_frames.append(newest_dna_frame) #adds the ORF to the frame
current_index = -3
find_all_ORFs_oneframe("123ATGTAG123ATG456TAG123")
def find_all_ORFs(dna):
""" Finds all non-nested open reading frames in the given DNA sequence in
all 3 possible frames and returns them as a list. By non-nested we
mean that if an ORF occurs entirely within another ORF and they are
both in the same frame, it should not be included in the returned list
of ORFs.
dna: a DNA sequence
returns: a list of non-nested ORFs
>>> find_all_ORFs("ATGCATGAATGTAG")
['ATGCATGAATGTAG', 'ATGAATGTAG', 'ATG']
This test makes sure that if the dna doesn't start with a start codon, it
still runs
>>> find_all_ORFs("AAAATGCCCTAG")
['ATGCCC']
"""
# TODO: implement this
frame_one = find_all_ORFs_oneframe(dna)
frame_two = find_all_ORFs_oneframe(dna[1:]) #finds frame shifted by 1 steps
frame_three = find_all_ORFs_oneframe(dna[2:]) #finds frame shifted by 2 steps
frame = frame_one+frame_two+frame_three
return frame
def find_all_ORFs_both_strands(dna):
""" Finds all non-nested open reading frames in the given DNA sequence on both
strands.
dna: a DNA sequence
returns: a list of non-nested ORFs
>>> find_all_ORFs_both_strands("ATGCGAATGTAGCATCAAA")
['ATGCGAATG', 'ATGCTACATTCGCAT']
"""
# TODO: implement this
original = find_all_ORFs(dna) #finds ORFS of original
new = get_reverse_complement(dna)
new = find_all_ORFs(new) #finds ORFs of switched
together = original + new #combines them
return together
def longest_ORF(dna):
""" Finds the longest ORF on both strands of the specified DNA and returns it
as a string
>>> longest_ORF("ATGCGAATGTAGCATCAAA")
'ATGCTACATTCGCAT'
"""
# TODO: implement this
dna_list = find_all_ORFs_both_strands(dna)
maximum_index = max(dna_list, key=len) #finds the longest ORF
return maximum_index
def longest_ORF_noncoding(dna, num_trials):
""" Computes the maximum length of the longest ORF over num_trials shuffles
of the specfied DNA sequence
dna: a DNA sequence
num_trials: the number of random shuffles
returns: the maximum length longest ORF """
# TODO: implement this
longest_ORF_shuffle = []
for i in range(num_trials): #shuffles for num_trials
dna = shuffle_string(dna)
maximum_shuffled_dna = longest_ORF(dna) #finds maximum of the current stirng
longest_ORF_shuffle = longest_ORF_shuffle + [maximum_shuffled_dna] #adds the maximum in the strand to a list of maximums in each strand
maximum_index = max(longest_ORF_shuffle, key=len) #finds the index of the longest ORF overall
return len(maximum_index)
def coding_strand_to_AA(dna):
""" Computes the Protein encoded by a sequence of DNA. This function
does not check for start and stop codons (it assumes that the input
DNA sequence represents an protein coding region).
dna: a DNA sequence represented as a string
returns: a string containing the sequence of amino acids encoded by the
the input DNA fragment
>>> coding_strand_to_AA("ATGCGA")
'MR'
>>> coding_strand_to_AA("ATGCCCGCTTT")
'MPA'
"""
# TODO: implement this
count = 0
amino_acids = [] #amino acid empty string
while count < len(dna):
count = count + 3
current_codon = dna[count-3:count] #finds next codon
if len(current_codon) == 3: #if the last codon is not a complete codon it won't break it
amino_acid = aa_table[current_codon] #calculates amino acid from the table
amino_acids = amino_acids + [amino_acid]
rejoin_string = ''.join(amino_acids) #rejoins them
return rejoin_string
def gene_finder(dna):
""" Returns the amino acid sequences that are likely coded by the specified dna
dna: a DNA sequence
returns: a list of all amino acid sequences coded by the sequence dna.
gene_finder("ATGAAACCCTTTGGGTAG")
'AAAA'
"""
# TODO: implement this
threshold = longest_ORF_noncoding(dna, 1500) #find length of maximum ORF
real_dna = []
Aminos = find_all_ORFs_both_strands(dna) #convert DNA to aminos
for ORF in Aminos:
if len(ORF) > threshold:
real_dna = real_dna + [coding_strand_to_AA(ORF)] #converts ORF to amino and adds to list
print("threshold",threshold)
print(real_dna)
return real_dna
gene_finder(dna_earliest)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.