blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
8c456bc90b38d4631e4e26c68a44d81a2a0776a4 | Walton0716/WaltonRepository | /BinarySearchTree/binarysearchtree最初版.py | 3,437 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 10:24:56 2019
@author: asus
"""
class TreeNode(object):
def __init__(self,val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def insert(self,root,val):
if root.val == None:
root.val = val
else:
if val <= root.val:
if root.left:
Solution().insert(root.left,val)
else:
root.left = TreeNode(val)
else:
if root.right:
Solution().insert(root.right,val)
else:
root.right = TreeNode(val)
return root
def preorder(self,root,list):
if root.val == None:
if root.left:
Solution().preorder(root.left,list)
if root.right:
Solution().preorder(root.right,list)
else:
list.append(root.val)
if root.left:
Solution().preorder(root.left,list)
if root.right:
Solution().preorder(root.right,list)
return list
def onlydelete(self,root,target):
if root.val == target:
root.val = None
if root.left:
Solution().onlydelete(root.left,target)
if root.right:
Solution().onlydelete(root.right,target)
return root
def delete(self,root,target):
list = []
Solution().onlydelete(root,target)
Solution().preorder(root,list)
length = len(list)
newroot = TreeNode(list[0])
for i in range(1,length,1):
Solution().insert(newroot,list[i])
return newroot
def search(self,root,target):
if root.val == None:
return False
if target < root.val:
if root.left:
return Solution().search(root.left,target)
else:
return False
elif target == root.val:
return root
elif target > root.val:
if root.right:
Solution().search(root.right,target)
else:
return False
def modify(self,root,target,new_val):
if root.val == None:
return False
else:
if target < root.val:
if root.left:
Solution().modify(root.left,target,new_val)
else:
return False
elif target == root.val:
root.val = new_val
elif target > root.val:
if root.right:
Solution().modify(root.right,target,new_val)
else:
return False
return root
#################################
root = TreeNode(5)
node1 = TreeNode(4)
node2 = TreeNode(7)
node3 = TreeNode(8)
node4 = TreeNode(6)
node5 = TreeNode(3)
root.left = node1
root.right = node2
root.right.right = node3
root.right.left = node4
root.left.left = node5
"""
list = []
print(Solution().preorder(root,list))
root1 = Solution().insert(root,5)
list = []
print(Solution().preorder(root1,list))
root2 = Solution().delete(root,5)
list = []
print(Solution().preorder(root2,list))
print(Solution().search(root,3) == root.left.left)
"""
root3 = Solution().modify(root,7,8)
list = []
print(Solution().preorder(root3,list))
|
a351f5ed13a3f2765d0dda6676fb296d87bd4e5c | masipcat/Informatica | /Q2/Tasques/3:3 Composició i ocultació de la informació/Exercici 1/moneder.py | 894 | 3.921875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=======
Moneder
=======
"""
class moneder(object):
def __init__(self, m1=0, m2=0, m3=0):
self._dict = {
"1": m1,
"2": m2,
"3": m3
}
def obteMonedesM1(self):
"""
Obté el primer grup de monedes
"""
return self._dict[2]
def obteMonedesM2(self):
"""
Obté el segon grup de monedes
"""
return self._dict[2]
def obteMonedesM3(self):
"""
Obté el tercer grup de monedes
"""
return self._dict[3]
def camviMonedesM1(self, d):
self._dict[1] += d
return self._dict[1]
def camviMonedesM2(self, d):
self._dict[2]+=d
return self._dict[2]
def camviMonedesM3(self, d):
self._dict[3]+=d
return self._dict[3]
def dinersAlMoneder(self):
return sum([key * value for key, value in self._dict.items()])
def afegirMonedes(self, s):
for a in self._dict:
self._dict[a] += s._d[a]
|
746af178a480c7aaf597d2bf4b168371f0ba5ff9 | SSANTHOSHXIB/KATTIS-SOLUTIONS | /ISITHALLOWEEN.COM.py | 112 | 3.640625 | 4 | dateInput = input()
if dateInput == "DEC 25" or dateInput == "OCT 31":
print('yup')
else:
print('nope')
|
dc28d8d10b4f49b99fefcc8589f1e75ce32202c1 | mouni186/Python-Programming | /program 2/py2.py | 440 | 4 | 4 | def Count():
NumList = []
num = int(input("Enter the number of elements: "))
for i in range(0, num):
elements = int(input("Enter the numbers: "))
NumList.append(elements)
search = int(input("Enter the number to count: "))
count = 0
for i in range (0, num):
if(search == NumList[i]):
count = count + 1
print(search , " occured ", count, " times")
Count()
# eppai tha varutu |
bc281d25854f9c3b75ba4484fa89da97ed0c7c8b | taareek/python-oop | /oop_02.py | 1,312 | 4.1875 | 4 | #Class variable
class Employee():
salary_raise = 1.07
num_of_empls =0
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
Employee.num_of_empls += 1
def employee_information(self):
print('Name: '+self.first_name+ ' '+ self.last_name)
print('Salary: ' + str(self.salary))
def apply_salary_raise(self):
self.salary = self.salary * self.salary_raise
return self.salary
rahim = Employee('Abdur','Rahim', 35000)
alex = Employee('Alex', 'Zingals', 25000)
print(type(rahim.salary))
rahim.employee_information()
print(rahim.apply_salary_raise())
alex.employee_information()
print(alex.apply_salary_raise())
print(rahim.__dict__)
print(alex.__dict__)
#print(Employee.__dict__)
rahim.salary_raise = 1.09 #updated salary for rahim
print(rahim.apply_salary_raise())
print(alex.apply_salary_raise())
print(rahim.__dict__)
print(Employee.salary_raise )
print(alex.__dict__)
print(rahim.salary_raise)
print(alex.salary_raise) # did not updated alex salary_raise as well as the class variable
print(Employee.num_of_empls)
faruk = Employee('Omar', 'Faruk', 75000)
print(faruk.employee_information())
print(Employee.num_of_empls)
|
bfbbc18112089a13896d2a35cd2ae3d2c1fa2ca2 | xly1524/data-complexity | /dcm/fast_mst.py | 6,416 | 3.765625 | 4 | # A Python program for Prims's MST for
# adjacency list representation of graph
import math
import numpy as np
from collections import defaultdict
# Converts from adjacency matrix to adjacency list
def convert_matrix_to_list(matrix):
adjList = defaultdict(list)
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] > 0:
newNode = [j, matrix[i][j]]
adjList[i].append(newNode)
return adjList
class Heap():
def __init__(self):
self.array = []
self.size = 0
self.pos = []
def newMinHeapNode(self, v, dist):
minHeapNode = [v, dist]
return minHeapNode
# A utility function to swap two nodes of
# min heap. Needed for min heapify
def swapMinHeapNode(self, a, b):
t = self.array[a]
self.array[a] = self.array[b]
self.array[b] = t
# A standard function to heapify at given idx
# This function also updates position of nodes
# when they are swapped. Position is needed
# for decreaseKey()
def minHeapify(self, idx):
smallest = idx
left = 2 * idx + 1
right = 2 * idx + 2
if left < self.size and self.array[left][1] < self.array[smallest][1]:
smallest = left
if right < self.size and self.array[right][1] < self.array[smallest][1]:
smallest = right
# The nodes to be swapped in min heap
# if idx is not smallest
if smallest != idx:
# Swap positions
self.pos[ self.array[smallest][0] ] = idx
self.pos[ self.array[idx][0] ] = smallest
# Swap nodes
self.swapMinHeapNode(smallest, idx)
self.minHeapify(smallest)
# Standard function to extract minimum node from heap
def extractMin(self):
# Return NULL wif heap is empty
if self.isEmpty() == True:
return
# Store the root node
root = self.array[0]
# Replace root node with last node
lastNode = self.array[self.size - 1]
self.array[0] = lastNode
# Update position of last node
self.pos[lastNode[0]] = 0
self.pos[root[0]] = self.size - 1
# Reduce heap size and heapify root
self.size -= 1
self.minHeapify(0)
return root
def isEmpty(self):
return True if self.size == 0 else False
def decreaseKey(self, v, dist):
# Get the index of v in heap array
i = self.pos[v]
# Get the node and update its dist value
self.array[i][1] = dist
# Travel up while the complete tree is not
# hepified. This is a O(Logn) loop
while i > 0 and self.array[i][1] < self.array[(i - 1) // 2][1]:
# Swap this node with its parent
self.pos[ self.array[i][0] ] = (i-1) // 2
self.pos[ self.array[(i-1)//2][0]] = i
self.swapMinHeapNode(i, (i - 1) // 2)
# move to parent index
i = (i - 1) // 2;
# A utility function to check if a given vertex
# 'v' is in min heap or not
def isInMinHeap(self, v):
if self.pos[v] < self.size:
return True
return False
class Graph():
def __init__(self, adjacency_matrix):
self.V = adjacency_matrix.shape[0]
self._graph = convert_matrix_to_list(adjacency_matrix)
def _build_edges(self, parent, n):
edges = []
for i in range(1, n):
edges.append([parent[i], i])
return np.array(edges)
# The main function that prints the Minimum
# Spanning Tree(MST) using the Prim's Algorithm.
# It is a O(ELogV) function
def PrimMST(self):
# Get the number of vertices in graph
V = self.V
# key values used to pick minimum weight edge in cut
key = []
# List to store contructed MST
parent = []
# minHeap represents set E
minHeap = Heap()
# Initialize min heap with all vertices. Key values of all
# vertices (except the 0th vertex) is is initially infinite
for v in range(V):
parent.append(-1)
key.append(math.inf)
minHeap.array.append(minHeap.newMinHeapNode(v, key[v]))
minHeap.pos.append(v)
# Make key value of 0th vertex as 0 so
# that it is extracted first
minHeap.pos[0] = 0
key[0] = 0
minHeap.decreaseKey(0, key[0])
# Initially size of min heap is equal to V
minHeap.size = V
# In the following loop, min heap contains all nodes
# not yet added in the MST.
while minHeap.isEmpty() == False:
# Extract the vertex with minimum distance value
newHeapNode = minHeap.extractMin()
u = newHeapNode[0]
# Traverse through all adjacent vertices of u
# (the extracted vertex) and update their
# distance values
for pCrawl in self._graph[u]:
v = pCrawl[0]
# If shortest distance to v is not finalized
# yet, and distance to v through u is less than
# its previously calculated distance
if minHeap.isInMinHeap(v) and pCrawl[1] < key[v]:
key[v] = pCrawl[1]
parent[v] = u
# update distance value in min heap also
minHeap.decreaseKey(v, key[v])
return self._build_edges(parent, V)
def MST(adjacency_matrix):
graph = Graph(adjacency_matrix)
return graph.PrimMST()
# Debug
# if __name__ == "__main__":
# a = np.array(
# [[0, 9, 75, 2, 0, 10],
# [9, 0, 95, 19, 42, 99],
# [75, 95, 0, 51, 66, 12],
# [2, 19, 51, 0, 31, 22],
# [0, 42, 66, 31, 0, 89],
# [10, 99, 12, 22, 89, 0]]
# )
# graph = Graph(a)
# print("Adjacency List:")
# for i in graph._graph:
# print(i, end ="")
# for node in graph._graph[i]:
# print(" -> {}".format(node[0]), end ="")
# print()
# print("="*20)
# MST = graph.PrimMST()
# print(MST)
|
7c6fc943a34565ce06690d2852e32b64db640ba2 | JakobKallestad/Python-Kattis | /src/Multigram.py | 598 | 3.546875 | 4 | from collections import Counter
word = list(input())
l_word = len(word)
l_word_half = l_word//2
size = 1
answer = '-1'
def solved():
global answer, size, l_word, word
if l_word % size != 0:
return False
original_counts = Counter(word[0:size])
for i in range(size, l_word, size):
if l_word - i < size:
return False
next_counts = Counter(word[i:i+size])
if original_counts != next_counts:
return False
answer = word[0:size]
return True
while size <= l_word_half and not solved():
size += 1
print(''.join(answer)) |
5adcd4ecc5e69441fc3adcaf61d720a1c4ebea6e | ShubhangiDabral13/Data_Structure | /Linked List/Linked_List_3_Node.py | 788 | 4.59375 | 5 | #Linked List Implementation to create a list which consist of 3 nodes.
#Class Node
class Node:
#To Initialize object
def __init__(self,data):
self.data = data
self.next = None
#Class to create link between nodes
class Linked_List:
def __init__(self):
self.head = None
#To print the data of the nodes
def print(self):
temp = self.head
while(temp):
print("{}".format(temp.data),end = " ")
temp = temp.next
# Start with the empty lis
link = Linked_List()
first = Node(1)
second = Node(2)
third = Node(3)
link.head = first
# Link first node with second
first.next = second
# Link second node with the third node
second.next = third
third.next = None
link.print()
|
d9de4f137a7ada0acd97f6edaed5250ac2027c49 | 240-coding/2020-winter-python | /0114 - gui/2 - answer.py | 228 | 3.703125 | 4 | import tkinter
window = tkinter.Tk()
label = tkinter.Label(window, text = "Hello, Python",
bg = "black", fg = "yellow",
font = ("times", 48, "bold"))
label.pack()
window.mainloop()
|
0e1b4f0b51586d9873330005b515def5f320357e | mangodayup/month02-resource | /note/day04_all/day04/regex01.py | 447 | 3.5 | 4 | """
正则表达式 re模块示例
"""
import re
text = "Alex:1996,Sunny:1998"
# 使用“ ” 替换匹配到的内容
msg = re.sub("\W+","##",text,2)
print(msg)
# 使用\W+匹配内容切割 text
# result = re.split('\W+',text,2)
# print(result)
# 使用正则表达式匹配字符串中符合规则的部分
# 如果正则表达式有组,则只能返回组对应的匹配部分
# result = re.findall("(\w+):(\d+)",text)
# print(result)
|
bf0f4300ce9563b2e2c2eb229e0bc505c50a9d37 | surajkawadkar/vita | /PYTHON/Assignment_1/temp_small_program.py | 285 | 3.765625 | 4 | start= int(input())
end= int(input())
for num in range(start,end):
temp_num=num
power=len(str(num))
sum=0
while(num>0):
last_digit=num%10
sum+=last_digit**power
num=num//10
if sum==temp_num:
print(temp_num,end=',')
|
9610dc7e0b0e29df0a6adbfd4ec5d267d9817834 | Static-Void-Academy/M0_C8 | /test_intersection.py | 2,740 | 3.59375 | 4 | import unittest
from intersection import check_overlap
class TestSecuritySystem(unittest.TestCase):
def test_small_and_small(self):
"""Tests a smaller crime completely union w/ larger crime"""
c1 = ['bathroom', 'kitchen']
c2 = ['kitchen']
actual = check_overlap(c1, c2)
self.assertEqual(True, actual)
def test_larger_and_larger(self):
"""Both crime scenes are the same."""
c1 = ['bathroom', 'kitchen', 'cutting board']
c2 = ['cutting board', 'kitchen', 'bathroom']
actual = check_overlap(c1, c2)
self.assertEqual(True, actual)
def test_small_and_larger1(self):
"""Tests a smaller crime completely union w/ larger crime"""
c1 = ['bathroom', 'kitchen']
c2 = ['cutting board', 'kitchen', 'bathroom']
actual = check_overlap(c1, c2)
self.assertEqual(True, actual)
def test_small_and_larger2(self):
"""Tests that flipping small/large overlap doesn't affect results"""
c1 = ['cutting board', 'kitchen', 'bathroom']
c2 = ['bathroom', 'kitchen']
actual = check_overlap(c1, c2)
self.assertEqual(True, actual)
def test_small_and_small_duplicates(self):
"""Tests a smaller crime completely union w/ larger crime"""
c1 = ['bathroom', 'kitchen', 'bathroom', 'bathroom']
c2 = ['kitchen', 'kitchen', 'kitchen', 'kitchen']
actual = check_overlap(c1, c2)
self.assertEqual(True, actual)
def test_small_and_small_no_match(self):
"""Tests two small sets without matches"""
c1 = ['cutting board']
c2 = ['bathroom']
actual = check_overlap(c1, c2)
self.assertEqual(False, actual)
def test_small_and_large_no_match(self):
"""Tests one small, one large set without matches"""
c1 = ['cutting board', 'kitchen', 'bathroom']
c2 = ['veranda']
actual = check_overlap(c1, c2)
self.assertEqual(False, actual)
def test_small_and_large_some_match(self):
"""Tests two large sets with some matches, but not enough"""
c1 = ['cutting board', 'kitchen', 'bathroom', 'backyard']
c2 = ['bathroom', 'cutting board', 'porch', 'veranda']
actual = check_overlap(c1, c2)
self.assertEqual(False, actual)
def test_large_and_large_duplicates_no_match(self):
"""Tests a smaller crime completely union w/ larger crime"""
c1 = ['bathroom', 'kitchen', 'veranda', 'backyard', 'bathroom', 'bathroom']
c2 = ['kitchen', 'kitchen', 'kitchen', 'bedroom', 'drapes', 'coffee grinder']
actual = check_overlap(c1, c2)
self.assertEqual(False, actual)
if __name__ == '__main__':
unittest.main()
|
e186773c52495899088bdc035cb2e6bc160b9586 | gyang274/leetcode | /src/1400-1499/1452.favoriate.companies.subset.py | 599 | 3.515625 | 4 | from typing import List
class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
s = [set(x) for x in favoriteCompanies]
return [i for i, si in enumerate(s) if all(i == j or not si.issubset(sj) for j, sj in enumerate(s))]
if __name__ == '__main__':
solver = Solution()
cases = [
[["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]],
]
rslts = [solver.peopleIndexes(favoriteCompanies) for favoriteCompanies in cases]
for cs, rs in zip(cases, rslts):
print(f"case: {cs} | solution: {rs}")
|
573c6e1e1b9b2d8380aa73289ca4c76883237c64 | Concarne2/ProjectEuler | /PEuler_104.py | 726 | 3.625 | 4 | contains=[]
for i in range(0,10):
contains.append(False)
def ispan(n):
for dig in n:
if int(dig) == 0:
for i in range(0,10):
contains[i] = False
return False
if contains[int(dig)]:
for i in range(0,10):
contains[i] = False
return False
contains[int(dig)] = True
for i in range(0,10):
contains[i] = False
return True
fib1=1
fib2=1
for i in range(3,100):
temp = fib1 + fib2
fib1 = fib2
fib2 = temp
for i in range(100,1000000):
temp = fib1 + fib2
fib1 = fib2
fib2 = temp
'''
if ispan(str(fib2)[:9]):
# if ispan(str(fib2)[-9:]):
print(i)
'''
|
c8436ca00d6ee0ae179290d7eb33beda1297f64b | OlexandrGamchuk1/Homework-9 | /Exercise 7.py | 370 | 3.671875 | 4 | def palindrome():
my_list = []
my_dictionary = {}
for i in range(999, 99, -1):
for j in range(999, 99, -1):
a = str(i * j)
if a == a[::-1]:
my_dictionary[i * j] = f"{i} * {j}"
my_list.append(i * j)
maximum = max(my_list)
print(f"{maximum} = {my_dictionary.pop(maximum)}")
palindrome() |
8d488b3f1e0b805be818bcff4531bbc98e4f07c9 | ambilikn/Python-Exercises | /challenge_functions.py | 541 | 4.4375 | 4 | #To get the count of each character in a word
import operator
def count_characters(word):
dict = {}
print(dict)
for i in word:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
print("The count of characters in the word "+ word+" is "+ str(dict))
# Sort Dictionary by value using itemgetter
sorted_dict = sorted( dict.items(), key=operator.itemgetter(1), reverse=True)
print('Sorted Dictionary: ')
print(sorted_dict)
word = input("Enter a word")
count_characters(word)
|
4f14a921f0901dcbb9063cfce5b72c7433499a46 | caiocobacho/deeplearning4driver | /driver_distraido.py | 2,409 | 3.53125 | 4 | from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
model = Sequential()
model.add(Convolution2D(nb_filter=32, nb_row=3,
nb_col=3, input_shape=(3, 150, 150)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(nb_filter=64, nb_row=3, nb_col=3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# o model ate agora, tem como outputs mapas de funcionalidade 3d (height, width, features)
# converte nossos mapas de recursos 3D em vetores de recursos 1D
model.add(Flatten())
model.add(Dense(64)) # 64 neurons
model.add(Activation('relu'))
model.add(Dropout(0.5)) # Faz um drop de 50% dos neurons
# Camada de saida: Classifica os dez estados do motorista
model.add(Dense(10))
model.add(Activation('softmax'))
# Compila o model
model.compile(loss='categorical_crossentropy',
optimizer='adadelta', metrics=['accuracy'])
# Config de aumento para gerar training data
train_datagen = ImageDataGenerator(
rescale=1.0/255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
# a validação de imagem esta escalada em 1/255, nenhum outro aumento para nossa validacao de dados
test_datagen = ImageDataGenerator(rescale=1.0/255)
# esse é o gerador que ira ler imagens en contradas em sub pastas de 'data/train',
# e indefinitivamente gera batch de dados de imagem aumentados!
train_generator = train_datagen.flow_from_directory('data/train', target_size=(150, 150),
batch_size=32, class_mode='categorical')
# Este é o gerador de dados de validação
validation_generator = test_datagen.flow_from_directory('data/validation', target_size=(150, 150),
batch_size=32, class_mode='categorical')
# trainando convolutional neural network
model.fit_generator(train_generator, samples_per_epoch=20924, nb_epoch=20,
validation_data=validation_generator, nb_val_samples=800)
# Salvando os weights
model.save_weights('driver_state_detection_small_CNN.h5')
|
df2d54500c1c5fb1c66d2d7927d9f14eb26e8545 | yashdesai01/python | /City/city.py | 3,172 | 3.796875 | 4 | import os
maxi = 20
cityFile = open("city.bin","wb+")
n= int(input("How Many Entries="))
for loop in range(n):
city = input("Enter " + str(loop + 1) + " City Name: ")
if(len(city) < 20):
city = city + (maxi-len(city)) * ' '
city = city.encode()
cityFile.write(city)
cityFile.seek(0)
size = os.path.getsize("city.bin")
n = int(size/maxi)
while True:
pos = 0
cityFile.seek(0)
print("1.Display All Record")
print("2.Search City")
print("3.Insert City")
print("4.Delete City")
print("5.Update City")
print("6. Exit")
ch = int(input("Enter Your Choice: "))
if(ch == 1):
for loop in range(n):
data = cityFile.read(maxi)
print(data.decode())
pos+=maxi
cityFile.seek(pos)
elif(ch == 2):
pos = 0
found = False
searchCity = input("Enter city name which you want to search=")
for loop in range(n):
name = cityFile.read(maxi)
name = name.decode()
if name.rstrip() .upper() == searchcity.upper():
found = True
print(name.rstrip(), "found on ",(loop+1) ,"position")
break
pos+=maxi
cityFile.seek(pos)
if found == False:
print(searchCity , "not found")
elif(ch == 3):
name = input("Enter new city name=")
cityFile.seek(0,2)
if(len(name) < 20):
name = name + (maxi - len(name)) * ' '
name = name.encode()
cityFile.write(name)
n +=1
print("No of Records:",n)
elif(ch == 4):
cityFile.seek(0)
deleteCity = input("Which city do you want to delete..??")
file2 = open("newfile.bin","wb")
for loop in range(n):
name = cityFile.read(maxi)
name = name.decode()
if name.rstrip().upper() !=deleteCity.upper():
file2.write(name.encode())
pos+=maxi
cityFile.close()
file2.close()
os.remove("city.bin")
os.rename("newfile.bin","city.bin")
cityFile = open("city.bin","rb+")
size = os.path.getsize("city.bin")
n = int(size/maxi)
elif(ch == 5):
found = False
pos=0
oldName = input("Enter old City Name=")
newName = input("Enter New City Name=")
if(len(newName) < 20 ):
newName = newName + (maxi - len(newName)) * ' '
if(len(oldName) < 20 ):
oldName = oldName + (maxi - len(oldName)) * ' '
for loop in range(n):
cityFile.seek(pos)
name = cityFile.read(maxi)
name = name.decode()
if oldName.upper() == name.upper():
found = True
cityFile.seek(-20,1)
cityFile.write(newName.encode())
pos+=maxi
if found==True:
print("Records Update Successfully:")
else:
print("No records found:")
elif (ch == 6):
break
cityFile.close()
|
26174d96472042836e5c85b7e399dc880e125a0f | grigorghazaryan/python-homeworks | /Homework Dict and Files/homework_06.py | 386 | 4.09375 | 4 | # 6. Write a Python program to make a dict from these two lists.
# lst1: ['hello', 'bye-bye', 'moon', 'sun', 'star'], lst2: ['բարև', 'հաջող', 'լուսին', 'արև', 'աստղ']
lst1 = ['hello', 'bye-bye', 'moon', 'sun', 'star']
lst2 = ['բարև', 'հաջող', 'լուսին', 'արև', 'աստղ']
_dict = {}
for l1,l2 in zip(lst1,lst2):
_dict[l1] = l2
print(_dict) |
9d66500a0d487467d590fd28fd9c16b37d0a172e | FarzanaHaque/CS440 | /HW1/astar12extra.py | 4,819 | 3.71875 | 4 | import queue
from collections import defaultdict
import math
#weight of a single move, found experimentally
c = .01
def maze_parse(path_to_file):
file = open(path_to_file, "r")
maze = []
for line in file:
x_line = []
for c in line:
if(c != '\n'):
x_line.append(c)
maze.append(x_line)
file.close()
return maze
def maze_print(maze):
for line in maze:
for c in line:
print(c, end="")
print()
def man_dist(x1, y1, x2, y2):
return abs(abs(x2)-abs(x1)) + abs(abs(y2) - abs(y1))
def man_dist(p1, p2):
return abs(abs(p1[0])-abs(p2[0])) + abs(abs(p1[1]) - abs(p1[1]))
def find_all_nodes(maze):
nodes = []
for row in range(0, len(maze)):
for column in range(0, len(maze[row])):
if(maze[row][column] == '.'):
nodes.append((row, column))
return nodes
def dict_for_graph(nodes):
node_dict = {}
for i in range(0, len(nodes)):
node_dict[nodes[i]] = i
return node_dict
def g(cost, maze, current):
nodes = find_all_nodes(maze)
q = queue.PriorityQueue()
if(len(nodes) == 0):
return cost
for node_u in nodes:
dist = man_dist(node_u, current)
q.put(dist)
return q.get() + cost
def astar(maze, start):
q = queue.PriorityQueue()
q.put((g(0, maze, start), start[0], start[1]))
parents = {}
cost_map = {}
cost_map[start] = 0
visited = set([(start[0], start[1])])
dest = ()
total_cost = 0
visit_counter = '1';
old_start = start
node_ex = 0
while (len(find_all_nodes(maze)) != 0):
node = q.get()
if maze[node[1]][node[2]]=='.':
maze[node[1]][node[2]] = visit_counter
visit_counter = chr(ord(visit_counter) + 0)
if(ord(visit_counter) == ord(':')):
visit_counter = 'a'
curr = (node[1], node[2])
solution=[curr]
while curr!=(old_start[0], old_start[1]):
curr=parents[curr]
solution.append(curr)
total_cost += (len(solution) - 1)
q = queue.PriorityQueue()
q.put((g(total_cost, maze, (node[1], node[2])), node[1], node[2]))
parents = {}
cost_map = {}
cost_map[(node[1], node[2])] = 0
visited = set([(node[1], node[2])])
dest = ()
old_start = (node[1], node[2])
node_ex += 1
if maze[node[1]][node[2]+1]!='%' and (node[1],node[2]+1) not in visited: #add right
visited.add((node[1], node[2]+1))
q.put((g(cost_map[(node[1], node[2])]+c, maze, (node[1],node[2]+1)), node[1], node[2]+1))
if((node[1], node[2]+1) not in parents.keys() or cost_map[parents[(node[1],node[2]+1)]] > cost_map[(node[1], node[2])]+c):
parents[(node[1],node[2]+1)]=(node[1], node[2])
cost_map[(node[1],node[2]+1)] = cost_map[(node[1], node[2])]+c
if maze[node[1]+1][node[2]]!='%' and (node[1]+1,node[2]) not in visited: #down
visited.add((node[1]+1, node[2]))
q.put((g(cost_map[(node[1], node[2])]+c, maze, (node[1]+1,node[2])), node[1]+1, node[2]))
if((node[1]+1, node[2]) not in parents.keys() or cost_map[parents[(node[1]+1,node[2])]] > cost_map[(node[1], node[2])]+c):
parents[(node[1]+1,node[2])]=(node[1], node[2])
cost_map[(node[1]+1,node[2])] = cost_map[(node[1], node[2])]+c
if maze[node[1]][node[2]-1]!='%' and (node[1],node[2]-1) not in visited: #left
visited.add((node[1], node[2]-1))
q.put((g(cost_map[(node[1], node[2])]+c, maze, (node[1],node[2]-1)), node[1], node[2]-1))
if((node[1], node[2]-1) not in parents.keys() or cost_map[parents[(node[1],node[2]-1)]] > cost_map[(node[1], node[2])]+c):
parents[(node[1],node[2]-1)]=(node[1], node[2])
cost_map[(node[1],node[2]-1)] = cost_map[(node[1], node[2])]+c
if maze[node[1]-1][node[2]]!='%' and (node[1]-1,node[2]) not in visited: #up
visited.add((node[1]-1, node[2]))
q.put((g(cost_map[(node[1], node[2])]+c, maze, (node[1]-1,node[2])), node[1]-1, node[2]))
if((node[1]-1, node[2]) not in parents.keys() or cost_map[parents[(node[1]-1,node[2])]] > cost_map[(node[1], node[2])]+c):
parents[(node[1]-1,node[2])]=(node[1], node[2])
cost_map[(node[1]-1,node[2])] = cost_map[(node[1], node[2])]+c
print("cost is %d" % total_cost)
print("len of visited %d" % node_ex)
maze = maze_parse("bigmaze12.txt")
sol = astar(maze,(11,14))
maze_print(maze)
|
4b57d7961e74d8e8455cbc4c833bb106273ef51d | upputuriyamini/yamini | /76.py | 141 | 3.640625 | 4 | n=int(raw_input())
f=0
for i in range (1,n):
if n%i==0:
f=i
if f>1:
print 'yes'
else:
print 'no'
|
c2df4d422f64be577ce45da2ebb611c9049be590 | GongFuXiong/leetcode | /topic13_tree/T124_maxPathSum/interview.py | 1,508 | 3.515625 | 4 | '''
124. 二叉树中的最大路径和
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
输出: 42
'''
import sys
sys.path.append("..") # 这句是为了导入_config
from T_tree.Tree import Tree
class Solution:
def maxPathSum(self, root):
self.max_path_sum = float('-inf')
def dfs(node):
if not node: # 边界情况
return 0
left = dfs(node.left)
right = dfs(node.right)
cur_max = max(node.val,node.val+left,node.val+right)
self.max_path_sum = max(self.max_path_sum,cur_max,node.val+left+right)
return cur_max
dfs(root)
return self.max_path_sum
if __name__ == "__main__":
tree = Tree()
solution = Solution()
while 1:
str1 = input()
if str1 != "":
node_list = str1.split(",")
for node in node_list:
tree.add(node)
print(f"层次遍历:{tree.traverse(tree.root)}")
res = solution.maxDepth(tree.root)
print(res)
else:
break
|
1a5f5f42f8058b3f1c82b3b4d8adc2c6cba248a1 | hellophanh/Nguyen_Phuong_Anh_D4E18 | /homework/hw_session1.py | 909 | 3.65625 | 4 | # Session 1: Variables and data types
# Exercise 1
# Input x
x = float(input("Enter x: "))
import math
# Calculate and output y1 and y2
y1 = (x ** 2 + 10 * x + math.sqrt(x) + 3 * x + 1) * 4
print("y1 = ", y1)
a = math.sin(math.pi * x ** 2) + math.sqrt(x ** 2 + 1)
b = math.e ** (2 * x) + math.cos((math.pi) * x / 4)
y2 = a / b
print("y2 = ", y2)
# Exercise 2
# Input số tiền
y = int(input("Số nghìn đồng: ", ))
# Tính số tờ của từng mệnh giá tiền
a = int(y //100)
b = int(y % 100)
c = int(b // 50)
d = int(b % 50)
e = int(d // 20)
f = int(d % 20)
g = int(f / 10)
# Output kết quả
print("y = ", a, "tờ 100.000", "+", c, "tờ 50.000", "+", e, "tờ 20.000", "+", g, "tờ 10.000")
# Exercise 3
# Input số có 3 chữ số
x = str(input("Nhập số có 3 chữ số: "))
a = int(x[0])
b = int(x[1])
c = int(x[2])
sum = a + b + c
print("Tổng các chữ số là", sum)
|
786aa42fea9b16d0cdec04b6e7ed88a1e24ec7fc | wjay88/LearningPython | /08-6单例与重写new方法.py | 1,570 | 4.125 | 4 | # class Dog(object):
# def __init__(self):
# print("---init方法----")
#
# def __str__(self):
# print("---str方法----")
# return "对象描述信息"
#
# def __del__(self):
# print("---del方法----")
#
# def __new__(cls, *args, **kwargs):
# print("---new方法----")
# return object.__new__(cls)
#
#
# xtq = Dog()
# print(xtq)
# 构造方法的概念:
# 既有初始化又有新建。python中将其分为两步。
# 1、调用__new__方法类创建对象,然后找一个变量来接收__new__的返回值,这个返回值表示创建出来的对象的引用
# 2、__init__(刚刚创建出来的对象的应用。)初始化。
# 3、返回对象的引用。
#
# 重写__new__方法的原因。
# 单例对象的创建
#
# class Dog(object):
# pass
#
# a = Dog()
# b = Dog()
# a和b指向同一个对象就是单例。如何实现?过程与新建对象方法有关,想到__new__方法。所以重写__new__方法。
class Dog():
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance == None:
cls.__instance = object.__new__(cls)
return cls.__instance
else:
return cls.__instance
def __init__(self, name):
self.name = name
a = Dog("旺财")
print(id(a))
print(a.name)
b = Dog("哮天犬")
print(id(b))
print(b.name)
为了防止两次print都执行,将__init__修改为:
# def __init__(self,name):
# if Dog.__init_flag == False
# self.name = name
# Dog.__init_flag = True |
cbc3c549cbf067d0c998a48e6b1ad398d863e21a | MTaylorfullStack/flex_lesson_transition | /jan_python/week_three/user.py | 1,295 | 3.828125 | 4 | ## Create a User class
# users should have first names, last names, emails and passwords
# users should be able to "say hello"
class Account:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
class User:
def __init__(self, first, last, email, password):
self.first=first
self.last=last
self.email=email
self.password=password
self.account=Account()
def say_hello(self):
print(f"{self.first} {self.last} says hello")
return self
def change_name(self, new_name):
self.first=new_name
return self
def wrestling_move(self, move_name, target):
print(f"{self.first} did move {move_name} to {target.first}")
return self
first_user=User("Dwayne", "Johnson", "rock@wwe.com", "whatscookin")
# print(first_user)
second_user=User("Rey", "Mysterio", "rey@wwe.com", "luchador")
# print(first_user)
print(first_user.wrestling_move("slam", second_user))
# first_user.change_name("The Rock")
# second_user.say_hello().say_hello().say_hello().say_hello()
# print(first_user.account.deposit(100000))
# print(first_user.account.balance)
|
123e3006876433d2cb500a88ce68628a0eb45ca6 | piyushkashyap07/linked-list | /Reverse LL (Recursive).py | 2,552 | 3.9375 | 4 | # Given a singly linked list of integers, reverse it using recursion and return the head to the modified list. You have to do this in O(N) time complexity where N is the size of the linked list.
# Note :
# No need to print the list, it has already been taken care. Only return the new head to the list.
# Input format :
# The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
# The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space.
# Remember/Consider :
# While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element
# Output format :
# For each test case/query, print the elements of the updated singly linked list.
# Output for every test case will be printed in a seperate line.
# Constraints :
# 1 <= t <= 10^2
# 0 <= M <= 10^4
# Where M is the size of the singly linked list.
# Time Limit: 1sec
# Sample Input 1 :
# 1
# 1 2 3 4 5 6 7 8 -1
# Sample Output 1 :
# 8 7 6 5 4 3 2 1
# Sample Input 2 :
# 2
# 10 -1
# 10 20 30 40 50 -1
# Sample Output 2 :
# 10
# 50 40 30 20 10
from sys import stdin, setrecursionlimit
setrecursionlimit(10 ** 6)
#Following is the Node class already written for the Linked List
class Node :
def __init__(self, data) :
self.data = data
self.next = None
def reverseLinkedListRec(head) :
if head is None or head.next is None:
return head
smallhead=reverseLinkedListRec(head.next)
head.next.next=head
head.next=None
return smallhead
#Taking Input Using Fast I/O
def takeInput() :
head = None
tail = None
datas = list(map(int, stdin.readline().rstrip().split(" ")))
i = 0
while (i < len(datas)) and (datas[i] != -1) :
data = datas[i]
newNode = Node(data)
if head is None :
head = newNode
tail = newNode
else :
tail.next = newNode
tail = newNode
i += 1
return head
def printLinkedList(head) :
while head is not None :
print(head.data, end = " ")
head = head.next
print()
#main
t = int(stdin.readline().rstrip())
while t > 0 :
head = takeInput()
newHead = reverseLinkedListRec(head)
printLinkedList(newHead)
t -= 1 |
bf244f7e12530c887f9a9cc69790e3967a8cc9d0 | GreatTwang/lccc_solution | /Python/ds design/Insert Delete GetRandom O(1).py | 1,530 | 4.03125 | 4 | class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.data_dict = {}
self.data_list = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.data_dict:
return False
self.data_dict[val] = len(self.data_list)
self.data_list.append(val)
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.data_dict:
return False
pos = self.data_dict[val]
if pos < len(self.data_list):
tail = len(self.data_list) - 1
tail_val = self.data_list[tail]
self.data_list[pos], self.data_list[tail] = self.data_list[tail], self.data_list[pos]
self.data_list.pop()
self.data_dict[tail_val] = pos
del self.data_dict[val]
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.data_list)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom() |
25237f986ae7a2c8f762e8c2ef8a0d1663d31e26 | agustin107/Python | /ST Columbia/funciones.py | 4,184 | 3.828125 | 4 | from datetime import*
#funciona de auto-menu
def menu(lista,nombre):
opcion = '';
#deducimos los valores que se pueden ingresar
opcionesValidas = [];
for i in range(len(lista)):
opcionesValidas.append(i+1);
while(not opcion in opcionesValidas):
print("\n"+nombre);
for i in range(len(lista)):
print(i+1," -> ",lista[i]);
opcion = leerNumero("elija una opcion");
return(opcion);
#resume un verdadero falso
def pregunta(cadena):
continuar = str(input(cadena+"? S/N\n"));
if(continuar == "s" or continuar == "S"):
return(True);
return(False);
#funciona de forma analoga al input()
#permite que solo se ingresen numeros o reales
def leerNumeroReal(cadena):
cadena = cadena+": ";
numeros = ["1","2","3","4","5","6","7","8","9","0"];
continuar = True;#forzamos la entrada al bucle
while(continuar):
continuar = False;#habilitamos la salida del bucle
decimalYaEscrito = False;#perminte poner punto solo una vez
valor = str(input(cadena));#leemos el dato
for i in valor:
if(not i in numeros):#si no es un numero
if(i == "." and not decimalYaEscrito):#si es un punto y aun nuo se lo escribio
decimalYaEscrito = True;#registra que el punto ya esta escrito
else:
print("Debe ingrsesar solo numeros");
print("Y en su defecto un punto en lugar de coma");
continuar = True;
return(float(valor));
#funciona de forma analoga al input()
#permite que solo se ingresen numeros
def leerNumero(cadena):
cadena = cadena+": ";
while(True):
valor = str(input(cadena));
if(str.isnumeric(valor)):
return(int(valor));
else:
print("Debe ingrsesar solo numeros");
#te dice si una fecha es mayor, menor o igual que la actual
def comparar(fecha):
if(datetime.now().year < fecha.year):
return("mayor");#si el año es mayor la fecha es mayor
elif(datetime.now().year > fecha.year):
return("menor");#si el año es menor la fecha es menor
elif(datetime.now().year == fecha.year):#si el año es igual comparamos los meses
if(datetime.now().month < fecha.month):
return("mayor");#si el mes es mayor la fecha es mayor
elif(datetime.now().month > fecha.month):
return("menor");#si el mes es menor la fecha es menor
elif(datetime.now().month == fecha.month):#si el mes es igual comparamos los dias
if(datetime.now().day > fecha.day):
return("menor");#si el dia es menor la fecha es menor
elif(datetime.now().day < fecha.day):
return("mayor");#si el dia es mayor la fecha es mayor
elif(datetime.now().day == fecha.day):
return("igual");#si el dia igual la fecha es igual
#devuelve una fecha valida
def validarFecha():
continuar = True;
while(continuar):
#el mes y el dia
dia = leerNumero("Escriba el dia");
mes = leerNumero("Escriba el mes");
try:#intentamos
d = datetime(datetime.now().year,mes,dia);#si la fecha esta mal, devuelve un error y salta al except:
continuar = False;#si la fecha esta bien sale del bucle
except:#si la fecha dio error
input("Fecha Incorrecta");#presione enter para continuar...
return(d);
def imprimirFechaOk(fecha):
if(fecha.month == 1):
mes='Enero'
elif(fecha.month == 2):
mes='Febrero'
elif(fecha.month == 3):
mes='Marzo'
elif(fecha.month == 4):
mes='Abril'
elif(fecha.month == 5):
mes='Mayo'
elif(fecha.month == 6):
mes='Junio'
elif(fecha.month == 7):
mes='Julio'
elif(fecha.month == 8):
mes='Agosto'
elif(fecha.month == 9):
mes='Septiembre'
elif(fecha.month == 10):
mes='Octubre'
elif(fecha.month == 11):
mes='Noviembre'
else:
mes='Diciembre'
print('Dia: ',fecha.day,' / Mes: ',mes,' / Año: ',fecha.year)
|
b5b955e43553cfafedf6f2e2593458933a7d75af | rsthecoder/Python | /Apps/2- 1 Shifting elements with DEQUE .py | 828 | 4.3125 | 4 | """ Write a program that takes two inputs; one of them is a list and the other is a number,
and returns the list obtained by shifting the elements in the list n places to the right (left)
when n is positive (negative).
Use wrap-around: if an element is shifted beyond the end of the list,
then continue to shift starting at the beginning of the list. """
import collections # importing collections module
while True:
try:
user_list = list(input("Enter a list: ")) # user enters a list
a_list = collections.deque(user_list) # making a Deque list
shift = int(input("Shift: ")) # user enters a number to rotate the list
a_list.rotate(shift) # using rotate method
print(list(a_list)) # printing the list
except:
print("You made a faulty input, please try again!")
|
cab295f3840187c9fb57b6ed1448ccd78be09cc1 | daniel-reich/ubiquitous-fiesta | /MNePwAcuoKG9Cza8G_8.py | 196 | 3.609375 | 4 |
def build_staircase(height, block):
t = []
for j in range(1, height + 1):
b_len = block * j
d_len = "_" * (height - j)
t.append(list(b_len + d_len))
return t
|
987867da191ca3004fef17bd180cee2b412eec46 | jihunJeong/MAT3008_2020_HYU | /Assignment2/min_newton_method.py | 698 | 3.90625 | 4 | def origin_calculate(num):
cal = 0
for i in range(len(function)):
cal += num**(i) * function[len(function)-i-1]
return cal
def diff_calculate(num):
cal = 0
for i in range(len(function)-1):
cal += num**(i) * function[len(function)-i-2] * (i+1)
return cal
def newton_raphson(num):
old_x = num
while True:
new_x = old_x - (origin_calculate(old_x) / diff_calculate(old_x))
if abs((new_x - old_x) / new_x) < 0.0001:
print(new_x)
break
old_x = new_x
if __name__ == "__main__":
function = list(map(float, input().split())) #함수의 계수를 공백 기준으로 입력 받아 다양한 함수 적용 가능하게 함
num = float(input())
newton_raphson(num)
|
d9dc724b2f93a96524678b37d3976b25bf88e231 | yleong/proj_euler | /python/3.py | 1,866 | 3.5625 | 4 | #!/usr/bin/python
"""
generate list of primes using sieve of eratosthenes
then perform trial division using that?
"""
def main():
n = 600851475143
# n = 7913077 * 13 * 2 * 2
import math
max = int(math.sqrt(n))
# primes = sieve(set(range(2, max+1)))
primes = set(range(2, max+1))
# print "primes are ", primes
print n
# time to prime factorize n
largestSoFar = 0
while True:
found = False
for p in primes:
if p > n: break
if n % p == 0:
found = True
print "found prime factor", p
n = n/p
print "new n is ", n
largestSoFar = mymax(p, largestSoFar)
break
if not found:
largestSoFar = mymax(n, largestSoFar)
break
print largestSoFar
#will just filter candidates to give you only the primes
def sieve(candidates):
primes = set()
while len(candidates) > 0:
currPrime = smallestInSet(candidates)
# print "currprime is", currPrime
primes.add(currPrime)
removeMultiples(candidates, currPrime)
# print "currlist is", candidates
return primes
#removes all multiples of num from list
def removeMultiples(myset, num):
maxnum = biggestInSet(myset)
currmult = num
while currmult <= maxnum:
if currmult in myset: myset.remove(currmult)
currmult = currmult + num
def smallestInSet(myset):
smallest = myset.pop()
myset.add(smallest)
for x in myset:
if x < smallest:
smallest = x
return smallest
def biggestInSet(myset):
biggest = myset.pop()
myset.add(biggest)
for x in myset:
if x > biggest:
biggest = x
return biggest
def mymax(a, b):
return a if a > b else b
if __name__ == "__main__":
main()
|
741486d1dc2ca7b8ac2804c22deb61c2fa8ceb15 | josealsola29/PythonCourse_corean | /Dia1_Tarea4.py | 205 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 13:00:06 2020
@author: JALSOLA
"""
def Multip(*num):
sum = 0
for i in num:
sum = sum + i
return print(sum)
Multip(10,51,13,42,62,8)
|
6fde650f92ae01074fa3f7e94d9ed22552fcc8b8 | gbeinas/Python_Beginers | /DataTypes/List_Functions.py | 2,374 | 4.71875 | 5 | # --------- List Functions ----------------
# IN GENERAL LISTS ARE SIMILAR TO ARRAYS DATA STRUCTURES IN OTHER PROGRAMMING LANGUAGES
# In this tutorial we are going to learn about some very basic functions that can be used for list
#
# - add two lists : + operation
# - size of a list : len
# - adda new item to the list : append
# - number of times an item appears to the list : count
shoppinglist = "eggs,milk,carrot,bread,sugar"
shoppinglist2 = ["eggs", "milk", "carrot", "bread", "sugar"]
# How to delete a list item
print("My list before the deletion : " )
print shoppinglist2
del shoppinglist2[4]
print("My list after the deletion : ")
print shoppinglist2
# How to add two lists - It is the same thing as to add two strings.The second array will be placed at the end
# of the first one. Let's see an example
print("The first array is : ")
array_1 = [1,3,5]
print array_1
print("The second array is : ")
array_2 = [4,6,8]
print array_2
array_3 = array_1 + array_2
print("The sum of array_1 and array_2 is : ")
print array_3
print (" ")
# To learn the size of my list, meaning how much item includes, I have to use the predefined function 'len'.
# Let's see an example of how to use this
print("The size of my list is : {0:d}".format(len(array_1)))
# How to use Max and Min functions. Returns the maximum and the minimum number within a list. Let's try it
print("The maximum number of the array_1 is : {0:d} and the minimum is : {1:d}".format((max(array_1)),min(array_1)))
print(" ")
# How to add an item to the list
print ("My list before adding an item is : " + str(shoppinglist2))
shoppinglist2.append("Brocoli")
print ("My list after adding an item is : " + str(shoppinglist2))
print(" ")
# How much times an item appears to a list. See the example below
print("My list consists of these items : " + str(shoppinglist2))
print(" ")
shoppinglist2.append("cacao")
shoppinglist2.append("cacao")
shoppinglist2.append("cacao")
shoppinglist2.append("orange")
shoppinglist2.append("orange")
shoppinglist2.append("orange")
shoppinglist2.append("orange")
shoppinglist2.append("orange")
shoppinglist2.append("banana")
shoppinglist2.append("orange")
print("My list now consists of these items : " + str(shoppinglist2))
print(" ")
print("How much times orange appears to my list ? Orange appears : {0:d} times".format(shoppinglist2.count("orange")))
print(" ") |
300c6f125c6c3f0320e66151b9031d22afc6d491 | sssunda/solve_algorithms | /programmers/sum_of_two_numbers.py | 194 | 3.71875 | 4 | def solution(a, b):
if a > b:
a, b = b, a
answer = sum([x for x in range(a, b+1)])
return answer
if __name__ == '__main__':
a = 3
b = 3
print(solution(a,b))
|
9b07de65aacbe2d86d294968742d9dd74e76509c | VanessaTan/LPTHW | /EX15/ex15.py | 606 | 3.8125 | 4 | #importing agrv (a feature) from sys (a package)
from sys import argv
#using argv to get a filename
script, filename = argv
#Makes a file object with open command
txt = open(filename)
#prints a message with set variable filename
print "Here's your file %r:" % filename
#putting a function (read) on txt - commands given to a file by using period
print txt.read()
#prints a message
print "Type the filename again:"
#sets variable that makes you type in the file name manually
file_again = raw_input("> ")
#sets the variable
txt_again = open(file_again)
#prints txt and command
print txt_again.read()
|
313a0135b7c7ea38cdf5d5257f6cfeb78aaecffc | rcaixias/estudopython | /ex012.py | 136 | 3.796875 | 4 | produto = float(input('Qual é o valor do produto? '))
print('O valor do produto com 5% de desconto é {:.2f} R$'.format(produto*0.95)) |
9a2acb0edd2e12b3520662b2dcea16624ec84ddf | 116pythonZS/YiBaiExample | /055.py | 302 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding=utf8 -*-
# Created by carrot on 2017/8/28.
"""
题目:学习使用按位取反~。
"""
def main():
a = 234
b = ~a
print('The a\'s 1 complement is %d' % b)
a = ~a
print('The a\'s 2 complement is %d' % a)
if __name__ == "__main__":
main()
|
913769db38fead74273b0a18bea03bc5cad001a1 | sbsdevlec/PythonEx | /Hello/Lecture/Example_wikidocs/Ex016.py | 3,085 | 3.890625 | 4 | """
016 문자열 거꾸로 뒤집기
문자열을 거꾸로 뒤집어 출력하라.
string = "파이선은 재미있다."
실행 예:
'NOHTYP'
"""
string = "파이선은 재미있다."
print(string)
# string[start:stop:step]
print(string[::-1])
# print(string[:-1])
print(type(reversed(string)))
print(reversed(string))
print(''.join(reversed(string)))
"""
여러분이 알아야 할 파이썬 문자열에 관한 몇 가지 것들이 있습니다 :
파이썬에서는 문자열이 변경되지 않습니다 . 문자열을 변경해도 문자열은 수정되지 않습니다. 새로운 것을 만듭니다.
문자열은 슬라이스 가능합니다. 문자열을 자르는 것은 문자열의 한 지점에서 앞으로 또는 앞으로 다른 지점으로 주어진
증가분만큼 새로운 문자열을 제공합니다. 그들은 아래 첨자에 슬라이스 표기법 또는 슬라이스 객체를 사용합니다.
string[start:stop:step]
중괄호 밖에서 슬라이스를 만들려면 슬라이스 객체를 만들어야합니다.
slice_obj = slice(start, stop, step)
string[slice_obj]
"""
# 슬라이스객체 사용
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
print(string[reverse_slice])
# 슬라이스객체 사용
slice_obj = slice(None, None, -1)
print(string[slice_obj])
# 1줄
print("파이선은 재미있다."[::-1])
# 함수이용
def reversed_string(a_string):
return a_string[::-1]
print(reversed_string(string))
# 선생님이 원했던 것
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
print(reverse_a_string_slowly(string))
"""
참조
"""
### example02 -------------------
## start (with positive integers)
print('coup_ate_grouping'[0]) ## => 'c'
print('coup_ate_grouping'[1]) ## => 'o'
print('coup_ate_grouping'[2]) ## => 'u'
## start (with negative integers)
print('coup_ate_grouping'[-1]) ## => 'g'
print('coup_ate_grouping'[-2]) ## => 'n'
print('coup_ate_grouping'[-3]) ## => 'i'
## start:end
print('coup_ate_grouping'[0:4]) ## => 'coup'
print('coup_ate_grouping'[4:8]) ## => '_ate'
print('coup_ate_grouping'[8:12]) ## => '_gro'
## start:end
print('coup_ate_grouping'[-4:]) ## => 'ping' (counter-intuitive)
print('coup_ate_grouping'[-4:-1]) ## => 'pin'
print('coup_ate_grouping'[-4:-2]) ## => 'pi'
print('coup_ate_grouping'[-4:-3]) ## => 'p'
print('coup_ate_grouping'[-4:-4]) ## => ''
print('coup_ate_grouping'[0:-1]) ## => 'coup_ate_groupin'
print('coup_ate_grouping'[0:]) ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or stop:end:stride)
print('coup_ate_grouping'[-1:]) ## => 'g'
print('coup_ate_grouping'[-1::1]) ## => 'g'
print('coup_ate_grouping'[-1::-1])## => 'gnipuorg_eta_puoc'
## combinations
print('coup_ate_grouping'[-1::-1][-4:])## => 'puoc' |
871c14754024f1deb0bfa9822662caca2731d921 | brendascc/prueba-phyton | /brenda/3.8.py | 252 | 3.796875 | 4 | a=int(input("cual tabla quieres?: "))
b=int(input("hasta que numero deseas: "))
for var in range(1,b+1):
print(var, "x", a, "=", var*a)
input("...")
for i in "AMIGO":
print(f"Dame una {i}")
print("¡AMIGO!")
#imprime amigo uno por uno
|
1c06e972800299a16af0934403036218ae7782f0 | miyad/simuLab2 | /stub code.py | 554 | 3.609375 | 4 | from scipy import stats
import numpy as np
'''
Code to generate chi-square values where q are the levels and df is the degrees of freedom.
'''
q_list = [0.25,0.5,0.75,0.9,0.95,0.975,0.99]
for df in range(1,20):
st = ""
for q in q_list:
a = stats.chi2.ppf(q=q,df=df)
st = st + str(a) + " "
print("________",st)
'''
Code to generate upper q critical point of the normal distribution
'''
print(stats.norm.ppf(q=0.95))
dictionary = {}
a = [2,2,3]
a = tuple(a)
print(a)
dictionary[a] = 1
dictionary[a]+=2
print(dictionary[a]) |
b7c4f3bea3e5e68148a1d8a74221a529794c686c | Prashambhuta/learn-python | /edx-mitx-6.00.1x/pset_1/pset1_p3_sample_solution.py | 499 | 4.125 | 4 | # sample solution as per available in discussions.
"""
Find the largest alphabetically sequence of strings
"""
s = "asdfhhfueissdfdabcd"
i = 0
temp = s[i]
long = ""
while i < len(s) - 1:
if s[i + 1] >= s[i]:
temp += s[i + 1]
# print(temp)
i += 1
if len(temp) > len(long):
long = temp
elif s[i + 1] < s[i]:
temp = s[i + 1]
i += 1
if len(long) == 0:
long = s[0]
print("Longest substring in alphabetical order is: %s" % long)
|
529dd6491117ee82b610c5f7db83a6f50e89b437 | andradenathan/num-inteiros-e-criptografia-2020-2 | /pratica/cifraDeCesar.py | 706 | 3.671875 | 4 | def encripta_mensagem(texto, shift = 3):
mensagem = ""
for i in range(len(texto)):
letra = texto[i]
if(letra.isupper()):
mensagem += chr((ord(letra) + shift - 65) % 26 + 65)
else:
mensagem += chr((ord(letra) + shift - 97) % 26 + 97)
return mensagem
def desencripta_mensagem(mensagem_encriptada, shift = 3):
mensagem = ""
for i in range(len(mensagem_encriptada)):
letra = mensagem_encriptada[i]
if (letra.isupper()):
mensagem += chr((ord(letra) - shift - 65) % 26 + 65)
else:
mensagem += chr((ord(letra) - shift - 97) % 26 + 97)
return mensagem
|
1bca66306b9887e27216a1c02c7c272471b749b7 | codeartisanacademy/stuart-shaun | /country_add.py | 1,994 | 3.96875 | 4 | import sqlite3
def create_connection(db):
connection = None
try:
connection = sqlite3.connect(db)
except Exception as error:
print('There is an error: ' + error )
return connection
def insert_city(connection, name, population, country_id):
if connection:
insert_sql = "INSERT INTO cities(name, population, country) VALUES('{0}', {1}, {2})".format(name, population, country_id)
cursor = connection.cursor()
cursor.execute(insert_sql)
connection.commit()
# print(cursor.lastrowid)
city = select_city(connection, cursor.lastrowid)
return city
else:
print("No connection")
def select_city(connection, id):
if connection:
select_sql = "SELECT * FROM cities WHERE id={0}".format(id)
cursor = connection.cursor()
cursor.execute(select_sql)
city = cursor.fetchone()
return city
else:
print("No connection")
def update_city(connection, name, population, id):
if connection:
#city = select_city(connection, id)
if name and population:
update_sql = "UPDATE cities SET name = {0}, population = {1} WHERE id = {2}".format(name, population, id)
else:
if name:
update_sql = "UPDATE cities SET name = {0} WHERE id = {1}".format(name, id)
else:
update_sql = "UPDATE cities SET population = {0} WHERE id = {1}".format(population, id)
cursor = connection.cursor()
cursor.execute(update_sql)
connection.commit()
print("updated")
connection = create_connection('citydb.db')
with connection:
new_city_name = input("Enter the city name: ")
new_city_population = input("Enter the population for {0}: ".format(new_city_name))
new_city_country = input("Enter the country id (1-3): ")
city = insert_city(connection, new_city_name, int(new_city_population), int(new_city_country))
print(city)
|
e2500a94d1a54feb6ce91964f8b6cb6731aba4b6 | Osmandursunn/Python-Bootcamp-Assigments | /5. HAFTA 4. ODEV HACIM HESAPLAMA.py | 3,000 | 3.625 | 4 | while True:
try:
while True:
pi = 3.14
print("""
Islemler:
A.Alan Hesaplama
B.Hacim Hesaplama
""")
islem = input("Lutfen Yapmak Istediginiz Islemi Secin:")
if islem == "A" or "a":
print("""
Alan Hesaplama Islemleri:
1.Kare Alani
2.Dikdortgen Alani
3.Ucgen Alani
""")
islem = input("Lutfen Alanini Hesaplamak Istediginiz Sekli Secin:")
if islem == "1":
kenar_uzunlugu = int(input("Kenar Uzunlugunu Girin: "))
kare_alan = kenar_uzunlugu ** 2
print("Karenin Alani:", kare_alan)
elif islem == "2":
kisa_kenar = int(input("Kisa Kenar Uzunlugunu Girin: "))
uzun_kenar = int(input("Uzun Kenar Uzunlugunu Girin: "))
dikdirtgen_alan = kisa_kenar * uzun_kenar
print("Dikdortgenin Alani:", dikdirtgen_alan)
elif islem == "3":
yukseklik = int(input("Ucgenin Yuksekligini Girin: "))
taban = int(input("Yuksekligin Ait Oldugu Taban Uzunlugunu Girin: "))
ucgen_alan = (yukseklik * taban) / 2
print("Ucgenin Alani:", ucgen_alan)
else:
print("Lutfen Gecerli Bir Islem Girin!")
continue
elif islem == "B" or "b":
print("""
Hacim Hesaplama Islemleri:
1.Kup Hacmi
2.Kure Hacmi
3.Koni Hacmi
""")
islem = input("Lutfen Hacmini Hesaplamak Istediginiz Sekli Secin:")
if islem == "1":
kenar_uzunlugu = int(input("Kupun Kenar Uzunlugunu Girin: "))
kup_hacim = kenar_uzunlugu ** 3
print("Kupun Hacmi:", kup_hacim)
elif islem == "2":
yari_cap = int(input("Kurenin Yaricapini Girin: "))
kure_hacim = (4 / 3) * (pi * (yari_cap ** 3))
print("Kurenin Hacmi:", kure_hacim)
elif islem == "3":
yukseklik = int(input("Koninin Yuksekligini Girin: "))
yari_cap = int(input("Koniye Ait Tabaninin Yaricapini Girin: "))
koni_hacim = (1 / 3) * (pi * (yari_cap ** 2)) * yukseklik
print("Koninin Hacmi:", koni_hacim)
else:
print("Lutfen Gecerli Bir Islem Girin!")
continue
else:
print("Lutfen Gecerli Bir Islem Girin!")
continue
except:
print("Hatali Islem!")
continue
|
98cc8534bb1a3c6ecc1f6d8161acb13c9cb2d6f4 | hungnv132/algorithm | /recursion/linear_sum.py | 247 | 3.796875 | 4 |
# Performance is O(n)
def _linear_sum(S, n):
if n==0:
return 0
else:
return S[n-1] + _linear_sum(S, n-1)
def sum(S):
return _linear_sum(S, len(S))
if __name__ == '__main__':
S = [1, 2, 3, 4, 5]
print(sum(S)) |
598e0b17346aa6ea6c8aacba6de1649a4af14d88 | BipronathSaha99/dailyPractiseCode | /fun_3.py | 424 | 4.375 | 4 | '''
Write a function called showNumbers that takes a parameter called limit. It should print all the numbers between
0 and limit with a label to identify the even and odd numbers. For examaple-
0 even
1 odd
2 even
3 odd
'''
n=int(input("enter the number:"))
def showNumbers(n):
for i in range(n+1):
if n%2==0:
return "even"
else:
return "odd"
print(showNumbers(n)) |
d1fe71ca3519ddafb17dd116ab0d2f01cf8cfcfc | kidexp/91leetcode | /tree/1145BinaryTreeColoringGame.py | 1,694 | 3.734375 | 4 | from types import coroutine
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
def find_node(root):
if root is None:
return None
if root.val == x:
return root
left = find_node(root.left)
right = find_node(root.right)
return left or right
def count_nodes(root):
if not root:
return 0
return 1 + count_nodes(root.left) + count_nodes(root.right)
node = find_node(root)
left_child_nodes = count_nodes(node.left)
right_child_nodes = count_nodes(node.right)
return (
left_child_nodes > n / 2
or right_child_nodes > n / 2
or (n - left_child_nodes - right_child_nodes - 1) > n / 2
)
if __name__ == "__main__":
solution = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.left.left.left = TreeNode(8)
root.left.left.right = TreeNode(9)
root.left.right.left = TreeNode(10)
root.left.right.right = TreeNode(11)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
print(solution.btreeGameWinningMove(root, n=11, x=3))
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print(solution.btreeGameWinningMove(root=root, n=3, x=1))
|
a898fe8f2447acde6b92ba45800951e5b4a39dc6 | BoyanH/Freie-Universitaet-Berlin | /OOP/Python/Homework3/Aufgabe22.py | 1,189 | 4.03125 | 4 | def finde(array, element): #why not find people, wtf
assert (type(array) == list), "List expected as input!"
indexOfSearchedElement = -1
for i in range(0, len(array)):
if array[i] == element:
indexOfSearchedElement = i
break
assert (indexOfSearchedElement == -1 or array[indexOfSearchedElement] == element), "Something went terribly wrong!"
return indexOfSearchedElement
def findeUsingWhile(array, element):
assert (type(array) == list), "List expected as input!"
indexInArray = 0
lenOfArray = len(array)
indexOfSearchedElement = -1
while(indexInArray < lenOfArray and array[indexInArray] != element):
if (indexInArray == lenOfArray - 1) and (array[indexInArray] != element): #last element
#element not found, break loop in order not to execute the else statement
break
indexInArray += 1
else:
return indexInArray
return -1
print("findeUsingWhile([4,23,1,23,23,123,13], 123): ", findeUsingWhile([4,23,1,23,23,123,13], 123))
print("findeUsingWhile([4,23,1,23,23,123,13], 123): ", findeUsingWhile([4,23,1,23,23,123,13], 48))
print("findeUsingWhile() == finde(): ", findeUsingWhile([4,23,1,23,23,123,13], 48) == finde([4,23,1,23,23,123,13], 48))
|
011488c61722d2d7e319874c582a835495a21bcd | MaxMeiY/learnPython | /class/classtools.py | 826 | 3.5625 | 4 | class AttrDisplay:
'''
Provides an inheritable display overload method that
shows instances with their class names and a
name=value pair for each attribute stored on the
instance itself.
'''
def gatherAttrs(self):
attrs = []
for key in sorted(self.__dict__):
attrs.append('%s=%s' % (key,
getattr(self, key)))
return ', '.join(attrs)
def __repr__(self):
return '[%s: %s]' % (self.__class__.__name__,
self.gatherAttrs())
if __name__ == '__main__':
class TopTest(AttrDisplay):
count = 0
def __init__(self):
self.attr1 = TopTest.count
self.attr2 = TopTest.count+1
TopTest.count += 2
class SubTest(TopTest):
pass
|
383c991be002c19245836c750b22d652cf993e3e | Nmazil-Dev/PythonCrashCoursePractice | /pygal practice/5-10.py | 764 | 3.53125 | 4 | from die import Die
import matplotlib.pyplot as plt
die_1 = Die(6)
die_2 = Die(6)
results = []
for roll_num in range(100):
result = die_1.roll() + die_2.roll()
results.append(result)
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result+1):
frequency = results.count(value)
frequencies.append(frequency)
label =[]
for x in range(2, max_result+1):
label.append(x)
plt.plot(label, frequencies , linewidth =5)
#set chart title and label axes
plt.title("Results D6 + D6", fontsize=24)
plt.xlabel('D6 + D6', fontsize=14)
plt.ylabel("Frequency of Result", fontsize=14)
#set size of tick labels
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
|
36b8b790c371f8d9a494d7bf96dec72f2f82762b | korosh-khosravi/home2020 | /Library/Practise.py | 394 | 3.625 | 4 |
thickness = 7
height = 21
c = '|'
w = 'WELCOME'
print(c.rjust(5, '@'))
for i in range(thickness//2):
print((c*i).rjust((height//2), '-') + c.center(3, '.') + (c*i).ljust((height//2), '-'))
print(w.center(height, '-'))
for i in range(thickness//2):
print((c * ((thickness//2)-i-1)).rjust((height // 2), '-') + c.center(3, '.') + (c * ((thickness//2)-i-1)).ljust((height // 2), '-'))
|
b1ed049c8852ada27eb97a4e532ffb25c2aca00a | Otukoya52/Loops-Functions-task | /auth.py | 5,246 | 3.625 | 4 | import random
from datetime import datetime
import validation
import database
from getpass import getpass
def init():
print("Welcome to BankThemeji \n")
now = datetime.now()
thisTime = now.strftime("%a %d-%m-%Y %I:%M:%S %p")
print('Current Session:', thisTime)
have_account = input("\n Do you have an account with us?:>> \n 1. (Yes) \n 2. (No) \n")
is_valid_have_account = validation.have_account_validation(have_account)
if is_valid_have_account:
if int(have_account) == 1:
login()
elif int(have_account) == 2:
register()
else:
print("You have selected an invalid option \n")
init()
else:
print("You have selected an invalid option \n")
init()
def login():
print("********** Login **********")
account_number_from_user = input('What is your account number?: \n')
is_valid_account_number = validation.account_number_validation(account_number_from_user)
if is_valid_account_number:
password = getpass("What is your password \n")
user = database.authenticated_user(account_number_from_user, password)
if user:
bank_operation(user)
else:
print ('Invalid Account Number or Password \n')
login()
else:
print("Account number invalid: Account number should be up to 10 digits and only integers")
init()
def register():
print("********** Register **********")
email = input("What is your email address? \n")
first_name = input("What is your first name? \n")
last_name = input("What is your last name? \n")
password = getpass("create a password for yourself \n")
account_balance = input("What is your account balance \n")
account_number = generating_account_number()
is_user_created = database.create(account_number, first_name, last_name, email, password, account_balance)
if is_user_created:
print("Your Account Has been created")
print(" === ===== ====== ===== ===")
print(f"Your account number is: {account_number}")
print("Make sure you keep it safe")
print(" === ===== ====== ===== ===")
login()
else:
print("Something went wrong. Please try again")
register()
def bank_operation(user_details):
print (f"Welcome {user_details[0], user_details[1]}")
selected_option = input("What would you like to do? \n 1. Check Balance \n 2. Deposit \n 3. Withdraw \n 4. Logout \n 5. Exit \n")
is_valid_selected_option = validation.selected_option_validation(selected_option)
if is_valid_selected_option:
if int(selected_option) == 1:
get_current_balance(user_details)
elif int(selected_option) == 2:
deposit_operation(user_details)
elif int(selected_option) == 3:
withdrawal_operation(user_details)
elif int(selected_option) == 4:
logout()
elif int(selected_option) == 5:
exit()
else:
print("You have selected an invalid option")
bank_operation(user_details)
else:
bank_operation(user_details)
def get_current_balance(user_details):
print (f"Your balance is {user_details[4]}")
other_operations(user_details)
def deposit_operation(user_details):
deposit_amount = int(input("How much would you like to deposit?: \n"))
is_valid_deposit_amount = validation.deposit_amount_validation(deposit_amount)
if is_valid_deposit_amount:
user_details[4] += int(deposit_amount)
print("Deposit Successful!")
print(f"Your balance is #{user_details[4]}")
else:
deposit_operation(user_details)
def withdrawal_operation(user_details):
print (f"Your balance is {user_details[4]}")
withdraw_amount = input('How much would you like to withdraw?: \n')
is_valid_withdraw_amount = validation.withdraw_amount_validation(withdraw_amount)
if is_valid_withdraw_amount:
if int(withdraw_amount) > user_details[4]:
print (f"You do not have sufficient funds. Your balance is {user_details[4]}")
else:
user_details[5] -= int(withdraw_amount)
print("Withdrawal Successful")
print (f"Your balance is now {user_details[4]}")
other_operations(user_details)
else:
withdrawal_operation(user_details)
def other_operations(user_details):
options = input("Would you like to perform another operation? \n 1. Yes \n 2. No \n")
is_valid_options = validation.other_operations_validation(options)
if is_valid_options:
if int(options) == 1:
bank_operation(user_details)
elif int(options) == 2:
login()
else:
print("You have selected an invalid option")
other_operations(user_details)
else:
other_operations(user_details)
def logout():
login()
def exit():
init()
def generating_account_number():
return random.randrange(1111111111, 9999999999)
init() |
bdbd59b741fa3da9d986d39f33a2b1a00dd4745c | shrirangmhalgi/Python-Bootcamp | /9. Rock Paper Scissors/rock_paper_scissors_v1.py | 1,119 | 4.125 | 4 | while True:
print("\n...Rocks...")
print("...Papers...")
print("...Scissors...")
print("...-1 to exit...")
player1_input = input("Player 1 enter your choice... : ")
print("\n" * 20) #you can repeat something n number of times by giving multiplication sign
if player1_input == "-1" :
quit();
player2_input = input("Player 2 enter your choice... :")
if player1_input == "scissors" :
if player2_input == "papers" :
print("Player 1 wins...")
elif player2_input == "rocks" :
print("Player 2 wins...")
else :
print("Its a draw...")
elif player1_input == "rocks" :
if player2_input == "scissors" :
print("Player 1 wins...")
elif player2_input == "papers" :
print("Player 2 wins...")
else :
print("Its a draw...")
else :
if player2_input == "rocks" :
print("Player 1 wins...")
elif player2_input == "scissors" :
print("Player 2 wins...")
else :
print("Its a draw...")
print("\n")
|
72833495fc0d5ab5180bbbd3cc98462bbb005ee5 | ysjin0715/python-practice | /chapter6/study.py | 1,268 | 4.15625 | 4 | #2.
print('방문을 환영합니다!')
print('방문을 환영합니다!')
print('방문을 환영합니다!')
print('방문을 환영합니다!')
print('방문을 환영합니다!')
# for i in range(1000):
# print('방문을 환영합니다!')
#4.
for i in [1, 2, 3, 4, 5]:
print('방문을 환영합니다')
#5.
for i in [1, 2, 3, 4, 5]:
print("i=",i)
for a in [1, 2, 3, 4, 5]:
print("9*",a,"=",9*a)
#6.
for b in range(5):
print('방문을 환영합니다')
print(list(range(10)))
#7.
for i in range(1,6,1):
print(i,end="")
for i in range(10,0,-1):
print(i,end="")
#8.
import turtle
t=turtle.Turtle()
t.shape('turtle')
for count in range(6):
t.circle(100)
t.left(360/6)
#9.
response='아니'
while response=='아니':
response=input('업마, 다됬어?');
print('먹자')
#10.
password=""
while password!='pythonisfun':
password=input('암호를 입력하시오: ')
print('로그인 성공')
#11.
count=1
sum=0
while count<=10:
sum=sum+count
count=count+1
print('합계는',sum)\
#12.
t.up()
t.goto(0,0)
t.down()
i=0
while i<4:
t.forward(100)
t.right(90)
i=i+1
#13.
while True:
light=input('신호등 색상을 입력하시오: ')
if light=='blue':
break
print('전진!') |
c5d4d92a28d5f4b08bfe6a5621b25d1346fa4d8b | tpt5cu/python-tutorial | /language/python_27/popular_tasks/random_.py | 451 | 3.78125 | 4 | import random
def random_float():
'''Generate a float in the range [0.0, 1.0)'''
for _ in range(10):
print(random.random())
def random_integer():
'''Range is inclusive of lower and upper bound'''
print(random.randint(0, 100))
def random_list_item():
my_list = ['A', 'list', 'of', 'values']
print(random.choice(my_list))
if __name__ == '__main__':
random_float()
#random_integer()
#random_list_item() |
bfae9a72383464c014f479dfab957134443c3dae | iSkylake/Algorithms | /Tree/LongPathBinTree.py | 1,265 | 3.890625 | 4 | # Create a function that returns the longest path in a Binarty Tree
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Binary_Tree:
def __init__(self):
self.root = None
self.size = 0
# First attempt
# def long_path(root):
# count = 0
# max_path = 0
# def _long_path(node, count):
# nonlocal max_path
# if node == None:
# if count >= max_path:
# max_path = count
# return
# count += 1
# _long_path(node.left, count)
# _long_path(node.right, count)
# count -= 1
# _long_path(root, count)
# print(max_path)
# Cleaner version
def long_path(root):
max_path = 0
def traverse(node, length):
if not node:
return
nonlocal max_path
max_path = max(max_path, length)
traverse(node.left, length+1)
traverse(node.right, length+1)
traverse(root, 1)
print(max_path)
bin_tree = Binary_Tree()
a = Node('a')
b = Node('b')
c = Node('c')
d = Node('d')
e = Node('e')
f = Node('f')
g = Node('g')
h = Node('h')
i = Node('i')
j = Node('j')
k = Node('k')
bin_tree.root = a
a.left = b
a.right = c
b.left = d
b.right = e
e.right = f
f.left = h
c.right = g
d.left = i
i.left = j
j.right = k
long_path(a)
|
3a3ad7937fee92e9f6bcb96464ce336647461760 | akiniwa/hobby | /python/p.matplotlib/01.plot.py | 152 | 3.875 | 4 | """show curve Y =X ** 2 with x in [0, 99]"""
import matplotlib.pyplot as plt
X = range(100)
Y = [value ** 2 for value in X]
plt.plot(X, Y)
plt.show()
|
957f78196b983ce6f8a6ac70bf750100b8e2fe36 | MasterOfDisguise/pystructs | /list.py | 6,927 | 4.15625 | 4 | import unittest
class List(object):
def __init__(self):
self.head = None
print 'new'
def append(self, value):
end_node = self.head
new_node = Node(value)
if self.head is None:
self.head = Node(value)
elif self.head is not None:
while end_node.next is not None:
end_node = end_node.next
end_node.next = new_node
def __len__(self):
len = 0
if self.head is None:
return len
elif self.head is not None:
true = True
target = self.head
len += 1
while true:
if target.next is None:
true = False
return len
target = target.next
len += 1
def __getitem__(self, item):
target = self.head
if item > len(self):
print "Error, item does not exist"
elif item <= len(self):
for i in range(item):
target = target.next
return target.value
def insert(self, place, item):
new_node = Node(item)
target = self.head
target2 = self.head
if place == 0:
new_node.next = self.head
self.head = new_node
else:
for i in range(place-1):
target = target.next
for i in range(place):
target2 = target2.next
target.next = new_node
new_node.next = target2
def remove(self, item):
target = self.head
running = True
while running:
target = target.next
if target.next.value == item:
target.next = target.next.next
running = False
if target.next.value is None:
print "item not in list"
running = False
def index(self, item):
target = self.head
place = 0
running = True
if target.value == item:
return place
while running:
place += 1
target = target.next
if target.value == item:
return place
elif target is None:
print "item not in list"
running = False
def count(self, item):
target = self.head
number = 0
while target is not None:
if target.value == item:
number += 1
target = target.next
return number
def reverse(self):
length = len(self)
prev_node = None
cur_node = self.head
next_node = cur_node.next
while next_node is not None:
cur_node.next = prev_node
prev_node = cur_node
cur_node = next_node
next_node = cur_node.next
cur_node.next = prev_node
self.head = cur_node
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class TestList(unittest.TestCase):
def test_new_list_is_empty(self):
my_list = List()
#len(my_list) calls my_list.__len__()
self.assertEquals(len(my_list), 0)
def test_can_add_one_thing_to_list(self):
my_list = List()
my_list.append('a')
self.assertEquals(len(my_list), 1)
#my_list[0] calls my_list.__getitem__(0)
self.assertEquals(my_list[0], 'a')
def test_can_add_many_things_to_list(self):
my_list = List()
my_list.append('a')
my_list.append('b')
my_list.append('c')
my_list.append('d')
self.assertEquals(len(my_list), 4)
self.assertEquals(my_list[0], 'a')
self.assertEquals(my_list[1], 'b')
self.assertEquals(my_list[2], 'c')
self.assertEquals(my_list[3], 'd')
def test_can_insert_into_middle_of_list(self):
my_list = List()
my_list.append('a')
my_list.append('b')
my_list.append('c')
my_list.insert(1, 'd') #1 is the index. This should put d at index 1, and shove everything else forward
self.assertEquals(len(my_list), 4)
self.assertEquals(my_list[0], 'a')
self.assertEquals(my_list[1], 'd')
self.assertEquals(my_list[2], 'b')
self.assertEquals(my_list[3], 'c')
def test_can_remove_item_from_list(self):
my_list = List()
my_list.append('a')
my_list.append('b')
my_list.append('c')
my_list.append('d')
my_list.remove('c')
self.assertEquals(len(my_list), 3)
self.assertEquals(my_list[0], 'a')
self.assertEquals(my_list[1], 'b')
self.assertEquals(my_list[2], 'd')
def test_can_find_item_in_list(self):
my_list = List()
my_list.append('a')
my_list.append('b')
my_list.append('c')
my_list.append('d')
self.assertEquals(my_list.index('a'), 0)
self.assertEquals(my_list.index('b'), 1)
self.assertEquals(my_list.index('c'), 2)
self.assertEquals(my_list.index('d'), 3)
def test_can_count_item_in_list(self):
my_list = List()
my_list.append('a')
my_list.append('b')
my_list.append('c')
my_list.append('a')
my_list.append('c')
my_list.append('d')
my_list.append('a')
self.assertEquals(my_list.count('a'), 3)
self.assertEquals(my_list.count('b'), 1)
self.assertEquals(my_list.count('c'), 2)
self.assertEquals(my_list.count('d'), 1)
self.assertEquals(my_list.count('e'), 0)
# we'll come back to this one later
# def test_can_sort_list(self):
# my_list = List()
# my_list.append('c')
# my_list.append('a')
# my_list.append('d')
# my_list.append('b')
# my_list.sort()
# self.assertEquals(len(my_list), 4)
# self.assertEquals(my_list[0], 'a')
# self.assertEquals(my_list[1], 'd')
# self.assertEquals(my_list[2], 'b')
# self.assertEquals(my_list[3], 'c')
def test_can_reverse_list(self):
my_list = List()
my_list.append('a')
my_list.append('b')
my_list.append('c')
my_list.append('d')
my_list.reverse()
self.assertEquals(len(my_list), 4)
self.assertEquals(my_list[0], 'd')
self.assertEquals(my_list[1], 'c')
self.assertEquals(my_list[2], 'b')
self.assertEquals(my_list[3], 'a')
def test_can_add_many_kinds_of_things_to_list(self):
my_list = List()
my_list.append('a')
my_list.append(2)
my_list.append('abcde')
my_list.append([1, 2, 3])
self.assertEquals(len(my_list), 4)
self.assertEquals(my_list[0], 'a')
self.assertEquals(my_list[1], 2)
self.assertEquals(my_list[2], 'abcde')
self.assertEquals(my_list[3], [1, 2, 3])
|
b1f37d0a9a5d003672c1c3d17a2c72b0a9094b57 | mxmaria/coursera_python_course | /week4/Быстрое возведение в степень.py | 709 | 4.375 | 4 | # Возводить в степень можно гораздо быстрее, чем за n умножений!
# Для этого нужно воспользоваться следующими рекуррентными соотношениями: aⁿ = (a²)ⁿ/² при четном n, aⁿ=a⋅aⁿ⁻¹ при нечетном n.
# Реализуйте алгоритм быстрого возведения в степень.
def power(a, n):
if n == 0:
return 1
elif n == 1:
return a
elif n % 2 != 0:
return a * power(a, n - 1)
elif n % 2 == 0:
return power(a * a, n / 2)
a = float(input())
n = int(input())
print(power(a, n))
|
79c1b13269b69b98eb8faecf36b88a3941399015 | Omar7102/fundamentos | /NumeroMayoryMenor.py | 286 | 4 | 4 | #Programa que muestra el menor y mayor entre dos numeros
n= input('digite un numero')
b= input('digite un numero')
if (n>b) :
print('el numero mayor es:',n)
print('el numero menor es:', b)
else:
print('el numero mayor es:',b)
print('el numero menor es:',n)
|
b2f25aa1340b3191b8b398542d48e8f9dfdb1200 | bnemchak/petting_zoo | /Attractions/Amazon.py | 500 | 3.75 | 4 | from attractions.attraction import Attraction
class Amazon(Attraction):
def __init__(self, attraction_name, description):
super().__init__(attraction_name, description)
def add_animal(self, animal):
try:
if animal.slither_speed > -1:
self.animals.append(animal)
print(f"{animal} can be found in {self.attraction_name}")
except AttributeError as ex:
print(f"{animal} does not belong in {self.attraction_name}")
|
279d5b61812f238cb9b992fadff9a9ac9771e112 | AfaqAnwar/Rennon | /data/handlers/comment_to_db.py | 6,250 | 3.765625 | 4 | import sqlite3
import json
from datetime import datetime
"""
Reddit Comment Database Creation Script.
Filters and creates a sqlite3 database from a .JSON of Reddit comments.
@Author Afaq Anwar
@Version 04/02/2019
"""
# List of Reddit Corpus Comments saved as .JSON
data_files = ['2017-01', '2017-02', '2017-03', '2017-12', '2018-01', '2018-10', '2018-11', '2018-12']
# Final commit to sql database.
sql_commit = []
connection = sqlite3.connect('{}.db'.format("reddit_data"))
cursor = connection.cursor()
# Creates the initial table within the database.
def create_table():
cursor.execute("""CREATE TABLE IF NOT EXISTS parent_reply
(parent_id TEXT PRIMARY KEY, comment_id TEXT UNIQUE, parent TEXT, comment TEXT,
subreddit TEXT, unix INT, score INT)""")
# Cleans the data to avoid tokenizing of unnecessary data.
def format_data(data):
data = data.replace("\n", " newlinechar ")
data = data.replace("\r", " newlinechar ")
data = data.replace('"', "'")
return data
# Finds the parent of a comment based on a parent id.
# This helps set up the from - to reply structure.
def find_parent(pid):
try:
sql = "SELECT comment FROM parent_reply WHERE comment_id = '{}' LIMIT 1".format(pid)
cursor.execute(sql)
result = cursor.fetchone()
if result != None:
return result[0]
else:
return False
except Exception as e:
print("find_parent", e)
return False
# Checks if the data is acceptable before being pushed to the databse.
def check_if_acceptable(data):
if len(data.split(' ')) > 105 or len(data) <= 1:
return False
elif len(data) > 500:
return False
# Blocks removed comments from being inserted.
elif data == "[deleted]" or data == "[removed]":
return False
# Filters out all links (hopefully).
elif "https://" in data or "http://" in data or "www." in data or ".com" in data:
return False
else:
return True
# Finds the score of a comment that is linked to a parent.
def find_existing_score(pid):
try:
sql = "SELECT score FROM parent_reply WHERE parent_id = '{}' LIMIT 1".format(pid)
cursor.execute(sql)
result = cursor.fetchone()
if result != None:
return result[0]
else:
return False
except Exception as e:
print("find_score_parent", str(e))
return False
def commit_builder(sql):
global sql_commit
sql_commit.append(sql)
if len(sql_commit) > 5000:
cursor.execute("BEGIN TRANSACTION")
for s in sql_commit:
try:
cursor.execute(s)
except:
pass
connection.commit()
sql_commit = []
# Replaces a comment with a parent.
def sql_insert_replace_comment(comment_id, parent_id, parent, comment, subreddit, time, score):
try:
sql = """UPDATE parent_reply SET parent_id = ?, comment_id = ?, parent = ?, comment = ?, subreddit = ?, unix = ?, score = ? WHERE parent_id =?;""".format(parent_id, comment_id, parent, comment, subreddit, int(time), score, parent_id)
commit_builder(sql)
except Exception as e:
print("INSERT REPLACE COMMENT", str(e))
# Attaches a comment to a parent with no previous comment.
def sql_insert_has_parent(comment_id, parent_id, parent, comment, subreddit, time, score):
try:
sql = """INSERT INTO parent_reply (parent_id, comment_id, parent, comment, subreddit, unix, score) VALUES ("{}","{}","{}","{}","{}",{},{});""".format(parent_id, comment_id, parent, comment, subreddit, int(time), score)
commit_builder(sql)
except Exception as e:
print('INSERT HAS PARENT', str(e))
# Inserts a new comment as the parent, aka a new thread.
def sql_insert_no_parent(comment_id, parent_id, comment, subreddit, time, score):
try:
sql = """INSERT INTO parent_reply (parent_id, comment_id, comment, subreddit, unix, score) VALUES ("{}","{}","{}","{}",{},{});""".format(parent_id, comment_id, comment, subreddit, int(time), score)
commit_builder(sql)
except Exception as e:
print("INSERT NO PARENT", str(e))
if __name__ == "__main__":
create_table()
row_count = 0
pairs = 0
none_scores = 0
for file in data_files:
print("FILE LOADED - " + str(file))
with open("/home/afaq/Projects/Data/Datasets/RedditCommentCorpus/{}/RC_{}".format(file.split("-")[0], file), buffering=1000) as f:
for row in f:
row_count += 1
row = json.loads(row)
score = row['score']
# To avoid type comparisons with some malformed data sets, the score is prechecked.
if score is None:
none_scores += 1
continue
parent_id = row['parent_id'].split('_')[1]
comment_id = row['id']
body = format_data(row['body'])
created_utc = row['created_utc']
subreddit = row['subreddit']
parent_data = find_parent(parent_id)
# Filters out type of comment before committing to database.
if score >= 2:
if check_if_acceptable(body):
existing_comment_score = find_existing_score(parent_id)
if existing_comment_score:
if score > existing_comment_score:
sql_insert_replace_comment(comment_id, parent_id, parent_data, body, subreddit, created_utc, score)
else:
if parent_data:
sql_insert_has_parent(comment_id, parent_id, parent_data, body, subreddit, created_utc, score)
pairs += 1
else:
sql_insert_no_parent(comment_id, parent_id, body, subreddit, created_utc, score)
if row_count % 100000 == 0:
print("Total rows read: {}, Paired Rows: {}, Invalid Comments: {}, Time: {}, File: {}".format(row_count, pairs, str(none_scores), str(datetime.now()), str(file)))
none_scores = 0
|
b524ce2855c5bf23d28405d93705a5f6c8c1dee1 | vazqjose/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 228 | 3.984375 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
uniqueList = []
total = 0
for item in my_list:
if item not in uniqueList:
uniqueList.append(item)
total = total + item
return total
|
5cd1a6a445a913976579fd641ed09bcee53a0f3e | Sdann26/Estructura-de-Datos | /Proyecto/Trabajo.py | 6,010 | 3.703125 | 4 | import math
print ("\n\t\tMONTICULO BINARIO\n")
class MonticuloBinario: #Constructor del Monticulo Binario
def __init__(self):
self.listaMonticulo = [0]
self.tamanoActual = 0
### INSERSION ###
def insertar(self,k): # Metodo para insertar elemento en el monticulo
self.listaMonticulo.append(k) # Agrega un elemento al final de la lista
self.tamanoActual = self.tamanoActual + 1
self.flotar(self.tamanoActual)
def flotar(self,i): # Metodo para poner en orden elevandolo
while i // 2 > 0: # Verifica si la posicion del padre es 0 para salir del bucle
if self.listaMonticulo[i] < self.listaMonticulo[i // 2]: # Compara el elemento con su padre y si el padre es mayor estos cambian de sitio
tmp = self.listaMonticulo[i // 2]
self.listaMonticulo[i // 2] = self.listaMonticulo[i]
self.listaMonticulo[i] = tmp
i = i // 2
### ELIMINACION ###
def eliminar(self,k):
encontrado = 0; # Revisa si el elemento esta o no esta(Inicializa como si no estuviera)
for i in range(1,self.tamanoActual+1):
if(k == self.listaMonticulo[i]): # Busca el elemento en la lista
encontrado = encontrado + 1
self.listaMonticulo[i] = self.listaMonticulo[i] - k # Se vuelve el elemento minimo
self.flotar(i) # Ordenamos el arbol elevando el elemento minimo
self.eliminarMin() # Eliminamos este elemento que ahora es minimo
break
if(encontrado == 0):
print("El elemento no fue encontrado\n")
def eliminarMin(self): # Metodo para eleminar el elemento minimo(Raiz)
valorSacado = self.listaMonticulo[1]
self.listaMonticulo[1] = self.listaMonticulo[self.tamanoActual] # Le da el valor del ultimo elemento de la lista(Monticulo) al primero
self.tamanoActual = self.tamanoActual - 1
self.listaMonticulo.pop() # Quita el ultimo elemento de la lista
self.hundir(1)
return valorSacado
def hundir(self,i): # Metodo para poner en orden hundiendolo
while (i * 2) <= self.tamanoActual: # Verifica que el hijo sea menor que el padre(Este pasa a ser el ultimo elemento)
hm = self.hijoMin(i) # Le pasamos el valor de la posicion del hijo
if self.listaMonticulo[i] > self.listaMonticulo[hm]:
tmp = self.listaMonticulo[i]
self.listaMonticulo[i] = self.listaMonticulo[hm]
self.listaMonticulo[hm] = tmp
i = hm
def hijoMin(self,i):
if i * 2 + 1 > self.tamanoActual:
return i * 2
else: #Nos devuelve la posicion del menor hijo
if self.listaMonticulo[i*2] < self.listaMonticulo[i*2+1]:
return i * 2 #Hijo Izquierdo
else:
return i * 2 + 1 #Hijo Derecho
### INCREMENTAR LLAVE ###
def incrementarLlave(self,k,cant):
encontrado = 0; # Revisa si el elemento esta o no esta(Inicializa como si no estuviera)
for i in range(1,self.tamanoActual+1):
if(k == self.listaMonticulo[i]): # Busca el elemento en la lista
encontrado = encontrado + 1
self.listaMonticulo[i] = self.listaMonticulo[i] + cant # Le suma la cantidad deseada
self.hundir(i) # Ordenamos el arbol bajando el elemento
break
if(encontrado == 0):
print("El elemento no fue encontrado\n")
### DECREMENTAR LLAVE ###
def decrementarLlave(self,k,cant):
encontrado = 0; # Revisa si el elemento esta o no esta(Inicializa como si no estuviera)
for i in range(1,self.tamanoActual+1):
if(k == self.listaMonticulo[i]): # Busca el elemento en la lista
encontrado = encontrado + 1
self.listaMonticulo[i] = self.listaMonticulo[i] - cant # Le resta la cantidad deseada
self.flotar(i) # Ordenamos el arbol subiendo el elemento
break
if(encontrado == 0):
print("El elemento no fue encontrado\n")
### CONSTRUCCION ###
def construirMonticulo(self,unaLista):
i = len(unaLista) // 2 # Comenzaremos con la mitad del arbol
self.tamanoActual = len(unaLista) # Le pasa el tamaño de lista
self.listaMonticulo = [0] + unaLista[:] # Pasa todos los datos
while (i > 0): #Hunde todos los elementos desde la mitad al inicio
self.hundir(i)
i = i - 1
### IMPRIMIR ###
def imprimir():
k = 1
espacio = int(math.log(MonticuloBinario.tamanoActual,2))
espacio = espacio + 1
for i in range((espacio-1)**2):
print (" ",end="")
for i in range(1,MonticuloBinario.tamanoActual+1):
for j in range(espacio**2):
print(" ",end="")
print(MonticuloBinario.listaMonticulo[i], end=" ")
for j in range(espacio**2):
print(" ",end="")
if (i+1) % pow(2,k) == 0: # Realiza el salto de linea para bajar de nivel al arbol
print("")
k = k + 1
espacio = espacio - 1
for i in range((espacio-1)**2):
print (" ",end="")
print("")
### MENU ###
MonticuloBinario = MonticuloBinario()
print ("\t\tMenú de Opciones\n")
opc = 0
while opc != 6:
print ("1. Construccion de un monticulo")
print ("2. Insertar dato")
print ("3. Eliminar dato")
print ("4. Incrementar una llave")
print ("5. Decrementar una llave")
print ("6. Salir\n")
print ("Elige una opción: ",end="")
opc = int(input())
if opc == 1:
lista = []
n = int(input("Cuantos valores deseas agregar al arbol: "))
for i in range(n):
dato = int(input("Agregando valor "+str(i+1)+": "))
lista.append(dato)
MonticuloBinario.construirMonticulo(lista)
print("")
imprimir()
print("")
elif opc == 2:
dato = int(input("Que dato desea insertar: "))
MonticuloBinario.insertar(dato)
print("")
imprimir()
print("")
elif opc == 3:
dato = int(input("Que dato desea eliminar: "))
MonticuloBinario.eliminar(dato)
print("")
imprimir()
print("")
elif opc == 4:
dato = int(input("Que llave desea incrementar: "))
cant = int(input("En cuanto lo quiere incrementar: "))
MonticuloBinario.incrementarLlave(dato,cant)
print("")
imprimir()
print("")
elif opc == 5:
dato = int(input("Que llave desea decrementar: "))
cant = int(input("En cuento lo quiere decrementar: "))
MonticuloBinario.decrementarLlave(dato,cant)
print("")
imprimir()
print("")
elif opc == 6:
print("\t\tHasta pronto...")
elif (opc <= 0) or (opc >= 7):
print ("No ha insertado ninguna de las opciones\n")
|
e093219aefcf7b6f276998f6007439da54065c9b | felixyh/Lets_Python | /D10/s1.py | 1,482 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
name = " aleX"
# a.移除name 变量对应的值两边的空格,并输入移除后的内容
# v = name.strip()
# print(v)
# b.判断name 变量对应的值是否以"al"开头,并输出结果
# if name.startswith("al"):
# print("name is started with 'al' ")
# else:
# pass
# c.判断name 变量对应的值是否以"X"结尾,并输出结果
# if name.endswith("X"):
# print("name is ended with 'X' ")
# else:
# pass
# d.将name 变量对应的值中的“l”替换为“p”,并输出结果
# v = name.replace("l", "p")
# print(v)
# e.将name 变量对应的值根据“l”分割,并输出结果。
# v = name.split("l")
# print(v)
# f.请问,上一题e.分割之后得到值是什么类型(可选)?
# v = name.split("l")
# print(type(v))
# g.将name 变量对应的值变大写,并输出结果
# v = name.upper()
# print(v)
# h.将name 变量对应的值变小写,并输出结果
# v = name.casefold()
# print(v)
# i.请输出name 变量对应的值的第2 个字符?
# print(name[1])
# j.请输出name 变量对应的值的前3 个字符?
# print(name[:3])
# print(name[0:3])
# k.请输出name 变量对应的值的后2 个字符?
# print(name[-2:])
# l.请输出name 变量对应的值中“e”所在索引位置?
# print(name.find("e"))
# m.获取子序列,仅不包含最后一个字符。如:oldboy则获取oldbo;root则获取roo
# print(name.strip(name[-1]))
|
cecc8acdd7b31d0c6741877d060e5e42e9b0a5ec | odioman/whohastoeatthechilipepper | /main.py | 1,345 | 4.03125 | 4 | # first round
userin1 = int(input('We start with 13 chocolates and 1 chili pepper. Who has to eat the chili pepper? Enter 1,2 or 3: '));
while userin1 >= 4:
userin1 = int(input('Needs to be 1, 2, or 3: '))
if userin1 <= 3:
break
chili1 = int(4 - userin1)
chococounter = 13 - 4
print('You picked ', userin1, 'computer chose', chili1)
print('Chococounter:', chococounter)
# second round
userin2 = int(input('We start with 13 chocolates and 1 chili pepper. Who has to eat the chili pepper? Enter 1,2 or 3: '));
while userin2 >= 4:
userin2 = int(input('Needs to be 1, 2, or 3: '))
if userin2 <= 3:
break
chili2 = int(4 - userin2)
chococounter2 = chococounter - 4
print('You picked ', userin2, 'computer chose', chili2)
print('Chocounter:', chococounter2)
# third round
userin3 = int(input('We start with 13 chocolates and 1 chili pepper. Who has to eat the chili pepper? Enter 1,2 or 3: '));
while userin3 >= 4:
userin3 = int(input('Needs to be 1, 2, or 3: '))
if userin3 <= 3:
break
userin3 = int(input('Needs to be 1, 2, or 3: '))
chili3 = int(4 - userin2)
chococounter3 = chococounter2 - 4
print('You picked ', userin3, 'computer chose', chili3)
print('Chocounter:', chococounter3)
# pepeer round
userin4 = int(input('Last round. You pick: '))
print('COMPUTER EATS THE PEPPER! Lucky you')
|
ccfc236057bed0b957ed7e19e727b660c64360d7 | girishkumaral/leet | /[1150]Check If a Number Is Majority Element in a Sorted Array.py | 2,611 | 4.0625 | 4 | # Given an integer array nums sorted in non-decreasing order and an integer
# target, return true if target is a majority element, or false otherwise.
#
# A majority element in an array nums is an element that appears more than
# nums.length / 2 times in the array.
#
#
# Example 1:
#
#
# Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
# Output: true
# Explanation: The value 5 appears 5 times and the length of the array is 9.
# Thus, 5 is a majority element because 5 > 9/2 is true.
#
#
# Example 2:
#
#
# Input: nums = [10,100,101,101], target = 101
# Output: false
# Explanation: The value 101 appears 2 times and the length of the array is 4.
# Thus, 101 is not a majority element because 2 > 4/2 is false.
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 1000
# 1 <= nums[i], target <= 10⁹
# nums is sorted in non-decreasing order.
#
# Related Topics Array Binary Search 👍 302 👎 31
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def isMajorityElement(self, nums: List[int], target: int) -> bool:
def findsmaller(l, r):
found = False
while l <= r:
if l == r:
return l-1, found
m = (r-l) // 2 + l
if not found and nums[m] == target:
found = True
if not m:
return -1, found
if nums[m-1] < target and nums[m] == target:
return m-1, found
elif nums[m] >= target:
r = m-1
else:
l = m+1
return -1, found
left, found = findsmaller(0, len(nums)-1)
if not found:
return False
def findGreater(l, r):
_found = False
while l <= r:
if l == r:
return r+1, _found
m = (r-l) // 2 + l
if not _found and nums[m] == target:
_found = True
if m >= len(nums)-1:
return len(nums), _found
if nums[m+1] > target and nums[m] == target:
return m + 1, _found
elif nums[m] <= target:
l = m+1
else:
r = m-1
return len(nums), _found
right, _ = findGreater(0, len(nums) - 1)
print(left, right)
if right-left-1 > len(nums) // 2:
return True
return False
# leetcode submit region end(Prohibit modification and deletion)
|
bc2e22a0419a9528f78ba358f63cb8865926b4ae | korynewton/code-challenges | /leetcode/MiddleOfLinkedList/solution.py | 650 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
#inititalize a fast and slow pointer
fast = slow = head
#while we are not at the end and not at last node, keep incrementing pointers
while fast and fast.next != None:
#increment fast twice as fast as slow
fast = fast.next.next
slow = slow.next
#when fast reaches the end slow should be at middle node
return slow
|
ba8fa4fd789d66b38644519328fc86bc9911b819 | MatthewManley/data-sec-project-3 | /main.py | 5,281 | 3.828125 | 4 | import os
import sys
import file_io
from encryption import generate_key, InvertedIndex, encryptSha256, encryptAesCbc, decryptAesCbc
key = 'key'
func = 'func'
def keygen(args: list):
expected = 1
if len(args) != expected:
print(f'Invalid number of arugments for function keygen, got {len(args)}, expected {expected}')
print('Arguments: key_file')
raise ValueError()
path = args[0]
key = generate_key(256 / 8)
file_io.write_file(path, key)
def encryption(args: list):
expected = 4
if len(args) != expected:
print(f'Invalid number of arugments for function encryption, got {len(args)}, expected {expected}')
print('Arguments: key_file, index_file, plain_text_folder, ciphertext_folder')
raise ValueError()
key_file = args[0] # Read the key from this file
index_file = args[1] # Write the index to this file
plaintext_folder = args[2] # Read all plaintexts from this folder
ciphertext_folder = args[3] # Write all ciphertexts to this folder
key_file_contents = file_io.read_file(key_file)
# Create new inverted index
inverted_index = InvertedIndex()
if not os.path.exists(ciphertext_folder):
os.makedirs(ciphertext_folder)
# Find the names of all files in the plaintext folder
plaintext_file_names = filter(
lambda file_name: os.path.isfile(
os.path.join(plaintext_folder, file_name)),
os.listdir(plaintext_folder))
for plaintext_file_name in plaintext_file_names:
full_plaintext_path = os.path.join(
plaintext_folder, plaintext_file_name)
plaintext = file_io.read_file(full_plaintext_path)
words = plaintext.split(' ')
# Add file to index
for word in words:
inverted_index.addEntry(encryptSha256(word), plaintext_file_name.replace('f', 'c'))
# Encrypt file and write to ciphertext folder
iv_hex, encrypted_hex = encryptAesCbc(plaintext, key_file_contents)
enc_file_content = f'{iv_hex}\n{encrypted_hex}'
full_cipher_path = os.path.join(
ciphertext_folder, plaintext_file_name.replace('f', 'c'))
file_io.write_file(full_cipher_path, enc_file_content)
print('Encrypted Index')
print(inverted_index)
# Write inverted index file to disk
file_io.write_file(index_file, inverted_index.serialize())
def token_generation(args: list):
expected = 2
if len(args) != expected:
print(f'Invalid number of arugments for function search, got {len(args)}, expected {expected}')
print('Arguments: token, output_file')
raise ValueError()
token = args[0]
output_file = args[1]
hashed = encryptSha256(token)
print(f'Input Token: {token}')
print(f'Output Hash: {hashed}')
file_io.write_file(output_file, hashed)
def search(args: list):
expected = 4
if len(args) != expected:
print(f'Invalid number of arugments for function search, got {len(args)}, expected {expected}')
print('Arguments: index_file, token_file, ciphertext_folder, key_file')
raise ValueError()
index_file = args[0] # Read the index from this file
token_file = args[1] # Read the token from this file
ciphertext_folder = args[2] # Read encrypted files from this directory
key_file = args[3] # Read decryption key from this file
index_file_contents = file_io.read_file(index_file)
token_file_contents = file_io.read_file(token_file)
key_file_contents = file_io.read_file(key_file)
# Create new InvertedIndex from disk contents
inverted_index = InvertedIndex(index_file_contents)
# Find file names under this token
file_names = inverted_index.search(token_file_contents)
print(f'Files matching token {token_file_contents}: {",".join(file_names)}')
# Decrypt each file and print its contents
for file_name in file_names:
full_ciphertext_path = os.path.join(ciphertext_folder, file_name)
full_ciphertext_contents = file_io.read_file(full_ciphertext_path)
iv_hex, ciphertext = full_ciphertext_contents.split('\n')
cleartext = decryptAesCbc(ciphertext, key_file_contents, iv_hex)
print(f'{file_name} decrypted contents: {cleartext}')
def main(args: list):
argument_functions = [
{
key: 'keygen',
func: keygen
},
{
key: 'enc',
func: encryption
},
{
key: 'token',
func: token_generation
},
{
key: 'search',
func: search
}
]
possible_args = ', '.join(map(lambda x: x[key], argument_functions))
try:
first_arg = args[1].lower()
thing: dict = next(
filter(lambda x: x[key] == first_arg, argument_functions)
)
except IndexError:
print(f'First argument missing, it should be one of the following: {possible_args}')
raise ValueError()
except StopIteration:
print(f'Invalid first argument, it should be one of the following: {possible_args}')
raise ValueError()
# Call the function with the rest of the arugments
thing[func](args[2:])
if __name__ == "__main__":
main(sys.argv)
|
c32a17834bf88ab5b88223314bd0b4bc7d5d8175 | SwetaNikki/Python-Assignment-4 | /AreaOfTriangle.py | 854 | 4.25 | 4 | """
1.1 Write a Python Program(with class concepts) to find the area of the triangle using the below
formula.
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
Function to take the length of the sides of triangle from user should be defined in the parent
class and function to calculate the area should be defined in subclass.
"""
import math
class TakingInput:
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
a = int(input("Enter a value : "))
b = int(input("Enter b value : "))
c = int(input("Enter c value : "))
class AreaOfTriangle(TakingInput):
def __init__(self,a,b,c):
super().__init__(a,b,c)
def area(self):
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
return area
ob = AreaOfTriangle(a,b,c)
print("Area of Triangle : {}".format(ob.area()))
|
f01da590d193712dc2125b7d926f1b5d36589090 | DipendraDLS/Python_Basic | /05. List/list_concatination_and_join.py | 826 | 4.53125 | 5 | #list concatination
# Example 1 : using + operator
list1 = [1, 2]
list2 = [3, 4]
list3 = list1 + list2
print(list3)
# Example 2: using append() method
list4 = [1, 3, 5, 7, 9]
list5 = [2, 4, 6, 8, 10]
for i in list5 :
list4.append(i)
print(list4)
# Example 4 : using extend() method
test_list3 = [1, 4, 5, 6, 5]
test_list4 = [3, 5, 7, 2, 5]
# using list.extend() to concat
test_list3.extend(test_list4)
print(test_list3)
# Example 5 : concatinating list value with delimiter
string_list = ['1', '2', '3', '4']
print(type(string_list))
string_delimiter = "."
print(type(string_delimiter))
a = string_delimiter.join(string_list)
print(type(a))
print(a)
# Example 6:
import numpy as np
nested_list_a = [[2, 4], [6, 8]]
nested_list_b = [[1, 3],[9, 0]]
c = np.concatenate((nested_list_a, nested_list_b))
print(c) |
5e0a4c463228bc6f78fb1c2f7eb420bb42044592 | cathuan/LeetCode-Questions | /python/q394.py | 1,008 | 3.6875 | 4 | class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
digit = ""
for w in s:
if w.isdigit():
digit += w
else:
if digit:
stack.append(digit)
digit = ""
stack.append(w)
if w == "]":
stack = self.expand(stack)
return "".join(stack)
def expand(self, stack):
assert stack.pop() == "]"
content = stack.pop()
contents = []
while content != "[":
contents.append(content)
content = stack.pop()
contents.reverse()
content = "".join(contents)
repeat = int(stack.pop())
fmt = "".join([content for _ in range(repeat)])
stack.append(fmt)
return stack
if __name__ == "__main__":
s = "3[a2[c]]"
print Solution().decodeString(s) |
0968853ba940209c5fbf6be5dad1f37a1e285ef6 | loveniuzi/Python- | /猜数字小组/记录你的成绩.py | 1,307 | 3.5625 | 4 | ##统计游戏数据:玩家姓名、总游戏次数(玩家每猜中答案算玩了一次游戏)、
##总游戏轮数(玩家每猜一个数字算玩了一轮游戏)、最快猜中轮数,
##并将结果保存在文件中(请大家本次任务都将数据写入 game_one_user.txt )
import random
# min_count表示最快猜中的轮数,times表示总游戏次数
min_count = 100
times = 0
playAgain = 'y'
while playAgain == 'y':
name = input("请输入你的姓名:")
secret = random.randint(1, 100)
count = 0
guess = 101 # count表示猜了几次猜对了
while secret != guess:
guess = int(input("请猜一个1到100之间的整数:"))
count = count + 1
if guess > secret:
print("你猜的数字大了")
elif guess < secret:
print("你猜的数字小了")
else:
print(f"恭喜你!猜对了数字是:{secret},你一共猜了{count}次。")
times = times + 1
if count < min_count:
min_count = count
playAgain = input("你是否还要继续游戏?(继续输入y)").lower()
file = open("game_one_user.txt", "w")
file.write(f"{name} {str(times)} {str(min_count)}")
file.close()
|
c1d4d6f0b5cc0515d2861c6bb5914f4d7ac87741 | skskdmsdl/python-study | /09. Exception/4. finally.py | 1,379 | 3.65625 | 4 | # finally
# 에러가 발생하든 하지 않든 무조건 실행되는 구문
class BigNumberError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
try:
print("한 자리 숫자 나누기 전용 계산기입니다.")
num1 = int(input("첫 번째 숫자를 입력하세요: "))
num2 = int(input("첫 번째 숫자를 입력하세요: "))
if num1 >= 10 or num2 >=10:
raise BigNumberError(f"입력값 : {num1}, {num2}")
print(f"{num1} / {num2} = {int(num1 / num2)}")
except ValueError:
print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")
except BigNumberError as err:
print("에러가 발생하였습니다. 한 자리 숫자만 입력하세요.")
print(err)
finally:
print("계산기를 이용해 주셔서 감사합니다.")
### 추가 공부 ###
# 예제1
try:
z = 'Kim' # 'Cho' 예외 발생
x = name.index(z)
print('{} Found it! {} in name'.format(z, x + 1))
except Exception as e:
print(e) # 에러 내용 출력
# pass # 임시로 에러 해결 시 예외 처리
else:
print('ok! else!')
finally:
print('ok! finally!') # 무조건 수행 됨
print()
# 예제2
# 예외처리는 하지 않지만, 무조건 수행 되는 코딩 패턴
try:
print('try')
finally:
print('finally')
print()
|
e342001801654cf432525f47a3886e9ce244a295 | TaRDiSpace/LeetCode | /1-50/39_Combination_Sum.py | 728 | 3.734375 | 4 | """
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
"""
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def rec(l, target, p, tmp):
if target == 0:
res.append(tmp)
return
for i in range(p, len(l)):
if target < l[i]:
return
else:
rec(l, target - l[i], i, tmp + [l[i]])
tmp = []
res = []
candidates.sort()
rec(candidates, target, 0, tmp)
return res
|
3f6e75283e364572554992762a79958112191cc9 | mhmmdk/being-software-engineer | /CrackingTheCodingInterview/1. Arrays and Strings/1.6 String Compression.py | 1,037 | 4.5 | 4 | # String Compression: Implement a method to perform basic string compression using the counts
# of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the
# "compressed" string would not become smaller than the original string, your method should return
# the original string. You can assume the string has only uppercase and lowercase letters (a - z).
def compress_string(input_str):
current_chr = input_str[0]
current_count = 1
result_str = []
for i in range(1, len(input_str)):
if current_chr == input_str[i]:
current_count += 1
else:
result_str.append(current_chr)
result_str.append(str(current_count))
current_chr = input_str[i]
current_count = 1
result_str.append(current_chr)
result_str.append(str(current_count))
if len(result_str) < len(input_str):
return result_str
return input_str
if __name__ == '__main__':
s1 = input().strip()
print(''.join(compress_string(s1)))
|
ef6a9ffc5272e94503aa2773b3c6225339685ec7 | meenuraghav/iNeuron | /iNeuron.py | 2,227 | 3.90625 | 4 | string="Hello"
num=upper=lower=0
for i in string:
if i.islower():lower+=1
elif i.isupper(): upper+=1
##########################################################################################
# Difference between list.append() and list.extend()
list1 = [1,2,"Prashanth",3,9+7j]
list2 = ["Hello",619]
print("Append : ")
list1.append(list2) # list within a list
print(list1)
## Will work only in jupyter (%%time) To find the time taken for a particular cell to execute
list1 = [1,2,"Prashanth",3,9+7j]
list2 = ["Hello",619]
print("Extend : ")
list1.extend(list2)
print(list1)
##########################################################################################
## for else condition
sum1=0
for i in list1:
if i==2:
break # will completely come out and will not go the else also
sum1+=i
else:
print("This sum is ",sum1)
sum1=0
for i in list1:
if i==2:
sum1+=i
else:
print("This sum is ",sum1) # Will get execute if the for is executed successfully
print("The final sum out of the loop : ",sum1)
##########################################################################################
list1 = [1,2,3,4,5,6,7]
sum_odd = sum_even = 0
for i in list1:
if i%2==0:
sum_even+=i
if sum_even>20:
break
else:
sum_odd+=i
if sum_odd>20:
break
else: # Will get execute if the for is executed successfully
print("Odd sum = {} and Even sum = {}".format(sum_odd,sum_even))
#########################################################################################
str1 = "Prashanth"
print(str1)
print(str1[:])
print("Reverse of a string : ",str1[::-1])
str1 = "This is , good "
str1.split() # Splits when there is a space
str1.split(';') # Splits what ever character is given
str1.split('s') # to ommit s
str1.partition('s') # to include s
str1 = "Prashanth"
str1.find('a') # Will get only the index of the first occurence
str1.center(20,'@') # Will make the string padded with (@5+9(len of the string)+6@)
str1.isalnum()
str1.isalpha()
str1 = "Pras/hanth"
print(str1.expandtabs())
#########################################################################################
|
b9f91893c487ef79b3840ee693165315210c5f8d | angel-sinn/python-basics | /python_logic/14.global_nonlocal.py | 360 | 3.828125 | 4 | # global keyword
total = 0
def count():
global total # declare we are using global total variable
total += 1
return total
count()
count()
print(count())
# nonlocal keyword
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner: ", x) # inner: nonlocal
inner()
print("outer: ", x) # outer: nonlocal
outer() |
9326e429799a5a592fb4fda591cc65c20e94fbe8 | DerDroog/Transactions_Database | /database.py | 6,609 | 3.875 | 4 | from tkinter import *
import tk_main
import sqlite3
# NEXT STEPS
# Load database entry - modify / delete
# Display current transaction id
root = Tk()
root.title('Transaction manager')
conn = sqlite3.connect("transactions.db")
c = conn.cursor()
c.execute("""SELECT * FROM transactions""")
a = c.fetchall()
print(a)
# Create Submit Function for Database
def submit():
# Create a database or connect to one
conn = sqlite3.connect('transactions.db')
# Create Cursor
c = conn.cursor()
c.execute(
"""INSERT INTO transactions (date, val_num, voucher, qty, price, currency, rate)
VALUES (:date, :val_num, :voucher, :qty, :price, :currency, :rate)""",
{
'date': date.get(),
'val_num': val_num.get(),
'voucher': voucher.get(),
'qty': qty.get(),
'price': price.get(),
'currency': currency.get(),
'rate': rate.get()
})
# Commit Changes
conn.commit()
# Close Database
conn.close()
# Clear the Text Boxes
date.delete(0, END)
voucher.delete(0, END)
val_num.delete(0, END)
qty.delete(0, END)
price.delete(0, END)
currency.delete(0, END)
rate.delete(0, END)
# Create Query Function
def query():
global query
query = Tk()
query.title('Abfrage ausführen')
query.geometry('500x500')
voucher_num_label = Label(query, text='Beleg-Nr.')
voucher_num_label.grid(row=0, column=0)
global voucher_num
voucher_num = Entry(query, width=20)
voucher_num.grid(row=0, column=1)
query_voucher = Button(query, text="Beleg anzeigen", command=show_voucher)
query_voucher.grid(row=1, column=0)
modify_voucher = Button(query, text="Beleg bearbeiten", command=modify)
modify_voucher.grid(row=1, column=1)
# conn = sqlite3.connect('transactions.db')
# c = conn.cursor()
# c.execute("SELECT * FROM transactions")
# records = c.fetchall()
# print(records)
query.mainloop()
return
def show_voucher():
conn = sqlite3.connect('transactions.db')
conn.row_factory = sqlite3.Row
c = conn.cursor()
voucherqry = voucher_num.get()
c.execute("SELECT * FROM transactions WHERE voucher = ? ", (voucherqry,))
result = c.fetchall()
memb_total = 0
for member in result: # Loop through Row Object
for key in member: # Loop through Dictionary
column_descr = Label(query, text=str(member.keys()[memb_total]))
column_descr.grid(column=memb_total, row=3)
memb_total += 1
output_total = 0
for j in range(0, len(result)):
for i in result[j]:
results_label = Label(query, text=str(i))
results_label.grid(column=output_total, row=4)
output_total += 1
print(dict(result[j]), i, "\n")
return
# Function to modify current voucher
def modify():
modify = Tk()
modify.title("Beleg bearbeiten")
modify.geometry('500x200')
conn = sqlite3.connect("transactions.db")
# c = conn.cursor()
# c.execute("""UPDATE transactions
# Set
# date = :date
# val_num = :val_num
# voucher = :voucher
# qty = :qty
# price = :price
# currency = :currency
# rate = :rate)
# WHERE
# voucher = :voucher_num
# """,
# {
# 'date': date.get(),
# 'val_num': val_num.get(),
# 'voucher': voucher.get(),
# 'qty': qty.get(),
# 'price': price.get(),
# 'currency': currency.get(),
# 'rate': rate.get(),
# 'voucher_num': voucher_num.get()
# })
modify.mainloop()
conn.close()
# Introduction Label
title_label = Label(root, text="Database transactions", font='Arial 14 bold')
title_label.grid(row=0, column=0, padx=20, ipady=10, columnspan=2)
# Create Text Entry Boxes
textbox_row = 4
date = Entry(root, width=15)
date.grid(row=2, column=1, padx=20, sticky=S)
voucher = Entry(root, width=15)
voucher.grid(row=2, column=2, padx=20, sticky=S)
val_num = Entry(root, width=15)
val_num.grid(row=textbox_row, column=0, padx=20, sticky=W)
qty = Entry(root, width=15)
qty.grid(row=textbox_row, column=1, padx=20)
price = Entry(root, width=15)
price.grid(row=textbox_row, column=2, padx=20)
currency = Entry(root, width=15)
currency.grid(row=textbox_row, column=3, padx=20)
rate = Entry(root, width=20)
rate.grid(row=textbox_row, column=4, padx=20)
# Create Text Box Labels
labels_row = 3
transactionid_label = Label(root, text="Transaktions ID:")
transactionid_label.grid(row=1, column=0, padx=20, sticky=NW)
number = StringVar()
conn = sqlite3.connect("transactions.db")
c = conn.cursor()
c.execute("""SELECT Max(transactionid) FROM transactions""")
max_trans_id = c.fetchone()
number.set(max_trans_id)
transactionid = Label(root, textvar=number)
transactionid.grid(row=2, column=0, padx=20, sticky=SW)
date_label = Label(root, text="Transaktionsdatum")
date_label.grid(row=1, column=1, padx=20, sticky=NW)
voucher_label = Label(root, text="Beleg")
voucher_label.grid(row=1, column=2, padx=20, sticky=NW)
val_num_label = Label(root, text="Valorennummer")
val_num_label.grid(row=labels_row, column=0, padx=20, sticky=W)
qty_label = Label(root, text="Anzahl")
qty_label.grid(row=labels_row, column=1, padx=20, sticky=W)
price_label = Label(root, text="Preis")
price_label.grid(row=labels_row, column=2, padx=20, sticky=W)
currency_label = Label(root, text="Währung")
currency_label.grid(row=labels_row, column=3, padx=20, sticky=W)
rate_label = Label(root, text="FW-Kurs")
rate_label.grid(row=labels_row, column=4, padx=20, sticky=W)
# Create Submit Button
submit_btn = Button(root, text="Add Record to Database", command=submit)
submit_btn.grid(row=6, column=0, columnspan=5, pady=10, padx=10, ipadx=100)
# Create a Query Button
query_btn = Button(root, text="Abfrage", command=query)
query_btn.grid(row=0, column=4)
root.mainloop()
# conn = sqlite3.connect('transactions.db')
# Create Cursor
# c = conn.cursor()
# c.execute("""
# CREATE TABLE transactions (
# transactionid INTEGER PRIMARY KEY AUTOINCREMENT,
# date text NOT NULL,
# voucher integer NOT NULL UNIQUE,
# val_num integer NOT NULL,
# qty real NOT NULL,
# price real NOT NULL,
# currency text,
# rate real )""")
|
8d92f5f785d08899dbe21bf3718a64a966f24217 | arorabj/UdacityData_Wrangling | /SparkPractice/src/main/python/SparkOptimization.py | 2,177 | 3.875 | 4 | # Use Cases in Business Datasets
# Skewed datasets are common. In fact, you are bound to encounter skewed data on a regular basis.
# In the video above, the instructor describes a year-long worth of retail business’ data.
# As one might expect, retail business is likely to surge during Thanksgiving and Christmas, while the rest of the year would be pretty flat.
# Skewed data indicators: If we were to look at that data, partitioned by month, we would have a large volume during November and December.
# We would like to process this dataset through Spark using different partitions, if possible. What are some ways to solve skewness?
# 1. Data preprocess
# 2. Broadcast joins
# 3. Salting
# 1. Use Alternate Columns that are more normally distributed:
# E.g., Instead of the year column, we can use Issue_Date column that isn’t skewed.
# 2. Make Composite Keys:
# For e.g., you can make composite keys by combining two columns so that the new column can be used as a composite key. For e.g, combining the Issue_Date and State columns to make a new composite key titled Issue_Date + State. The new column will now include data from 2 columns, e.g., 2017-04-15-NY. This column can be used to partition the data, create more normally distributed datasets (e.g., distribution of parking violations on 2017-04-15 would now be more spread out across states, and this can now help address skewness in the data.
# 3. Partition by number of Spark workers:
# Another easy way is using the Spark workers.
# If you know the number of your workers for Spark,
# then you can easily partition the data by the number of workers df.repartition(number_of_workers) to repartition your data evenly across your workers.
# For example, if you have 8 workers, then you should do df.repartition(8) before doing any operations.
import pandas as pd
from pyspark.sql import SparkSession
path = "/Users/anantarora/Downloads/DataSets/Amazon/parking_violation.csv"
data = pd.read_csv(path)
print (data.columns)
print (data.year.value_counts())
spark=SparkSession.builder.appName("Practice1").getOrCreate()
data = spark.read.csv(path)
# below will repartition the data
data.repartition(6)
|
c29b415f2afe9def687b5dca2d5eda8a7b95e696 | qianyuqianxun36963/a-Code_online | /code/2-python/git-online/1-python_base/src/5-函数/3-函数参数类型.py | 2,902 | 3.734375 | 4 | #coding=gbk
#
#
#******************************************************************
'''
ȷ˳뺯ʱʱһ
printme()봫һȻ
'''
def printme( str ):
"ӡκδַ"
print (str);
return;
#printme
printme('this is required');
#printme()
# Ĭϲֵ
#******************************************************************
'''
õʽָһĬֵַĺʱԴбȶҪٵIJ
'''
def defaultpara(para1,para2=' love',para3=' you'):
print(para1+para2+para3)
defaultpara('I')
defaultpara('I',' like',' her')
defaultpara('I',' want')
'''
Ĭֵڶʱִкʱ㣬ˣ
'''
i = 5
def f(arg=i): #ĬֵҲɱ
# def f(arg=5): #ʵһ൱ˡ
print(arg)
i = 6
f()
f(6)
'''
ĬֵֻһΡĬֵбֵʵױĶʱͬ
磬ĺںùлۻIJ
'''
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
'''
㲻Ĭֵĵйд
'''
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
#ؼֲ
#******************************************************************
'''
ؼֲ
ؼֲͺùϵܣʹùؼֲȷIJֵ
ʹùؼֲʱ˳ʱһ£Ϊ Python ܹòƥֵ
ʵں printme() ʱʹò
'''
def printinfo( name, age ):
"ӡκδַ"
print ("name: ", name);
print ("age: ", age);
return;
#printinfo
printinfo( age=50, name="runoob" );
#
#******************************************************************
'''
ҪһܴȵʱIJЩ2ֲͬʱ
Ǻţ*ıδıںʱûָһԪ顣ҲԲδı:
'''
def printinfo( arg1, *vartuple ):
"ӡκδIJ"
print (": ")
print (arg1)
for var in vartuple:
print (var)
return;
# printinfo
printinfo( 10 );
printinfo( 70, 60, 50 );
|
69129a3f2b97cec491443175fbb7d7ef72089c56 | alexchonglian/pyalgo | /03-par2.py | 346 | 3.6875 | 4 | def match(pars):
s = []
d = {'(':')','[':']','{':'}'}
for i in pars:
if i in '([{':
s.append(i)
elif i in '}])':
if s == []:
return False
if d[s.pop()]!= i:
return False
return s == []
print(match('{{([][])}()}'))
print(match('[{()]'))
print(match('{{([][])}()}'))
print(match('[[{{(())}}]]'))
print(match('[][][](){}')) |
8c342917a4ab608fadb48819fd80346d5f45d2c0 | aburmd/leetcode | /Regular_Practice/easy/18_21_Merge_Two_Sorted_Lists.py | 1,207 | 4.0625 | 4 |
"""
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self,L1,L2):
if not L1:
return L2
elif not L2:
return L1
else:
if L1.val > L2.val:
L2.next=self.mergeTwoLists(L2.next,L1)
return L2
else:
L1.next=self.mergeTwoLists(L1.next,L2)
return L1
"""
Second Commit: Nothing much different than previous.But, looks cleaner and easy to read
Runtime: 32 ms, faster than 80.81% of Python3 online submissions for Merge Two Sorted Lists.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Merge Two Sorted Lists.
First Commit:
Runtime: 28 ms, faster than 97.91% of Python3 online submissions for Merge Two Sorted Lists.
Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Merge Two Sorted Lists.
"""
|
dbdbb094439ab068c845cf45418bb11593148c7d | al-okdev/oop | /main.py | 6,126 | 3.609375 | 4 | class Student:
def __init__(self, name, surname, gender):
self.name = name
self.surname = surname
self.gender = gender
self.finished_courses = []
self.courses_in_progress = []
self.grades = {}
def grade_item_student(self):
ocenka = map(sum, list(self.grades.values()))
ocenka = list(ocenka)
count_ocenka = map(len, list(self.grades.values()))
count_ocenka = list(count_ocenka)
result_ocenka = sum(ocenka) / sum(count_ocenka)
return result_ocenka
def __str__(self):
return 'Имя: ' + self.name + '\nФамилия: ' + self.surname + '\nСредняя оценка за домашние задания: ' + str(self.grade_item_student()) + '\nКурсы в процессе изучения: '+str(", ".join(self.courses_in_progress))+'\nЗавершенные курсы: '+str(", ".join(self.finished_courses))
def __lt__(self, other):
if not isinstance(other, Student):
print('Not a Student!')
return
return self.grade_item_student() < other.grade_item_student()
def rate_hw_lecturer(self, course, lecturer, grade):
if isinstance(lecturer, Lecturer) and course in lecturer.courses_attached:
if course in lecturer.grades_for_lectures:
lecturer.grades_for_lectures[course] += [grade]
else:
lecturer.grades_for_lectures[course] = [grade]
else:
return 'Ошибка'
class Mentor:
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.courses_attached = []
class Lecturer(Mentor):
def __init__(self, name, power):
super().__init__(name, power)
self.grades_for_lectures = {}
def grade_item_lecturer(self):
ocenka = map(sum, list(self.grades_for_lectures.values()))
ocenka = list(ocenka)
count_ocenka = map(len, list(self.grades_for_lectures.values()))
count_ocenka = list(count_ocenka)
result_ocenka = sum(ocenka) / sum(count_ocenka)
return result_ocenka
def __lt__(self, other):
if not isinstance(other, Lecturer):
print('Not a Lecturer!')
return
return self.grade_item_lecturer() < other.grade_item_lecturer()
def __str__(self):
return 'Имя: ' + self.name + '\nФамилия: ' + self.surname + '\nСредняя оценка за лекции: ' + str(self.grade_item_lecturer())
class Reviewer(Mentor):
def rate_hw(self, student, course, grade):
if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:
if course in student.grades:
student.grades[course] += [grade]
else:
student.grades[course] = [grade]
else:
return 'Ошибка'
def __str__(self):
return 'Имя: ' + self.name + '\nФамилия: ' + self.surname
def sum_grade_student (student_list, name_kurs):
# Cредняя оценка за домашние задания по всем студентам
result_list = []
for student_item in student_list:
if name_kurs in student_item.grades:
result_list.append(sum(student_item.grades[name_kurs])/len(student_item.grades[name_kurs]))
if result_list:
result = sum(result_list)/len(student_list)
else:
result = 'Указанного курса нет в программе'
return result
def sum_grade_lecturer (lecturer_list, name_kurs):
# Средняя оценка за лекции всех лекторов
result_list = []
for lecturer_item in lecturer_list:
if name_kurs in lecturer_item.grades_for_lectures:
result_list.append(sum(lecturer_item.grades_for_lectures[name_kurs])/len(lecturer_item.grades_for_lectures[name_kurs]))
if result_list:
result = sum(result_list)/len(student_list)
else:
result = 'Указанного курса нет в программе'
return result
student1 = Student('Ruoy', 'Eman', 'your_gender')
student1.courses_in_progress += ['Python']
student1.courses_in_progress += ['C++']
student1.finished_courses += ['HTML']
student2 = Student('Ruoy2', 'Eman2', 'your_gender2')
student2.courses_in_progress += ['Python']
student2.courses_in_progress += ['C++']
mentor = Mentor('Some', 'Buddy')
mentor.courses_attached += ['Python']
# Reviewer ставит оценки студентам
reviewer = Reviewer('Ivan', 'Popov')
reviewer.courses_attached += ['Python']
reviewer.courses_attached += ['C++']
reviewer.rate_hw(student1, 'Python', 8)
reviewer.rate_hw(student1, 'Python', 8)
reviewer.rate_hw(student1, 'Python', 8)
reviewer.rate_hw(student1, 'C++', 10)
reviewer.rate_hw(student1, 'C++', 10)
reviewer.rate_hw(student1, 'C++', 10)
reviewer.rate_hw(student2, 'C++', 6)
reviewer.rate_hw(student2, 'C++', 6)
reviewer.rate_hw(student2, 'C++', 6)
lecturer1 = Lecturer('Elena', 'Nikolaeva')
lecturer1.courses_attached += ['Python']
lecturer1.courses_attached += ['C++']
student1.rate_hw_lecturer('Python', lecturer1, 8)
student1.rate_hw_lecturer('Python', lecturer1, 8)
student1.rate_hw_lecturer('C++', lecturer1, 8)
student1.rate_hw_lecturer('C++', lecturer1, 8)
lecturer2 = Lecturer('Viktor', 'Evdeev')
lecturer2.courses_attached += ['Python']
lecturer2.courses_attached += ['C++']
student1.rate_hw_lecturer('C++', lecturer2, 10)
student1.rate_hw_lecturer('C++', lecturer2, 10)
# №3
print(student1)
print()
print(student2)
print()
print(student1 > student2)
print('\n')
print(lecturer1)
print()
print(lecturer2)
print()
print(lecturer1 > lecturer2)
# №4
print('\n')
student_list = [student1, student2]
print(f"Cредняя оценка за домашние задания по всем студентам: {sum_grade_student(student_list, 'C++')}")
lecturer_list = [lecturer1, lecturer2]
print(f"Средняя оценка за лекции всех лекторов: {sum_grade_lecturer(lecturer_list, 'C++')}") |
15a925618fab77bb279a7bef349e631f8ecfac04 | vietanhtran2710/projectEuler | /highlyDivisibleTriangularNumber.py | 588 | 3.84375 | 4 | from math import sqrt
from collections import Counter
def isPrime(value):
for i in range(2, int(sqrt(value))):
if value % i == 0:
return False
return True
def getPrimeFactorList(value):
result = []
prime = 2
while (value != 1):
while not isPrime(prime) or value % prime != 0:
prime += 1
result.append(prime)
value //= prime
return result
num = 1
value = 2
while True:
num += value
value += 1
lst = getPrimeFactorList(num)
dct = Counter(lst)
factorCount = 1
for val in dct.values():
factorCount *= (val + 1)
if factorCount + 1 >= 500:
print(num)
break
|
6b20808c85e761e10844e86968d45d91a5e1119c | idest/andestm_standalone | /meccolormap.py | 1,861 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib as mpl
def make_colormap(seq):
"""Return a LinearSegmentedColormap
seq: a sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
"""
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
cdict = {'red': [], 'green': [], 'blue': []}
for i, item in enumerate(seq):
if isinstance(item, float):
r1, g1, b1 = seq[i - 1]
r2, g2, b2 = seq[i + 1]
cdict['red'].append([item, r1, r2])
cdict['green'].append([item, g1, g2])
cdict['blue'].append([item, b1, b2])
return mcolors.LinearSegmentedColormap('CustomMap', cdict)
c = mcolors.ColorConverter().to_rgb
jet_white = make_colormap(
[c('darkblue'), c('cyan'), 0.33, c('cyan'), c('orange'), 0.66, c('orange'), c('red'), 0.85, c('red'), c('white')])
def reverse_colourmap(cmap, name = 'my_cmap_r'):
"""
In:
cmap, name
Out:
my_cmap_r
Explanation:
t[0] goes from 0 to 1
row i: x y0 y1 -> t[0] t[1] t[2]
/
/
row i+1: x y0 y1 -> t[n] t[1] t[2]
so the inverse should do the same:
row i+1: x y1 y0 -> 1-t[0] t[2] t[1]
/
/
row i: x y1 y0 -> 1-t[n] t[2] t[1]
"""
reverse = []
k = []
for key in cmap._segmentdata:
k.append(key)
channel = cmap._segmentdata[key]
data = []
for t in channel:
data.append((1-t[0],t[2],t[1]))
reverse.append(sorted(data))
LinearL = dict(zip(k,reverse))
my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
return my_cmap_r
jet_white_r = reverse_colourmap(jet_white)
|
8ee477c100aa420e75e6f999a9ea3f82e942174e | airbusgeo/playground-to-up42 | /up42/utils.py | 716 | 3.953125 | 4 | def create_directory(directory, parents=False, exist_ok=False):
"""Create the output directory if it is not already existing.
Arguments:
directory {pathlib.Path} -- A path to the output directory for the generated files.
parents {bool} -- If parents is true, any missing parents of this path are created as needed;
If parents is false (the default), a missing parent raises FileNotFoundError.
exist_ok {bool} -- If exist_ok is false, FileExistsError is raised if the target directory already exists.
If exist_ok is true, FileExistsError exceptions will be ignored.
"""
directory.mkdir(parents=parents, exist_ok=exist_ok)
|
d57d977cda2f3761736aca3c3d42a95447673e0c | woonji913/til | /코테대비/20190227/돼지.py | 702 | 3.515625 | 4 | def pig(data):
find = []
for i in range(len(data)):
if data[i][1] == 'Y':
find.append(1)
else:
find.append(0)
for k in range(len(find) - 1):
if find.count(1) == 1:
if find[-1] == 1:
return data[-1][0]
else:
return 'F'
elif find.count(1) == 0:
return 'F'
else:
if find[k] == 1 and find[k + 1] == 0:
return 'F'
elif find[k] == 1 and find[k + 1] == 1:
return data[k][0]
N = int(input())
data = [tuple(input().split()) for _ in range(N)]
data.sort()
if N == 0:
print('F')
else:
print(pig(data)) |
c287f09119088e5ba59f1ae5d257f351e0eaec09 | satanas/leetcode | /easy/missing-number.py | 603 | 3.890625 | 4 | # Approach
# Sort the array and iterate it comparing the value of the num against its index
# If they're different, then the missing number is the index.
class Solution:
def missingNumber(self, nums):
sorted_nums = sorted(nums)
# [0, 1] => [0, 1, 2]
for i in range(len(sorted_nums)):
if i != sorted_nums[i]:
return i
return len(sorted_nums)
if __name__ == "__main__":
s = Solution()
print(s.missingNumber([3,0,1]))
print(s.missingNumber([0,1]))
print(s.missingNumber([9,6,4,2,3,5,7,0,1]))
print(s.missingNumber([0])) |
ca1fb675671b2776828c7c749a0501a348f09307 | ColdGrub1384/Pyto | /Pyto/Samples/Matplotlib/ellipse_demo.py | 1,728 | 3.921875 | 4 | """
============
Ellipse Demo
============
Draw many ellipses. Here individual ellipses are drawn. Compare this
to the :doc:`Ellipse collection example
</gallery/shapes_and_collections/ellipse_collection>`.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
NUM = 250
ells = [Ellipse(xy=np.random.rand(2) * 10,
width=np.random.rand(), height=np.random.rand(),
angle=np.random.rand() * 360)
for i in range(NUM)]
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(np.random.rand())
e.set_facecolor(np.random.rand(3))
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.show()
#############################################################################
# ===============
# Ellipse Rotated
# ===============
#
# Draw many ellipses with different angles.
#
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
delta = 45.0 # degrees
angles = np.arange(0, 360 + delta, delta)
ells = [Ellipse((1, 1), 4, 2, a) for a in angles]
a = plt.subplot(111, aspect='equal')
for e in ells:
e.set_clip_box(a.bbox)
e.set_alpha(0.1)
a.add_artist(e)
plt.xlim(-2, 4)
plt.ylim(-1, 3)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.patches
matplotlib.patches.Ellipse
matplotlib.axes.Axes.add_artist
matplotlib.artist.Artist.set_clip_box
matplotlib.artist.Artist.set_alpha
matplotlib.patches.Patch.set_facecolor
|
d6a972b2432754e4c7c178fa888ed288f501ebc5 | gustavomarquezinho/python | /study/python-brasil/exercises/sequential-structure/sequential-structure - 008.py | 271 | 3.515625 | 4 | # 008 - Faça um programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
print(f'Salário: R${float(input("Ganhos por hora: R$")) * float(input("Horas trabalhadas: ")) :.2f}') |
0cfafca8322822b5b09688dc051a1b89e88f62fb | fabzer0/codeReview-Andela | /pig_latin_converter_1/test_pig_latin.py | 1,079 | 3.71875 | 4 | import unittest
from main import pig_latin_converter
class Test(unittest.TestCase):
def test_input_as_string(self):
with self.assertRaises(TypeError) as context:
pig_latin_converter(1)
pig_latin_converter(False)
self.assertEqual(
'Argument should be a string',
context.exception.message,
'String inputs allowed only'
)
def test_correct_output_if_vowel_at_first_pos(self):
result1 = pig_latin_converter('andela')
result2 = pig_latin_converter('ipsum')
self.assertEqual(result1, 'andelaway')
self.assertEqual(result2, 'ipsumway')
def test_correct_output_if_first_pos_not_vowel(self):
result1 = pig_latin_converter('dryer')
result2 = pig_latin_converter('chemistry')
result3 = pig_latin_converter('verge')
self.assertEqual(result1, 'erdryay')
self.assertEqual(result2, 'emistrychay')
self.assertEqual(result3, 'ergevay')
if __name__ == '__main__':
unittest.main()
|
cb55fac49f8c3cad5d6454af07ef385c27e80792 | BingoJYB/Data-Structure-and-Algorithm | /108.convert-sorted-array-to-binary-search-tree.py | 1,758 | 3.84375 | 4 | #
# @lc app=leetcode id=108 lang=python3
#
# [108] Convert Sorted Array to Binary Search Tree
#
# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
#
# algorithms
# Easy (68.49%)
# Likes: 8160
# Dislikes: 411
# Total Accepted: 868.9K
# Total Submissions: 1.3M
# Testcase Example: '[-10,-3,0,5,9]'
#
# Given an integer array nums where the elements are sorted in ascending order,
# convert it to a height-balanced binary search tree.
#
# A height-balanced binary tree is a binary tree in which the depth of the two
# subtrees of every node never differs by more than one.
#
#
# Example 1:
#
#
# Input: nums = [-10,-3,0,5,9]
# Output: [0,-3,9,-10,null,5]
# Explanation: [0,-10,5,null,-3,null,9] is also accepted:
#
#
#
# Example 2:
#
#
# Input: nums = [1,3]
# Output: [3,1]
# Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 10^4
# -10^4 <= nums[i] <= 10^4
# nums is sorted in a strictly increasing order.
#
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
root = TreeNode()
self.buildBST(0, len(nums)-1, nums, root)
return root
def buildBST(self, lo, hi, nums, node):
if lo > hi:
return None
mid = (lo + hi) // 2
node.val = nums[mid]
node.left = self.buildBST(lo, mid-1, nums, TreeNode())
node.right = self.buildBST(mid+1, hi, nums, TreeNode())
return node
# @lc code=end
|
bd2e193f605c3928a9599383e76f82d803c21783 | dragonesse/aoc | /day09.py | 2,928 | 3.734375 | 4 | import sys
import utils.inputReaders as ir
import utils.locationHelpers as lh
print("Day 9: Rope Bridge")
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#read file
motion_head = ir.read_oneline_records_as_list_entries(puzzle_file)
def is_adjacent(tail_pos,head_pos):
adj = False
distance = lh.get_manhattan_dist(tail_pos,head_pos)
if tail_pos[0] == head_pos[0] or tail_pos[1]==head_pos[1]:
if distance <=1:
adj =True
elif distance == 2:
adj = True
return adj
def move_tail(from_pos,head_pos):
new_pos = [from_pos[0],from_pos[1]]
vect_x = head_pos[0] - from_pos [0]
vect_y = head_pos[1] - from_pos [1]
if not is_adjacent (from_pos, head_pos ):
# the same row
if vect_y == 0:
new_pos[0] = from_pos [0] + int(vect_x/2)
# the same col
elif vect_x == 0:
new_pos[1] = from_pos [1] + int(vect_y/2)
# diagonal
elif abs(vect_x) > abs(vect_y):
new_pos [0] = from_pos [0] + int(vect_x/2)
new_pos [1] = from_pos [1] + vect_y
elif abs(vect_x) < abs(vect_y):
new_pos [0] = from_pos [0] + vect_x
new_pos [1] = from_pos [1] + int(vect_y/2)
else:
new_pos [0] = from_pos [0] + int(vect_x/2)
new_pos [1] = from_pos [1] + int(vect_y/2)
return new_pos
def move_head(from_pos,direction):
new_pos = [from_pos[0],from_pos[1]]
if direction == "L":
new_pos[0] = from_pos[0]-1
elif direction == "R":
new_pos[0] = from_pos[0]+1
elif direction == "U":
new_pos[1] = from_pos[1]+1
elif direction == "D":
new_pos[1] = from_pos[1]-1
return new_pos
tail_spots = [[0,0]]
head_pos = [0,0]
tail_pos = [0,0]
for move in motion_head:
direction, dist = move.split(' ')
dist = int(dist)
for step in range(dist):
head_pos = move_head (head_pos, direction )
tail_pos = move_tail (tail_pos, head_pos)
if tail_pos not in tail_spots:
tail_spots.append(tail_pos)
print ("Part 1: number of positions the tail visited: {}".format(len(tail_spots)))
tail_spots = [[0,0]]
head_pos = [0,0]
num_tails = 9
tail_pos = []
for i in range(num_tails):
tail_pos.append([0,0])
for move in motion_head:
direction, dist = move.split(' ')
dist = int(dist)
for step in range(dist):
head_pos = move_head (head_pos, direction )
tail_pos[0] = move_tail (tail_pos[0], head_pos)
for t in range(1,num_tails):
tt = [tail_pos[t][0],tail_pos[t][1]]
tail_pos[t] = move_tail (tail_pos[t], tail_pos[t-1])
if tail_pos[8] not in tail_spots:
tail_spots.append(tail_pos[8])
print ("Part 2: number of positions the tail visited: {}".format(len(tail_spots)))
|
7fa3de90559fc91ec2019dc80cef1383d3887858 | Jakksan/pythonDrawingANeighborhood | /diagram_neighborhood.py | 3,628 | 4.03125 | 4 | from turtle import *
import math
import time
setup(1000,1000)
goto(0,0)
penup()
def drawTriangle(x, y, tri_base, tri_height, color):
# Calculate all the measurements and angles needed to draw the triangle
side_length = math.sqrt((0.5*tri_base)**2 + tri_height**2)
base_angle = math.degrees(math.atan(tri_height/(tri_base/2)))
top_angle = 180 - (2 * base_angle)
# Draw the triangle using the calculations from above
penup()
goto(x, y)
pendown()
setheading(0)
fillcolor(color)
begin_fill()
forward(tri_base)
left(180 - base_angle)
forward(side_length)
left(180 - top_angle)
forward(side_length)
end_fill()
penup()
def drawRectangle(x, y, rec_width, rect_height, color):
penup()
goto(x, y)
pendown()
setheading(0)
fillcolor(color)
begin_fill()
for each in range(2):
forward(rec_width)
left(90)
forward(rect_height)
left(90)
end_fill()
penup()
def drawCircle(x, y, radius, color):
penup()
setheading(0)
setpos(x, (y-radius))
pendown()
fillcolor(color)
begin_fill()
circle(radius)
end_fill()
penup()
def drawTree(x, y, tree_height, color):
drawRectangle((x-(tree_height * 0.1)), y, (tree_height * 0.2), tree_height * 0.5, "sandy brown")
drawCircle(x, (y + (tree_height * 0.75)), (tree_height * 0.25), color)
def drawHouse(x, y, house_width, house_height, primary_color, secondary_color):
# Define some variables that will be useful for house construction
roof_height = house_height * 0.2
building_height = house_height * 0.8
# Draw building
drawRectangle(x, y, house_width, building_height, primary_color)
# create variables needed for drawing the door
door_width = house_width / 8
door_height = house_height / 4
# Draw door
door_x = x+(house_width * 0.75)
door_y = y
drawRectangle(door_x, door_y, door_width, door_height, "brown")
drawCircle(door_x + door_width*3/4, door_y + door_height/2, 3, "gold")
# Draw roof
overhang = 20
drawTriangle(x-(overhang / 2), (y + building_height), (house_width + overhang), roof_height, secondary_color)
# Draw window
window_size = building_height / 2
window_x = (x+(house_width * 0.2))
window_y = y + (building_height / 3)
drawRectangle(window_x, window_y, window_size, window_size/2, "light blue")
# Draw the window sections
goto(window_x + window_size/2, window_y)
pendown()
goto(window_x + window_size/2, window_y + window_size/2)
penup()
goto(window_x, window_y + window_size/4)
pendown()
goto(window_x + window_size, window_y + window_size/4)
penup()
def drawPumpkin(x, y, radius):
drawRectangle(x, y+radius-3, radius/4, radius/2, "orange")
begin_fill()
fillcolor("white")
drawCircle(x, y, radius)
end_fill()
def drawTownSign(x, y, text):
letters = len(list(text))
sign_width = (letters*10)+10
# Draw the rectangular feet of the sign
drawRectangle((x+sign_width/2-5), y, 10, 75, "brown")
drawRectangle((x-sign_width/2-5), y, 10, 75, "brown")
if letters < 10:
sign_width = 120
drawRectangle(x-(0.5*sign_width), y+15, sign_width, 60, "light grey")
setpos(x, y+50)
write("Welcome to", align="center", font=("Monaco", 12, "normal"))
setpos(x, y+20)
write(text, align="center", font=("Monaco", 12, "normal"))
drawRectangle(-300, 250, 40, 80, "light grey")
drawTriangle(-250, 250, 40, 40, "light blue")
drawCircle(-180, 270, 20, "pink")
drawTree(-150, 230, 70, "green")
input()
|
1def8f6c5acfd244387977d8bc2b077038f405bd | gdamira97/python | /python/hash.py | 180 | 3.609375 | 4 | import hashlib
def hash():
'''a=input('Enter text')
b=md5.new()
b.update(a)
print(b)'''
print (hashlib.md5("whatever your string is").hexdigest())
hash()
|
44be33f3844430ac3cc03cefc16eb52daf2b0b2c | alifa-ara-heya/My-Journey-With-Python | /day_06/again_string.py | 2,468 | 4.4375 | 4 | #Day_6: August/02/2020
#In the name 0f Allah..
#Me: Alifa Ara Heya
#Topic: index, isupper function, file and replace function
course = 'python for beginners by Mosh and Asabeneh'
print(course[0])
name = "Alifa ara Heya"
#index
print(name[0]) #output: A (0 is the index here)
print(name[1]) #output: l
print(name[2]) #output: i
print(name[3]) #output: f
print(name[4]) #output: a
print()
print(name[-1]) #output: a, (-1 index starts counting from last.)
print(name[-2]) #output: y
print(name[-3]) #output: e
print(name[-4]) #output: H
print(name[-5]) #output: 'space'
print(name[-6]) #output: a
sentence = "You are beautiful."
#0123456789
print(sentence[0 : 3]) #output: You
print(sentence[0 : ]) #output: You are beautiful. (the default end index is 0)
print(sentence[4 : 7]) #output: are
print(sentence[8 : ]) #output: beautiful.
print(sentence[0 : 7]) #output: You are
print(sentence[: 7]) #output: You are (the default start index is 0)
another_sentence = sentence
print(another_sentence) #output: You are beautiful.
another_sentence = sentence[:]
print(another_sentence) #output: You are beautiful.
#find and replace:
print(sentence.find("beautiful")) #output: 8
print(sentence.replace("beautiful", "absolutely beautiful")) #output: You are absolutely beautiful.
#"in" is a Python membership operator.
print('beautiful' in sentence) #output: True (in is an operator which produces Boolean value)
print('ugly' in sentence) #output: False
name = "Jennifer"
#01234567
print(name[0 : 1]) #output : J
print(name[0 : -1]) #output: Jennife
print(name[1 : -1]) #output: ennife
print(name[-1]) #output: r
print(name[1]) #output: e
print()
print(name.find('e')) #output: 1
print(name.find('E')) #output: -1 .find method is case sensitive.
print(name.find('J')) #output: 0 because, the index no of J is 0 here.
print(name.find('f')) #output: 5
#.isupper method:
print(name.isupper()) #False
name = name.upper()
print(name) #JENNIFER
print(name.isupper()) #True
print(len(name)) #8
#.index method to find the index number:
print(name.index("J")) #index num: 0
print(name.index("E")) #index num: 1
print(sentence.index("beautiful")) #index num: 8 |
7f117b598304ca25de87cdbd4a13e796344125de | SmileAK-47/pystuday | /rangPythonZiDongHua/ZiDian5/5.1.py | 722 | 3.5625 | 4 | '''
#keys()、values()和 items()方法
spam = {'color': 'red', 'age': 42}
for v in spam.values():
print(v)
for k in spam.keys():
print(k)
for i in spam.items():
print(i)
#5.1.3 检查字典中是否存在键或值
# in
#not in
#5.1.4 get()方法
picnicItems = {'apples': 5, 'cups': 2}
print('i am bringing '+ str(picnicItems.get('cups',0))+' cups.')
print('i an pringing '+str(picnicItems.get('eggs',100))+ ' eggs')
'''
#5.1.5 setdefault()方法
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
|
47cba5ba5df339964e60da0eb4453b746bc67e70 | ktkayathri/Code_Contests | /subarray_sum.py | 305 | 3.796875 | 4 | """
Given an array of integers (both positive and negative numbers), and a sum value as input, find the total subarrays that added up
would result in the given input sum.
For example,
input array - [1,2,3,0] and sum = 3
possible sub arrays with sum = 3 are: [1,2], [3], [3,0]
so, output should be 3.
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.