blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a5c38b65f7450f72e062fb15a553e0fdb873ad58 | AP-Skill-Development-Corporation/SRIT-Python-Workshop_-31-05-2021-to-12-06-2021- | /lambda-fn-examples.py | 922 | 4.1875 | 4 | ''' lambda fun- An anonymous function means function without name
It can take any no.of arguments at a time but contain only single expression
used to return fun objects
restricted to only single exp.
syntax:lambda arg(s): exp
rem= lambda num:num%2
print(rem(9))
num=int(input())
print("remainder is ",rem(num))
sq=lambda x:x**2
print(sq(int(input())))
product=lambda x,y:x*y
print(product(2,3))
quotient=lambda x,y:x/y
print(quotient(9,5))
def test_fun(num):
return lambda x:x*num
res=test_fun(20)
res2=test_fun(int(input("enter first number:")))
print("result is ",res(5))
print("2nd result is ",res2(int(input("enter second number:"))))
num_li=[8,11,23,8,4,5,10,34,3]
filtered_list = list(filter(lambda num: (num > 7), num_li))
print(filtered_list) '''
num_li=[8,11,23,8,4,5,10,34,3]
even_list=list(map(lambda num:num%2,num_li))
print(even_list)
|
3f5a2a6a7799d9aa62c4fd4df133ffc96e0a6deb | billgoo/LeetCode_Solution | /Top Interview Questions/146. LRU Cache.py | 782 | 3.671875 | 4 |
class LRUCache:
def __init__(self, capacity: 'int'):
self.capacity = capacity
self.hashmap = dict()
def get(self, key: 'int') -> 'int':
if key not in self.hashmap:
return -1
else:
self.hashmap[key] = self.hashmap.pop(key)
return self.hashmap[key]
def put(self, key: 'int', value: 'int') -> 'None':
if key in self.hashmap:
self.hashmap.pop(key)
else:
if len(self.hashmap) == self.capacity:
self.hashmap.pop(list(self.hashmap.keys())[0])
self.hashmap[key] = value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value) |
a9679cfdeb41f3a5afa1ecc834030c96e99c3e5e | globalize9/mfe2020 | /timedelta.py | 596 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 21 14:55:29 2019
@author: yushi
"""
import math
import os
import random
import re
import sys
import datetime as dt
# Complete the time_delta function below.
def time_delta(t1, t2):
t1aa = dt.datetime.strptime(t1, '%a %d %B %Y %H:%M:%S %z')
t2aa = dt.datetime.strptime(t2, '%a %d %B %Y %H:%M:%S %z')
return(int(abs((t1aa-t2aa).total_seconds())))
t = int(input())
secondsArr = [None] * t
for t_itr in range(t):
t1 = input()
t2 = input()
secondsArr[t_itr] = time_delta(t1,t2)
print(secondsArr[t_itr]) |
c9e17382c139b97f5f578cb9a548e784b272a0f2 | OneChoose/python | /start/disct_method.py | 151 | 3.5625 | 4 |
new_list = ["bobby1", "bobby2"]
new_dict = dict.fromkeys(new_list, {"company":"immmm"})
for key, value in new_dict.items():
print(key,value) |
fb027dd407a92b38c0de5ac211b6e00e501d091d | SimonFans/LeetCode | /Array/L56_merge interval.py | 1,070 | 4.15625 | 4 | Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
<1> sort by first element in each interval say as x[0]
<2> if result list is empty or previous interval end < next interval start,
append current interval to the result list
else which means they ovelapped each other, we will select the max(previous.end,next.end)
then update the previous end with max value
"""
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x:x[0])
merge_res=[]
for interval in intervals:
if len(merge_res)==0 or merge_res[-1][1]<interval[0]:
merge_res.append(interval)
else:
merge_res[-1][1]=max(merge_res[-1][1],interval[1])
return merge_res
|
c352aaa6deb28fc9e85e95c859a9f49462f70869 | IvAlyosha/Python_Ivanov_main | /Основы Python/dz4.4.py | 602 | 3.671875 | 4 | person_1 = {
'name': 'Elf',
'health': 100,
'damage': 50,
'armor': 4
}
person_2 = {
'name': 'orc',
'health': 120,
'damage': 80,
'armor': 1.1
}
print(f'{person_1["name"]} {person_1["health"]}, {person_2["name"]} {person_2["health"]}')
def defence(defence, damage):
return damage / defence
def attack(defen, agr):
defen["health"] -= defence(defen["armor"], agr["damage"])
return defen
person_1 = attack(person_1, person_2)
person_2 = attack(person_2, person_1)
print(f'{person_1["name"]} {person_1["health"]}, {person_2["name"]} {person_2["health"]}')
|
a9c90a67cec243f825a195a472d896ac3148f42e | salvador-dali/algorithms_general | /interview_bits/level_6/06_dp/04_matrix_dp/05_max-rectangle-in-binary-matrix.py | 777 | 3.65625 | 4 | # https://www.interviewbit.com/problems/max-rectangle-in-binary-matrix/
def largest_rect(arr):
stack, maximum, pos = [], 0, 0
for pos, height in enumerate(arr):
start = pos
while True:
if not stack or stack[-1][1] < height:
stack.append((start, height))
break
maximum = max(maximum, stack[-1][1] * (pos - stack[-1][0]))
start, _ = stack.pop()
pos += 1
for start, height in stack:
maximum = max(maximum, height * (pos - start))
return maximum
def largest_matrix(arr):
for i in xrange(1, len(arr)):
for j in xrange(len(arr[0])):
if arr[i][j]:
arr[i][j] = 1 + arr[i - 1][j]
return max(largest_rect(i) for i in arr)
|
dbd1d0663d153bddb455880734443fb2952ac0b1 | MerlYanez13/c98 | /swap.py | 284 | 3.75 | 4 | def swap():
file1=input("please enter first file: ")
file2=input("please enter second file: ")
a=open(file1,'r')
data1=a.read()
b=open(file2,'r')
data2=b.read()
a=open(file1,'w')
a.write(data2)
b=open(file2,'w')
b.write(data1)
swap() |
dd62c31a15bedad609aa7c5dbb64649708c8252e | ElizabethRoots/python_practice | /jupyter_practice/create_and_run_cells.py | 1,237 | 4.0625 | 4 | # Practicing Jupyter
welcome_message = 'Hello, Jupyter'
first_cell = True
if first_cell == True:
print(welcome_message)
result = 1200/5
second_cell = True
if second_cell == True:
print(result)
# -----------------------------
'''
Ctrl + Enter: run selected cell
Shift + Enter: run cell, select below
Alt + Enter: run cell, insert below
Up: select cell above
Down: select cell below
Enter: enter edit mode
A: insert cell above
B: insert cell below
D, D (press D twice): delete selected cell
Z: undo cell deletion
S: save and checkpoint
Y: convert to code cell
M: convert to Markdown cell (we'll talk about Markdown cells later in this lesson)
Some of the most useful keyboard shortcuts we can use in edit mode include the following:
Ctrl + Enter: run selected cell
Shift + Enter: run cell, select below
Alt + Enter: run cell, insert below
Up: move cursor up
Down: move cursor down
Esc: enter command mode
Ctrl + A: select all
Ctrl + Z: undo
Ctrl + Y: redo
Ctrl + S: save and checkpoint
Tab: indent or code completion
Shift + Tab: tooltip (for instance, if you press Shift + Tab while the cursor is within the parentheses of a built-in function, a tooltip with documentation will pop up)
'''
# -----------------------------
|
ba4aeff2c6ec66b5b865ddb5d57b8d3deb86fea3 | QuincyWork/AllCodes | /Python/Codes/Practice/LeetCode/211 Add and Search Word - Data structure design.py | 1,913 | 3.9375 | 4 |
# define const variable
_MAX_LETTER_SIZE = 27;
_STRING_END_TAG = '#';
class TireNode(object):
def __init__(self,x):
self.value = x
self.childNodes = {}
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TireNode(0)
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
word = word + _STRING_END_TAG
currentNode = self.root
childNode = None
for value in word:
childNode = currentNode.childNodes.get(value)
if not childNode:
childNode = TireNode(value)
currentNode.childNodes[value] = childNode
currentNode = childNode
def __searchChild(self,node,value):
currentNode = node
if not value:
return True
result = False
if value[0] == '.':
for key,child in currentNode.childNodes.items():
if self.__searchChild(child,value[1:]):
result = True
break
else:
child = currentNode.childNodes.get(value[0])
if child:
result = self.__searchChild(child,value[1:])
return result
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
word = word + _STRING_END_TAG
return self.__searchChild(self.root, word)
if __name__ == '__main__':
d = WordDictionary()
d.addWord("bad")
d.addWord("dad")
d.addWord("mad")
print(d.search("bad"))
print(d.search("pad"))
print(d.search(".ad"))
print(d.search("b.."))
|
f660be1425aacda6f26ae4197bbe8a1c7367dcd3 | gabriellaec/desoft-analise-exercicios | /backup/user_257/ch25_2020_09_30_12_37_34_054037.py | 235 | 3.65625 | 4 | import math
v = float(input(" Qual a velocidade? "))
a = math.radians(float(input("Qual o angulo? ")))
g = 9.8
d=(v*v math.sin(2*a/g)
if d < 98:
print("Muito perto")
elif d > 102:
print("Muito longe")
else:
print("Acertou!")
|
4318f101afa3e5b77e7086e2fc08668bbd6b330b | cfleur/MazeNav | /Maze0.py | 1,778 | 3.765625 | 4 | #!/usr/bin/python
import random
def randObsticals(blockedCells, grid):
i = 0
while i < blockedCells:
for y in range(len(grid)):
for x in range(len(grid[y])):
rx = random.randint(0, len(grid[y]))
ry = random.randint(0, len(grid))
if y == ry:
if x == rx:
if grid[y][x] != "x":
grid[y][x] = "x"
i += 1
if i >= blockedCells:
return
def printGrid(grid):
for y in range(len(grid)):
for x in range(len(grid[y])):
print(grid[y][x], " ", end='')
print()
def gridSpace(xAxis, yAxis, blockedCells):
grid = [["o" for x in range(xAxis)] for y in range(yAxis)]
randObsticals(blockedCells, grid)
return grid
def StartEnd(grid): # get start point and end point
print ('Enter coordinates of starting point in the form "column row" (top left is 0 0)')
s = input('> ')
s = str.split(s)
for i in range(len(s)):
s[i] = int(s[i])
print ('Enter coordinates of ending point in the form "column row" (top left is 0 0)')
e = input('> ')
e = str.split(e)
for i in range(len(e)):
e[i] = int(e[i])
print(e,s)
grid[s[1]][s[0]] = 's'
grid[e[1]][e[0]] = 'e'
return grid
def main():
x = int(input("Enter number of columns (x axis): "))
y = int(input("Enter number of rows (y axis): "))
blockedCells = int(input("Enter number of cells to be blocked: "))
grid = gridSpace(x,y,blockedCells) # x, y, num of blocked cells (random position)
printGrid(grid)
gridSE = StartEnd(grid)
printGrid(gridSE)
if __name__ == "__main__": main()
|
172e39e4b88d1cf2d46f31e532cc1bad1d05cbfc | kmlsim/30DaysOfCode-Python | /day6.py | 871 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
testCase = int(raw_input())
if (testCase >= 1 and testCase <= 10):
loop = 0
while (loop < testCase):
# informa uma string para ser testada.
string = (raw_input())
# verifica se a string obedece uma das constraints
strSize = len(string)
if ( strSize >= 2 and strSize <= 10000):
even = []
odd = []
for i in range(0, strSize):
if (i % 2 == 0):
char = string[i]
even.append(char)
else:
char = string[i]
odd.append(char)
print ''.join(even) + " " + ''.join(odd)
else:
print "String lenght out of size."
loop = loop + 1
else:
print "Number of test cases is out of range."
|
04fbd6af93d9d8a504230a3679e2a7c52c929ab1 | GauravSharma531/DS_ALGO_BOOTCAMP | /01_getting_started/CommonElements/CommonElements.py | 1,020 | 3.8125 | 4 | from random import randint
class CommonElements:
size = 0
arr1 = []
arr2 = []
def init(self):
print("Size of arrays")
# take input from console
self.size = int(input())
print(self.size)
# Initialize two same size array and asign some random values
self.arr1 = [randint(0,100)for i in range(0,self.size)]
self.arr2 = [randint(0,100)for i in range(0,self.size)]
# Basic Thinking : iterate every element in first array and check in second array if element exists.
def findCommonElementSolution1(self,arr1,arr2):
numberOfCommenElements = 0
for i in range(0,self.size):
for j in range(0,self.size):
if arr1[i]==arr2[j]:
numberOfCommenElements+=1
break
return numberOfCommenElements
obj = CommonElements()
obj.init()
commonElements = obj.findCommonElementSolution1(obj.arr1,obj.arr2)
print("Total comman elements are %d" %(commonElements))
|
6f98a56dd52d5ad54ca52d6046a8022e8bd197df | startFromBottom/programmers_problems_renewal | /coding test practice/Full Search/소수 찾기.py | 768 | 4.1875 | 4 | """
problem link : https://programmers.co.kr/learn/courses/30/lessons/42839?language=python3
"""
import math
from typing import List
from itertools import permutations
def is_prime_number(n: int) -> bool:
if n == 1 or n % 2 == 0:
return False
k = math.sqrt(n)
i = 3
while i <= k:
if n % i == 0:
return False
i += 2
return True
def all_permutations(numbers: str) -> List[int]:
N = len(numbers)
res = []
for i in range(1, N + 1):
case = list((map(lambda x: int("".join(x)), list(permutations(numbers, i)))))
res.extend(case)
return list(set(res))
def solution(numbers):
all_cases = all_permutations(numbers)
return len([n for n in all_cases if is_prime_number(n)])
|
9c70e9f7e9fb171752a67d909b5f96762fee9ec2 | TangDL/python100days | /leetcode/isMatch.py | 437 | 3.578125 | 4 | class Solution:
def isMatch(self, s: str, p: str):
if not p: return not s
firstmatch = len(s)>=1 and (s[0]==p[0] or p[0]=='.')
if len(p)>=2 and p[1] == '*':
return self.isMatch(s, p[2:]) or (firstmatch and self.isMatch(s[1:], p))
else:
return firstmatch and self.isMatch(s[1:], p[1:])
if __name__=="__main__":
s = Solution()
res = s.isMatch('aaaa', '.*')
print(res) |
e2b836f5351599909a45e9d67d5b3f44009587c8 | companyabab/Dhanu | /fib.py | 339 | 3.515625 | 4 | import datetime
mydate = datetime.date(1943,3, 13) #year, month, day
print (mydate.strftime("%A"))
print ("dhanu")
print ("auto triggring this time")
print ("lets try this time")
print ("one more time ")
print ("success")
print ("CI CD")
print ("testing")
print ("test1")
print ("testing slack")
print ("testing")
print ("hello")
|
4431bc1ff29c1756cadfe72deb800d517b0dc6c5 | vinaysannaiah/Python- | /Simple/Write_to_File.py | 936 | 4.65625 | 5 | # This code is about how to write to a file:
#there are many ways:
#To replace the existing lines in the File
#to append the lines in the file
# Write to a file: Rewrite the existing lines
text = "Writing to a file"
#Create a file if there is none or use the existing file.
#The file can be of any format
saveFile = open("sample.txt", "w") # "w" - to write to a file
saveFile.write(text) # write the text into the file
saveFile.close() # close the file
# Appending to a file: Append the new lines
text = "appending to a file"
#Create a file if there is none or use the existing file - here we use the existing file.
#The file can be of any format
saveFile = open("sample.txt", "a") # "a" - to append to a file
#It literally places the new entry next to its previous entry to avoid this we can write a new line in between:
saveFile.write('\n')
saveFile.write(text) # write the text into the file
saveFile.close() # close the file
|
41403e637d790297d3fc1045af4b7f33e4acf3be | Vital-Fernandez/vital_tests | /security_checks/pandas_saving_txt.py | 416 | 3.96875 | 4 |
import pandas as pd
from pandas_indexing import modifying_df, XY
# Initialize data of lists
data = [{'a':4, 'b': 2, 'c': 3}, {'a': 10, 'b': 20, 'c': 30}]
# Creates pandas DataFrame by passing
df = pd.DataFrame(data, index=['first', 'second'])
print(df)
modifying_df(df)
print(df)
x, y = None, 1
my_values = XY(x, y)
print(my_values.x, my_values.y)
my_values.swap()
print(my_values.x, my_values.y)
print(x, y)
|
63ad64496277f084a53971581d97cf584ad21d5c | weih201/code-repos | /python repo/Mapreduce/join.py | 723 | 3.625 | 4 | import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: id
mr.emit_intermediate(record[1], record)
def reducer(key, list_of_record):
# key: id
# value: list of record
order=()
for elem in list_of_record:
if elem[0]== "order":
order = elem
break
for elem in list_of_record:
if elem[0]== "line_item":
mr.emit(order+elem)
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
6af7ebbac45dbc01feb2c313b898b716a81d888a | subham1994/Algorithms | /Graphs/connectivity.py | 1,172 | 3.984375 | 4 | from Graphs.graph_builder import build_undirected_graph
'''
connectivity in undirected graphs
- Vertices V and W are connected if there is a path between them.
- Preprocess graph to answer queries of the form `is V connected to w` in constant.
- `is connected to` relation is an Equivalence relation(Reflexive, Symmetric, Transitive).
'''
ids = {}
def connected(u, v):
return ids.get(u) == ids.get(v)
def dfs(source, count):
source.color = 'gray'
ids[source] = count
for neighbour in source.connections():
if neighbour.color == 'white':
neighbour.parent = source
dfs(neighbour, count)
source.color = 'black'
def main():
graph, _ = build_undirected_graph()
for index, vertex in enumerate(graph):
if vertex.color == 'white':
dfs(vertex, index)
assert connected(graph.get_vertex('u'), graph.get_vertex('x'))
assert connected(graph.get_vertex('u'), graph.get_vertex('v'))
assert connected(graph.get_vertex('v'), graph.get_vertex('u'))
assert connected(graph.get_vertex('w'), graph.get_vertex('z'))
assert not connected(graph.get_vertex('u'), graph.get_vertex('w'))
print('all test cases passed')
if __name__ == '__main__':
main()
|
3b8aa06942b7e1b01a10315ed6d12f51e9553378 | Yao-9/LeetCode150 | /Python/stringMani/lengthOfLastWord.py | 236 | 3.578125 | 4 | class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
l_split = s.split()
if not l_split:
return 0
else:
return len(l_split[-1])
A = Solution()
print A.lengthOfLastWord(" ")
|
6800825a0ee932fc8ac3c8461a1b1e9cd8995cf2 | germandouce/Computacion | /Exámenes/Parcialito 3.2 4-12-20 Estructuras de datos simples 2.py | 1,633 | 3.78125 | 4 | '''Realizar un programa en PYTHON que permita generar aleatoriamente 20 números pares entre
0 y 100 y determinar cuántos vinieron repetidos (se considera repetición desde la
segunda aparición del número en adelante), cuántos fueron por debajo del número 50;
cuántos mayores o iguales a 50 (estos últimos incluyendo repeticiones) . Mostrar
todos los números ingresados sin repeticiones.
Ej:
Números generados internamente: (32,0,34,2,92,68,38,4,74,58,76,8,78,92,46,20,24,92,58,28)
Salida:
Cantidad repetidos: 3
Números generados debajo de 50: 11
Arriba o igual a 50: 9'''
#ojo, numtot tiene solo los pares NO RPETEIDOS. casi nunca tiene 20...
#opcion 1
'''
import random #comentado altenativa
numtot=set()
repe=0
sup50=0
inf50=0 #omitir
for i in range(20):
num=random.randint(0,100)
num=num//2*2
if num in numtot:
repe+=1
if num>=50:
sup50+=1
else: #omitir
inf50+=1 #omitir
numtot.add(num)
print('cantidad de repetidos: ',repe)
print('arriba de 50:', sup50)
print('debajo de 50:', inf50) #20-sup50
print('mumeros generados:')
for numeros in numtot:
print(numeros)'''
#opcion 2
from random import choice
numeros=set()
sub=0
for i in range(20):
n=choice(range(0,101,2))
if n<50:
sub+=1
numeros.add(n)
print('Cantidad repetidos',20 - len(numeros)) #TOTAL GENERADOS (20) MENOS los que estan en
print('Números generados') #numeros, que al ser un conjunto, son los NO REPETIDOS.
for n in numeros: #= REPETIDOS
print(n)
print('debajo de 50',sub)
print('Arriba o igual a 50',20-sub)
exit()
|
9de69d1312d7d5c638086613345931084b173328 | kaashdesai1/Data-Structures | /A3/bst.py | 2,326 | 3.96875 | 4 | #!/usr/bin/python
import random
#Node for tree
class Node:
def __init__(self, x):
self.element = x
self.leftchild = None
self.rightchild = None
class Dictionary:
def __init__(self):
self.root = Node(None)
#to count number of nodes to a node
self.path = 0
def INSERT(self, x):
if self.root == None:
self.root = Node(x)
else:
#CAll helper function
self.INSERT_NODE(self.root, x)
#Helper function to evaluate insertion
def INSERT_NODE(self, current, x):
if x <= current.element:
if current.leftchild == None:
current.leftchild = Node(x)
else:
self.INSERT_NODE(current.leftchild, x)
elif x > current.element:
if current.rightchild == None:
current.rightchild = Node(x)
else:
self.INSERT_NODE(current.rightchild, x)
def MEMBER(self, x):
#Call helper function
return self.FIND_NODE(self.root, x)
#Helper function to find member
def FIND_NODE(self, current, x):
#Later we will ned to -2 from path to exclude root and final node
self.path = self.path + 1
if current == None:
return False
elif x == current.element:
return True
elif x < current.element:
return self.FIND_NODE(current.leftchild, x)
else:
return self.FIND_NODE(current.rightchild, x)
def PRINT_PATH(self):
#path -2 because we exclude root and node itself from calculation
return self.path - 2
def main():
f = open('bst.txt','w')
f.write("Log 2 of 99 is 6.6. Below is average of node visited: \n\n")
tries = 1
for t in range(0,6):
f.write("n = 99 iteratirons = " + str(tries*1000) + "\n")
sum = 0.00
for j in range(0,tries*1000):
tree = Dictionary()
rand_int = random.sample(xrange(1,100),99)
for i in rand_int:
tree.INSERT(i)
if tree.MEMBER(random.randint(1,50)) != False:
sum = sum + tree.PRINT_PATH()
f.write("Average node visited = " + str(sum/(tries*1000)) + "\n")
tries = tries + 1
f.close()
main()
|
abc704d0fd64f84192510f8e87b8b967d8217adf | thevur0/Python | /Practice/DataStruct.py | 1,801 | 3.828125 | 4 | edward = ['Edward Gumby', 42]
print (edward)
john = ['John Smith', 50]
database = [edward, john]
print(database)
#索引
greeting = 'Hello'
print(greeting[0], greeting[-1])
#切片
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
print(months[3:5]) # ['April', 'May']
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[7:10]) # [8, 9, 10]
print(numbers[-3:-1]) # [8, 9]
print(numbers[-3:0]) # []
print(numbers[-3:]) # [8, 9, 10]
print(numbers[:3]) # [1, 2, 3]
print(numbers[:]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[0:10:1]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[0:10:2]) # [1, 3, 5, 7, 9]
print(numbers[::4]) # [1, 5, 9]
print(numbers[8:3:-1]) # [9, 8, 7, 6, 5]
print(numbers[::-2]) # [10, 8, 6, 4, 2]
print([1, 2, 3] + [4, 5, 6]) # [1, 2, 3, 4, 5, 6]
print([1, 2, 3] + ['World']) # [1, 2, 3, 'World']
print([1, 2, 3]*3) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
print([None] * 10) # [None, None, None, None, None, None, None, None, None, None]
print(1 in [1, 2, 3])# True
print([1, 2] in [1, 2, 3]) # False
print([1, 2] in [1, [1, 2], 3]) # True
numbers = [100, 34, 678]
print(len(numbers),max(numbers),min(numbers))
numbers.append(51)
numbers.remove(100)
numbers[0] = 10
del numbers[1]
numbers.extend([1,2,3])
numbers.pop()
print(numbers)
name = list('Hello')
name[len(name):] = ' World'
print(name)
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
numbers.insert(0,0)
numbers.append(9)
numbers.append(10)
numbers.pop()
numbers[0:4:1] = []
print(numbers, numbers.index(7))
x = [4, 6, 2, 1, 7, 9]
y = sorted(x)
print(y)
print(x)
x.sort()
x.reverse()
print(x)
print((1,2,3))
print(3 * (40 + 2,))
print(tuple([1, 2, 3]))
x = 1, 2, 3
print(x[1],x[0:2]) |
25519e2ec15e3633a406009d1a2805950d0f3873 | Gfuqiang/obj | /compute/sort/mergesort.py | 1,235 | 3.90625 | 4 | """
归并排序:
分治思想
https://mp.weixin.qq.com/s/YY63D6ZkC4Jhon2H6-ZAKw
https://www.cnblogs.com/shierlou-123/p/11310040.html
"""
def merge_sor(list_data: list) -> list:
# 将列表拆分为只有一个元素
if len(list_data) <= 1:
return list_data
meddle = len(list_data) // 2
# 这里递归将列表一分为2,直到无法继续分割
left_list = merge_sor(list_data[:meddle])
right_list = merge_sor(list_data[meddle:])
return merge_list(left_list, right_list)
def merge_list(left_list, right_list):
result_list = []
j = h = 0
# 判断索引不能越界
while j < len(left_list) and h < len(right_list):
if left_list[j] < right_list[h]:
result_list.append(left_list[j])
j += 1
else:
result_list.append(right_list[h])
h += 1
# 判断其中一个列表为空时,将另一列表中元素全部加入新列表
if len(left_list) == j:
result_list.extend(right_list[h:])
else:
result_list.extend(left_list[j:])
return result_list
if __name__ == '__main__':
list_data = [1, 3, 7, 4, 2, 8, 9]
result_list = merge_sor(list_data)
print(result_list) |
fa5dba2ea418df59a20c12ffd2e1d5a2881f37eb | abhishekdesai1990/python-oops | /oop4-class-inheritance.py | 1,588 | 3.578125 | 4 | class Employee:
hike_percent = 0.4 # This is a class variable and can be shared acrross all the instance
def __init__(self, first, last, pay):
self.first = first #this are instance variables
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
#always pass self(Instance) in regular method
def fullname(self):
return self.first + ' ' + self.last
def pay_hike(self):
return self.pay * self.hike_percent #we should always use self in place of Employee thus we can set hike seperate;y for each instance
# This is class method and can be used as additional constructor to class.
@classmethod
def takes_param_in_hyphen(cls, in_str):
fname, lname, pay = in_str.split('_')
return cls(fname,lname,int(pay))
@classmethod
def takes_param_in_slash(cls, in_str):
fname, lname, pay = in_str.split('/')
return cls(fname,lname,int(pay))
#Static method does not need cls or self to be passed, but it does logical work of class
@staticmethod
def is_working(date):
if date.weekday() == 6 or date.weekday() == 7:
return False
return True
class Developer(Employee):
def __init__(self, first, last, pay, specialization):
super().__init__(first, last, pay)
self.specialization = specialization
#Not need to pass instance(), as it will take automatically
emp_1 = Developer('John', 'Doe', 50000, 'javascript')
emp_2 = Developer('Stephin', 'Hill', 60000 , 'python')
print(emp_1.fullname()) |
194d8baac99a81715d8b835f0383a329749f5a03 | paulsavoie/wikiwsd | /wsd/wikipedia/wikipediapreprocessor.py | 12,560 | 3.71875 | 4 | import threading
import Queue
import logging
WAIT_QUEUE_TIMEOUT = 2 # in seconds
class WikipediaPreProcessor(threading.Thread):
'''The WikipediaPreProcessor class preprocesses text and removes tags, unnecessary links and
other information and keeps the text only
'''
'''constructor
@param input_queue if the preprocessor is used as a thread, articles are read from this queue [optional]
@param output_queue if the preprocessor is used as a thread, articles are written to this queue [optional]
'''
def __init__(self, input_queue=None, output_queue=None):
threading.Thread.__init__(self)
self._input_queue = input_queue
self._output_queue = output_queue
self._end = False
self._REMOVE_PAIRS=(
(u'{{', u'}}'),
(u'=====', u'====='),
(u'====', u'===='),
(u'===', u'==='),
(u'==', u'=='),
(u'[http', u']'),
(u'[File:', u']'),
(u'[Category:', u']')
)
# html tags can end with /> or </tag-name> and needs to be handled separately
# <!-- --> comments also as they can spread multiple lines
'''processes a single article and cleans the text
@param article a dictionary with a text field that contains the text (will be modified to hold the new text)
@return the article with clean text only containing valid links
'''
def process(self, article):
new_text = ''
next_line_starts_in_comment = False
line_starts_in_comment = False
next_line_in_tag = 0
line_in_tag = 0
html_tags = []
# iterate over lines
lines = article['text'].strip().split('\n')
for line in lines:
line = line.strip()
# reset html tags if an empty line (probably one was not properly closed somewhere)
if len(line) == 0:
html_tags = []
# STEP 1 - remove hyphens and restore tags
line = line.replace("'''", "")
line = line.replace("''", "")
line = line.replace('<', '<')
line = line.replace('>', '>')
# keep <sub> and <sup> tags if preceeded by uppercase letter (chemical element)
index = 1
while line.find('<sub>', index) != -1:
index = line.find('<sub>', index)+5
letter_before = line[index-6]
end = line.find('</sub>', index)
content = line[index:end]
# check if content is numeric and letter is uppercase
if content.isdigit() and letter_before == letter_before.upper():
line = line[:index-5] + content + line[end+6:]
index = index-5
# check if the line starts in a comment
line_starts_in_comment = next_line_starts_in_comment
next_line_starts_in_comment = False
# check if the line starts in a tag
line_in_tag = next_line_in_tag
next_line_in_tag = 0
# STEP 2 - remove comments
while line.find('<!--') != -1 or line_starts_in_comment:
start = 0
if not line_starts_in_comment:
start = line.find('<!--')
line_starts_in_comment = False
end = line.find('-->')
if end == -1:
next_line_starts_in_comment = True
line = line[0:start]
else:
# a problem occurred, just ignore the line
if start > end:
line = ''
else:
line = line[0:start] + line[end+3:]
# STEP 3 - remove html tags
index = 0
outer_start_tag = line.find('<')
# if the line already starts within an html tag
if len(html_tags) != 0:
outer_start_tag = 0
while line.find('<', index) != -1:
start = False
index = line.find('<', index)+1
# if the tag is the last sign in the line, just remove it
if index == len(line):
line = line[:-1]
else:
end_tag = line.find('>', index)
if end_tag == -1:
line = line[:line.find('<', index)]
else:
# if tag is a closing tag
if line[index] == '/':
# this query is necessary as some invalid close tags appear on wikipedia - nothging to be done about that
if len(html_tags) != 0:
html_tags.pop()
# this is the outermost html tag
if len(html_tags) == 0:
line = line[:outer_start_tag] + line[end_tag+1:]
# start with next tag
outer_start_tag = line.find('<')
index = 0
# not a closing tag
else:
# a simple tag without an ending one, just remove it
if line[end_tag-1] == '/':
line = line[0:index-1] + line[end_tag+1:]
index-= 1
# if this was the outermost tag, start from the next tag
if index == outer_start_tag:
outer_start_tag = line.find('<')
# a normal tag is simply pushed to the stack
else:
tag_name = line[index:end_tag]
# ignore unclean br tags
if tag_name != 'br':
html_tags.append(line[index:end_tag])
# TODO: refactor
if len(html_tags) > 0:
# there is an opening tag somewhere
if line.find('<') != -1:
line = line[:line.find('<')]
else: # everything is already within a tag
line = ''
# STEP 4 - remove invalid lines
# STEP 9 - strip the line
line = line.strip(' *\r\n')
# remove link-only lines
if len(line) > 4 and line.find('[[') == 0 and line.find('[[', 1) == -1 and line.find(']]') == len(line)-2:
line = ''
# simply ignore too short lines and those that start with an incorrect token
if len(line) > 4 and line[0:2] != ' |' and line[0] != '|' and line[0] != '!':
# STEP 5 - remove incorrect links
line = self._remove_incorrect_links(line)
# STEP 6 - remove pairs
for pair in self._REMOVE_PAIRS:
line = self._remove_pairs(line, pair)
# STEP 7 - remove end of line if { in it
line = self._remove_box(line)
# STEP 8 - remove emtpy brackets and double spaces that remained
line = self._remove_empty_brackets(line)
# append the cleaned line to the new text
if len(line) > 0:
new_text += line + '\n'
# set the cleaned text in the article and return it
article['text'] = new_text
return article
'''the main thread method - should not be called, use start() instead
'''
def run(self):
while not self._end:
try:
# retrieve a new article from the queue
article = self._input_queue.get(True, WAIT_QUEUE_TIMEOUT)
# ignore redirects
if article['type'] == 'article':
# process the article
logging.info('preprocessing article %s' % (article['title'].encode('ascii', 'ignore')))
self.process(article)
# add the cleaned article to the output queue
self._output_queue.put(article)
# mark the task as done
self._input_queue.task_done()
except Queue.Empty:
pass
'''ends the thread
'''
def end(self):
self._end = True
def _remove_pairs(self, line, pair):
length = len(pair[0])
start = line.find(pair[0])
end = line.find(pair[1], start+length)
while start != -1 and end != -1 and start < end:
inner = line.find(pair[0], start+length)
if inner != -1 and inner < end: # there is an inner pair, remove first
line = line[0:start] + self._remove_pairs(line[start+length:], pair)
else: # remove pair itself
line = line[0:start] + line[end+len(pair[1]):]
start = line.find(pair[0])
end = line.find(pair[1], start + length)
return line
def _remove_incorrect_links(self, line):
# iterate over all links
next_link = line.find('[[')
while next_link != -1:
following_link = line.find('[[', next_link+2)
next_colon = line.find(':', next_link)
next_separator = line.find('|', next_link)
next_end = line.find(']]', next_link)
# the next link is invalid if it contains a colon
if next_colon != -1 and (next_colon < next_end and (following_link == -1 or following_link > next_end or following_link > next_colon)):
# remove the opening link target
remove_characters_start = 2
# if there is a separator in the invalid link
if next_separator != -1 and (next_separator < next_end and (following_link == -1 or following_link > next_end or following_link > next_separator)):
# remove everything until the separator
remove_characters_start = (next_separator-next_link)+1
# find matching end brackets
# if there are inner links
if following_link != -1 and following_link < next_end:
# count inner links
inner_link_counter = 0
next_inner_link = following_link
while next_inner_link == -1 or next_inner_link < next_end:
inner_link_counter+= 1
next_inner_link = line.find('[[', next_inner_link+2)
next_end = line.find(']]', next_end+2)
# if a link is not closed, do not parse this line
if next_end == -1:
return ''
# find matching end brackets
end_link = next_end
#while inner_link_counter > 0:
# tmp = line.find(']]', end_link)
# # something went completely wrong here, ignore this line
# if tmp == -1:
# return ''
# else:
# end_link = line.find(']]', end_link+2)
# inner_link_counter-= 1
# if there is no inner_link
else:
end_link = next_end
# remove the ending tag first
line = line[:end_link] + line[end_link+2:]
# then remove the beginning of the link
line = line[:next_link] + line[next_link + remove_characters_start:]
# start at the removed link position
next_link = line.find('[[', next_link)
# if the link is valid
else:
# just continue to the next link
next_link = following_link
return line
def _remove_box(self, line):
if line.find('{') != -1:
line = line[0:line.find('{')]
return line
def _remove_empty_brackets(self, line):
line = line.replace('()', '')
line = line.replace('[]', '')
line = line.replace(' ', ' ')
line = line.replace(' .', '.')
line = line.replace(' ,', ',')
line = line.replace(' :', ':')
line = line.replace(' !', '!')
line = line.replace(' ', ' ')
return line |
fa205f354edd95df53c7dcfa2078e405b8be2e07 | shahpriyesh/PracticeCode | /SlidingWindow/SlidingWindowMaximum.py | 1,274 | 3.875 | 4 | from collections import deque
class SlidingWindowMaximum:
def slidingWindowMaximum(self, nums, k):
# This queue maintains indices of elements from biggest to smallest
qi = deque()
# insert the first biggest element in first k elements
for i in range(k):
while qi and nums[qi[-1]] <= nums[i]:
qi.pop()
qi.append(i)
res = [nums[qi[0]]]
for i in range(k, len(nums)):
# Remove indices from front of the deque which fell out of window
while qi and qi[0] < (i - k + 1):
qi.popleft()
# Remove indices from end of deque which have smaller elements than current element
while qi and nums[qi[-1]] <= nums[i]:
qi.pop()
# Insert current element's indice at right of deque
qi.append(i)
res.append(nums[qi[0]])
return res
object = SlidingWindowMaximum()
# print(object.slidingWindowMaximum([1, 2, 3, 1, 4, 5, 2, 3, 6], 3))
# print(object.slidingWindowMaximum([8, 5, 10, 7, 9, 4, 15, 12, 90, 13], 4))
# print(object.slidingWindowMaximum([1, -1], 1))
# print(object.slidingWindowMaximum([7, 2, 4], 2))
print(object.slidingWindowMaximum([9,10,9,-7,-4,-8,2,-6], 5)) |
5b736d700f1fbbccce8a46e40a1bc3aa58e29503 | 07160710/PythonPractice | /shurushuchu/shuchu_test_py3.py | 831 | 3.53125 | 4 | # pyhon3.x 输出
import sys
from time import sleep
# 输出一个值
print(123)
#输出变量
num = 10
print(num)
# 输出多个变量
num2 = 66
print(num, num2)
# 格式化输出
name = "kf"
age = 20
# 我的名字是xxx,年龄是xx
print("我的名字是" ,name , ",年龄是",age)
print("我的名字是%s,年龄是%d"%(name,age))
print("我的名字是{0}",",年龄是{1}".format(name, age))
# 输出到文件中
f = open("test3.txt","w")
print("i am a itman",file=f)
# print("xxxxxxxxxxxxxxxx",file=sys.stdout)
# 输出不自动换行
print("abc",end="\n")
# 输出的各个数据,使用分隔符分割
print("1","2","3",sep="----")
print("---------------------------------")
# flush 参数说明
# print("请输入账号\n",end="")
print("请输入账号\n",end="",flush=True)
# 休眠5s
sleep(5)
# print("睡了5s") |
9064201584aed56deaaaca90dfa7a40d2f0bc871 | GeekyBoy13/Mandelbrot | /fun.py | 1,321 | 3.734375 | 4 | import itertools
import matplotlib.pyplot as plt
# Takes the square of a complex number x + yi.
def complexy(x,y):
a=x
b=y
x=a**2 - b**2
y=2 * a * b
return x,y
# Determines whether the point x + yi is in the Mandelbrot Set
def run2(x,y):
count = 0
c=x
d=y
try:
while count < 900:
a=x
b=y
x = complexy(a,b)[0] + c
y = complexy(a,b)[1] + d
count += 1
except:
return False
return True
# Calculates all of the points that are in the Mandelbrot Set,
# and seperates them into real and imaginary parts and returns both parts.
def calculate():
m = 200
u = -1.2
i = 1.2
o = -2.4
p = 0.5
thingy = round((m**2 * ((i-u)*(p-o)))/100,0)
a=[]
b=[]
counter=0
for x,y in itertools.product(range(int(o*m), int(p*m)), range(int(u*m), int(i*m))):
if run2(x/m,y/m):
a.append(x/m)
b.append(y/m)
if round(counter/thingy, 0) != round((counter+1)/thingy, 0):
print(round(counter/thingy, 0))
counter += 1
return a,b
# Graphs the Mandelbrot Set
plt.style.use('bmh')
a, b = calculate()
plt.scatter(a, b, color='red', marker='o', s=0.1)
plt.ylim(-1.2, 1.2)
plt.xlim(-2.4, 0.5)
plt.xlabel('Real')
plt.ylabel('Imaginary')
plt.title('Mandelbrot Set')
plt.show()
|
8c31296e32503cb92e745f5187cec4699f42756b | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/rmlden001/mymath.py | 470 | 4.15625 | 4 | #DENISHA RAMALOO
#mYMATH
#ASSIGNMENT5
def get_integer(x):#creating function to apply to either variable n or k
t = input ("Enter "+x+":\n")#for input use + instead of ,
while not t.isdigit ():
t =input ("Enter "+x+":\n")
t= eval(t)
return t #return the value you are working with
def calc_factorial(x):#creating function to apply to any variable
factorial = 1
for i in range (1, x+1):
factorial *= i
return factorial |
c255d3cc0745bce4a552ed90c94ffe7c048e9dda | shenhaizhumin/myrepository | /application/util/date_util.py | 879 | 3.578125 | 4 | from datetime import datetime, timedelta
# value 为 python 中的 datetime 类型数据
def released_time(value):
"""自定义发布时间过滤器"""
created_time = value.timestamp() # 把发布时间转换成秒级时间戳
now_time = datetime.now().timestamp() # 获取当前时间戳(秒级)
duration = now_time - created_time
if duration < 60: # 小于一分钟
display_time = "刚刚"
elif duration < 60 * 60: # 小于一小时
display_time = str(int(duration / 60)) + "分钟前"
elif duration < 60 * 60 * 24: # 小于24小时
display_time = str(int(duration / 60 / 60)) + "小时前"
elif duration < 60 * 60 * 24 * 30: # 小于30天
display_time = str(int(duration / (60 * 60 * 24))) + "天前"
else:
display_time = value.strftime('%Y-%m-%d') # 大于30天
return display_time
|
728863cf9a4bcfabbe4834d2a0d3772f15cb09f6 | vaibhavg12/Problem-Solving-in-Data-Structures-Algorithms-using-Python3 | /Algorithms/2 Version/treeLevelOrderSpial.py | 5,869 | 3.609375 | 4 | from collections import deque
class Tree(object):
class Node(object):
def __init__(self, v, l=None, r=None):
self.value = v
self.lChild = l
self.rChild = r
def __init__(self):
self.root = None
def levelOrderBinaryTree(self, arr):
self.root = self.levelOrderBinaryTreeUtil(arr, 0)
def levelOrderBinaryTreeUtil(self, arr, start):
size = len(arr)
curr = self.Node(arr[start])
left = 2 * start + 1
right = 2 * start + 2
if left < size:
curr.lChild = self.levelOrderBinaryTreeUtil(arr, left)
if right < size:
curr.rChild = self.levelOrderBinaryTreeUtil(arr, right)
return curr
def PrintBredthFirst(self):
que = deque([])
output = []
temp = None
if self.root != None:
que.append(self.root)
while len(que) != 0:
temp = que.popleft()
output.append(temp.value)
if temp.lChild != None:
que.append(temp.lChild)
if temp.rChild != None:
que.append(temp.rChild)
print output
def PrintLevelOrderLineByLine(self):
que1 = deque([])
que2 = deque([])
temp = None
if self.root != None:
que1.append(self.root)
while len(que1) != 0 or len(que2) != 0 :
while len(que1) != 0:
temp = que1.popleft()
print temp.value,
if temp.lChild != None:
que2.append(temp.lChild)
if temp.rChild != None:
que2.append(temp.rChild)
print ""
while len(que2) != 0:
temp = que2.popleft()
print temp.value,
if temp.lChild != None:
que1.append(temp.lChild)
if temp.rChild != None:
que1.append(temp.rChild)
print ""
def PrintLevelOrderLineByLine2(self):
que = deque([])
temp = None
if self.root != None:
que.append(self.root)
while len(que) != 0 :
count = len(que)
while count > 0:
temp = que.popleft()
print temp.value,
if temp.lChild != None:
que.append(temp.lChild)
if temp.rChild != None:
que.append(temp.rChild)
count -= 1
print ""
def PrintSpiralTree(self):
stk1 = []
stk2 = []
output = []
temp = None
if self.root != None:
stk1.append(self.root)
while len(stk1) !=0 or len(stk2) != 0:
while len(stk1) != 0:
temp = stk1.pop()
output.append(temp.value)
if temp.rChild != None:
stk2.append(temp.rChild)
if temp.lChild != None:
stk2.append(temp.lChild)
while len(stk2) != 0:
temp = stk2.pop()
output.append(temp.value)
if temp.lChild != None:
stk1.append(temp.lChild)
if temp.rChild != None:
stk1.append(temp.rChild)
print output
"""
To see if tree is a heap we need to check two conditions:
1) It is a complete tree.
2) Value of a node is grater than or equal to it's left and right child.
"""
def findCountUtil(self, curr):
if curr == None:
return 0
return (1 + self.findCountUtil(curr.lChild) + self.findCountUtil(curr.rChild))
def findCount(self):
return self.findCountUtil(self.root)
def isCompleteTreeUtil(self, curr, index, count):
if curr == None:
return True
if index > count:
return False
return self.isCompleteTreeUtil(curr.lChild, index*2+1, count) and self.isCompleteTreeUtil(curr.rChild, index*2+1, count)
def isCompleteTree(self):
count = self.findCount()
return self.isCompleteTreeUtil(self.root, 0, count)
def isHeapUtil(self, curr, parentValue):
if curr == None:
return True
if curr.value < parentValue:
return False
return ( self.isHeapUtil(curr.lChild, parentValue) and self.isHeapUtil(curr.rChild, parentValue ))
def isHeap(self):
infi = -9999999
return self.isCompleteTree() and self.isHeapUtil(self.root, infi)
def isHeap2(self):
que = deque([])
que.append(self.root)
que.append(0)
que.append(-99999)
count = 0
while len(que) != 0:
curr = que.popleft()
currIndex = que.popleft()
parentValue = que.popleft()
if curr.value < parentValue or currIndex != count :
return False
count += 1
if curr.lChild != None :
que.append(curr.lChild)
que.append(currIndex * 2 + 1)
que.append(curr.value)
if curr.rChild != None :
que.append(curr.rChild)
que.append(currIndex * 2 + 2)
que.append(curr.value)
return True
"""
Use queue to traverse the tree. In queue you will keep index and parent value.
When you dequeue element from queue you will keep track count of element
count should be equal to the index value.
"""
t = Tree()
arr = [1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13,14,15,16,17,18,19,20]
t.levelOrderBinaryTree(arr)
t.PrintBredthFirst()
t.PrintLevelOrderLineByLine()
#print t.isCompleteTree()
print t.isHeap()
# t.PrintSpiralTree()
# t.PrintLevelOrderLineByLine()
# t.PrintLevelOrderLineByLine2()
# Print Level order sum
# Print level order max
# Print Level order sum max |
837e24ecd7f156750ff70729363fca6340616d16 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/48_11.py | 3,523 | 4.125 | 4 | Python – Extract ith Key’s Value of K’s Maximum value dictionary
Given Dictionary List, extract i’th keys value depending upon Kth key’s
maximum value.
> **Input** : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8,
> “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “best”, i
> = “is”
> **Output** : 11
> **Explanation** : best is max at 19, its corresponding “is” value is 11.
>
> **Input** : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8,
> “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “Gfg”, i =
> “is”
> **Output** : 16
> **Explanation** : Gfg is max at 9, its corresponding “is” value is 16.
**Method #1 : Using max() + lambda**
The combination of above functions can be used to solve this problem. In this,
we extract max of kth key using max() and lambda. Then ith key is extracted
from extracted dictionary.
## Python3
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Extract ith Key's Value of K's Maximum value dictionary
# Using max() + lambda
# initializing lists
test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
{"Gfg" : 8, "is" : 11, "best" : 19},
{"Gfg" : 9, "is" : 16, "best" : 1}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "best"
# initializing i
i = "Gfg"
# using get() to handle missing key, assigning lowest value
res = max(test_list, key = lambda ele : ele.get(K, 0))[i]
# printing result
print("The required value : " + str(res))
---
__
__
**Output**
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8
**Method #2 : Using max() + external function**
This is yet another way to solve this problem. This computes in similar way as
above method, just the difference being of usage of custom comparator rather
than lambda function.
## Python3
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Extract ith Key's Value of K's Maximum value dictionary
# Using max() + external function
# custom function as comparator
def cust_fnc(ele):
return ele.get(K, 0)
# initializing lists
test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
{"Gfg" : 8, "is" : 11, "best" : 19},
{"Gfg" : 9, "is" : 16, "best" : 1}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "best"
# initializing i
i = "Gfg"
# using get() to handle missing key, assigning lowest value
res = max(test_list, key = cust_fnc)[i]
# printing result
print("The required value : " + str(res))
---
__
__
**Output**
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
efe7bd94af4e287bb5a7f6dbd19e64def60bc250 | VincentDion/Project3OC | /classes.py | 5,473 | 3.984375 | 4 | # -*- coding: Utf-8 -*
"""Classes for the game MacGyver escapes !"""
import pygame
from pygame.locals import *
from constants import *
class Level:
"""
Creation of level class
"""
def __init__(self, file):
"""
Initialization of the Level class
"""
self.file = file
self.structure = 0
def generate(self):
"""
Method to generate a level based on a file.
Creation of a global list, with a list for each line in the file within
"""
with open(self.file, "r") as file:
#Main list
level_structure = []
for line in file:
#"Line list", one for each line
level_line = []
for sprite in line:
if sprite != '\n':
level_line.append(sprite)
level_structure.append(level_line)
self.structure = level_structure
def show_game(self, window):
"""
Method to display the game according to the list in generate()
Only walls, a tile for start and stairs for finish are displayed
No graphic clue for the Test tile
"""
wall = pygame.image.load(IMAGE_WALL).convert_alpha()
stairs = pygame.image.load(IMAGE_STAIRS).convert_alpha()
start = pygame.image.load(IMAGE_START).convert()
num_line = 0
for line in self.structure:
num_case = 0
for sprite in line:
#Conversion of the case position in pixels
x = num_case * SIZE_SPRITE
y = num_line * SIZE_SPRITE
if sprite == 'W':
window.blit(wall, (x,y))
elif sprite == 'S':
window.blit(start, (x,y))
elif sprite == 'F':
window.blit(stairs, (x,y))
num_case += 1
num_line += 1
class Characters:
"""
Creation of the Characters class,
corresponding to the characters controlled by the user,
and the badguy at the end.
"""
def __init__(self, sprite, level, case_x, case_y):
"""
Initialization of Hero class, attributes concern its sprite,
position in pixel and case and the level is in
"""
self.sprite = pygame.image.load(sprite).convert_alpha()
self.case_x = case_x
self.case_y = case_y
self.x = case_x * SIZE_SPRITE
self.y = case_y * SIZE_SPRITE
#in case there are more than one level in near future
self.level = level
def move(self, direction):
"""
Method for the movement of the hero, use of the directional keys
"""
if direction == 'right':
#In order to avoid going out of the screen, right and bottom only
if self.case_x < (NUMBER_SPRITE_SIDE - 1):
#Forbid the user to move in a wall
if self.level.structure[self.case_y][self.case_x+1] != 'W':
#Move of one case and its conversion in pixels
self.case_x += 1
self.x = self.case_x * SIZE_SPRITE
self.direction = self.sprite
if direction == 'left':
if self.case_x > 0:
if self.level.structure[self.case_y][self.case_x-1] != 'W':
self.case_x -= 1
self.x = self.case_x * SIZE_SPRITE
self.direction = self.sprite
if direction == 'up':
if self.case_y > 0:
if self.level.structure[self.case_y-1][self.case_x] != 'W':
self.case_y -= 1
self.y = self.case_y * SIZE_SPRITE
self.direction = self.sprite
if direction == 'down':
if self.case_y < (NUMBER_SPRITE_SIDE - 1):
if self.level.structure[self.case_y+1][self.case_x] != 'W':
self.case_y += 1
self.y = self.case_y * SIZE_SPRITE
self.direction = self.sprite
def sleep(self, sprite, level, case_x, case_y):
"""
Simple method to change the sprite of the agent,
This method concerns the enemies of the hero
"""
self.sprite = pygame.image.load(sprite).convert_alpha()
self.case_x = case_x
self.case_y = case_y
self.x = case_x * SIZE_SPRITE
self.y = case_y * SIZE_SPRITE
self.level = level
class QuestObjects:
"""
Creation of the class for the objects needed to finish the level.
Item are randomly placed but in the main code : mge_game.py
When the user grab an item, it is displaced to the inventory bar
"""
def __init__(self, sprite, level, case_x, case_y):
"""
Initialization of QuestObjects class, with attributes of position,
in case and pixels, and level they are in
"""
self.sprite = pygame.image.load(sprite).convert_alpha()
self.level = level
self.case_x = case_x
self.case_y = case_y
self.x = case_x * SIZE_SPRITE
self.y = case_y * SIZE_SPRITE
def move_inventory(self, pos_x, pos_y):
"""
Method for moving the grabbed item in the inventory
For now the new position are given in the main code.
Must be changed soon to be implemented directly in this method
"""
self.x = pos_x
self.y = pos_y
|
dbb18d8bf587a07c7b4948d240c5a4165de8e764 | zachRudz/60-425_a1_miningFrequentItemsets | /pcy.py | 6,835 | 3.609375 | 4 | import datetime
import my_hashmap as hm
from collections import defaultdict
DEBUG = True
def a_priori(input_file, num_baskets, support_threshold):
min_required_occurrences = num_baskets * support_threshold
if DEBUG:
print("Minimum number of occurrences to be considered frequent: {}".format(min_required_occurrences))
# -- Pass 1 --
# Any frequent pairs would have to contain items that would be also considered frequent
# Therefore, we can go through the baskets and eliminate all items which are not considered "frequent"
# No frequent pairs would contain items which are not frequent
if DEBUG:
print("Starting pass 1...")
# Our hashmap/dict of possibly frequent items
# Default value of any basket will always be 0
global key_pair
items = defaultdict(lambda: 0)
hashed_pairs = hm.my_hashmap(num_buckets=int(num_baskets / 2))
with open(input_file, 'r') as fp:
# Reading up to $num_basket baskets
for basket_index in range(num_baskets):
# Fetching the values from the line (as strings), and removing the newline character at the end
line = fp.readline()
tmp_items = line.split(' ')[: -1]
# Making note of each item's appearance in a basket
for i in tmp_items:
items[i] += 1
# Hashing each pair of items to our hashmap of pairs.
# Note that each bucket of this hashmap correlates to one or more pairs.
for a in range(len(tmp_items) - 1):
for b in range(a + 1, len(tmp_items)):
hashed_pairs.increment_count(a, b)
if DEBUG:
print("Number of unique items: {}".format(len(items)))
# -- Between Passes --
# Replacing our buckets of pairs with a bitvector
# In other words, a bucket is considered frequent if the count for that bucket exceeds our support threshold.
# In this function, we clear our reference to the hashmap, so it's not unlikely that GC will run here or soon after
if DEBUG:
print("Pass 1 complete. Inbetween passes...")
hashed_pairs.convert_to_bitmap(min_required_occurrences)
# Now that we have a hashmap of items, and their counts, we can toss out items which are NOT frequent
to_remove = []
for item_index in items:
if items[item_index] < min_required_occurrences:
# Making a list of item indicies we can toss
# Python doesn't like you modifying the length of collections while iterating over them,
# which is why we're doing this in two steps.
to_remove.append(item_index)
for item_index in to_remove:
items.pop(item_index)
if DEBUG:
print("Number of unique, frequent items: {}".format(len(items)))
# -- Pass 2 --
# Now that we have the list of items which are frequent, we can find each combination of items,
# where both of the items in the pair are frequent. Therefore, through monotonicity, that pair would be frequent.
if DEBUG:
print("Starting pass 2...")
frequent_pairs = defaultdict(lambda: 0)
with open(input_file, 'r') as fp:
# Reading up to $num_basket baskets
for basket_index in range(num_baskets):
# Fetching the values from the line (as strings), and removing the newline character at the end
line = fp.readline()
tmp_items = line.split(' ')[: -1]
# Recording the number of frequent pairs in which both items are frequent
# Fetching all combinations of this basket's items
for a in range(len(tmp_items) - 1):
for b in range(a + 1, len(tmp_items)):
# Making sure both items are frequent
if items[tmp_items[a]] > min_required_occurrences and items[tmp_items[b]] > min_required_occurrences:
# Making sure the pair of items hash to a frequent bucket
if hashed_pairs.get_from_bitmap(a, b):
frequent_pairs[(a, b)] += 1
# -- Verification --
# Now that we have a list of "frequent pairs", in which both of its items are frequent, we need to verify that
# each of these frequent pairs actually has a support greater than the threshold.
prev_total_frequent_pairs = len(frequent_pairs)
pairs_to_pop = []
for key_pair in frequent_pairs:
if frequent_pairs[key_pair] < min_required_occurrences:
pairs_to_pop.append(key_pair)
# Going through and popping all of these pairs, since they're not frequent
# Doing this outside the previous for loop because python doesn't like it when you modify the size of an iterable
# object while iterating over it
for pair in pairs_to_pop:
if DEBUG:
print("Popping {}: {} occurrences.".format(pair, frequent_pairs[pair]))
frequent_pairs.pop(pair)
if DEBUG:
print("Frequent pairs before verification: {}".format(prev_total_frequent_pairs))
print("Frequent pairs after verification: {}".format(len(frequent_pairs)))
print("-- Frequent pairs --")
for key_pair in frequent_pairs:
print("{}: {}".format(key_pair, frequent_pairs[key_pair]))
return frequent_pairs
def main():
# Reading chunk size from the terminal
chunk_percentage = float(input("How much of the file do you want to look through? (In percentage format pls): "))
if chunk_percentage > 1 or chunk_percentage < 0:
print("Error: The chunk percentage must be between 0.0 and 1.0.")
return
# Reading support threshold from the terminal
support_threshold = float(input("What is your support threshold? (In percentage format pls): "))
if support_threshold > 1 or support_threshold < 0:
print("Error: The support threshold must be between 0.0 and 1.0.")
return
# Starting the clock
start_time = datetime.datetime.now()
print("Start time: {}".format(start_time))
print("")
# Finding the number of lines in our file
input_file = 'retail.txt'
total_num_lines = 0
with open(input_file, 'r') as fp:
while fp.readline():
total_num_lines += 1
# Calculating how many baskets (read: lines) we're going through
num_baskets = int(total_num_lines * chunk_percentage)
if DEBUG:
print("Number of baskets: {}".format(num_baskets))
# Doing a_priori things
frequent_pairs = a_priori(input_file, num_baskets, support_threshold)
# Stopping the clock
end_time = datetime.datetime.now()
diff_time = end_time - start_time
print("")
print("Start time: {}".format(start_time))
print("End time: {}".format(end_time))
print("Total elapsed time: {}".format(diff_time))
if __name__ == "__main__":
main()
|
641ee69833689bc8716ff8b1d6349f0589456423 | jason12360/AID1803 | /pbase/day03/day03practise03.py | 193 | 3.75 | 4 | # 1.输入一个数,用变量x绑定,根据x的值打印x行,hello world
# 用while语句来左
x = int(input('请输入一个数'))
while x > 0:
x -= 1
print('hello world') |
ceefd6cc5551cfce0ba12bb3f3ab2dfae991d17f | aaron0215/Projects | /Python/HW4/primes.py | 970 | 4.1875 | 4 | #Aaron Zhang
#CS021 Green group
#This is a program to check whether input number is prime
#Lead user to input a number is more than 1
#Use modulus symbol to defind whether a number is prime
#When finding the number is not prime, the calculation will be terminated
#If there is no number can be divided, output prime result
print('Welcome to my prime number detector.')
print('Provide an integer and I will determine if it is prime.')
print()
keep_going='y'
while keep_going=='y'or keep_going=='Y':
d=2
p = True
num=int(input('Enter an integer > 1: '))
while num<d and p:
num=int(input('Input must be > 1, try again: '))
if num==d:
print(num,'is prime')
p=False
while num>d and p:
if num%d == 0:
print(num,'is not prime')
p=False
d+=1
if p:
print(num,'is prime')
p=False
keep_going=input('Do you want to try another number? (Y/N) : ')
|
27a875a9d4c411a9e50a180663df270d00f2790f | TvBMcMaster/gsa_election_validation | /validate_election_results.py | 8,248 | 3.515625 | 4 | '''
Validate GSA Election Results from Google Forms with verified student lists provided by university
'''
import os
import sys
import csv
from datetime import datetime
DEFAULT_OUTPUT_DIR = "validation_results_{}".format(datetime.now().strftime('%Y%m%d'))
class InvalidCSVFileError(Exception):
pass
class StudentListFormat(object):
# Format specific data for the student list
EMAIL_HEADER = 5 # The column number of the email value
FACULTY_HEADER = 0 # The column number of the faculty value
INTERNATIONAL_HEADER = 6 # The column number of the international value
INTERNATIONAL_LABEL = 'Visa' # The label for the international classifier
class ResultsListFormat(object):
# Format specific data for the form entries
EMAIL_HEADER = 1 # The column number of the email value
FACULTY_HEADER = -1 # The column number of the faculty value
INTERNATIONAL_HEADER = 2 # The column number of the international value
INTERNATIONAL_LABEL = 'Yes' # The label for the international classifier
def create_parser():
# Generate and return the command line parser
parser = argparse.ArgumentParser("GSA Elections Validator")
parser.add_argument('-r', '--results', help="Results CSV file from Google Forms")
parser.add_argument('-s', '--students', help="Student List CSV file from SGS")
parser.add_argument(
'-d', '--destination',
default=DEFAULT_OUTPUT_DIR,
help="Destination folder to create for all output files. Default: {}".format(DEFAULT_OUTPUT_DIR)
)
return parser
def validate_options(parser, opts):
# Check argument parser options are valid
try:
check_valid_csv_file(opts.results)
except InvalidCSVFileError as e:
print("Argument Error: [Results] {}".format(str(e)))
print()
parser.print_help()
sys.exit(1)
try:
check_valid_csv_file(opts.students)
except InvalidCSVFileError as e:
print("Argument Error: [Students] {}".format(str(e)))
print()
parser.print_help()
sys.exit(1)
create_destination_folder(opts.destination)
print("Reading from Student List: {}".format(opts.students))
print("Reading from Results List: {}".format(opts.results))
def create_destination_folder(dirname):
# Create destination folder
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError:
print("Argumment Error: [Directory] Canot create destination folder: {}".format(dirname))
sys.exit(1)
else:
print("Warning: [Directory] Destination Folder Exists: {}. Results will be overridden.".format(dirname))
def check_valid_csv_file(csv_file):
# Check CSV File exists
if csv_file is None:
raise InvalidCSVFileError("No CSV File Found")
if not os.path.exists(csv_file):
raise InvalidCSVFileError("CSV File {} does not exist".format(csv_file))
def read_student_list(filename, comments=None, headers=None):
# Read student list from a csv file
#
# Data saved in following format:
# {
# <str> email: [<str> faculty, <bool> international]
# }
print("Reading Student List: {}".format(filename))
students = {}
with open(filename, 'r') as f:
reader = csv.reader(f)
# Headers
if comments is not None:
try:
[next(reader) for i in range(int(comments))]
except ValueError:
print("Warning: Problem reading header comments [{}] in student file {}".format(comments, filename))
if headers is not None:
headers = next(reader)
for row in reader:
try:
email = row[StudentListFormat.EMAIL_HEADER].lower()
faculty = row[StudentListFormat.FACULTY_HEADER].title()
international = row[StudentListFormat.INTERNATIONAL_HEADER] == StudentListFormat.INTERNATIONAL_LABEL
except IndexError:
print("Error: Cannot parse row: {}".format(row))
else:
students[email] = [faculty, international]
print("Read {} lines from student list".format(reader.line_num))
return students
def results_datetime_str():
# Format a nice datetime string for the results file
return "Results From {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def write_results_header(filename, comment_str, header_str=None):
# Overwrites a given file with initial comments and optional headers
with open(filename, 'w', newline="") as f:
f.write("# " + comment_str+os.linesep)
f.write("# " + results_datetime_str()+os.linesep)
if header_str is not None:
f.write(str(header_str)+os.linesep)
def void_student(f, row, reason):
# Void a student for a given reason, the reason is included in the voided results file
print("VOIDING STUDENT: [{}] {}".format(reason, row[ResultsListFormat.EMAIL_HEADER]))
f.write(",".join(row + [reason])+os.linesep)
def validate_student(f, row):
# Validate a student, write their data to the validated results file
f.write(",".join(row)+os.linesep)
def validate_results_list(students_list, results_list, destination_dir):
# Read election results list from csv file
print("Validating Election Results")
# Read student list
students = read_student_list(students_list)
# Create and set up results files, voided and validated
voided_file = os.path.join(destination_dir, 'voided_results.csv')
validated_file = os.path.join(destination_dir, 'validated_results.csv')
summary = {'entries': 0, 'validated': 0, 'voided': 0} # Statistics counts
# Read the results file and validate each row
with open(results_list, 'r') as f:
reader = csv.reader(f)
# Get the header string and write them to the results files
results_header = next(reader)
write_results_header(voided_file, 'VOIDED STUDENTS', header_str=",".join(results_header + ['Reason']))
write_results_header(validated_file, 'VALIDATED STUDENTS', header_str=",".join(results_header))
void_f = open(voided_file, 'a', newline="")
validate_f = open(validated_file, 'a', newline="")
print("FacultyHeader: {}".format(ResultsListFormat.FACULTY_HEADER))
print("InternationalHeader: {}".format(ResultsListFormat.INTERNATIONAL_HEADER))
for row in reader:
summary['entries'] += 1
# Extract validation data from row.
# Warng about bad formatting in a single row, nope out for any other exception
try:
email = row[ResultsListFormat.EMAIL_HEADER].lower()
if ResultsListFormat.FACULTY_HEADER > 0:
faculty = row[ResultsListFormat.FACULTY_HEADER].title()
else:
faculty = None
if ResultsListFormat.INTERNATIONAL_HEADER > 0:
international = row[ResultsListFormat.INTERNATIONAL_HEADER] == ResultsListFormat.INTERNATIONAL_LABEL
else:
international = None
except IndexError:
print("Error: Bad formatting encountered while reading Results file: {}[{}]".format(results_list, reader.line_num))
continue
except Exception:
print("Error: Unexpected Error encountered while processing row: [{}]{}".format(reader.line_num, row))
print("Nopeing out...")
break
continue
# Compare data against student list
if email not in students:
void_student(void_f, row, 'Not in Student List')
summary['voided'] += 1
elif faculty is not None:
if students[email][0].lower() != faculty.lower():
void_student(void_f, row, "Incorrect Faculty: Expected [{}] Got [{}] ".format(faculty, students[email][0]))
summary['voided'] += 1
elif students[email][1] != international:
void_student(void_f, row, "Incorrect International Status: Expected [{}] Got [{}]".format(international, students[email][1]))
summary['voided'] += 1
else:
validate_student(validate_f, row)
summary['validated'] += 1
void_f.close()
validate_f.close()
# Print summary
print("Done!")
print()
print("Saved validated entries to: {}".format(validated_file))
print("Saved voided entries to: {}".format(voided_file))
print()
print("Summary")
print("Num Entries: {}".format(summary['entries']))
print("Validated Entries: {}".format(summary['validated']))
print("Voided Entries: {}".format(summary['voided']))
if __name__ == '__main__':
import argparse
parser = create_parser() # Create command line argument parser
opts = parser.parse_args() # Parse the command line arguments
validate_options(parser, opts) # Check provided argument options are sane
# Validate results with provided command line options
validate_results_list(opts.students, opts.results, opts.destination)
|
c0130afe62bc6752d68640c1000ce22f2c2785ed | rodneycagle/hello-world | /TurtleNuminput.py | 525 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 10:43:01 2020
@author: cagle_restricted
"""
import turtle
turtle.bye()
t = turtle.getturtle()
t.color("green", "red")
t.width(5)
size = int(turtle.numinput("Triangle Size","What size triangle do you want?",300,100,560))
# intitialize turtle position
t.penup()
t.left(270)
t.forward(size/2)
t.left(270)
t.forward(size/2)
t.left(180)
t.pendown()
# triangle loop
t.begin_fill()
for k in range(3):
t.forward(size)
t.left(120)
t.end_fill()
|
7aa0a393be321bc1f7ab7b7a246018f2d472db81 | yurisimao/PYTHON-INIT-PROJECTS | /enumerate.py | 121 | 3.765625 | 4 | any_list = ["bola", "acabate", "cachorro"]
for i, nome in enumerate(any_list): #Trás o indice e o valor
print(i, nome) |
9c84ba4f7d53940ca2a8f0e35204579e17e1915f | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/68_2.py | 2,886 | 4.5 | 4 | Python – Change Datatype of Tuple Values
Sometimes, while working with set of records, we can have a problem in which
we need to perform a data type change of values of tuples, which are in its
2nd position, i.e value position. This kind of problem can occur in all
domains that include data manipulations. Let’s discuss certain ways in which
this task can be performed.
**Input** : test_list = [(44, 5.6), (16, 10)]
**Output** : [(44, '5.6'), (16, '10')]
**Input** : test_list = [(44, 5.8)]
**Output** : [(44, '5.8')]
**Method #1 : Usingenumerate() \+ loop**
This is brute force way in which this problem can be solved. In this, we
reassign the tuple values, by changing required index of tuple to type cast
using appropriate datatype conversion functions.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Change Datatype of Tuple Values
# Using enumerate() + loop
# initializing list
test_list = [(4, 5), (6, 7), (1, 4), (8,
10)]
# printing original list
print("The original list is : " + str(test_list))
# Change Datatype of Tuple Values
# Using enumerate() + loop
# converting to string using str()
for idx, (x, y) in enumerate(test_list):
test_list[idx] = (x, str(y))
# printing result
print("The converted records : " + str(test_list))
---
__
__
**Output :**
The original list is : [(4, 5), (6, 7), (1, 4), (8, 10)]
The converted records : [(4, '5'), (6, '7'), (1, '4'), (8, '10')]
**Method #2 : Using list comprehension**
The above functionality can also be used to solve this problem. In this, we
perform similar task as above method, just in one liner way using list
comprehension.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Change Datatype of Tuple Values
# Using list comprehension
# initializing list
test_list = [(4, 5), (6, 7), (1, 4), (8,
10)]
# printing original list
print("The original list is : " + str(test_list))
# Change Datatype of Tuple Values
# Using list comprehension
# converting to string using str()
res = [(x, str(y)) for x, y in test_list]
# printing result
print("The converted records : " + str(res))
---
__
__
**Output :**
The original list is : [(4, 5), (6, 7), (1, 4), (8, 10)]
The converted records : [(4, '5'), (6, '7'), (1, '4'), (8, '10')]
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
30881807f0a8abe800313c8afb956ac0aa23d7ff | coolboy-ccp/PythonLearn | /Base/Base1.py | 1,754 | 4.09375 | 4 |
# 高级特性
#切片
def testSlice():
nums = [1,2,3,4,5,6,7]
print(nums[:3])
print(nums[1:3])
print(nums[-2:])
#前六个数,每两个截取一个
print(nums[:6:2])
#迭代
def testIteration():
dict = {'a':1, 'b':2, 'c':3}
keys = ''
values = ''
kvs = ''
for key in dict:
keys = keys + key + ','
for value in dict.values():
values = values + '%d' % value + ','
for k,v in dict.items():
kvs = kvs + '%s:%d' % (k,v) + ','
print(keys[:-1], values[:-1], kvs[:-1])
#列表生成式
def testListComprehensions():
print(list(range(1, 10)))
print([x * x for x in range(1, 10)])
print([m + n for m in 'ABC' for n in 'XYZ'])
lstr = ['Ha', 'HHLK', 'KKF1']
print([l.lower() for l in lstr])
def mutiTable():
[print('%s * %s = %s ' %(x, y, x * y), end='\n' if x == y else '\t') for x in range(1, 10) for y in range(1, x + 1)]
def mutiTbale1():
for i in range(1, 10):
for j in range(1, i + 1):
print(r"%s * %s = %s " % (i, j, i * j), end='\t')
print(" ")
#生成器
def testGenerator():
gs = (x * x for x in range(9))
print(gs)
gsnums = []
for s in gs:
gsnums.append(s)
print(gsnums)
fibs = fib(6)
fibsnums = []
for f in fibs:
fibsnums.append(f)
print(fibsnums)
##斐波那契
#在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
if __name__ == '__main__':
#mutiTbale1()
mutiTable()
#testSlice()
#testIteration()
#testListComprehensions()
#testGenerator()
|
9c496cfadc8c3bdb5ed6dea52977adccd8ff62ac | eurisko-us/games-cohort-1 | /tic-tac-toe/strategy.py | 986 | 3.5625 | 4 | import random
from game import Game
from minimax import Minimax
class TestStrategy:
def __init__(self,player_num):
self.player_num = player_num
def move(self,current_game):
for x in range(len(current_game)):
for y in range(len(current_game[0])):
if current_game[x][y] == 0:
return (x,y)
class MinimaxStrategy:
def __init__(self,player_num):
self.player_num = player_num
def move(self,current_game):
minimax = Minimax(current_game,self.player_num)
move = minimax.best_move()
return move
class RandomStrategy:
def __init__(self,player_num):
self.player_num = player_num
def move(self,current_game):
empty_spaces = []
for x in range(len(current_game)):
for y in range(len(current_game[0])):
if current_game[x][y] == 0:
empty_spaces.append((x,y))
return random.choice(empty_spaces)
|
fbb71f5944888557b27d1876debe2dcf5550f010 | dixit5sharma/Learn-Basic-Python | /Ch3_Functions_2.py | 158 | 3.984375 | 4 | def avg(a,b):
av=(a+b)/2
return av
p=int(input("Enter number 1 : "))
q=int(input("Enter number 2 : "))
r=avg(p,q)
print("Average of",p,"&",q,"=",r)
|
7b2c4bc7489f836c4e8f9c1801d1c184059ca393 | cfezequiel/ai-project1-main | /Road.py | 3,393 | 3.984375 | 4 | #!/usr/bin/python
#
#
#
# /file Road.py
#
# Copyright (c) 2012
#
# Benjamin Geiger <begeiger@mail.usf.edu>
# Carlos Ezequiel <cfezequiel@mail.usf.edu>
from math import cos, sin, atan2
import GraphUtil
class Road (object):
"""Represents the connection between two City objects."""
def __init__ (self, origin, destination):
self.origin = origin
self.destination = destination
self.create_line()
def create_line (self):
"""Creates the graphical representation of the road as a line object."""
# If origin and destination are not specified, set the line to None
if self.origin is None or self.destination is None:
self.line = None
else:
# Get the center coordinates of both origin and destination
# As well as their radius
x1 = self.origin.location.x
y1 = self.origin.location.y
r1 = self.origin.radius
x2 = self.destination.location.x
y2 = self.destination.location.y
r2 = self.destination.radius
# Compute x,y offsets so that that the line touches the boundaries
# of origin and destination and not their centers
theta = atan2(y2 - y1, x2 - x1)
dx1 = r1 * cos(theta)
dy1 = r1 * sin(theta)
dx2 = r2 * cos(theta)
dy2 = r2 * sin(theta)
# Create the line
self.line = GraphUtil.Line(
GraphUtil.Point(x1 + dx1, y1 + dy1),
GraphUtil.Point(x2 - dx2, y2 - dy2))
self.line.setArrow("last")
self.reset()
def draw (self, canvas):
"""Draws this object on the specified canvas."""
self.line.canvas = canvas
if self.status == "unprobed":
self.line.setOutline("gray")
elif self.status == "probed":
self.line.setOutline("black")
elif self.status == "traveled":
self.line.setOutline("blue")
else:
self.line.setOutline("green")
self.line.draw()
def reset (self):
"""Resets the road state.
This sets the road state to 'unprobed'.
"""
self.status = "unprobed"
if self.line is not None and self.line.canvas is not None:
self.line.setOutline("gray")
self.line.setWidth(1)
def probe (self):
"""If the road state is 'unprobed', this sets the state to 'probed'."""
if self.status == "unprobed":
if self.line.canvas is not None:
self.line.setOutline("black")
self.line.setWidth(1)
self.line.canvas.lift(self.line.id)
self.status = "probed"
def travel (self):
"""If the road state is 'probed', this sets the state to 'traveled'."""
if self.status == "probed":
if self.line.canvas is not None:
self.line.setOutline("blue")
self.line.setWidth(2)
self.line.canvas.lift(self.line.id)
self.status = "traveled"
def highlight (self):
"""Highlights the road."""
if self.line.canvas is not None:
self.line.setOutline("red")
self.line.setWidth(4)
self.line.canvas.lift(self.line.id)
# vim: set et sw=4 ts=4:
|
7bd2a2193914cf222db6810fa16a61f07820957c | anjalirmenon/sierpinski | /sierpfract.py | 849 | 3.5625 | 4 | # sierpinski using any coordinates of screen
import pygame
black = (0,0,0)
screen = pygame.display.set_mode((1000,1000))
screen.fill(black)
def midpoint(x,y):
midx = (x[0] + y[0])/2.0
midy = (x[1] + y[1])/2.0
return (midx,midy)
#line_draw(screen,(x1,y1),(x2,y2))
# centrx = x2
# centry = y2
def tri(screen,red,x,y,z):
red = (255,0,0)
pygame.draw.polygon(screen,red,(x,y,z),0)
def sierp(screen,red,x,y,z,deep):
if(deep <=0):
tri(screen,red,x,y,z)
else:
a = midpoint(x,y)
b = midpoint(x,z)
c = midpoint(y,z)
sierp(screen,red,x,a,b,deep-1)
sierp(screen,red,y,a,c,deep-1)
sierp(screen,red,z,b,c,deep-1)
def main():
wt = 1000
ht = 1000
pygame.init()
white = (255,255,255)
sierp(screen,white,(300,50),(0,350),(600,350),3)
pygame.display.update()
wait = raw_input("press any key to quit...")
pygame.quit()
main()
|
b0b45d5251c9abc315cb1f78d474e645d9ee6a0f | artemiygordienko/itmo-python | /lesson-01.py | 2,476 | 3.71875 | 4 | who = 'Python'
print('Hello,',who)
# простые (Скалярные) типы данных
"""
- целые числа - int
- дробные числа - float
- комплексные числа - complex
- логические флаги - bool
- строки - str, bytes
"""
i1 = 1
i2 = -2
i3 = 0b010101 # двоичная
i4 = 0o455 # восьмеричная
i5 = 0xaa # шестнадцатеричная
print(i4)
print(i5)
print(i3)
f1 = 1.23
f2 = -1.23
f3 = 12e-3
f4 = 12e3
print(f3)
print(f4)
c1 = 3.14j # комплексные числа
b1 = True
b = False
s1 = 'Hello'
s2 = b'Hello' # байтовая строка
s3 = r'Hello' # сырая строка, экранирование выключено
s4 = "Hello"
s5 = '''
''' # многострочный текст
s6 = """
""" # многострочный текст
# Составные (сложные) типы данных
'''
- кортеж - tuple
- список - list
- словари - dict
- множество - set
- объекты - object
'''
t1 = (1,'Иван Иванович', True, ('Python',))
l1 = [1,'Иван Иванович', True, ('Python',)]
d1 ={
'id':1,
'fio':'Иван Иванович',
'is_developer': True,
'skills': ['python']
}
s1 = {1, 2, 3}
s2 = set()
print(d1['fio'], d1['skills'][0])
print(t1, t1[1],t1[3][0])
l1[2] = False
print(l1, l1[1], l1[3][0])
# Специальные типы данных
'''
- пустота (остутствие значения) - None
'''
a = None
# Как определить тип переменной?
print(type(a), type(l1))
# Как выполнить явное приведение типа?
s66 = '123'
i66 = int(s66)
print(type(i66))
i77 = '255'
i78 = 255
print(int(i77, 8), hex(255), oct(255), bin(255))
# Операторы
'''
- Арифметические: + - * / %(остаток от деления) // **
- Сравнение: ==(ровно) !=(не ровно) <>(не ровно) >(больше) < (меньше) <= >=
- Присваивание: = =+ -= *= /= %= //= **=
- Логические: and or not
- Принадлежности: in(есть ли элемент в списке), not in
- Тождественности: is, not is
- Побитовые: &(и) |(или) ^(xo исключающая или) ~(отрицание) << >> (сдвиги влево и вправо)
'''
# i = 1
# i = i + 1
# i += 1
|
d790e69d3cc0748e5082013bae119a15be23c7fe | adamhartleb/python_workout | /2_strings/exercise_7.py | 210 | 3.71875 | 4 | def translate(letter):
vowels = 'aeiou'
if letter in vowels:
return 'ub' + letter
return letter
def ubbi_dubbi(word):
return ''.join(map(translate, word))
print(ubbi_dubbi('elephant')) |
6f633d3cadca4aa24dfdbf28424410295d1691da | yashshah4/Data-Science-Projects | /Miscellaneous/Collatz.py | 390 | 4.1875 | 4 | def collatz(number):
if number%2 == 0:
print (number//2)
return (number//2)
else:
print (number*3+1)
return (number*3+1)
try:
n = int(input("Enter a number : "))
p=n
while True:
p = collatz(p)
if p == 1:
break
else:
continue
except ValueError:
print("Invalid input: Enter a number")
|
665996f24ef2a1258a51c11eaacada885b331752 | Supriyapandhre/Test-Repository | /OOPS_concepts/data_hiding.py | 1,870 | 4.375 | 4 | """
Data hiding in python is to show the intention to hide the data, but actually we don't hide the data.
_ : (single underscore)
__ : (double underscore)
"""
class student:
# Write class documentation
"""
This class contains all information about the student, which includes name, phone, email, address
etc.
"""
# class variables
name = 'John'
_age = 25 #(with single underscore as prefix)
__phone = 6464645645 #(with double underscore as prefix)
def __init__(self, school_name, address):
self._school_name = school_name
self.__address = address
def _shows_student_address(self):
print(f"Student address : {self.__address}")
def __school_name(self):
print("School Name :", self._school_name)
def all_data_method(self):
print("This method contains all the student data")
obj = student('International School', 'Mumbai')
#access data without underscore
print("Name :", obj.name)
obj.all_data_method()
# Access variable or data with single underscore (_)
# In single under score we don't show in suggestion those variable and methods which has (_) as prefix
# but we can access.
print("Age :", obj._age)
obj._shows_student_address()
# Access variable or method which has double under score as prefix in the name
# double under as prefix means more restriction on the data to access out side the class.
# obj._classname__variablename
print("Phone :", obj._student__phone)
obj._student__school_name()
##############################
#get all the method of the class
print(type(obj))
print(dir(obj))
str1 = 'hello'
print(type(str1))
print("#"*50)
# Use magic method to get class info
print("class name :", obj.__class__)
print("module name :", obj.__module__)
print("Get variables and method, ", obj.__dir__())
print("Get class documentation :", obj.__doc__) |
f4033b1246f8b2843f400c162433b8f55bd993b5 | anweshachakraborty17/Python_Bootcamp | /P66_Check if a key exists.py | 261 | 4.21875 | 4 | #Check if a key exists
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
#Yes, 'model' is one of the keys in the thisdict dictionary |
061eb67854c629786d82b2c0eedcd77240448f22 | ABHIINAV12/project-euler | /Summation of primes.py | 251 | 3.859375 | 4 | def isprime(a):
if a==2:
return 1
if a%2==0:
return 0
curr=2
while(curr*curr<=a):
if a%curr==0:
return 0
curr+=1
return 1
def main():
ans=0
for i in range(2,2000000):
if isprime(i):
ans+=i
print(ans)
main()
|
1c7bf5132ff29eba70a4ad350fb5bf11e9b6dbeb | david-xander/Algorithms-Practice-python | /sorting/sort_the_hard_way.py | 634 | 3.890625 | 4 |
def main():
data=[5,4,1,8,7,2,6,3]
print('HARD WAY SORTING ', data, ': ', hardway(data))
def hardway(data):
#
# INPUT (list)
# O(n**2)
#
res=[]
for item in data:
if len(res)==0:
res.append(item)
else:
inserted=False
for index, subitem in enumerate(res):
if not inserted and item<subitem:
res.insert(index, item)
inserted=True
if not inserted:
res.append(item)
return res
if __name__ == "__main__":
# execute only if run as a script
main() |
687d11173a44690ba38f568ed163dc0d9fa9fe19 | Katsiarynka/Algorithms | /tree.py | 740 | 3.53125 | 4 | # coding:utf-8
from collections import deque
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def __repr__(self):
return '%s (%s %s)' % (self.val, self.left or '', self.right or '')
def constructTreeFromList(nodes):
print nodes
if not nodes:
return
root = TreeNode(nodes[0])
cur = root
childs = deque()
for i, val in enumerate(nodes[1:]):
if not i % 2:
cur.left = val if val is None else TreeNode(val)
childs.append(cur.left)
else:
cur.right = val if val is None else TreeNode(val)
childs.append(cur.right)
if i % 2:
cur = childs.popleft()
return root
print(constructTreeFromList([1,2,3,4,5,None,6, None, None, None, None, 7,8, None, None]))
|
35fac3e7a78031f4637ee6dc3762ba5a64c706fb | raymondhfeng/raymondhfeng.github.io | /data_structures_and_algorithms/moderate.py | 1,370 | 3.609375 | 4 | def swap(): # swaps two elements in place without using a temprorary variable
a = 10
b = 15
a = a+b
b = a-b
a = a-b
def countZeroes(n): # computes the number of trailing zeros in n factorial
currPower = 1
counter = 0
while pow(5,currPower) <= n:
multiple = 1
while multiple*pow(5,currPower) <= n:
counter += 1
multiple += 1
currPower += 1
return counter
def allPairs(arr,n):
numToIndex = {}
for i in range(len(arr)):
if arr[i] in numToIndex:
numToIndex[arr[i]] += [i]
else:
numToIndex[arr[i]] = [i]
print(numToIndex)
result = []
for i in range(len(arr)):
if n - arr[i] in numToIndex:
for index in numToIndex[n - arr[i]]:
if index != i:
result += [(i,index)]
return result
def maxSubArray(nums):
"""
:type nums: List[int]
:rtype: int
"""
currMax = -1 * sys.maxint
runningSum = 0
for i in range(len(nums)):
if nums[i] >= 0:
runningSum += nums[i]
if runningSum > currMax:
currMax = runningSum
else:
if currMax < 0 and nums[i] > currMax:
currMax = nums[i]
elif runningSum + nums[i] < 0:
runningSum = 0
else:
runningSum += nums[i]
return currMax
def main():
arr = [1,2,3,4,5,6,7,8,9,10]
print(allPairs(arr,10))
if __name__ == "__main__":
main() |
5e2137abdb3a2d23e265f1a965347d4a0d0767e6 | JPogodzinski/RSA | /RSA.py | 1,512 | 3.859375 | 4 | import random
import time
def isPrime(n):
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def GCD(x, y):
while y != 0:
pom = y
y = x % y
x = pom
return x
def isCoPrime(x, y):
if GCD(x, y) == 1:
return True
return False
if __name__ == '__main__':
start = time.time()
p = random.randrange(1000, 10000)
while not isPrime(p):
p = random.randrange(1000, 10000)
print ("p", p)
q = random.randrange(1000, 10000)
while not isPrime(q):
q = random.randrange(1000, 10000)
print ("q", q)
n = p * q
print("n", n)
phi = (p - 1) * (q - 1)
print("phi", phi)
e = random.randrange(2, phi)
while not isPrime(e) & isCoPrime(e, phi):
e = random.randrange(2, phi)
print ("e", e)
d = 2
for i in range(2, phi):
if (e * i - 1) % phi == 0:
d = i
print ("d", d)
end = time.time()
print (end - start)
start=time.time()
m1 = "Confusion In HerEyesThatSaysItAllShe'sLostControl"
print("Message: ",m1)
c = []
for a in m1:
temp = 0
temp = ord(a)
temp = temp ** e % n
c.append(temp)
print ("Encrypted text: ", c)
end = time.time()
print (end - start)
start=time.time()
m2 = ""
for a in c:
temp = 0
temp = a ** d % n
m2 = m2 + chr(temp)
print("Decrypted text: ", m2)
end=time.time()
print (end-start)
|
bcd7fdf86ac33a625f369e33a68c610ba9e3b8d8 | mayconkwutke/Python-Fundation-26-Abr-a-06Mai | /AT-DIA-02/Aula2.py | 4,778 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 27 19:17:10 2021
@author: Maycon
"""
import os
# Exercicio 1 - Escreva um programa python que escreva na tela o texto abaixo
# com a saída de exemplo, usando somente 1 comando print:
## Twinkle, twinkle, little star, How I wonder what you are! Up above the
## world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are!
###
###Twinkle, twinkle, little star,
### How I wonder what you are!
### Up above the world so high,
### Like a diamond in the sky.
###Twinkle, twinkle, little star,
### How I wonder what you are!
print("""Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are!""")
# Exercicio 2 - Escreva um programa Python que aceite uma sequência de números ou strings
# separados por vírgula do usuário e gere uma lista e uma tupla com esses números.
dados = ('Python.py', 'java.jar', 123, 24, 10)
lista = [dados]
ntupla = tuple(dados)
# Exercício 3 - Da lista de arquivos apresente somente as extensões. Ex: .java, .py, .cpp
listDir = ('./')
for l in os.listdir(listDir):
print (l.split('.')[-1])
# Exercício 4 - Utilizando o código e a lista da atividade 3, crie um dicionario
# agrupando os valores e retornando dicionarios onde a chave é a extensão e o valor
# é a quantidade de vezes que a extensão aparece.
diclista = dict()
for l in os.listdir(listDir):
if (l.split('.')[-1]) not in diclista:
diclista[l.split('.')[-1]] = 1
else:
diclista[l.split('.')[-1]] += 1
print (diclista)
# Exercício 5 - Escreva um programa Python que o usario precise entrar com um valor
# para obter a diferença entre um determinado número e 17, se o número for maior
# que 17, retorne o dobro da diferença absoluta.
## Observação use a funcao int(valor) para converter o texto em inteiro
valor = input('Digite um valor: ')
if int(valor) <= 17:
print (17 - int(valor))
else:
print ((int(valor) - 17)*2)
# Exercício 6 - Escreva um programa Python para calcular a soma de três números
# entrados pelo usuário, se os valores forem iguais, retorne três vezes o valor da soma dos 3.
num1 = int(input('Digite o primeiro numero:'))
num2 = int(input('Digite o segundo numero:'))
num3 = int(input('Digite o terceiro numero:'))
total = num1 + num2 + num3
if num1 == num2 and num1 == num3:
print ([total]*3)
else:
print (num1 + num2 + num3)
# Exercício 7 - Escreva um programa Python para concatenar todos os elementos
# de uma lista em uma string, separando cada um com um hifen, e retorná-la.
## Utilize a lista filenames
contact_string = str()
for file in os.listdir(listDir):
contact_string += file + '-'
print (contact_string)
lista = ['Banana', 'maça', 123, 29, 'teste']
String = lista[0] + "-" + lista[1] + "-" + str(lista[2]) + "-" + str(lista[3]) + "-" + lista[4]
print (String)
# Exercício 8 - Crie um programa que fique recebendo numeros do usuario
# até que ele digite -1.
# Em seguida crie uma tupla com os valores de divisão de piso por 2 de cada valor.
## Obervação 1 : O numero de controle nao pode aparecer na tupla final
num = int()
lista_valores = list()
valor_piso = int()
while num != -1:
num = int(input("Digite um numero:"))
if num > 0:
valor_piso = num // 2
lista_valores.append(valor_piso)
else:
print ('Fim da execução')
print (tuple(lista_valores))
print()
# Exercicio 10 - Imprime todos os números pares de uma determinada lista de
# números na mesma ordem e interrompe a impressão se qualquer número que vier
# depois de 237 na sequência.
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
for x in numbers:
if x == 237:
print(x)
break;
elif x % 2 == 0:
print (x)
# Exercicio 11 - Crie um dicionario que tem como chave seu primeiro nome,
# e os valores são outro dicionarios com as informações sobre:
# Idade, sobrenome, email e DDD
# Em seguida imprima na tela apresentando como textos:
dict_leo = {"nome":"Leonardo", "dados":{"Idade":35, "sobrenome":"Lacerda", "email":"leolacerdagaller@live.com","DDD":11}}
print("""
Ola eu sou o %s %s, tenho %i anos. Meu email é %s e meu DDD é %i
""" % (dict_leo["nome"],
dict_leo["dados"]["sobrenome"],
dict_leo["dados"]["Idade"],
dict_leo["dados"]["email"],
dict_leo["dados"]["DDD"]) )
|
54acadc2fb5af27b386dd4ead0cbfcdd62492a53 | kirane61/letsUpgrade | /Day3/ContactBook.py | 526 | 3.796875 | 4 |
#Contact Book
howManyContact = int(input("Enter the number of contacts you want to add: "))
contactDictionary = {}
for i in range(0,howManyContact):
name = input("Enter Name:")
number1 = input("Enter number1:")
number2 = input("Enter number2:")
imageurl = input("Enter imageUrl:")
email = input("Enter email:")
website = input("Enter website:")
contactDictionary[name]= {
"name":name,
"number1":number1,
"number2":number2,
"imageurl":imageurl,
"email": email,
"website": website
}
|
3ddfecb6576243b6a361e7583d7f4e68a76ea73c | whywhs/Leetcode | /Leetcode127_M.py | 1,478 | 3.65625 | 4 | # 单词接龙。这个题目是典型的广度优先搜索题目。值得学习的地方有两个,一个是双向BFS,另一个是set操作。
# 双向BFS。即从前往后,从后往前均进行BFS,当一方的BFS结果大于另一方,则改从小的一方继续进行。
# set操作。a={'ccc'}这个定义就是一个set变量。然后set是有len的操作,同时set的加是add,set的减是remove,set的update是迭代的加入变量。
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList:
return 0
if len(beginWord)==1:
return 2
count,result,result_e,sub = 1,{beginWord},{endWord},set()
while(len(result)!=0):
if len(result)>len(result_e):
result,result_e = result_e,result
for i in wordList:
for j in result:
if self.judge(i,j):
if i in result_e:
return count+1
sub.add(i)
result,sub = sub,set()
count += 1
return 0
def judge(self,a,b):
k = 0
for i in range(len(a)):
if a[i]!=b[i]:
k += 1
if k!=1:
return False
return True
|
161d7c4aa979390dc29d03ca6a7a87f2093cd1a9 | shankar7791/MI-10-DevOps | /Personel/AATIF/Assesment/01-MAR/nummatch.py | 236 | 3.671875 | 4 | li = numberList
print("Given list is ", numberList)
firstElement = numberList[0]
lastElement = numberList[-1]
if (firstElement == lastElement)
return True
else
return False
numList = [10, 20, 30, 40, 10]
print("result is", li(numList)) |
354b81f408c0b2aac776b55920f1252c9155ba21 | nitsas/py3datastructs | /dict_heap.py | 2,527 | 4.125 | 4 | """
A pseudo-heap implemented using a dictionary.
Operations:
- __len__
- insert
- pop / pop_min
- peek / find_min
- decrease_key
I use this until I find the time to implement a Fibonacci heap.
Author:
Christos Nitsas
(nitsas)
(chrisnitsas)
Language:
Python 3(.4)
Date:
August, 2014
"""
__all__ = ['DictHeap']
class DictHeap:
"""
A pseudo-heap implemented using a dictionary.
I use this until I find the time to implement a Fibonacci heap.
"""
def __init__(self):
"""Initialize an empty heap."""
self._items = {}
def __len__(self):
"""Return the number of items in the heap as an int."""
return len(self._items)
def insert(self, item, item_key):
"""
Insert a new item with key item_key to the heap.
item -- the item to be inserted
item_key -- the item's key
If the item was already in the heap just update its key.
"""
self._items[item] = item_key
def decrease_key(self, item, new_item_key):
"""
Update the item's key in the heap.
This can even increase the item key.
"""
self._items[item] = new_item_key
def peek(self):
"""
Return the item with the lowest key currently in the heap; None if
the heap is empty.
Careful if the heap actually contains items set to None; in that case,
this method returning None doesn't necessarily mean the heap is empty.
"""
try:
# set "first" dict item as temporary min
min_item, min_key = next(iter(self._items.items()))
except StopIteration:
raise LookupError('peek into empty heap')
# find actual min item
for item, key in self._items.items():
if key < min_key:
min_item = item
min_key = key
return min_item
def pop(self):
"""
Remove and return the item with the lowest key currently in the heap;
None if the heap is empty.
Careful if the heap actually contains items set to None; in that case,
this method returning None doesn't necessarily mean the heap is empty.
"""
try:
# find min item
min_item = self.peek()
except LookupError:
raise LookupError('pop from empty heap')
# remove min item
del(self._items[min_item])
return min_item
|
a201c66eac73e8c930465612672dbcfdac138ebe | Aditi1203/CMPE-295 | /Dataset_CYBHi/SegmentedScalogramFromCSV.py | 3,805 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
"""
Script to generate Scalograms from CSV files.
1. Change variable path to folder loacation of the dataset.
2. Change variable path1 to path+/Scalogram
3. Change number of items
Tip: If program crashes, and suppose 2 subjects are completed, copy those 2 subject scalograms
and save it somewhere else.
"""
import pandas as pd
import numpy as np
#import cv2
import os
#import imutils
from PIL import Image
from skimage import io
import imutils
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pywt
from scipy import signal
#import ecg_plot
def load_data(number_of_items=100):
# -----------------------------------Change variable here------------------
path = "butterworth_segments"
if not os.path.exists(path+"/Scalogram"):
os.makedirs(path+"/Scalogram")
# -----------------------------------Change variable here------------------
path1 = "scalogram_module/Scalogram"
data = []
curated_data = {"segments": []}
for subject_name in os.listdir(path)[:number_of_items]:
if not os.path.exists(path1+"/"+subject_name):
os.makedirs(path1+"/"+subject_name)
if subject_name == ".DS_Store":
continue
if subject_name == "Scalogram":
continue
print("Going through subject:" + subject_name)
base = os.path.basename(path+"/"+subject_name)
labelData = os.path.splitext(base)[0]
print(labelData)
i = 0
for items in os.listdir(path+"/"+subject_name):
if items == ".DS_Store":
continue
else:
try:
if items.endswith(".csv"):
i = i+1
print(str(i)+" begin")
scalName = str(items)+".png"
df1 = np.genfromtxt(
path+"/"+subject_name+"/"+items, delimiter=',')
# print(type(df1))
# -----------------------To show Segment plot. Comment scalogram plt---
# plt.plot(df1)
# plt.show()
# -----------------------------------------------
im1 = df1
cwtmatr, freqs = pywt.cwt(
im1, 14, 'mexh', sampling_period=360)
plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',
vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) # doctest: +SKIP
# -------------To display scalogram------------
# plt.show() # doctest: +SKIP
# -----------------------------------------------
plt.savefig(path1+"/"+subject_name+"/"+scalName)
# image1=cv2.imread(path+"/Scalogram"+"/"+subject_name+"/"+items)
# -------To display saved png image------------------------
# plt.imshow(image1)
# plt.show()
# ------------------------------------------------------
plt.close()
del(im1)
del(df1)
# curated_data['segments'].append(df1)
# print(df1)
except:
df = None
# data.append(data_model) # Save all the data
return {}
# -----------------------------------Change variable here------------------
# --------------------Change number_of_items to 24 or as many number of people you want to convert---
data = load_data()
|
14fa5284e40a1e254b709e0e5d44202d3b61be59 | dylcruz/Python_Crash_Course | /chapter 7/whileDictionaries.py | 928 | 3.703125 | 4 | unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for user in confirmed_users:
print(user.title())
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
print()
responses = {}
polling_active = True
while polling_active:
name = input("What is your name? ")
response = input("What mountain would you like to climb some day? ")
responses[name] = response
repeat = input("Would you like to let another person respond (y/n)? ")
if repeat == 'n':
polling_active = False
print("\n---- Poll Results ----")
for name, response in responses.items():
print(name.title() + " would like to climb Mount " + response.title()) |
87f5f7f5da418e8d1dfb0413229658e668e5eee9 | pisces0009/PythonProgram | /hamburger7.py | 2,572 | 4.1875 | 4 | ##############################################################
# fILE: humberger7.py
# Author: Prasad Kale
# Date: january.24,2018
# Purpose:Calculating cost or burgers, drinks and french fries
##############################################################
# print headings
print("\n ... Hamburger 7 ....")
print("======================\n")
#declaration of price constant
costHamburger =1.75
costCheese =0.55
costDrink =0.99
costFrenchFries =1.55
#i/p order and amount received from customer
noHamburgers = input("\n enter amount hamburgers desired==>")
cheese = input("\nDo you want cheese on it?(Y/N)==>")
#decide weather cheese is required
if cheese == 'Y' or cheese == 'y':
noCheeses = input("\nHow many with cheese?,0 for none ==>$")
else:
noCheeses = 0
#endif
#input number of drinks and fries
noDrinks =input("\nEnter amount of drink desired,0 for none ==>$ ")
noFrenchFries=input("\nEnter the number of french fries desired, 0 for none ==>$")
#calc cost of hamburgers
hambCost = float(noHamburgers) * costHamburger
print("....cost of burger is $",hambCost)
#add cost of cheese
cheeseCost = float(noCheeses) * costCheese
print("....cost of cheese is $",cheeseCost)
#add cost of drinks
drinkCost = float(noDrinks) * costDrink
print("....cost of drink is $",drinkCost)
#add cost of french fries
ffCost = float(noFrenchFries) * costFrenchFries
print("....cost of french fries is $",ffCost)
totalCost = hambCost + cheeseCost + drinkCost + ffCost
print("....total cost is $",totalCost)
#input payment amount
amtGiven = input("\nAmount tended:$")
#calculate change
change = float(amtGiven) - totalCost
#output change
print("\n your change from", amtGiven,"dollars is $", change)
print("\n....end of job...")
#end main
#########################################################################################
OUTPUT:
#########################################################################################
C:\Users\PRASAD>hamburger7.py
... Hamburger 7 ....
======================
enter amount hamburgers desired==>10
Do you want cheese on it?(Y/N)==>y
How many with cheese?,0 for none ==>$10
Enter amount of drink desired,0 for none ==>$ 10
Enter the number of french fries desired, 0 for none ==>$10
....cost of burger is $ 17.5
....cost of cheese is $ 5.5
....cost of drink is $ 9.9
....cost of french fries is $ 15.5
....total cost is $ 48.4
Amount tended:$50
your change from 50 dollars is $ 1.6000000000000014
....end of job...
######################################################################################### |
c125e75056756b38768472bc67e1094603be5453 | carlosmontoyargz/Introduction-to-Algorithms | /Foundations/Find-Maximum-Subarray-Lineal.py | 1,104 | 4 | 4 | #!/usr/bin/python
"""Programa que encuentra la mayor subsecuencia dentro de un arreglo.
A diferencia de la version recursiva, este algoritmo se ejecuta en tiempo
lineal.
"""
def FindMaximumSubarray(A):
"""Encuentra la mayor subsecuencia dentro de la lista A.
Si se recibe una lista vacia se lanza una excepcion de tipo IndexError.
Retorna:
max_left -- El indice izquierdo del subarreglo
max_right -- El indice derecho del subarreglo
suma -- La suma total del subarreglo
"""
max_left = 0
max_right = 0
suma = A[0]
p = 0
suma_p = A[0]
for i in range(1, len(A)):
suma_p += A[i]
if suma_p <= 0:
p = i
suma_p = A[i]
if suma_p > suma:
max_left = p
max_right = i
suma = suma_p
return (max_left, max_right, suma)
A = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]
print(A)
res = FindMaximumSubarray(A)
print A[res[0]:res[1] + 1], res[2]
B = [-2, -1, -13, -4, -3, -7]
print(B)
res = FindMaximumSubarray(B)
print B[res[0]:res[1] + 1], res[2]
|
d985eb10992757ffe787a228ccf70c8536a2dd4e | yuuuhui/Basic-python-answers | /梁勇版_6.5.py | 985 | 4.15625 | 4 | num1,num2,num3 = eval(input("Enter three numbers as x,y,z:"))
def sort(num1,num2,num3):
if num1 <= num2 and num1 <= num3:
print(num1,end = " ")
if num2 <= num3:
print(num2,end = " ")
print(num3,end = " ")
elif num3 < num2:
print(num3,end = " ")
print(num2,end =" ")
elif num2 <= num1 and num2 <= num3:
print(num2,end = " ")
if num1 <= num3:
print(num1,end =" ")
print(num3,end =" ")
elif num3 < num1:
print(num3,end =" ")
print(num1,end =" ")
elif num3 <= num1 and num3 <= num2:
print(num3,end = " ")
if num1<= num2:
print(num1,end = " ")
print(num2,end = " ")
elif num2< num3:
print(num2,end = " ")
print(num1,end = " ")
elif num1 == num2 == num3:
print(num1,num2,num3)
sort(num1,num2,num3)
|
93ad90574a520db5c75ad77c773bd45f9bf3801b | MaryanneNjeri/pythonModules | /.history/robort_20200727110140.py | 550 | 3.890625 | 4 | def uniquePaths(m,n):
# use dynamic programming and answer is at arr[m][n]
# let's create and empty grid with 0's
grid = [[0 for x in range(m)] for y in range(n)]
print(grid)
# then using the top down uproach we shall prefill all the
# i,j i = 0 and j+1
# then i +1 ,j = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if i == 0 or j == 0:
grid[i][j] = 1
print(grid)
uniquePaths(3,2) |
d692240c2fbea8c09d39fad50598d96ffd5af3a2 | swj8905/Onlie_Live_0529 | /03_곱셈 계산기.py | 170 | 3.578125 | 4 | num1 = int(input("첫번째 숫자 >> ")) # int() : 문자열 --> 정수형
num2 = int(input("두번째 숫자 >> "))
print(f"곱셈 결과는 {num1 * num2}입니다.")
|
bdaf8cdd71d6f31b1bb9f4ca00fd90bb997e410e | Maxwell-Hunt/NEAT | /Main.py | 1,066 | 3.625 | 4 | from Population import Population
from Network import Network
from math import floor
#################################
class Player:
def __init__(self,brain=None):
self.brain = None
if(brain == None):
self.brain = Network(2,1)
else:
self.brain = brain
def update(self):
self.brain.fitness += self.brain.feedForward([0,1])[0]
self.brain.fitness += self.brain.feedForward([1,0])[0]
self.brain.fitness += 1 - self.brain.feedForward([0,0])[0]
self.brain.fitness += 1 - self.brain.feedForward([1,1])[0]
self.brain.fitness *= self.brain.fitness
self.brain.fitness *= 10
pop = Population(Player,150,fitnessGoal=120,initiallyConnected=True,stepSize=0.8)
def go():
pop.run()
print("--------------")
print("Running Generation " + str(len(pop.bestOverTime)))
print("--------------")
print(pop.bestFit)
print(pop.avgFit)
pop.evaluate()
while pop.solution == None:
go()
pop.plot()
|
5e7d16c58fcf416397368706b7e9296831f5d0df | masset151/Grupo-5---Entorno-Servidor | /Sprint 2/Individual/Andres Masset/Practica_02.py | 3,147 | 3.578125 | 4 | import math
# ==========================================================
# Desarrollo Web - Entorno Servidor
# Ciclo Superior Desarrollo Web
# Curso 2020-21
# Segunda práctica
# ===========================================================
# APELLIDOS, NOMBRE:
# DNI:
# Práctica 2: Programación orientada a objetos
# =================================
# En esta práctica veremos algunos ejercicios de Python, con una
# orientación a objetos.
# -----------
# EJERCICIO 1
# -----------
#
# Escribir una clase general llamada "Figura" con los atributos de
# cualquier figura geométrica. Posteriormente se pide implementar las
# clases "Círculo", "Cuadrado" y "Triángulo" con sus correspondientes
# atributos y funciones.
# En este ejercicio os tendréis que enfrentar con la herencia entre clases,
# colocando toda la información general en la clase "Figura" y
# posteriormente sobreescribir esos métodos con los diferentes
# comportamientos de cada figura.
# Por ejemplo:
#
# La clase "Cuadrado" tendrá una función area donde se devolverá el
# area de un cuadrado.
#
# Nota: Son necesarios los siguientes datos, perímetro, area, diámetro.
class Figura():
def ___init___(self,perimetro,area,diametro,a,b):
self.perimetro = perimetro
self.area = area
self.diametro = diametro
def AreaCuadrado(a,b):
area = a*b
return area
def PerimetroCuadrado(a,b):
perimetro = a + a + b + b
return perimetro
def AreaCirculo(a):
b = math.pi
area = b * a ** 2
return area
def DiametroCirculo(a):
diametro = a * 2
return diametro
def PerimetroCirculo(a):
b = math.pi
perimetro = 2 * b * a
return perimetro
def AreaTriangulo(a,b):
area = a*b/2
super(Figura,)
return area
def PerimetroTriangulo(a,b,c):
perimetro = a+b+c
return perimetro
class Cuadrado(Figura):
a = 0
b = 0
def ___init___(self,perimetro,area):
self.area = area
self.perimetro = perimetro
Figura.AreaCuadrado(a,b)
Figura.PerimetroCuadrado(a,b)
class Circulo(Figura):
a = 0
def ___init___(self,perimetro,area,diametro,a,b):
self.area = area
self.perimetro = perimetro
self.diametro = diametro
self.a = a
self.b = b
Figura.AreaCirculo(a)
Figura.PerimetroCirculo(a)
Figura.DiametroCirculo(a)
class Triangulo(Figura):
a = 0
b = 0
c = 0
def ___init___(self,perimetro,area,diametro,a,b,c):
self.perimetro = perimetro
self.area = area
self.diametro = diametro
Figura.AreaTriangulo(a,b)
Figura.PerimetroTriangulo(a,b,c)
print(" Area Cuadrado ",Cuadrado.AreaCuadrado(5,10))
print(" Perimetro Cuadrado ",Cuadrado.PerimetroCuadrado(5,5))
print(" Area Circulo ",Circulo.AreaCirculo(5))
print(" Diametro Circulo",Circulo.DiametroCirculo(5))
print(" Perimetro de un Circulo",Circulo.PerimetroCirculo(5))
print(" Area Triangulo ",Triangulo.AreaTriangulo(5,10))
print(" Perimetro Triangulo",Triangulo.PerimetroTriangulo(5,5,5))
|
58523e7fa797343e7995a7d35ec1f2f85dc0245c | nullgad/learnPython | /working_scripts/quadraticEquation.py | 1,155 | 4.28125 | 4 | #How to find the root of a quadratic equation
#the equation is (-b+sqrt((sqr(b)-4*a*c)))/2a and (-b-sqrt((sqr(b)-4*a*c)))/2a
#
import math
print("\n\n\nSimple Calculatr to find the Root of a Quadatic Eqution!..\n\n\n")
print("The Quadratic equation is (ax^2)+bx+c where a not= 0\n\n\n")
a=int(input("Enter the value of a : "))
b=int(input("Enter the value of b : "))
c=int(input("Enter the value of c : "))
if a!= 0:
print("our Quadratic Equation is :" "("+str(a)+ "x^2)+"+str(b)+"x+"+str(c)+"\n")
# equation (-b+sqrt((sqr(b)-4*a*c)))/2a
#finding determinant = (b^2)-4ac
def base(num1,num3):
return (b**2)-(4*num1*num3)
det=base(a,c)
if det == 0 :
root1=-b/(2*a)
print("the root -b/(2a)= " + str(root1))
elif det > 0:
root2=((-b-(math.sqrt(det)))/(2*a))
root3=((-b+(math.sqrt(det)))/(2*a))
print("the root -b+-((b^2)-(4ac))/(2a)= \n\n" + str(root2)+ "\n" + " and "+ "\n" + str(root3))
else :
print("The asnwer includes an Imaginary number which at this point am not able to do in python ")
else:
print("Qadratic equation cannot have value of a = 0 \n")
|
c34f427615f0189fc9251ab686510c5b687f24ce | loqum/Curso-Python | /Tema13_Ejercicio1.py | 1,014 | 3.890625 | 4 | import sqlite3
NAME_TABLE = "Coches"
def get_connection(name_db):
return sqlite3.connect(name_db)
def create_table(cursor, name_table):
cursor.execute(name_table)
def insert_table(db_connection, cursor, name_table, item):
cursor.execute("INSERT INTO " + name_table + " VALUES (" + item + ")")
db_connection.commit()
def show_all_table(db_cursor, name_table):
return db_cursor.execute("SELECT * FROM " + NAME_TABLE).fetchall()
def show_by_name(db_cursor, name_table, name_car):
return db_cursor.execute("SELECT * FROM " + name_table + " WHERE Nombre = '" + name_car + "'").fetchall()
db_connection = get_connection('C:/Users/ruben/OneDrive/Python/ejemplo.db')
db_cursor = db_connection.cursor()
#create_table(db_cursor, "CREATE TABLE Coches (Id INT, Nombre TEXT, Precio INT)")
#insert_table(db_connection, db_cursor, "Coches", "1, 'Mercedes', 54000")
#print(show_all_table(db_cursor, NAME_TABLE))
#print(show_by_name(db_cursor, NAME_TABLE, "Mercedes"))
db_connection.close()
|
231ce3073491d5f42fc20753bb916a1827963829 | AhmedRaafat14/CodeForces-Div.2A | /118A - StringTask.py | 1,743 | 3.59375 | 4 | """
Petya started to attend programming lessons.
On the first lesson his task was to write a simple program.
The program was supposed to do the following: in the given string,
consisting if uppercase and lowercase Latin letters, it:
1. deletes all the vowels,
2. inserts a character "." before each consonant
3. replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants.
The program's input is exactly one string, it should return the output as a
single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task.
==============
Input
The first line represents input string of Petya's program.
This string only consists of uppercase and lowercase Latin letters and
its length is from 1 to 100, inclusive.
==============
Output
Print the resulting string. It is guaranteed that this string is not empty.
==============
Sample test(s)
Input
tour
Output
.t.r
Input
Codeforces
Output
.c.d.f.r.c.s
Input
aBAcAba
Output
.b.c.b
"""
## Running Time ========> 122 ms
## input string of Petya's program
user_word = raw_input()
## convert it to lower case string
## 3. replaces all uppercase consonants with corresponding lowercase ones.
user_word = user_word.lower()
## define vowels string
vowels = 'aoyeui'
## define new word
new_word = ''
## loop through user string and check if character not in vowels string
## add it to new word string and add before it '.'
## 1. deletes all the vowels,
## 2. inserts a character "." before each consonant,
for char in user_word:
if char not in vowels:
new_word += '.' + char
## print new word
print(new_word)
|
ce9a0aaccc2591e315565500719b295eeefef2ef | EinarPall/skoli | /assignment 5/ass5.py | 1,094 | 4.03125 | 4 | # Assignment 5
# dæmi 1
# Algorithm that finds the maximum positive interger input by user.
# The user repeatedly inputs numbers until a negative value is entered.
# num_int = int(input("Input a number: ")) # Do not change this line
# # Fill in the missing code
# max_int = 0
# while num_int >= 0:
# if num_int > max_int:
# max_int = num_int # max_int verður að num_int ef inputtið hjá user er stærra en inputtin að undan
# # og max_int helst þá í stærstu tölunni
# num_int = int(input("Input a number: "))
# print("The maximum is", max_int) # Do not change this line
# dæmi 2
# summ 3 seinsutu tölur saman til að fá næstu
# input, hvað þú vilt fá margar tölur
# u=+3+6+11
# print(u) = 20
n = int(input("Enter the length of the sequence: ")) # Do not change this line
n1=1
n2=2
n3=3
if n == 1:
print(n1)
elif n == 2:
print(n1,n2)
elif n == 3:
print(n1,n2,n3)
else:
print(n1,n2,n3,end=' ')
for i in range(4,n+1):
n4=n1+n2+n3
print(n4,end=' ')
n1=n2
n2=n3
n3=n4
|
163003d9beff3d1eadb5a7c7cc2e819323373563 | ITAM-Coding-Rush/Coding-Rush-19 | /semana1/CR19-El-numero-perfecto/solutions/90.py | 274 | 3.59375 | 4 | n = int(input())
if n == 0:
print("No es perfecto")
else:
if n < 0:
n = - n
sumadiv = 0
for i in range(1, n):
if n % i == 0:
sumadiv += i
if n == sumadiv:
print("Es perfecto")
else:
print("No es perfecto")
|
53180a05ec22042a9a4cf965b154107e90015936 | Android-Ale/PracticePython | /mundo3/Teste.py | 1,484 | 4.15625 | 4 | print("PADARIA ELIZA MARTINEZ")
print("Digite 'A' para refrigerante")
print("Digite 'B' para salgados")
b = input('O que você deseja ?')
if b == 'A' or b == 'a':
print('Refrigerantes:')
print('Guarana Antartica [1]')
print('Coca Cola [2]')
print('Fanta [3]')
print('Dole Guarana [4]')
print('Pepse [5]')
print('Digite o número: ')
n = int(input())
if n == 1:
print('Você quer Guarana Antartica ?')
print('Digite (s) para sim ou (n) para não.')
p = str(input()).lower()
if p == 's':
print('Ok')
else:
if p == 'n':
print('Escolha outro')
else:
print('tente novamente')
if n == 2:
print('Você quer Coca Cola ?')
print('Digite (s) para sim ou (n) para não.')
p = str(input()).lower()
if p == 's':
print('Ok')
else:
if p == 'n':
print('Escolha outro')
else:
print('tente novamente')
if n == 3:
print('Você quer Fanta ?')
print('Digite (s) para sim ou (n) para não.')
p = str(input()).lower()
if p == 's':
print('Ok')
else:
if p == 'n':
print('Escolha outro')
else:
print('tente novamente')
if n == 5:
print('Você quer Pepse ?')
print('Digite (s) para sim ou (n) para não.')
p = str(input()).lower()
if p == 's':
print('Ok')
else:
if p == 'n':
print('Escolha outro')
else:
print('tente novamente')
|
37979080cc5065fb552bee1e10cecd027191ab47 | lm-t/cs9h | /unit_converter.py | 2,058 | 4.25 | 4 | 'Project 2a: Unit Converter'
print '''\n\t\tUnit Converter by Luis Torres
You can convert Distances , Weights , and Volumes to one another,
but only within units of the same category, which are shown below.'''
print "Input your measurements to convert in the following format '1 ft in m'."
print '''\n Distances: ft cm mm mi m yd km in
Weights: lb mg kg oz g
Volumes: floz qt cup mL L gal pint\n'''
distances_m = {'m': 1.0, 'cm': 0.01, 'mm': 0.001, 'km': 1000, 'in': 0.0254, 'ft': 0.3048, 'yd': 0.9144, 'mi': 1609.34}
weights_kg = {'kg': 1.0, 'g': 0.001, 'mg': 0.000001, 'oz': 0.0283495, 'lb': 0.453592}
volumes_L = {'L': 1.0, 'mL': 0.001, 'gal': 3.78541, 'pint': 0.473176, 'qt': 946353, 'cup': 0.236588, 'floz': 0.0295735}
def conversions(amount, conv_from, conv_to):
"""Returns converted amount from conv_from to conv_to.
>>> conversions(120, 'mL', 'L')
0.12
>>> conversions(150, 'lb', 'kg')
68.0388
"""
if conv_from in distances_m:
return (distances_m[conv_from] / distances_m[conv_to]) * amount
elif conv_from in weights_kg:
return (weights_kg[conv_from] / weights_kg[conv_to]) * amount
else:
return (volumes_L[conv_from] / volumes_L[conv_to]) * amount
def user_input():
"""Takes input from the user and returns the converted amount. It keeps on repeating until the user wants to quit"""
string = raw_input("What would you like to convert?, type 'q' to quit: ")
if 'q' in string:
return None
elif ' in ' not in string or len(string.split(' ')) != 4:
print "format unclear, please follow the format '1 ft in m'"
return user_input()
else:
input = string.split(' ')
amount = float(input[0])
conv_from = input[1]
conv_to = input[3]
conv_num = conversions(amount, conv_from, conv_to)
if '.' in input[0]:
print "%f %s = %f %s" % (amount, conv_from, conv_num, conv_to)
else:
print "%d %s = %f %s" % (amount, conv_from, conv_num, conv_to)
return user_input()
user_input()
|
d10d37582ad0ec2b2c7b28e5e95f6af80d266344 | gitMan2019/Python-Java-work | /randomness_perpetua.py | 6,143 | 3.84375 | 4 | # Randomness Perpetua
"""
Pygame base template for opening a window
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import pygame
PI = 3.14159
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
ORANGE = (255, 128, 0)
pygame.init()
# Set the width and height of the screen [width, height]
size = (700, 700)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Randomness Perpetua")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Rectangle starting point for x
rect_x = 0
# Rectangle increment
rect_change_x = 5
# Yellow circle starting point for y
cir_y = 50
# Yellow circle increment
cir_change_y = 5
# Orange circle starting point for x
cir_x = 150
# Orange circle increment
cir_change_x = 5
# Starting points for stick figure
# Starting points for left leg
leg1_x = 200
leg1_y = 500
leg1_2x = 250
leg1_2y = 400
# Increments for left leg
leg1_change_x = 2
leg1_change_y = 0
leg1_change_2x = 2
leg1_change_2y = 0
# Starting points for right leg
leg2_x = 300
leg2_y = 500
leg2_2x = 250
leg2_2y = 400
# Increments for right leg
leg2_change_x = 2
leg2_change_y = 0
leg2_change_2x = 2
leg2_change_2y = 0
# Starting points for body
body_x = 250
body_y = 400
body_2x = 250
body_2y = 300
# Increments for body
body_change_x = 2
body_change_y = 0
body_change_2x = 2
body_change_2y = 0
# Starting points for left arm
arm1_x = 200
arm1_y = 350
arm1_2x = 250
arm1_2y = 350
# Increments for left arm
arm1_change_x = 2
arm1_change_y = 0
arm1_change_2x = 2
arm1_change_2y = 0
# Starting points for right arm
arm2_x = 250
arm2_y = 350
arm2_2x = 300
arm2_2y = 350
# Increments for right arm
arm2_change_x = 2
arm2_change_y = 0
arm2_change_2x = 2
arm2_change_2y = 0
# Starting points for head
head_x = 220
head_y = 240
# Increments for head
head_change_x = 2
head_change_y = 0
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
if cir_y > 659 or cir_y < 42:
cir_change_y *= -1
if cir_x > 659 or cir_x < 150:
cir_change_x *= -1
if arm2_2x > 500:
leg1_change_x = 0
leg1_change_y = 5
leg1_change_2x = 0
leg1_change_2y = 5
leg2_change_x = 0
leg2_change_y = 5
leg2_change_2x = 0
leg2_change_2y = 5
body_change_x = 0
body_change_y = 5
body_change_2x = 0
body_change_2y = 5
arm1_change_x = 0
arm1_change_y = 5
arm1_change_2x = 0
arm1_change_2y = 5
arm2_change_x = 0
arm2_change_y = 5
arm2_change_2x = 0
arm2_change_2y = 5
head_change_x = 0
head_change_y = 5
if head_y > 699:
done = True
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
screen.fill(BLUE)
# --- Drawing code should go here
# Prints more silly text when arm reaches certain point
if arm2_2x > 500:
font = pygame.font.SysFont("Calibri", 25, True, False)
text = font.render("Oh no! Mr. Bill!", True, WHITE)
screen.blit(text, [150, 180])
# Printing silly text to screen
font = pygame.font.SysFont("Calibri", 25, True, False)
text = font.render("Two suns?! I must be on Tatooine.", True, WHITE)
screen.blit(text, [150, 150])
# Draw green rectangle for ground
pygame.draw.rect(screen, GREEN, [rect_x, 500, 700, 200])
rect_x += rect_change_x
# Draw yellow circle for sun
pygame.draw.circle(screen, YELLOW, [50, cir_y], 40)
cir_y += cir_change_y
# Draw orange circle for other sun
pygame.draw.circle(screen, ORANGE, [cir_x, 50], 40)
cir_x += cir_change_x
# Draw two legs for body of guy
pygame.draw.line(screen, BLACK, [leg1_x, leg1_y], [leg1_2x, leg1_2y], 3)
# Only need to horizontally move leg
leg1_x += leg1_change_x
leg1_y += leg1_change_y
leg1_2x += leg1_change_2x
leg1_2y += leg1_change_2y
# Only need to horizontally move leg
pygame.draw.line(screen, BLACK, [leg2_x, leg2_y], [leg2_2x, leg2_2y], 3)
leg2_x += leg2_change_x
leg2_y += leg2_change_y
leg2_2x += leg2_change_2x
leg2_2y += leg2_change_2y
# Draw line for body and another for arms
pygame.draw.line(screen, BLACK, [body_x, body_y], [body_2x, body_2y], 3)
body_x += body_change_x
body_y += body_change_y
body_2x += body_change_2x
body_2y += body_change_2y
# Draw line for left arm
pygame.draw.line(screen, BLACK, [arm1_x, arm1_y], [arm1_2x, arm1_2y], 3)
arm1_x += arm1_change_x
arm1_y += arm1_change_y
arm1_2x += arm1_change_2x
arm1_2y += arm1_change_2y
# Draw line for right arm
pygame.draw.line(screen, BLACK, [arm2_x, arm2_y], [arm2_2x, arm2_2y], 3)
arm2_x += arm2_change_x
arm2_y += arm2_change_y
arm2_2x += arm2_change_2x
arm2_2y += arm2_change_2y
# Draw full circle arc for head
pygame.draw.arc(screen, BLACK, [head_x, head_y, 60, 60], 0, 2*PI, 3)
head_x += head_change_x
head_y += head_change_y
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(20)
# Close the window and quit.
pygame.quit()
|
4bc69bebf504e10b27a568bed254db2896212f4f | Chantlog/Python-Projects | /guess.py | 396 | 4.09375 | 4 | import random
number = random.randrange(0,100)
guessedCorrectly = False
while guessedCorrectly == False:
guessed = int(input("Guess the number between 1-100: "))
if(number < guessed):
print("\n Number is lower, try again")
elif(number > guessed):
print("\n Number is higher, try again!")
else:
print("You got the number!")
guessedCorrectly = True |
2dcfc8ecf8614461b800adc3650aaab0b451f4df | rsacpp/misc | /qsort.py | 1,658 | 3.515625 | 4 | import random
def swap(arr, indexA, indexB):
if indexA == indexB:
return
if arr[indexA] == arr[indexB]:
return
arr[indexA], arr[indexB] = arr[indexB], arr[indexA]
def sort(arr, fromIndex, toIndex):
if fromIndex >= toIndex:
return
if fromIndex + 1 == toIndex:
if arr[fromIndex] > arr[toIndex]:
swap(arr, fromIndex, toIndex)
return
threshold = arr[fromIndex]
headIndex = fromIndex + 1
tailIndex = toIndex
while headIndex < tailIndex:
while headIndex < tailIndex:
if arr[headIndex] >= threshold:
break
else:
headIndex+=1
if headIndex == tailIndex:
break
while headIndex < tailIndex:
if arr[tailIndex] < threshold:
break
else:
tailIndex-=1
if headIndex == tailIndex:
break
if headIndex < tailIndex:
arr[headIndex] , arr[tailIndex] = arr[tailIndex], arr[headIndex]
headIndex+=1
tailIndex-=1
if headIndex > tailIndex:
pass
# 3, [1,2,1,0]
if arr[headIndex] < threshold:
swap(arr, fromIndex, headIndex)
sort(arr, fromIndex, headIndex - 1)
sort(arr, headIndex, toIndex)
# 3, [1, 2, 1,3]
if arr[headIndex] >= threshold:
swap(arr, fromIndex, headIndex -1)
sort(arr, fromIndex, headIndex -1)
sort(arr, headIndex, toIndex)
arr = []
n = 999
rangeFrom = 1
rangeTo = 0x123
for _ in range(0, n):
arr.append(random.randint(rangeFrom, rangeTo))
print(arr)
sort(arr, 0, n-1)
print(arr)
|
868851d699cb9b593142970c0a465c39526967dd | shubhamsahu02/cspp1-assignments | /M5/p3/square_root_bisection.py | 493 | 4 | 4 | # Write a python program to find the square root of the given number
# using approximation method
# testcase 1
# input: 25
# output: 4.999999999999998
"""Square root bisection"""
# testcase 2
# input: 49
# output: 6.999999999999991
INPUT_STRING = int(input())
EPSI_LON = 0.01
LOW = 0
HIGH = INPUT_STRING
GUESS = (LOW+HIGH)/2
while abs(GUESS**2-INPUT_STRING) >= EPSI_LON:
if GUESS**2 > INPUT_STRING:
HIGH = GUESS
else:
LOW = GUESS
GUESS = (LOW+HIGH)/2
print(GUESS)
|
ffd0be2fd32b1a1d6f85f29328de95758752ec40 | DamoM73/work-projects | /progress_report.py | 1,496 | 3.625 | 4 | import csv
class Student:
def __init__(self, given_name, family_name, email):
self.given_name = given_name
self.family_name = family_name
self.email = email
self.activities = []
def print_student(self):
print(self.given_name, self.family_name, self.email, end=" ")
for activity in self.activities:
print(activity.name, activity.progress, end=" ")
print("\n")
def add_activity(self,name):
self.activities.append(Activity(name))
class Subject:
def __init__(self, name):
self.name = name
self.students = []
def add_student(self,given_name, family_name, email):
self.students.append(Student(given_name,family_name,email))
def print_class(self):
for student in self.students:
student.print_student()
def add_activity(self,name):
for student in self.students:
student.add_activity(name)
def print_activities(self):
for activity in self.students[0].activities:
print(activity.name)
class Activity:
def __init__(self,name):
self.name = name
self.progress = 0
def load_students(Subject):
with open("students.csv", 'r') as file:
reader = csv.reader(file)
for row in reader:
Subject.add_student(row[0],row[1],row[2])
test = Subject("Test")
load_students(test)
test.add_activity("Test A")
test.print_class()
test.print_activities() |
a1542ee2517d421da24428a2860b162a17ca4be1 | berdoezt/Python-Challenge | /solution/15.py | 169 | 3.5625 | 4 | #!/usr/bin/python
import calendar
for i in range(1000, 2000):
if calendar.isleap(i):
c = calendar.monthcalendar(i, 1)
if c[0][3] == 1 and i % 10 == 6:
print i |
ef0b6f85a08479e5ac92c5f6083343309e176868 | MaKToff/SPbSU_Homeworks | /Semester 5/Formal languages/tester.py | 2,246 | 3.671875 | 4 | """
Tester for grammar.
Authors: Mikhail Kita, Sharganov Artem
"""
import sys
# Reads grammar rules from specified file.
def load_grammar(filename):
grammar = []
with open(filename, 'r') as f:
text = f.readlines()
for line in text:
left, right = line.split(" -> ")
right = right.replace("\n", "")
grammar.append((left, right))
return grammar
# Checks whether grammar can derive given string.
def check(grammar, string):
if (string == "00") | (string == "10"):
string = "S"
elif "1" in string:
string = "#" + string + "[q1]$"
elif len(string) > 2:
string = "#" + string[:-2] + "[q1]$"
derivation = []
finished = False
while not finished:
finished = True
for rule in grammar:
s = string.replace(rule[0], rule[1], 1)
if s != string:
string = s
derivation += [rule[0] + " -> " + rule[1]]
finished = False
break
if all(elem in ["0", "1"] for elem in string):
return derivation
# Generates all strings, which can be derived by the type-0 grammar.
def language0():
strings = ["1"]
for elem in strings:
derivation = check(grammar0, elem)
if derivation:
print(elem + " = " + str(int(elem, 2)))
strings += [elem + "0", elem + "1"]
# Generates all strings, which can be derived by the type-1 grammar.
def language1():
string = "0"
while True:
derivation = check(grammar1, string)
if derivation:
print(string + " = " + str(len(string)))
string += "0"
# Prints given derivation.
def print_derivation(derivation):
if derivation:
print(*derivation, sep='\n')
else:
print("Can't derive given string.")
grammar0 = load_grammar("grammar_type0.txt")
grammar1 = load_grammar("grammar_type1.txt")
if len(sys.argv) == 3:
if sys.argv[1] == "-d0":
print_derivation(check(grammar0, sys.argv[2]))
elif sys.argv[1] == "-d1":
print_derivation(check(grammar1, sys.argv[2]))
if len(sys.argv) == 2:
if sys.argv[1] == "-t0":
language0()
elif sys.argv[1] == "-t1":
language1()
|
6a2e2187371783d05ebb7da65ebc70bc9a701c8b | Byliguel/python1-exo7 | /code/chaines/chaines_code_2_2.py | 565 | 3.59375 | 4 | def transforme_en_latin_cochon(mot):
""" Transforme un mot en latin-cochon
Entrée : un mot (une chaîne de caractères)
Sortie : le mot transformé en latin cochon s'il commence par une consonne. """
premiere_lettre = mot[0]
reste_mot = mot[1:len(mot)]
if premiere_lettre not in ["A", "E", "I", "O", "U", "Y"]:
latin_cochon = reste_mot + premiere_lettre + "UM"
else:
latin_cochon = mot
return latin_cochon
# Test
mot = "SALOPETTE"
latin = transforme_en_latin_cochon(mot)
print("Le mot",mot,"devient",latin,"!") |
9cd01f030efd169e4e0eb5c5ca5398aa2ad603c7 | addyp1911/Python-week-1-2-3 | /python/Algorithms/VendingMachine/VendingMachineBL.py | 663 | 4 | 4 |
# ----------------------------------vendingmachine prg-----------------------------------------------
# VendingMachine.py
# date : 26/08/2019
# method to calculate the minimum number of Notes as well as the Notes to be returned by the Vending Machine as change
def calculateChange(bill):
notes=[1000,500,100,50,20,10,5,2,1]
notes_counter=[]
for i in range(0,9):
if(bill>=notes[i]):
notes_counter.append(bill//notes[i])
bill=bill-notes[i]*notes_counter[i]
else:
notes_counter.append(0)
for i in range(0,9):
if(notes_counter[i]!=0):
print(notes[i], notes_counter[i] ) |
b80f95f63b86c7553be512216c44ec5cd5ba5d66 | luisnarvaez19/Proyectos_Python | /edu/cursoLN/funciones/1- args_por_default.py | 192 | 3.515625 | 4 | '''
Created on Agosto 18, 2019
modified on April 16, 2020
Funciones y argumentos por defecto
@author: luis.
'''
i = 5
def f(arg=i):
print(arg)
i = 6
f()
# +58414-2840599 Pydroid 3
|
61c854db7b0a9f7be7a8186215faddf5ff40a83a | bblinder/home-brews | /threader_app.py | 1,817 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Turns a twitter thread URL into a thethreaderapp.com URL for easier reading"""
import argparse
import sys
import requests
parser = argparse.ArgumentParser(description="Get the thread ID from a twitter URL")
parser.add_argument("url", help="the URL of the thread")
args = parser.parse_args()
valid_twitter_domains = ["twitter.com", "mobile.twitter.com", "t.co"]
def format_url():
"""Format the URL to be valid"""
twitter_url = args.url
# remove www. from the URL
if "www." in twitter_url:
twitter_url = twitter_url.replace("www.", "")
# add https:// if it's missing
if not twitter_url.startswith("https://") and not twitter_url.startswith("http://"):
twitter_url = "https://" + twitter_url
return twitter_url
url = format_url()
# Make a HEAD request to the URL to check if valid/still exists
def check_url(url):
"""Testing the URL"""
try:
response = requests.head(url, timeout=5)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
def get_thread_id(url):
"""Get the thread ID from a twitter URL"""
if check_url(url):
if not any(domain in url for domain in valid_twitter_domains):
print("Invalid URL")
sys.exit(1)
else:
# sanitize the URL of query strings
url = url.split("?")[0]
return url.split("/")[-1]
else:
print("Invalid URL")
sys.exit(1)
def threader_app():
"""Generate a threader.app URL"""
thread_id = get_thread_id(url)
threader_domain = "https://threadreaderapp.com/thread/"
threader_url = threader_domain + thread_id + ".html"
print(threader_url)
if __name__ == "__main__":
threader_app()
|
5f9d45a2fad20d9eb2bf9fcf13eb57fe52ecb0a8 | wanghan79/2020_Python | /2018012956韩旭作业/结课作业.py | 2,105 | 3.5 | 4 | # -*- coding: utf-8 -*-
import random
import string
import pymongo
def gen_random(dtype, num, datatange=(10, 1000), str_num=8):
"""
随机数生成
:return:
"""
try:
start, end = datatange
if dtype is int:
return [random.choice(range(start, end + 1)) for _ in range(num)]
elif dtype is float:
return [random.uniform(start, end + 1) for _ in range(num)]
elif dtype is str:
return [''.join([random.choice(string.ascii_letters) for _ in range(str_num)]) for x in range(num)]
else:
print('请参入int、float、str类型的数据')
except:
print('传入参数错误')
def random_search(dtype, result, *datarange):
"""
随机数搜索
:return:
"""
try:
start, end = datarange
if dtype is int:
return [x for x in result if start <= x <= end]
elif dtype is float:
return [x for x in result if start <= x <= end]
elif dtype is str:
return [x for x in result if x.find(start) > -1 or x.find(end) > -1]
else:
print('请参入int、float、str类型的数据')
except:
print('传入参数错误')
# myclient = pymongo.MongoClient("mongodb://localhost:27017/")
# mydb = myclient["random"]
# mycol = mydb["str"]
# mydict = {'data': gen_random(str, 10)}
# mycol.insert_one(mydict)
# y = mycol.find_one()['data']
# print(y)
# print(random_search(str, y, 'a', 'at'))
#
# myclient = pymongo.MongoClient("mongodb://localhost:27017/")
# mydb = myclient["random"]
# mycol = mydb["int"]
# mydict = {'data': gen_random(int, 10)}
# mycol.insert_one(mydict)
# y = mycol.find_one()['data']
# print(y)
# print(random_search(int, y, 20, 500))
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["random"]
mycol = mydb["float"]
mydict = {'data': gen_random(float, 10)}
mycol.insert_one(mydict)
y = mycol.find_one()['data']
print(y)
print(random_search(float, y, 30, 700))
|
d79ec35400af3d79f22d65d1e51e9793c5912c02 | MonikaSophin/python_base | /2.1 number.py | 1,882 | 3.546875 | 4 | import math;
import random;
"""
2.1 基本数据类型 -- Number(数字)
"""
## 赋值与删除
a = 1
print(a)
del a
## 数字类型转换
a = 1.0
print(a)
a = int(a)
print(a)
a = float(a)
print(a)
a = complex(a)
print(a)
## 数字运算
a, b = 3 , 2
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b) #取整余
print(a ** b) #幂乘
## 数字常量
print("pi =", math.pi)
print("e =", math.e)
## 数学函数
print("abs(-10) =", abs(-10)) #绝对值
print("max(1, 2, 5) =", max(1, 2, 5))
print("min(1, 2, 5) =", min(1, 2, 5))
print("round(1.5555, 2) =", round(1.5555, 2))
print("math.fabs(-10) =", math.fabs(-10)) #绝对值
print("math.ceil(4.1) =", math.ceil(4.1)) #向上取整
print("math.floor(4.1) =", math.floor(4.1)) #向下取整
x = 1; print("math.exp(1) =", math.exp(x)) #e的x次方
print("math.log(math.e**100) =", math.log(math.e**100)) #loge 默认基数常量e
print("math.log(4, 2) =", math.log(4, 2)) #log2
print("math.log2(4) =", math.log2(4)) #log2
print("math.log10(100) =", math.log10(100)) #log10
print("math.modf(2.5) =", math.modf(2.5))
print("math.pow(2, 3) =", math.pow(2, 3)) #次幂
print("math.sqrt(4) =", math.sqrt(4)) #平方根
#三角函数等
print(math.sin(math.pi/6)) # 以弧度为单位,求其正弦值 180°(角度) = π(弧度)
print(math.degrees(math.pi)) # 弧度转为角度
print(math.radians(180)) # 角度转为弧度
## 随机数函数
_list = range(0, 10)
print(random.choice(_list)) # 从序列中随机取得一个元素
print(random.randrange(0, 10, 2)) # 开始为0,结束为10,步长为2的集合中随机取一个元素
print(random.random()) # 随机生成下一个实数,它在[0,1)范围内。
_list = [1, 2, 3, 5, 8]; random.shuffle(_list); print(_list) # 将列表随机排序,然后返回None。
print(random.uniform(7, 9)) # 随机生成下一个实数,它在[x,y]范围内。
|
f931efaaf6ee632d5adc6f331b7ed7239d8e4681 | DarkEnergySurvey/despyServiceAccess | /bin/serviceAccess | 2,090 | 3.8125 | 4 | #!/usr/bin/env python3
"""
serviceAccess -- print information from a service access file
syntax: serviceAccess [-l] [-f file] [-s section | -t tag] format
Format is a string format string drawing items from a python
dictionary. Python dictionary formats are of the form
%(key-i-ndictionary)s .
Example: Format "%(server)s:%(port)s" would print DESTEST:1521 if
server were DESTEST and port were 1521.
Options:
-f file specifies a service access file. If absent the defaulting rules
in DESDM 3 are to find a file.
-t tag specifies a tag, defined in DESDM-3. When -s is absent, -t is
used to sense the environment for a section. Tags are upper cased.
tag is use to provide any tag-specific processing of the file, for
example -t db causes the program to supply database related defaults.
-s section specifies a section in file to be used for formatting the
format string.
-l specifies loose checking of the service access file.
"""
if __name__ == "__main__":
import sys
import despyserviceaccess.serviceaccess as serviceaccess
from optparse import OptionParser
parser = OptionParser(usage=__doc__)
parser.add_option("-f", "--file", dest="filename",
help="serviceaccess file.")
parser.add_option("-s", "--section", dest="section",
help="section in file to use")
parser.add_option("-t", "--tage", dest="tag",
help="serviceaccess file.")
parser.add_option("-l", "--loose", action="store_true", dest="loose",
help="minimal check service access file")
(options, args) = parser.parse_args()
if len(args) != 1 or (not options.tag and not options.section):
print(__doc__)
sys.exit(1)
fmt = args[0]
filename = options.filename
keys = serviceaccess.parse(options.filename, options.section, options.tag)
if not options.loose:
serviceaccess.check(keys, options.tag)
print(fmt % keys)
sys.exit(0)
|
56462a189bd159affccf95bc8555fa7f5deaed3d | aneeshkher/HackerRank | /Mathematics/Strange-Grid/solution.py | 265 | 3.65625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
line = raw_input("")
r, c = map(int, line.split())
if r % 2 == 0:
answer = (int(r/2) - 1)*10 + 1 + (c - 1)*2
else:
answer = int(math.floor(r/2))*10 + (c - 1)*2
print answer |
84570868fea7b46d7d3a77cb88107e958dc44db5 | Huanyu-Liu/pythonLearningScript | /bagels.py | 1,890 | 3.953125 | 4 | import random
def getSecretNum(numOfDigit):
numberList = list(range(10))
random.shuffle(numberList)
secretNum = ""
for i in range(numOfDigit):
secretNum += str(numberList[i])
return secretNum
def getClues(guess, secretNum):
clue = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clue.append("Fermi")
elif guess[i] in secretNum:
clue.append("Pico")
if len(clue) == 0:
clue.append("Bagel")
if guess == secretNum:
return "You got it"
return " ".join(clue)
def isOnlyDigit(num):
if num == "":
return False
for i in num:
if i not in "0 1 2 3 4 5 6 7 8 9".split():
return False
return True
def playAgain():
print("Do you want to play again? (Yes or no)")
return input().lower().startswith('y')
NUMDIGITS = 3
MAXGUESS = 10
print('I am thinking of a %s-digit number. Try to guess what it is.' % (NUMDIGITS))
print('Here are some clues:')
print('When I say: That means:')
print(' Pico One digit is correct but in the wrong position.')
print(' Fermi One digit is correct and in the right position.')
print(' Bagels No digit is correct.')
while True:
secretNum = getSecretNum(NUMDIGITS)
print("I have thought up a number. You have %s guesses to get it." %(MAXGUESS))
numberOfGuess = 1
while numberOfGuess <= MAXGUESS:
guess = ""
while len(guess) != NUMDIGITS or not isOnlyDigit(guess):
guess = input("Guess #%s:\n" %(numberOfGuess))
clue = getClues(guess,secretNum)
numberOfGuess += 1
print(clue)
if guess == secretNum:
break
if numberOfGuess > MAXGUESS:
print("You have run out of guesses. You lose!")
if not playAgain():
break
|
8b0acfd9c3070da288ce4ea548901eec93f15400 | Xlszyp/hello | /标准库/双端队列_collections模块/collections方法集合.py | 639 | 3.578125 | 4 | #!/usr/bin/python3
#-*-coding:UTF-8-*-
from collections import deque
q=deque(range(5))
print('双端队列:',q)
#在结尾添加元素
q.append(5)
print('添加5到结尾',q)
#在开头添加元素
q.appendleft(6)
print('添加6到开头',q)
#提取出结尾的元素
print('提取末尾元素:',q.pop())
print('末尾元素被提取后的队列:',q)
#提取开头的元素
print('提取左边元素:',q.popleft())
print('左边元素被提取后的队列:',q)
#rotate方法调整队列元素的位置
q.rotate(1)
print('队列中元素向前移1:',q)
q.rotate(-1)
print('队列中元素向后移1:',q)
|
831f1154f288b8f78c4c5e759e5b34f97844f144 | charleskausihanuni/B2-Group-Project | /Dropdown with Search.py | 2,159 | 3.546875 | 4 | from Tkinter import *
import sqlite3 as sql
master = Tk()
col = StringVar(master)
col.set("Colour")
option = OptionMenu(master, col,"Any","", "Black", "Blue", "Green", "Red", "Silver", "White")
option.pack()
loc = StringVar(master)
loc.set("Location")
option = OptionMenu(master, loc,"Any","", "Birmingham", "Cardiff", "Dublin", "Glasgow", "London", "Manchester")
option.pack()
seat = StringVar(master)
seat.set("Seats")
option = OptionMenu(master, seat,"Any","", "2", "5", "7")
option.pack()
door = StringVar(master)
door.set("Doors")
option = OptionMenu(master, door,"Any","", "3", "5")
option.pack()
minp = StringVar(master)
minp.set("Min")
option = OptionMenu(master, minp,"Any","", "1000")
option.pack()
maxp = StringVar(master)
maxp.set("Max")
option = OptionMenu(master, maxp,"Any","", "30000")
option.pack()
def search():
colour_id = col.get()
location_id = loc.get()
seat_id = seat.get()
door_id = door.get()
minPrice = minp.get()
maxPrice = maxp.get()
master.quit()
print(colour_id, location_id, seat_id, door_id, minPrice, maxPrice)
#Search algorithm for all criteria
db = sql.connect('Car_Database.sqlite')
cursor = db.cursor()
cursor.execute('''SELECT * FROM Cars WHERE Colour=? and Location=? and Seats=? and Doors=? and Price BETWEEN ? AND ?''', (colour_id, location_id, seat_id, door_id, minPrice, maxPrice,))
user = cursor.fetchall()
print(user)
db.close()
button = Button(master, text="Search", command=search)
button.pack()
mainloop()
#list of result from searching
resultList=user
#list for make names to be sorted
nameList=[]
#final sorted list
Sorted_Name_List=[]
for n in resultList:
nameList.append(n[0])
def quicksort(lst):
if not lst:
return []
return (quicksort([x for x in lst[1:] if x < lst[0]])
+ [lst[0]] +
quicksort([x for x in lst[1:] if x >= lst[0]]))
unsort_list = nameList
sort_list = quicksort(unsort_list)
for x in nameList:
for y in resultList:
if x!=y[0]:
pass
else:
Sorted_Name_List.append(y)
print(sort_list)
|
14a8d4817ae960425d17a6741b82ceb32ab42c0f | alfir-v10/IntroToCryptography | /stream_cipher/open_file.py | 874 | 3.515625 | 4 | import numpy as np
def open_f(file_name):
file = open(file_name,'r')
f = file.read()
s = f.split(',')
s = s[:-1]
print('Вы выбрали последовательность сгенерированная по методу М-последовательностей. Данный файл содержит последовательность длиной ' + str(len(s)))
interval_in_posled = input('Введите интервал из последовательности, который хотите выбрать для тестирования(например, 0 10 значит от [0,10]): ')
interval_in_posled = interval_in_posled.split(' ')
interval_in_posled = [int(k) for k in interval_in_posled]
s_otr = np.array(s[interval_in_posled[0]:interval_in_posled[1]], dtype=int)
return s_otr, interval_in_posled |
913cb8fae1cdcf4acd63547367304f76c50fa746 | ellinx/LC-python | /TheSkylineProblem.py | 3,558 | 3.953125 | 4 | """
A city's skyline is the outer contour of the silhouette formed by all the buildings
in that city when viewed from a distance.
Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A),
write a program to output the skyline formed by these buildings collectively (Figure B).
Buildings Skyline Contour
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi],
where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height.
It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
For instance, the dimensions of all buildings in Figure A are recorded as:
[ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .
The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline.
A key point is the left endpoint of a horizontal line segment.
Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height.
Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
Notes:
1. The number of buildings in any input list is guaranteed to be in the range [0, 10000].
2. The input list is already sorted in ascending order by the left x position Li.
3. The output list must be sorted by the x position.
4. There must be no consecutive horizontal lines of equal height in the output skyline.
For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable;
the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]
"""
class Solution(object):
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
#[x, start/end, h, idx]
# special case 1: building a ends and build b starts at the same x, process b first
# special case 2: building a and build b starts at the same x, process highest height first
# special case 3: building a and build b ends at the same x, process lowest height first
def prepop(pq, removed):
while len(pq) and pq[0][1] in removed:
heapq.heappop(pq)
points = []
for i, building in enumerate(buildings):
x1, x2, h = building
points.append([x1, 0, -h, i])
points.append([x2, 1, h, i])
points.sort()
ret = []
cur = 0
removed = set()
pq = []
for x, se, h, idx in points:
# if a build starts
if se==0:
h *= -1
if h>cur:
ret.append([x,h])
cur = h
heapq.heappush(pq, [-h, idx])
continue
# if a building ends
prepop(pq, removed)
removed.add(idx)
if pq[0][1]==idx:
heapq.heappop(pq)
prepop(pq, removed)
nextHeight = -pq[0][0] if len(pq) else 0
if cur>nextHeight:
cur = nextHeight
ret.append([x, cur])
return ret
|
abb49fdc704f5ceb13af212255c11f6d6bd5ac2d | AFigaro/Power-indices | /utils/preprocessing.py | 2,181 | 3.78125 | 4 | # The functions to preprocess the excel file to dict format
import sys
sys.path.append(r'C:\\Python files\\Power indices\\indices')
sys.path.append(r'C:\\Python files\\Power indices\\utils')
from collections import OrderedDict
def dict_construct_over_data(data):
'''Create a dictionary from excel file. The excel file must have the special format,
described in Readme.'''
data_len = len(data)
all_parties = []
for i in range(0, data_len-1, 3):
year = data[i][0]
parties_names = data[i][1 : len(data[i]) - 6]
country = data[i + 1][0]
parties_data = data[i + 1][1 : len(data[i + 1]) - 2]
quota = data[i + 1][-1]
country_dict = dict()
country_dict['year'] = year
country_dict['country'] = country
country_dict['quota'] = quota
for i in range(len(parties_names)):
country_dict[parties_names[i]] = int(parties_data[i])
all_parties += [country_dict]
return all_parties
def OrderedDict_over_YearCountry(data):
'''Create an Ordered dict to provide the information to power indices functions'''
data_dictionary = dict_construct_over_data(data)
new_dictionary = []
for element in data_dictionary:
new_dictionary += [dict(sorted(element.items(), key=lambda t: t[0]))]
return new_dictionary
def Remove_element(lst, val):
return [value for value in lst if value != val]
def Num_key_index(sample, threshold):
'''Find the number of significant parties in the parliament.
As input it takes the dictionary of output from index functions'''
k = 0
for index in sample:
if index >= threshold:
k += 1
return k
def permut_names(country):
'''Add all possible headers for the country (if there where second elections in the same year
they are denoted as /1, the third with /2 and the forth with the /3)'''
return [str(country), str(country) + '/1', str(country) + '/2',
str(country) + '/3',str(country) + ' (without president support)', str(country) + '/1 (without president support)',
str(country) + '/2 (without president support)']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.