blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
050d1a40cd52edbaa112f07caaf261aa4b1d929b | tedtedted/Project-Euler | /004.py | 569 | 4.25 | 4 | """
A palindromic number reads the same both ways.
The largest palindrome made from the product of
two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
palindromes = []
def is_palindrome(num):
string = str(num)
first = string[:]
last = string[::-1]
return string[:] == string[::-1]
for i in range(100, 1000):
for j in range(100, 1000):
if is_palindrome(i * j):
palindrome = i * j
palindromes.append(palindrome)
print("The largest palindrome is:", sorted(palindromes)[-1]) |
157c747b2a2bec43efcdc6e91ef94948c667fa7e | llgeek/leetcode | /1110_DeleteNodesAndReturnForest/solution.py | 832 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
self.res = []
to_delete = set(to_delete)
def helper(node, first=True):
if not node:
return
if first and node.val not in to_delete:
self.res.append(node)
helper(node.left, node.val in to_delete)
helper(node.right, node.val in to_delete)
if node.left and node.left.val in to_delete:
node.left = None
if node.right and node.right.val in to_delete:
node.right = None
helper(root, True)
return self.res |
af62bbac155000eaa0994bc376ab5e8324e70f0d | bobur554396/PPII2021Spring | /w3/5.py | 280 | 3.75 | 4 | class Person:
# constructor
def __init__(self, n, a):
# print('Person class constructor called')
self.name = n
self.age = a
def show(self):
print(f'{self.name} -> {self.age}')
p = Person('Person1', 20)
# print(p.name)
# print(p.age)
p.show()
# del p
|
789d310d610b6fbf24038431ea26f52ce51e09a1 | NiamhOF/python-practicals | /practical-18/p18p2.py | 830 | 4.03125 | 4 | '''
Practical 18, Exercise 2
Define a function isCode
assign numcode the value 0
if the length of the string is less than 4
print an error
for all characters in the range 1 to the length of the string:
starting from the first letter in the string check if the next 4 letter are code
add 1 to numcode to move the position in the string on
return numcode
Ask user for a string
print the function isCode
'''
def isCode (s):
'''takes string and counts how many times the word code is in it'''
numcode = 0
if len(s) < 4:
print ('Error. Word must be longer than 3 letters.')
else:
for i in range (1, len(s)):
if s [i -1: i + 3] == 'code':
numcode += 1
return numcode
word = input ('Enter a string: ')
print (isCode(word))
|
b6a12eed08ecbd31ac9670ac8fd8980aa12e6f92 | WilliamW5/Tkinter | /frames.py | 455 | 3.609375 | 4 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Frames')
root.iconbitmap('Images\WillRagB.ico')
# puts padding inside of the frame
frame = LabelFrame(root, text="This is my Frame...", padx=50, pady=50)
# packs inside of the outside container
frame.pack(padx=100, pady=100)
b = Button(frame, text="Don't Click Here!")
b2 = Button(frame, text="...Or Here")
b.grid(row=0, column=0)
b2.grid(row=1, column=1)
root.mainloop()
|
3caec0bde19fc149c0d1d0cecfcfff3fac0c7301 | sach999/ScriptingLab | /ScriptingLab/SEE/6b.py | 899 | 3.609375 | 4 | from operator import itemgetter
sentences = []
class rev:
def __init__(self, sentence):
self.sentence = sentence
def reverse(self):
temp = ""
temparr = []
temparr = self.sentence.split(" ")
temparr.reverse()
for i in temparr:
temp = temp+i+" "
count = 0
for i in range(0, len(temp)):
ch = temp[i]
if(ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
count = count + 1
sentences.append({"count": count, "sentence": temp})
s1 = rev(input("Enter string 1: "))
s1.reverse()
s2 = rev(input("Enter string 2: "))
s2.reverse()
s3 = rev(input("Enter string 3: "))
s3.reverse()
sortedArr = sorted(sentences, key=itemgetter('count'), reverse=True)
print(sortedArr)
for s in sortedArr:
print(s["sentence"])
|
022bacc77140c5477266cf59e392eb0310b5e7d0 | Ketulia/199-SCHOOL-Introduction-to-Python-for-kids- | /2021-2022/VIII კლასი/8_1/004 (10.11.21)/4_1.py | 553 | 3.875 | 4 | num1 = 3
num2 = 5.78
num3 = 2 + 3j # 'Class <Complex>'
##print(num1, type(num1))
##print(num2, type(num2))
##print(num3, type(num3))
# -----------
##num1 = float(num1)
##print(num1, type(num1))
##
##num2 = int(num2)
##print(num2, type(num2))
# ---------
# real imag
print(num3)
x1 = num3.real
x2 = num3.imag
print(x1, x2)
print()
print(str(num3), type(str(num3)))
print()
print(int(x1), int(x2))
print(int(num3.real), int(num3.imag))
print()
num4 = 7
num4 = complex(num4)
print(num4)
num4 = 17.85
num4 = complex(num4)
print(num4)
|
bae8e0cb20ba424bb63249a76939811fdd34d972 | Shihabsarker93/BRACU-CSE111 | /Assignment 05/Problem 08.py | 885 | 3.703125 | 4 | # task-8
class Coordinates:
def __init__(self, x_axis, y_axis):
self.x_axis = x_axis
self.y_axis = y_axis
def detail(self):
return (self.x_axis, self.y_axis)
def __sub__(self, other):
a = self.x_axis - other.x_axis
b = self.y_axis - other.y_axis
return Coordinates(a, b)
def __mul__(self, other):
c = self.x_axis * other.x_axis
d = self.y_axis * other.y_axis
return Coordinates(c, d)
def __eq__(self, other):
if self.x_axis == other.x_axis:
return "The calculated coordinates are the same."
else:
return "The calculated coordinates are NOT the same."
p1 = Coordinates(int(input()), int(input()))
p2 = Coordinates(int(input()), int(input()))
p4 = p1 - p2
print(p4.detail())
p5 = p1 * p2
print(p5.detail())
point_check = p4 == p5
print(point_check)
|
36e561aa03f15656d5c234a76b54b975b264c0b0 | buhuipao/LeetCode | /2017/graph/bfs/populating-next-right-pointers-in-each-node-ii.py | 1,310 | 4.125 | 4 | # _*_ coding: utf-8
'''
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
添加一个右向指针
'''
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
# O(logN)
def connect(self, root):
if not root:
return root
_queue = [root]
n_last = last = root
while _queue:
node = _queue.pop(0)
if node.left:
_queue.append(node.left)
n_last = node.left
if node.right:
_queue.append(node.right)
n_last = node.right
if node == last:
node.next = None
last = n_last
else:
node.next = _queue[0] if _queue else None
|
f363b11eaf365e8e5affbbdc4707cd1a6877ea53 | chaitanyakulkarni21/Python | /Balguruswamy/1_Intro_To_Python/ReviewExercises/Prob9.py | 176 | 4.28125 | 4 | #WAP to demostrate While loop with else
count = 0
while count < 3:
print("Inside while loop...")
print(count)
count = count + 1
else:
print('Inside else statement...')
|
a7e0e2b3fadf2567b40b376867ab8b4684282607 | aalyar/Alya-Ramadhani_I0320123_Mas-Abyan_Tugas6 | /I0320123_Soal2_Tugas6.py | 284 | 3.6875 | 4 | nilai = int(input("\nMasukkan jumlah data: "))
print()
data = []
jumlah = 0
for i in range(0, nilai):
temp = int(input("Masukkan nilai ke-%d: " % (i+1)))
data.append(temp)
jumlah += data[i]
rata_rata = jumlah / nilai
print("\nNilai rata-rata = %0.2f" % rata_rata)
|
fcdcb843272006229c80b2c9f1af0d4d5a601d3b | ComputingTelU/SG-Basic-Prerequisite-Gen5.0-Batch2 | /DENI SAPUTRA HERMAWAN/DENI SAPUTRA_jawaban2.py | 745 | 3.75 | 4 | import re
#Deni Saputra
def case_email():
email = re.findall('\S+@\S+',a)
print(email)
def case_uang():
email = re.findall('[0-9]+',a)
b = [int(x)for x in email]
k = re.split(r'\s',a)
jum = 0
for i in k:
if i == "Ribu":
jum = jum + 1
elif i == "Juta":
jum = jum + 2
if jum == 1:
print(b[0]*1000)
elif jum == 2:
print(b[0]*1000000)
elif jum == 3:
print(b[0]*1000000000)
def case_waktu():
for x in range(0,len(a)):
if a[x] == ":":
print(a[x-2:x+3])
print("Test Case: ")
case = input()
print("Masukkan input: ")
a = input()
if case is "1":
case_waktu()
elif case == "2":
case_uang()
elif case == "3":
case_email()
else:
print("Test Case Tidak Ditemukan")
# email = re.findall('\S+@\S',a)
# print(email) |
64decdde3ee3d645252d0bd34b7e208dc4e0c626 | cravo123/LeetCode | /Algorithms/0356 Line Reflection.py | 1,089 | 3.65625 | 4 | # Solution 1, try to find middle x, and then prove it right
class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
if not points:
return True
d = set((x, y) for x, y in points)
# determine x_mid first
xs = list(set([x for x, _ in points]))
xs.sort()
if len(xs) % 2 == 1:
mid = xs[len(xs) // 2] * 2
else:
mid = xs[len(xs) // 2] + xs[len(xs) // 2 - 1]
for x, y in d:
if (mid - x, y) not in d:
return False
return True
# Solution 2, same idea as Solution 1. But use a more elegant way to
# determine middle point candidate
class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
if not points:
return True
target = min(x for x, _ in points) + max(x for x, _ in points)
d = set((x, y) for x, y in points)
for x, y in d:
if (target - x, y) not in d:
return False
return True |
ebb820d37fde39709f415b0f15be5f3b7a3213b2 | KavilanNaidoo/Lists | /spotcheck(1).py | 691 | 3.828125 | 4 | def initialise_frequency_array():
array = []
return array
def simulate_die_throwing(array):
import random
for count in range(6):
number = random.randint(1,6)
array.append(number)
return array
def display_result_array(array,number):
count = 0
count1 = 0
print("{0:^2} {1:^2}".format("Score","Frequency"))
for each in array:
print("{0:>3} {1:>7}".format(count+1,array[count1]))
count = count+1
count1=count1+1
def Frequency_of_die_score():
array = initialise_frequency_array()
number = simulate_die_throwing(array)
display_result_array(array,number)
Frequency_of_die_score()
|
870184e4e0f74a66ecdd724ce26c83d74553c34e | wilbertgeng/LeetCode_exercise | /92.py | 1,559 | 3.71875 | 4 | """92. Reverse Linked List II"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
### Practice:
if m == n or not head:
return head
p = dummy = ListNode(0)
p.next = head
for i in range(m-1):
p = p.next
tail = p.next
for i in range(n - m):
tmp = p.next
p.next = tail.next
tail.next = tail.next.next
p.next.next = tmp
return dummy.next
## Practice:
if m == n or not head:
return head
cur = dummy = ListNode(0)
dummy.next = head
for i in range(m-1):
cur = cur.next
tail = cur.next
for i in range(n - m):
tmp = p.next
p.next = tail.next
tail.next = tail.next.next
p.next.next = tmp
return dummy.next
##
if m == n or not head:
return head
dummy = ListNode(0)
dummy.next = head
p = dummy
for i in range(m-1):
p = p.next
tail = p.next
for j in range(n-m):
tmp = p.next
p.next = tail.next
tail.next = tail.next.next
p.next.next = tmp
return dummy.next
|
79c7d89e76247651dc8fe38b3a592a12e4275488 | waggertron/py_exercises | /sorting.py | 2,021 | 3.796875 | 4 | nums = [10, 9, 1, 7, 2, 6, 5, 4, 3, 0]
nums_small = nums[:4]
nums_empty = []
# bogo sort
def bogo_sort(nums):
nums = nums[:]
import random
l = len(nums)
while True:
random.shuffle(nums)
ordered = True
for i in range(1, l):
if nums[i - 1] > nums[i]:
ordered = False
if ordered:
break
return nums
print('bogo_small: ', bogo_sort(nums_small))
# bubble sort
def bubble_sort(nums):
nums = nums[:]
l = len(nums)
for i in range(l - 1):
for j in range(1, l - i):
if nums[j - 1] > nums[j]:
nums[j - 1:j + 1] = nums[j], nums[j - 1]
return nums
print('bubble: ', bubble_sort(nums))
print('bubble_small: ', bubble_sort(nums_small))
# insertion sort
def insertion_sort(nums):
nums = nums[:]
l = len(nums)
for i in range(1, l):
cur = nums[i]
for j in range(i, -1, -1):
if nums[j - 1] <= cur:
break
nums[j] = nums[j - 1]
nums[j] = cur
return nums
print('insertion_small:', insertion_sort(nums_small))
print('insertion:', insertion_sort(nums))
# merge sort
def merge_sort(nums):
if len(nums) <= 1:
return nums
split = len(nums) // 2
sorted_left = merge_sort(nums[:split])
sorted_right = merge_sort(nums[split:])
big, small = (sorted_left, sorted_right) if len(sorted_left) > len(sorted_right) else (sorted_right, sorted_left)
merged = []
b, s = 0, 0
while b < len(big) and s < len(small):
if small[s] <= big[b]:
merged.append(small[s])
s += 1
else:
merged.append(big[b])
b += 1
if b == len(big) and s == len(small):
return merged
else:
if b != len(big):
merged = [*merged, *big[b:]]
else:
merged = [*merged, *small[s:]]
return merged
print('merge_small', merge_sort(nums_small))
print('merge', merge_sort(nums))
|
fcfa703888d4d4ec7876804ea8fe879eac14a6f5 | taalaybolotbekov/chapter1.5-init | /task7/task7.py | 100 | 3.6875 | 4 | for i in range(1,7):
if i == 3:
continue
elif i == 6:
continue
print(i)
|
9e60d8b0e65659ea5b5f8f45d364b6d2f4e11b10 | pau1fang/learning_notes | /数据结构与算法/剑指offer_python语言/question48_最长不含重复字符的字符串.py | 629 | 3.765625 | 4 | def solution(string):
position = [-1 for _ in range(26)]
current_length = 0
max_length = 0
for i in range(len(string)):
if current_length == 0:
current_length = 1
else:
if position[ord(string[i])-ord('a')] < 0 or (i-position[ord(string[i])-ord('a')])>current_length:
current_length += 1
else:
current_length = i-position[ord(string[i])-ord('a')]
position[ord(string[i]) - ord('a')] = i
if current_length > max_length:
max_length = current_length
return max_length
print(solution("arabcacfr"))
|
39448aa5caf1b5a0751bac3b70adce7435a0fbd3 | codedeb/OOPS-DESIgn | /cards.py | 1,172 | 3.78125 | 4 | import random
class Card():
def __init__(self,suit, value):
self.suit = suit
self.value = value
def show(self):
print(f'{self.value} of {self.suit}')
class Deck():
def __init__(self):
self.cards = []
self.build()
def build(self):
for card in ['Spades', 'Hearts', 'Diamond', 'Club']:
for value in range(1,14):
self.cards.append(Card(card, value))
def show(self):
for val in self.cards:
val.show()
def shuffle(self):
for num in range(len(self.cards)-1,0,-1):
rand = random.randint(0,num)
self.cards[num], self.cards[rand] = self.cards[rand], self.cards[num]
def drawcard(self):
return self.cards.pop()
class Player():
def __init__(self, name):
self.name = name
self.hand = []
def draw(self,deck):
self.hand.append(deck.drawcard())
def showhand(self):
for card in self.hand:
card.show()
deck = Deck()
# deck.show()
deck.shuffle()
# # deck.show()
# card = deck.draw()
# card.show()
player = Player('xyz')
player.draw(deck)
player.showhand() |
a72142c8e509519bd61409030288eb8445593765 | wh2per/Programmers-Algorithm | /Programmers/Lv1/Lv1_나누어떨어지는숫자배열.py | 229 | 3.75 | 4 | def solution(arr, divisor):
answer = []
arr.sort()
for a in arr:
if a%divisor==0:
answer.append(a)
if len(answer)==0:
answer.append(-1)
return answer
print(solution([3,2,6],10)) |
61474798df10e9d5b2fd7c963d269c372bd8add4 | lastmayday/Euler | /46.py | 1,099 | 3.8125 | 4 | #-*- coding:utf-8 -*-
#! /usr/bin/env python
"""
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×1^2
15 = 7 + 2×2^2
21 = 3 + 2×3^2
25 = 7 + 2×3^2
27 = 19 + 2×2^2
33 = 31 + 2×1^2
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
"""
from itertools import product
def sieve(n):
numbers = range(2, n + 1)
p = 2
j = 0
done = False
while not done:
for i, n in enumerate(numbers):
if n % p == 0 and n != p:
numbers.pop(i)
j += 1
p = numbers[j]
if p ** 2 > n:
done = True
return numbers
def main():
primers = sieve(10000)
composites = set(n for n in range(2, 10000) if n not in primers)
twicesquares = set(2 * (n ** 2) for n in range(100))
sums = set(sum(c) for c in product(primers, twicesquares))
print min(n for n in composites if n not in sums and n % 2 != 0)
if __name__ == '__main__':
main()
|
bd06acf4c0bde80da5e2b87a47991d96dce87a3e | mayankbakhru/random_pycode | /socks.py | 993 | 3.796875 | 4 | def main():
total_socks = int(input())
colors = list(map(int, input().rstrip().split()))
if len(colors) != total_socks:
print ("error")
return 0
if not(1<=total_socks<=100) or not(1<=len(colors)<=100):
print("error")
return 0
numPairs = pair_up(total_socks,colors)
print(numPairs)
def pair_up(total_socks,colors):
counter = 1
numPairs = 0
for i in colors:
ind = -1
ind = colors.index(i,counter,total_socks) if i in colors[counter:total_socks] else -1
counter = counter + 1
if ind != -1:
numPairs += 1
#print ("inside pair_up" + str(numPairs))
#print (ind)
colors.pop(ind)
return numPairs
if __name__ == "__main__":
main()
""" Learnings:
1.
index function on list returns the first occurence of the element.
index function on a list throws an error if the element is not found
to handle that error I used a tertiary operator """
|
3b61029b4cb0dc8149e155356b857f6932c20bc6 | wxke/LeetCode-python | /46 全排列.py | 351 | 3.765625 | 4 | 全排列
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# a = list(itertools.permutations(nums,len(nums)))
# list1 = []
# for i in a:
# list1.append(list(i))
return list(itertools.permutations(nums,len(nums)))
|
9fd9471de4bc966cea9bcba6ff38f7e9b18175ca | kguarian/Classification-Algorithms | /knn/k-NN/get_data.py | 4,353 | 3.546875 | 4 | import numpy as np
from sklearn.datasets import load_breast_cancer
df = load_breast_cancer()
print("cancer keys: ", df.keys())
print("cancer feature names: ", df["feature_names"])
print("cancer data: ", df["data"])
# both lists of indices
neighborhood = None
indices = None
# unoptimized.
def shiftRight(array, start_index, k):
i = k-1
while i > start_index:
array[i] = array[i-1]
i = i-1
def scalar_dist_1d(v1, v2):
return abs(v1+v2)
def print_features(dataset):
names = dataset["feature_names"]
data = dataset["data"]
for i in range(0, len(data)):
for j in range(0, len(names)):
print(names[j], ": ", data[i][j], end="\t")
print("\n")
return
# returns array of indices (k nearest neighbors)
def insert_neighbor(distance_array, index_array, df, index, k_value, feature_index, value):
global neighborhood
global indices
upper_bound = 1
print(index)
neighborhood = distance_array.copy()
# Ω(n),θ(n), O(n) = (n^2/2+nlog n)
# NTS: don't pee and moan about python's speed if you're doing search/replace at O(n^2) ove n elements, k times for a dataset of size k, when everything will be sorted after the first run.
# this would be slow anywhere (to scale, at least).
# sort distances and indices
neighborhood_sz = len(df)
print(neighborhood)
distval = scalar_dist_1d(df[index][feature_index], value)
if index == 0:
index_array[0] = 0
distance_array[0] = distval
return distance_array, indices
else:
if index < k_value:
currindex = index
while (distval < distance_array[currindex] or index_array[currindex]==np.inf) and currindex >= 0:
currindex -= 1
if distval < distance_array[currindex]:
index_array[currindex] = index
distance_array[currindex] = distval
print("index < k case")
return distance_array, indices
else:
currindex = k_value-1
while distval < distance_array[currindex] and currindex >= 0:
currindex -= 1
currindex+=1
shiftRight(index_array, currindex, k_value)
shiftRight(distance_array, currindex, k_value)
print("index is", str(index))
print("distval is", str(distval))
if distval < distance_array[currindex] or distance_array[currindex] == np.inf:
if currindex == k_value:
print("value >", distance_array[k_value])
return distance_array, indices
index_array[currindex] = index
distance_array[currindex] = distval
print(distance_array, indices)
print("done")
print("exiting insert")
return distance_array, indices
def k_nn(feature_name, value, dataset, k):
global neighborhood
global indices
yea = 0
nea = 0
# edge case. ints are bigger.
if len(dataset) < k:
print("dataset too small for k-NN")
exit(1)
feature_index = None
# then using the typical (if < max_dist then ...)
neighborhood = np.zeros(k)
indices = np.zeros(k)
for i in range(k):
indices[i] = neighborhood[i] = np.inf
for i in range(0, len(dataset["feature_names"])):
if dataset["feature_names"][i] == feature_name:
feature_index = i
break
if i == len(dataset["feature_names"])-1:
print("didn't find feature name")
exit(1)
names = dataset["feature_names"]
data = dataset["data"]
for i in range(0, len(names)):
if feature_name == names[i]:
feature_index = i
for i in range(len(data)):
neighborhood, indices = insert_neighbor(
neighborhood, indices, data, i, k, feature_index, value)
print(dataset["target"])
print(neighborhood)
for i in range(len(indices)):
if dataset["target"][i] == 1.0:
yea = yea+1
else:
nea = nea+1
if yea > nea:
return 1
return 0
# value is integer
ref = {
"target": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
"data": [[101], [102], [150], [200], [300], [-2], [5], [-20], [50], [75]],
"feature_names": ["a"]
}
print(k_nn("mean perimeter", 130, df, 4))
c = k_nn('mean perimeter', 3, df, 4)
print(c)
|
dea20be5f3dc3675a907f0f491fef7ba03109fc1 | agomeso/Python-Challenge | /PyPoll/main.py | 2,018 | 3.875 | 4 | import csv
file_path = "./Resources/election_data.csv"
total_votes = 0
election = {"Voter ID": "", "County": "", "Candidate": ""}
got_votes = {}
output_file = "./Analysis/output.txt"
with open(file_path) as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile)
# Read the header row first(skip this step if there is no header)
csv_header = next(csvreader)
# print(f"CSV Header: {csv_header}")
# Read each row of data after the header
for row in csvreader:
# The total number of votes cast
total_votes = total_votes + 1
candidates = row[2]
lis = candidates.split()
# print(lis)
for c in lis:
# print(c)
if c in got_votes:
got_votes[c] = got_votes[c] + 1
else:
got_votes[c] = 1
# A complete list of candidates who received votes
# print(got_votes)
# print all the results
print("Election Results")
print("-------------------------")
print(f"Total Votes: {total_votes}")
print("-------------------------")
# The winner of the election based on popular vote.
winner = 0
for key, value in got_votes.items():
pct = round(value/total_votes*100, 3)
print(f"{key}: {pct} % ({value})")
if winner < value:
winner = value
elected = key
print("-------------------------")
print(f"Winner: {elected}")
print("-------------------------")
# output
with open(output_file, "w") as outputFile:
outputFile.write("Election Results\n")
outputFile.write("----------------------------\n")
outputFile.write(f"Total Votes: {total_votes}\n")
outputFile.write("----------------------------\n")
for key, value in got_votes.items():
pct = round(value/total_votes*100, 3)
outputFile.write(f"{key}: {pct} % ({value})\n")
outputFile.write("----------------------------\n")
outputFile.write(f"Winner: {elected}\n")
outputFile.write("----------------------------\n")
|
1593b1347d0e12c2826ed1b3cc97940521b0784e | Athena1004/python_na | /venv/Scripts/nana/multi_inherit.py | 343 | 3.59375 | 4 | #菱形继承实例
class A():
pass
class B(A):
pass
class C(A):
pass
class D(B,C):
pass
#构造函数的调用顺序
class A():
pass
class B(A):
def __init__(self):
print("B")
class C(B):#此时查找C的构造函数,如果没有,则向上按照MRO顺序查找父类,直到找到为止
pass
c = C() |
3745f30adedea7e9bf2393f85ae024f62b76e920 | AkiraKane/CityUniversity2014 | /Useful_Scripts/Remove_Punctuation.py | 259 | 4.25 | 4 | import string
list1 = ['da"!!!n', 'job??', 'dan#][ny']
def punctuationWord(x):
# Remove Punctuation from Word
for letter in string.punctuation:
x = x.replace(letter, '')
return str(x)
for word in list1:
print punctuationWord(word)
|
84a51ac0305ba889c1da2f12694be9834624b36d | Magdatm/isapykrk6 | /Day6/figures_calc.py | 499 | 3.84375 | 4 | # funkcja z dwoma parametrami boku prostokata, funkcja zwraca pole prostokata
def calculate_rectangular_area(side1, side2):
"""
Calculates area of rectangular.
:param side1: integer, greater than 0
:param side2: integer, greater than 0
:return: area based on multiplication of sides
"""
return side1 * side2
def calculate_sqare_area(side):
return side**2
if __name__ = '__main__':
rect_result = calculate_rectangular_area(14, 98)
print(rect_result)
|
a2ba015239b620b4165e7e728ff387263baf6fd7 | TraductoresSeccion2/pruebaKeila | /k2.py | 258 | 3.796875 | 4 | numeros=input("ingrse un numero")
numeros2=input("ingrse un numero2")
print"ingrse 1 para sumar 2 para restar"
respuesta=input(">>")
if respuesta==1:
print"el resultado "+str(numeros+numeros2)
if respuesta==2:
print"el resultado"+str(numeros-numeros2)
|
fbbb8779ac7aebf5cb0b24c3dc1953b7da0906df | hhugoac/CodeFightsPython | /CodeFights/newNumeralSystem.py | 300 | 3.546875 | 4 | def newNumeralSystem(number):
alphabet='ABCDEFGHIJKLMNOPQRSTUVWXY'
ind=alphabet.index(number)+1
ind1=alphabet.index(number)+1
if ind%2==0:
ind=ind/2
else:
ind=ind/2+1
lista=[]
for i in alphabet[:ind]:
lista.append(i+" + "+alphabet[ind1-1])
ind=ind-1
ind1=ind1-1
return lista
|
e2f7d94c200640b462122246c85776e42b9cce93 | idsdlab/basicai_sp21 | /lab_07_logistic_regression/lab-06_logistic_regression_plot.py | 1,630 | 3.5625 | 4 | import numpy as np
from matplotlib import pyplot as plt
# Score
# 0 : Fail, 1 : Pass
data = np.array([
[45, 0],
[50, 0],
[55, 0],
[60, 1],
[65, 1],
[70, 1]
])
# text file input/output
# x = data[:, 0] / 100
x = data[:, 0]
y = data[:, 1]
def sigmoid(x): # 시그모이드 함수 정의
return 1/(1+np.exp(-x))
w = np.random.uniform(low=0, high=20)
b = np.random.uniform(low=-20, high=10)
print('w: ', w, 'b: ', b)
num_epoch = 10000
learning_rate = 0.5
costs = []
eps = 1e-5
for epoch in range(num_epoch):
hypothesis = sigmoid(w * x + b)
cost = y * np.log(hypothesis + eps) + (1 - y) * np.log(1 - hypothesis + eps)
cost = -1 * cost
cost = cost.mean()
if cost < 0.0005:
break
# reference : https://nlogn.in/logistic-regression-and-its-cost-function-detailed-introduction/
w = w - learning_rate * ((hypothesis - y) * x).mean()
b = b - learning_rate * (hypothesis - y).mean()
costs.append(cost)
if epoch % 5000 == 0:
print("{0:2} w = {1:.5f}, b = {2:.5f} error = {3:.5f}".format(
epoch, w, b, cost))
print("----" * 15)
print("{0:2} w = {1:.5f}, b = {2:.5f} error = {3:.5f}".format(epoch, w, b, cost))
# # 예측
w = 3.22902
b = -185.41300
x = 45 # True : 0
pred_y = sigmoid(w * x + b)
print(pred_y)
x = 60 # True : 1
pred_y = sigmoid(w * x + b)
print(pred_y)
x = data[:, 0]
y = data[:, 1]
org_x = np.linspace(0, 100, 100)
pred_y = sigmoid(w * org_x + b)
plt.scatter(x, y)
plt.title("Pass/Fail vs Score")
plt.xlabel("Score")
plt.ylabel("Pass/Fail")
plt.plot(org_x, pred_y, 'r')
# plt.axis([0, 420, 0, 50])
plt.show() |
f44a1f7c8435960f1bdca27692924db5732200a2 | rohit-sonawane/abc-bank-python | /abcbank/bank.py | 815 | 3.796875 | 4 | class Bank:
def __init__(self):
self.customers = []
def addCustomer(self, customer):
self.customers.append(customer)
def customerSummary(self):
summary = "Customer Summary"
for customer in self.customers:
summary = summary + "\n - " + customer.name + " (" + self._format(customer.numAccs(), "account") + ")"
return summary
def _format(self, number, word):
return str(number) + " " + (word if (number == 1) else word + "s")
def totalInterestPaid(self):
total = 0
for c in self.customers:
total += c.totalInterestEarned()
return total
def getFirstCustomer(self):
try:
return self.customers[0].name
except Exception as e:
print(e)
return "Error" |
bfc04236fc65f8118edebadd41f0a983a23a7917 | sgowris2/coding-practice | /is_palindrome_permutation.py | 1,697 | 4.125 | 4 | # Write an efficient function that checks whether any permutation of an input string is a palindrome.
# Assumptions -
# 1. Only lower case letters.
# 2. Input is always valid, i.e. no empty strings.
# Solution -
# 1. If only one letter, return True.
# 2. If odd number of letters:
# return True if every letter except one has a matching letter in the string.
# 3. If even number of letters:
# return True is every letter has a matching letter in the string.
# Examples -
# 1. a = True
# 2. aa = True
# 3. ab = False
# 4. aabba = True
# 5. bbbbbb = True
# Runtime -
# n is length of string, so O(n) to add all chars to a dictionary
# Worst case O(n) to go through dictionary and find unmatched characters
# O(1) to check length of unmatched characters
# O(n)
def is_palindrome_permutation(string):
if string is None or not isinstance(string, str):
return False
if len(string) == 1:
return True
word_dict = {}
for char in string:
if char in word_dict.keys():
word_dict[char] = word_dict[char] + 1
else:
word_dict[char] = 1
unmatched_characters = find_unmatched_characters(word_dict)
if len(unmatched_characters) <= 1:
return True
else:
return False
def find_unmatched_characters(_word_dict):
return [key for key in _word_dict if _word_dict[key] % 2 == 1]
if __name__ == '__main__':
strings = ['civic',
'civil',
'a',
'dog',
'abacus',
'ababababa',
'aaa',
'bbbb']
for string in strings:
print(string + ' = ' + is_palindrome_permutation(string).__str__())
|
b1127cfae05b2abf032d742c168903531140f4ae | chaoluo1982/HelloWorld | /test.py | 205 | 3.890625 | 4 | list1= [1,2,3,4]
print (list1[0])
dictionary1 = {"name":"chao","age":"35"}
print (dictionary1.keys())
tuple1= (1,2,3,4)
print (tuple1)
print ("HelloWord1!")
print ("HelloWord2!")
print ("HelloWord3!")
|
ea74c41b820db70531bfbdd4e636c9aa04106816 | AbsolutN/Labb-4 | /LinkedQ.py | 1,813 | 3.5625 | 4 | class Node:
# class för att skapa noder till min linkedQ kö
def __init__(self, value):
# håller koll på värdet (value) av noden samt referens till nästa (next) nod
self.value = value
self.next = None
class LinkedQ:
def __init__(self):
# håller koll på första och sista värdet i kön
# värdet från början på första och sista är alltid None
self.__first = None
self.__last = None
def isEmpty(self):
# kollar om kön är tom
if self.__first is None:
# Returnerar True om den är tom
return True
else:
# Returnerar False om den inte är tom
return False
def enqueue(self, startord):
# Lägger till nytt objekt sist i kön
stamfar = Node(startord)
# Skapar en ny nod
if self.__first is None:
# Om listan är tom
self.__first = stamfar
self.__last = self.__first
# Blir första och sista värdet i kön samma
else:
# Om listan innehåller någonting
self.__last.next = new_node
# Vi ändrar den sista nodens referens från None till vår nya nod
self.__last = new_node
# ersätter sista värdet i kön med vår nya nod
def dequeue(self):
# Tar bort den första noden i kön samt returnerar värdet
if self.__first is not None:
# Om listan inte är tom
x = self.__first.value
# Sparar första värdet i vår kö
self.__first = self.__first.next
# Ersätter första värdet med den nod som är näst först
return x
# Returnerar värdet på noden som vi tog bort
q = LinkedQ()
print(q.isEmpty())
|
892997793cae1df90559d1c31af78103bb012d05 | roman-bachmann/Mini-DL-Framework | /src/activations.py | 1,829 | 3.984375 | 4 | from module import Module
def relu(input, inplace=False):
'''
Computes ReLU(x)= max(0, x) on an input tensor
Args:
input (FloatTensor): Any FloatTensor to apply ReLU activation on
inplace (bool, optional): Will operate inplace if True
'''
mask = input < 0
if inplace:
return input.masked_fill_(mask, 0)
return input.clone().masked_fill_(mask, 0)
''' Alternative way to threshold
mask = input >= t
output = input.clone().fill_(value)
return output.masked_scatter_(mask, input)
'''
class ReLU(Module):
''' Layer that applies the ReLU activation function to the input.
ReLU(x) = max(0, x) '''
def _init_(self):
super(ReLU, self)._init_()
def forward(self , input):
self.input = input
return relu(input, inplace=False)
def backward(self, grad_wrt_output):
return (self.input > 0).float() * grad_wrt_output
def param(self):
return []
class Tanh(Module):
''' Layer that applies the Tanh activation function to the input. '''
def _init_(self):
super(Tanh, self)._init_()
def forward(self, input):
self.input = input
return input.tanh()
def backward(self, grad_wrt_output):
return (1 - self.input.tanh().pow(2)) * grad_wrt_output
def param(self):
return []
class Sigmoid(Module):
''' Layer that applies the Sigmoid activation function to the input.
sigmoid(x) = 1 / (1 + e^(-x))'''
def _init_(self):
super(Sigmoid, self)._init_()
def forward(self, input):
self.input = input
return 1 / (1 + (-input).exp())
def backward(self, grad_wrt_output):
s = 1 / (1 + (-self.input).exp())
return (s * (1 - s)) * grad_wrt_output
def param(self):
return []
|
39e108cc35cb079f0c0f68ba4e5096b27da82b60 | SzymonSzott/ns-3-netfrastructure | /plot-he-wifi-performance.py | 967 | 3.5625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""nETFRAStructure example Python plotting script
- Description: Plots results of the `he-wifi-performance` ns-3 scenario
- Author: Szymon Szott <szott@kt.agh.edu.pl>
- Website: https://github.com/SzymonSzott/ns-3-netfrastructure
- Date: 2020-06-13
"""
import pandas as pd
import matplotlib.pyplot as plt
# Read data from CSV file
df = pd.read_csv('he-wifi-performance.csv', delimiter=',')
# Group by sum of all flows in a given experiment run (to obtain aggregate throughput)
df = df.groupby(['nWifi','RngRun'])['Throughput'].sum().reset_index()
# Group by nWifi and calculate average (mean) aggregate throughput
df = df.groupby(['nWifi'])['Throughput'].mean()
# Plot
ax = df.plot(title='IEEE 802.11ax Performance', marker='o', legend=False, ylim=(0,140))
ax.set(xlabel="Number of transmitting Wi-Fi stations", ylabel="Network throughput [Mb/s]")
# Save to file
plt.tight_layout()
plt.savefig('he-wifi-performance.png');
|
7fad64f829c3e47ca252bb78f39298821e3688e4 | thelsandroantunes/EST-UEA | /LPI/Listas/L3_LPI - funções/exe21l3.py | 892 | 4.1875 | 4 | # Autor: Thelsandro Antunes
# Data: 03/07/2017
# EST-UEA
# Disciplina: LP1
# Professora: Elloa B. Guedes
# 3 Lista de Exercicios (09/04/2015)
# Questao 21: Escreva uma funcao regraMPB que recebe como argumento uma palavra
# qualquer e retorne a palavra invalida caso verifique o uso da letra 'n'
# antes de 'p' ou 'b'. Caso contrario, retorne a palavra valida. Veja os
# asserts a seguir.
# * assert regraMPB("Gamba")
# * assert not regraMPB("Granpo")
def regraMPB(word):
r = "invalido"
for i in range(len(word)):
if((word[i] == "P") or (word[i] == "p")):
if((word[i-1] == "M") or (word[i-1] == "m")):
r = "Valido"
if((word[i] == "B") or (word[i] == "b")):
if((word[i-1] == "M") or (word[i-1] == "m")):
r = "Valido"
return r
word = raw_input("palavra? ")
print("%s "%regraMPB(word))
|
f000c8029f82c5f884930211fd8d0c4f35d7f63e | divyanshAgarwal123/PythonProjects | /aptech learning/pyhton idle codes/dict 6.py | 170 | 4.0625 | 4 | data1={100:'ramesh',101:'suraj',102:'alok'}
print(data1)
print(len(data1))
if len(data1) > 10:
print("it is greater then 10")
else:
print("it is smaller then 10") |
978b05b27ae2daac36e613f5490fb59745f57719 | Pedrohjsg/Edu | /librerias/funciones.py | 793 | 3.734375 | 4 | #-*- coding: utf-8 -*-
"""
FUNCIONES:
---------------------------------
def funcion1():
comando1
comando2
[return valor] #Solo para funciones que devuelven un valor
"""
def imprimir(): #Procedimiento
print "hola"
def funcion_holamundo(): #Funcion
return "Hola Mundo"
def nombre(nombre,apellido):
print nombre+" "+apellido
def parimpar(z1):
"""
if n1%2==0:
return "par"
else:
return "impar"
"""
return "par" if(z1%2==0) else "impar"
def datos(dni,nombre,*apellidos):
print "DNI: "+dni
print "Nombre: "+nombre
contador=1
for a in apellidos:
print "Apellido "+str(contador)+": "+a
contador+=1
def iniciales(nombre,*apellidos):
iniciales_lista=[]
iniciales_lista.append(nombre[0])
for x in apellidos:
iniciales_lista.append(x[0])
return iniciales_lista |
085baa638935fd76b043950a92dbc9c6f5c94bb9 | chjmil/AdventOfCode2020 | /Day05/binary_boarding.py | 2,328 | 3.921875 | 4 | import argparse
import os
import re
def get_seat_id(input: str):
"""
String contains F, B, R, and L. Convert it to a binary and then to decimal
F means it is the lower half, B means it is the upper half
R means upper half, L means lower half
"""
binary_input = re.sub('F|L', '0', input)
binary_input = re.sub('B|R', '1', binary_input)
row = int(binary_input[:-3], base=2)
column = int(binary_input[-3:], base=2)
seat = row * 8 + column
print(f"{input} = Row {row} Column {column}, seat {seat}")
return seat
def main(input_list_path: str):
"""
Parse through the provided file for the seat IDs
:param input_list_path (str): Path to the input file
"""
# Verify the file exists
if not os.path.exists(input_list_path):
print(f"Input file does not exist: {input_list_path}")
exit(1)
# Parse the file and store it in a list
with open(input_list_path, 'r') as f:
# List comprehension to ...
input = f.readlines()
largest_id = 0
seat_list = []
for i in input:
seat_id = get_seat_id(i.strip())
seat_list.append(seat_id)
largest_id = max(largest_id, seat_id)
# Print the solution
print("--------------------PART 1-----------------------")
print(f"Answer: {largest_id}")
# PART 2
my_seat = 0
seat_list.sort()
# Go through the sorted list and figure out which seat is missing
for i in range(len(seat_list)-2):
# Skip the first value since we are told that can't be the answer
if i == 0:
continue
# if the value's +1/-1 neighbor is there, then that means it can't be our seat
if seat_list[i]+1 == seat_list[i+1] and seat_list[i]-1 == seat_list[i-1]:
continue
# if we found the missing spot, then that means it is the next seat after seat_list[i]
my_seat = seat_list[i] + 1
break
print("--------------------PART 2-----------------------")
print(f"Answer: {my_seat}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run the program.")
parser.add_argument("--input-path", help="Path to the input file",
type=str, required=True)
args = parser.parse_args()
main(input_list_path=args.input_path) |
e5494f2f0b1a71554be84fe1427883dfc39323b0 | DitooAZ/Python-Games | /Space_Invaders/space_invaders.py | 6,878 | 3.921875 | 4 | # Space Invaders
import turtle
import os
import math
import random # To make the enemy start from random positions
# Set up the screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")
wn.bgpic("space_invader_background.gif")
# Register the shapes
turtle.register_shape("invader.gif")
turtle.register_shape("player.gif")
# Draw Border
border_pen = turtle.Turtle() # Creating a Turtle
border_pen.speed(0) # Setting the speed of drawing diagrams
border_pen.color("white")
border_pen.penup() # It will lift the pen and will prevent it from drawing
border_pen.setposition(-300, -300) # The center is (0,0)
border_pen.pensize(3) # Setting pensize
border_pen.pendown()
for side in range(4):
border_pen.fd(600) # Moving forward
border_pen.lt(90) # Moving left 90 degrees
border_pen.hideturtle() # Hiding the turtle cursor
# Set the score to 0
score = 0
# Draw the score
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-270, 260)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align="left", font=("Ariel",14,"normal"))
score_pen.hideturtle()
# Draw Game Over
game_over = turtle.Turtle()
game_over.speed(0)
game_over.color('red')
game_over.penup()
game_over.setposition(-230, 260)
game_over.hideturtle()
# Create the player turtle
player = turtle.Turtle()
player.color("blue")
player.shape("player.gif")
player.penup()
player.speed(0)
player.setposition(0, -250)
player.setheading(90) # Set the space ship facing upwards (since default position faces right side)
playerspeed = 15 # Setting the players speed
# Choose the number of enemies
number_of_enemies = 5
# Create an empty list of enemies
enemies = []
# Add enemies to the list
for i in range(number_of_enemies):
# Create the enemy
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color("red")
enemy.shape("invader.gif")
enemy.penup()
enemy.speed(0)
x = random.randint(-200, 200) # Starts each enemy at a different spot
y = random.randint(100, 250)
enemy.setposition(x, y)
enemyspeed = 2
# Create the player's bullet
bullet = turtle.Turtle()
bullet.color("yellow")
bullet.shape("triangle")
bullet.penup()
bullet.speed(0) # drawing speed
bullet.setheading(90) # So that the bullet points up
bullet.shapesize(0.5, 0.5) # Making the bullet size half of player size
bullet.hideturtle() # When the game starts we want our bullet to be hidden
bulletspeed = 20 # setting the bullet speed more the playerspeed
# Define bullet state
# ready - ready to fire
# fire - bullet is firing
bulletstate = "ready" # Bullet is ready to fire
# Move the player left and right
def move_left():
x = player.xcor()
#y = player.ycor()
x = x - playerspeed # x = x - playerspeed ( Changing value of x each time )
if x < -280: # Blocking the player from crossing
x = - 280
player.setx(x) # setting the player's location to new x
def move_right():
x = player.xcor()
x += playerspeed
if x > 280:
x = 280
player.setx(x)
def fire_bullet():
# Declare bulletstate as a global if it needs changed
global bulletstate # global variables can be read in python ( any changes in this function are reflected globally)
if bulletstate == "ready":
os.system("aplay laser.wav&") # To play the sound when the bullet is fired
bulletstate = "fire" # changing the bulletstate to fire
# Move the bullet to the just above the player
x = player.xcor()
y = player.ycor() + 10 # Each time the function is called the bullet moves 10 units above player position
bullet.setposition(x, y)
bullet.showturtle()
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2)) # (x^2 + y^2)^0.5
if distance < 15:
return True
return False
# Create keyboard bindings
turtle.listen() # Turtle is listening to your response
turtle.onkeypress(move_left, "Left") # On pressing the left key turtle will call the mov_left() function
turtle.onkeypress(move_right, "Right")
turtle.onkeypress(fire_bullet, "space") # Keyboard binding
# Main game loop
while True:
for enemy in enemies: # It loops through all elements in enemy and tests their condition
# Move the enemy
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
# Move the enemy back and down
if enemy.xcor() > 280: # Boundary Checking
# Move all enemies down
for e in enemies:
y = e.ycor()
y -= 40 # Every time the enemy hits the borders the enemy drops down by 40
e.sety(y) # Setting enemy position to the new y
# Change enemy direction
enemyspeed *= -1 # Each time the enemy hits the boundary it reverses its direction
if enemy.xcor() < -280:
# Move all enemies down
for e in enemies:
y = e.ycor()
y -= 40
e.sety(y)
# Change enemy direction
enemyspeed *= -1
# Check collision between the bullet and the enemy
if isCollision(bullet, enemy):
os.system("aplay explosion.wav&")
# Reset the bullet
bullet.hideturtle()
bulletstate = "ready" # So that we can fire the bullet again
bullet.setposition(0, -400) # It moves the bullet off the screen
score += 10
scorestring = "Score: %s" %score
score_pen.clear()
score_pen.write(scorestring, False, align="left", font=("Ariel", 14, "normal"))
# Reset the enemy
x = random.randint(-200, 200) # Starts each enemy at a different spot
y = random.randint(100, 250)
enemy.setposition(x, y)
# Check if there is collision between the player and the enemy
if isCollision(player, enemy):
os.system("aplay explosion.wav&")
player.hideturtle()
enemy.hideturtle()
print("Game Over")
gameoverstr = "Game Over: Your Score: %s" % score
gameover.write(gameoverstr, False, align="left", font=("Ariel", 14, "normal"))
exit(0)
break
# Move the bullet
if bulletstate == "fire": # We want to move the bullet only when it is "fire" state and not in "ready" state
y = bullet.ycor()
y += bulletspeed # To move the bullet
bullet.sety(y)
# Check to see if the bullet has gone to the top
if bullet.ycor() > 275:
bullet.hideturtle() # Hiding the turtle when the bullet reaches the top
bulletstate = "ready" # Allows us to fire another bullet on reaching the top
delay = input("Press Enter to finish.") |
2739d6a85e3539880d9f8773c16c10c30d85742a | MurluKrishna4352/Python-Learning | /def - calculator.py | 1,702 | 4.21875 | 4 | # def function
# calculator
print("HELLO WORLD !!!\n\n")
print("-----> Enter + for addition\n")
print("-----> Enter - for subtraction\n")
print("-----> Enter * for multiplication\n")
print("-----> Enter / for division\n")
#inputs
# addition function
def sum(x , y):
if (input_condition == "+"):
return x + y
# subtraction function
def subtraction( x , y ):
if (input_condition == "-"):
return x - y
# multiplication function
def multiplication(x , y):
if (input_condition == "*"):
return x * y
# division function
def division(x , y):
if (input_condition == "/"):
return x / y
while True :
number_1 = float(input("Provide the system with first number : "))
number_2 = float(input("Provide the system with the second number : "))
input_condition = input("Enter the condition : ")
if (input_condition == "+"):
print(number_1 , input_condition , number_2 , " = ", sum(number_1 , number_2))
elif (input_condition == "-"):
print(number_1 , input_condition , number_2 , " = ", subtraction(number_1 , number_2))
elif (input_condition =="*"):
print(number_1 , input_condition , number_2 , " = ", multiplication(number_1 , number_2))
elif (input_condition == "/"):
print(number_1 , input_condition , number_2 , " = ", division(number_1 , number_2))
else:
print("Invalid Input \n Try Again : - ) ")
print("Enter yes to quit and sustain to continue .")
sustainment = input("do yo want to quit ? : ")
if sustainment == "yes":
break
else:
continue
|
598fdc0e1c437fb4eeb5a1fd0ada790a2cc4a11f | alexshore/chessai | /Bishop.py | 1,341 | 3.578125 | 4 | # Importing required custom modules.
from Coordinate import Coordinate as C
from Piece import Piece
# Defines widely used global constants.
WHITE = True
BLACK = False
# Starts the definition of the class 'Bishop' using inheritence.
class Bishop(Piece):
# Defines the string representation and the piece value.
stringRep = 'B'
value = 3
def __init__(self, board, side, position, movesMade=0):
# Initialising function of the 'Bishop' class. Creates and assigns
# given values to the required attributes. Does this through both
# regular variable assignment and also through inheritance.
super(Bishop, self).__init__(board, side, position)
self.movesMade = movesMade
def getPossibleMoves(self):
# Function run to yield a group of all possible legal and illegal
# 'Move' objects to the calling function. Does this by providing a list
# of directions to the 'movesInDirectionFromPos' function which then
# returns the moves to be yielded.
pos = self.position
directions = [C(1, 1), C(-1, -1),
C(-1, 1), C(1, -1)]
for direction in directions:
for move in self.movesInDirectionFromPos(pos, direction,
self.side):
yield move
|
b681ebb3c83167b573a3fa9078f8b7d19000c3d8 | SargRub/MachineLearning | /homework_1/main.py | 132 | 3.53125 | 4 | language = input()
with open(f'{language}.text', 'r') as file:
data = file.readlines()
for line in data:
print(line) |
f3fb0dc1537312ac437db62586f240cc8b2ee970 | tengkuhanis/learningpython | /jiman_Quiz_1.py | 2,003 | 3.984375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self):
self.head = None
def AbirLinkedList(self, A, I):
curA = A.head
curI = I.head
while curA and curI:
if curA.val == curI.val:
curA = curA.next
curI = curI.next
elif curA.val > curI.val:
self.addToEnd(curI.val)
curI = curI.next
else:
self.addToEnd(curA.val)
curA = curA.next
while curA:
self.addToEnd(curA.val)
curA = curA.next
while curI:
self.addToEnd(curI.val)
curI = curI.next
def addToStart(self, data):
tempNode = ListNode(data)
tempNode.next=self.head
self.head = tempNode
del tempNode
def addToEnd(self, data):
start = self.head
if start is None:
self.addToStart(data)
else:
while start.next:
start = start.next
tempNode = ListNode(data)
start.next = tempNode
del tempNode
return True
def display(self):
start = self.head
if start is None:
print("Empty List!!!")
return False
while start:
print(str(start.val), end=" ")
start = start.next
if start:
print("-->", end=" ")
print()
Abir = Solution()
Ahmed = Solution()
Islam = Solution()
Ahmed.addToEnd(1)
Ahmed.addToEnd(3)
Ahmed.addToEnd(5)
Ahmed.addToEnd(6)
Ahmed.addToEnd(7)
Ahmed.addToEnd(10)
Islam.addToEnd(1)
Islam.addToEnd(2)
Islam.addToEnd(3)
Islam.addToEnd(4)
Islam.addToEnd(5)
Islam.addToEnd(8)
Islam.addToEnd(9)
Ahmed.display()
Islam.display()
Abir.AbirLinkedList(Ahmed,Islam) # I dont know how to test this so I assume my code is correct
Abir.display() |
40b1a0d8c5a2387167eadbb3cd93cb5a4d406c2d | tmr232/ProjectEuler | /problem23.py | 666 | 3.65625 | 4 | from itertools import count, takewhile, combinations_with_replacement
from utils import get_proper_divisors, take
MAX = 28123+10
def is_abundant(number):
return sum(get_proper_divisors(number)) > number
def iter_abundant_numbers():
return (n for n in count() if is_abundant(n))
def main():
print take(10, iter_abundant_numbers())
# print len(list(takewhile(lambda n: n < MAX, iter_abundant_numbers())))
table = {sum(x) for x in combinations_with_replacement(takewhile(lambda x: x <= MAX / 2, iter_abundant_numbers()), 2)}
print "Got table"
print sum(x for x in range(MAX) if x not in table)
if __name__ == "__main__":
main() |
cd6ef61aa230a7888ef6c706d77808930789530a | jojonki/atcoder | /abc/abc170a.py | 130 | 3.59375 | 4 | def main():
for i, x in enumerate(input().split()):
if x == '0':
print(i + 1)
return
main()
|
f999d0efe89824d870fcfd20efa1dee625c2ccc6 | liuliuch/robot_test | /testsuite/python/test.py | 411 | 3.640625 | 4 | def shiftingLetters(S, shifts):
"""
:type S: str
:type shifts: List[int]
:rtype: str
"""
# new = S
for i in range (len(shifts)- 1, -1, -1):
for j in range (0, i+1):
char = chr((ord(S[j]) - ord('a') + shifts[i]) % 26+ord('a'))
print(char)
S = S[:j]+char+S[j+1:]
print(S)
return S
a="aaa"
s=[1,2,3]
shiftingLetters(a,s)
|
d25966e165adba86684bfb09c8d45d04365a126c | alessandroliafook/P1 | /unidade4/samu/samu.py | 538 | 3.5 | 4 | # coding: utf-8
# Atendimentos no SAMU
# (C) / Alessandro Santos, 2015 / UFCG - PROGRAMAÇÃO 1
total_atendimentos = 0
atendimentos_mes = []
for i in range(12):
atendimentos = int(raw_input())
total_atendimentos += atendimentos
atendimentos_mes.append(atendimentos)
media_atendimentos = total_atendimentos / 12.0
print "Média mensal de atendimentos: %.2f" % media_atendimentos
print "----"
for mes in range(len(atendimentos_mes)):
if atendimentos_mes[mes] > media_atendimentos:
print "Mês %d: %d" % (mes + 1, atendimentos_mes[mes])
|
2f57565a11769a916681c3294de2771c1eb729cd | Anjualbin/workdirectory | /OOP/multilevelinher.py | 415 | 3.609375 | 4 |
class Person:
def pvalue(self,name,age):
self.name=name
self.age=age
class Child(Person):
def cvalue(self,address):
self.address=address
print(self.name,self.address)
class student(Child):
def info(self):
print(self.name)
print(self.address)
ch=Child()
ch.pvalue("Anu",12)
ch.cvalue("ert")
st=student()
st.pvalue("anju",15)
st.cvalue("abc")
st.info() |
45932ddd36dd554da89ddfd44ba8b57b652263cc | henrikmathiesen/python-first-step | /iv_gr.py | 545 | 3.578125 | 4 | #
# Input
print("Enter name")
name = input()
print("Enter EPS")
eps = input()
print("Enter growth rate")
gr = input()
print("Enter current PPS")
pps = input()
#
# Constants
noGrPe = 0.085
rrOfR = 0.03
#
# Convert input
eps = float(eps)
gr = float(gr)
gr = gr / 100
pps = float(pps)
#
# Calculate
iv = (eps * (noGrPe + (2 * gr)) * 4.4) / rrOfR
diff = iv / pps
#
# Convert result
iv = round(iv)
iv = str(iv)
pps = str(pps)
diff = str(diff)
#
# Print result
print(name + " >> " + "PPS: " + pps + " | IV: ~" + iv + " | DIFF: " + diff)
|
26b4746736dd13c1bca90c1a40ea1178f3e12665 | yonatanGal/Recursion-Exercise | /Recursion.py | 4,783 | 4.125 | 4 |
def print_to_n(n):
""" this function prints all the integers from 1 to n"""
if n < 1:
return
elif n >= 1:
print_to_n(n-1)
print(n)
def print_reversed(n):
""" this function prints all the integers from n to 1"""
if n < 1:
return
if n >= 1:
print(n)
print_reversed(n-1)
def is_prime(n):
""" this function checks if a given number n is prime """
if n == 2:
return True
if has_divisor_smaller_than(n, n-1) is False:
return True
else:
return False
def has_divisor_smaller_than(n, i):
""" this function checks if a given number n has dividers which are
smaller than i and bigger or equal to 2 """
if n < 0:
return True
if i - 1 == 1:
return False
elif n % (i - 1) == 0:
return True
return has_divisor_smaller_than(n, i - 1)
def exp_n_x(n, x):
""" this function gives a the sum of the exp powered by x series """
if n == 0:
return 1
else:
return (x**n)/factorial(n) + exp_n_x(n-1, x)
def factorial(n):
""" this function calculates the factorial of a given number n """
if n == 0:
return 1
else:
return n * factorial(n-1)
def play_hanoi(hanoi, n, src, dest, temp):
""" this function moves all the disks from src to dest according to the
laws of the game """
if n > 0:
play_hanoi(hanoi, n-1, src, temp, dest)
hanoi.move(src, dest)
play_hanoi(hanoi, n-1, temp, dest, src)
elif n <= 0:
return
def print_sequences(char_list, n):
""" this function receives a char list and returns all possible strings
of n length """
if n == 0:
return
k = len(char_list)
print_sequences_rec(char_list, '', k, n)
def print_sequences_rec(char_list, sequence, k, n):
""" this is the recursive function which runs on the char list
and gives us all possible strings of length n """
if n == 0:
print(sequence)
return
for i in range(k):
new_sequence = sequence + char_list[i]
print_sequences_rec(char_list, new_sequence, k, n-1)
def print_no_repetition_sequences(char_list, n):
""" same as print_sequences, but this time returns all strings of length
n without repeating characters"""
if n == 0:
return
k = len(char_list)
print_no_repetition_sequences_rec(char_list, '', k, n)
def print_no_repetition_sequences_rec(char_list, sequence, k, n):
""" this is the recursive function which runs on the char list
and gives us all possible strings of length n, without repeating
characters"""
if n == 0:
print(sequence)
return
for i in range(k):
if char_list[i] in sequence:
pass
else:
new_sequence = sequence + char_list[i]
print_no_repetition_sequences_rec(char_list, new_sequence, k, n-1)
def parentheses(n, valid_option="", open_bracket=0):
""" this function receives a number n, and return all legal permutations
of parentheses"""
if n == 0:
if open_bracket == 0:
return [valid_option]
return parentheses(n, valid_option + ")", open_bracket - 1)
if open_bracket == 0:
return parentheses(n - 1, valid_option + "(", open_bracket + 1)
return parentheses(n - 1, valid_option + "(", open_bracket + 1)\
+ parentheses(n, valid_option + ")", open_bracket - 1)
def up_and_right(n, k, combination=''):
""" this function return every possible combination of 'r' and 'u', that
will lead us to the given point (n,1) """
if n < 0 or k < 0:
return
if n == 0:
if k == 0:
print(combination)
return
else:
up_and_right(0, k-1, combination + 'u')
elif k == 0:
if n == 0:
print(combination)
return
else:
up_and_right(n-1, 0, combination + 'r')
elif n != 0 and k != 0:
up_and_right(n-1, k, combination + 'r'),\
up_and_right(n, k-1, combination + 'u')
def flood_fill(image, start):
""" this function receives a matrix (image) and a
position in the matrix (start), and based on them change the matrix """
if image == []:
return
if image[start[0]][start[1]] == '.':
image[start[0]][start[1]] = '*'
if image[start[0]-1][start[1]] == '.':
flood_fill(image, (start[0] - 1, start[1]))
if image[start[0]+1][start[1]] == '.':
flood_fill(image, (start[0] + 1, start[1]))
if image[start[0]][start[1]-1] == '.':
flood_fill(image, (start[0], start[1] - 1))
if image[start[0]][start[1]+1] == '.':
flood_fill(image, (start[0], start[1] + 1))
return
|
af8a72b2a9ad371110fab20f2f37c1fe9aefe3c4 | FabioAguera/IoT | /Ex2_par.py | 143 | 3.65625 | 4 | def epar():
num = float(raw_input())
x = num%2
if (x == 0):
print " par"
else:
print "no par"
|
c564298f9db388be848984bafb39d840bbf5fb73 | sudheemujum/Python-3 | /dict_find_key_value.py | 442 | 3.984375 | 4 | d={100:'A',200:'A',300:'A',400:'D'}
key=int(input('Enter key to get value:'))
if key in d:
print('The corresponding value is:', d.get(key),d[key])
else:
print('Entered key is not available')
value=input('Enter the values to get key:')
available=False
for k,v in d.items():
if v==value:
print('The corresponding key is:',k)
available=True
if available==False:
print('Entered value is not available')
|
716edbaef1bdda0e1854caaf7d40f39ff9e4a4b0 | daniel-reich/ubiquitous-fiesta | /7ECZC8CBEhy5QkvN3_22.py | 145 | 3.671875 | 4 |
def how_many_walls(n, w, h):
area=w*h
if area<n:
walls=n/area
return int(walls)
elif area==n:
return 1
else:
return 0
|
04240f49d75821619da4313f15ec304866baeb90 | obawany/hackathon-uOttawa-CSSA | /NextSequence.py | 3,539 | 3.734375 | 4 | class NextSequence:
# operation = ["*", "+","-","/","^"]
sequence = []
2, 4, 6, 8
def __init__(self):
print("Start")
def ask_sequence(self):
temp = input("Input your sequence, make sure your numbers are split by ',' with no spaces\n")
self.sequence = temp.split(",")
self.sequence = list(map(int, self.sequence))
def is_multiplication(self, c):
multiplyer = c[1] / c[0]
for a in range(1, len(c) - 1):
if multiplyer != c[a + 1] / c[a]:
return [False, False]
return [True,multiplyer]
def is_addition(self, a):
factor = a[1] - a[0]
for b in range(len(a) -1):
if a[b]+factor != a[b+1]:
return [False,False]
return [True , factor]
def pattern_differenceM(self, b):
dif_array = []
for a in range(len(b)-1):
dif_array.append(b[a+1]-b[a])
if self.is_multiplication(dif_array)[0]:
return self.is_multiplication(dif_array)
return False
def addition_prev(self,array):
last_number = 1
current_sum = 0
lastElement = array[len(array)-1]
for i in range(len(array)-2, 0, -1):
current_sum = current_sum + array[i]
if current_sum == lastElement:
second = len(array)-2
temp_sum = 1
for j in range(1,last_number+1):
temp_sum = temp_sum + (array[len(array)-2-j])
if(array[len(array)-2] == temp_sum):
return [True, last_number]
last_number = last_number+1
return[False, False]
def fucked_up_sequence_1(self):
last = self.sequence[len(self.sequence)-1]
second_last = self.sequence[len(self.sequence)-2]
if self.sequence[len(self.sequence)-3] == last / second_last:
if self.sequence[len(self.sequence)-4] == self.sequence[len(self.sequence)-2] / self.sequence[len(self.sequence)-3]:
return True
return False
def pattern_differenceA(self, b):
dif_array = []
for a in range(len(b) - 1):
dif_array.append(b[a + 1] - b[a])
if self.is_addition(dif_array)[0]:
return self.is_addition(dif_array)
return False
def findPattern(self):
half = len(self.sequence)
number = self.sequence[half]
temp1 = self.sequence
temp1.remove(number)
def next_value(self):
if (self.is_multiplication(self.sequence)[0]):
return int(self.sequence[1] / self.sequence[0] * self.sequence[len(self.sequence)-1])
if (self.is_addition(self.sequence)[0]):
return int(self.sequence[1]-self.sequence[0]+ self.sequence[len(self.sequence)-1])
if self.pattern_differenceA(self.sequence):
return int(self.sequence[len(self.sequence)-1] - self.sequence[len(self.sequence)-2])+self.pattern_differenceA(self.sequence)[1] + self.sequence[len(self.sequence) -1 ]
if self.fucked_up_sequence_1():
return int(self.sequence[len(self.sequence)-12]*self.sequence[len(self.sequence)-2])
if self.addition_prev(self.sequence)[0]:
sum = 1;
for i in range (self.addition_prev(self.sequence)[1]):
sum = sum + self.sequence[self.sequence[len(self.sequence)]-i]
return sum
a = NextSequence()
while True:
a.ask_sequence()
print ("The Next Number is : " + str(a.next_value()))
|
b6b8e982709ab893897efa7eef402499c5b598ac | akochetov/maze | /misc/orientation.py | 1,753 | 4.34375 | 4 | class Orientation:
"""
Orientation of maze, car etc. Means west, east, south and north.
To be replaced with angle against north in the future
"""
def __init__(self):
"""
Dummy init to eliminate warnings
"""
pass
WEST = 'WEST'
EAST = 'EAST'
SOUTH = 'SOUTH'
NORTH = 'NORTH'
# list used to change orientation by changing list index -1 for counter
# clock wise and +1 for clock wise rotations
rotation = [NORTH, EAST, SOUTH, WEST]
@staticmethod
def rotate(initial_orientation, cw):
"""
Static method. Changes orientation
:param initial_orientation: Orientation which has to be changed
:param cw: ClockWise. True or False. In case of False rotates counter
clock wise
:return: new orientation after rotation of initial_orientation
"""
index = Orientation.rotation.index(initial_orientation)
index = index + 1 if cw else index - 1
if index >= len(Orientation.rotation):
index = 0
if index < 0:
index = len(Orientation.rotation) - 1
return Orientation.rotation[index]
@staticmethod
def rotate_cw(initial_orientation):
"""
Rotate clock wise
"""
return Orientation.rotate(initial_orientation, True)
@staticmethod
def rotate_ccw(initial_orientation):
"""
Rotate counter clock wise
"""
return Orientation.rotate(initial_orientation, False)
@staticmethod
def flip(initial_orientation):
"""
Rotate 180 degrees
"""
return Orientation.rotate(
Orientation.rotate(initial_orientation, False),
False
)
|
6d8ff57c5bf8f96e7e88eb2c5cddecb93352b078 | Vexild/python---simple-bank-account-manager | /python2.py | 918 | 3.890625 | 4 | #luodaan lista tilitapahtumista
tilitapahtumat = []
#ja lista sallituista operaattoreista
sallitutOperaattorit = set(['o','p','O','P'])
def Task2Function():
saldo = 0
while True:
userInput = input("Anna toiminto: ")
toimitus = userInput[0:1]
summa = userInput[1:]
print("Antamasi toiminto: "+toimitus + " "+ summa)
if toimitus in sallitutOperaattorit:
if toimitus is 'p':
saldo += int(summa)
tilitapahtumat.append(str(toimitus)+" "+str(summa))
if toimitus is 'o':
saldo -= int(summa)
tilitapahtumat.append(str(toimitus)+" "+str(summa))
else:
print("Antamasi toiminto on virheellinen")
print("Saldo: "+str(saldo)+"\nTilitapahtumat: "+str(tilitapahtumat))
print("\n***********************************\n")
if __name__== "__main__":
Task2Function()
|
951d0fa87641f3b6365238b7dad5d6f118a7bcba | packetscaper/algos | /linkedlist.py | 2,038 | 3.921875 | 4 |
class Node():
def __init__(self,data=None,next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self,new_next):
self.next_node = new_next
class LinkedList():
def __init__(self,array=None,head=None):
self.head = head
if array != None:
for i in array:
self.insert_end(i)
def insert_beginning(self,data):
new_node = Node(data)
new_node.set_next(self.head)
self.head = new_node
def insert_end(self,data):
new_node = Node(data)
current = self.head
if self.head == None :
self.head = new_node
else :
while (current.get_next() != None ):
current = current.get_next()
current.set_next(new_node)
def print_list(self):
current = self.head
list = 'head--->'
while (current != None):
list = list+ str(current.get_data()) + '--->'
current = current.get_next()
print list + 'null'
def reverse_list(self):
new_head = self.head
old_head = self.head.get_next()
new_head.set_next(None)
current = old_head
while current!= None :
current = current.get_next()
old_head.set_next(new_head)
new_head = old_head
old_head = current
self.head = new_head
def get_count(self):
current = self.head
count = 0
while (current != None):
count = count + 1
current = current.get_next()
return count
def get_nth_from_last(self,n):
slow = self.head
fast = self.head
for i in range(1,n):
fast = fast.get_next()
while (fast.get_next()!=None):
fast = fast.get_next()
slow = slow.get_next()
return slow.get_data()
|
2363ebb4d0cb3b6ffd45f838b4e077ae8472efba | WildDogOdyssey/bitesofpy | /49/packt.py | 1,102 | 3.578125 | 4 | from collections import namedtuple
from bs4 import BeautifulSoup as Soup
import requests
PACKT = 'https://bites-data.s3.us-east-2.amazonaws.com/packt.html'
CONTENT = requests.get(PACKT).text
# =============================================================================
# with open('packet.html', 'r') as r:
# CONTENT = r.read()
# =============================================================================
Book = namedtuple('Book', 'title description image link')
def get_book():
"""make a Soup object, parse the relevant html sections, and return a Book namedtuple"""
soup = Soup(CONTENT, 'html.parser')
deal_section = soup.find(id="deal-of-the-day")
summary = deal_section.find(class_='dotd-main-book-summary float-left')
title = summary.find('h2').string.strip()
description = summary.find_all('div')[2].string.strip()
image = deal_section.find('img').get('src') #image
link = deal_section.find('a').get('href')
return Book(title=title, description=description, image=image, link=link)
print(get_book()) |
0d8d92882f5ae73c5e0331d4909fc18495c4e7eb | vsdrun/lc_public | /co_linkedin/68_Text_Justification.py | 3,757 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/text-justification/description/
Given an array of words and a length L,
format the text such that each line has exactly L
characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is,
pack as many words as you can in each line.
Pad extra spaces ' ' when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible.
If the number of spaces on a line do not divide evenly between words,
the empty slots on the left will be assigned more spaces than
the slots on the right.
For the last line of text,
it should be left justified and no extra space is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
[
"This is an",
"example of text",
"justification. "
]
"""
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
res = []
cur = [] # 此行目前獨立含的words
num_of_letters = 0 # 目前此行的 letters count
for w in words:
# 如果 此行的letters + 目前加入的word + words 之間至少一個空白.
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
# 使用餘數定理將空白平均(以最左邊為最多) 加到此行
# 的words 最後...
cur[i % (
len(cur) - 1 or # 注意!! 若只有兩字 則空白全在兩字之間
1)
] += ' '
res.append(''.join(cur))
# 此行已滿,清掉換下一行...
cur = []
num_of_letters = 0
# 新的一行
cur += [w] # 目前有那些獨立的words
num_of_letters += len(w)
# 注意!!! 使用ljust~
return res + [' '.join(cur).ljust(maxWidth)]
def rewrite(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
this_line = [] # 此行目前獨立含的words
this_line_word_cnt = 0 # 目前此行的 letters count
result = []
for w in words:
# 此行目前的字母的個數 + 以字數來算的區間空白 + 目前此字字數
if this_line_word_cnt + len(this_line) + len(w) > maxWidth:
for i in range(maxWidth - this_line_word_cnt):
# 使用餘數定理將空白平均(以最左邊為最多) 加到此行
# 的words 最後...
this_line[
i % (len(this_line) - 1 or 1)] += ' '
result.append(''.join(this_line))
# 此行已滿,清掉換下一行...
this_line = []
this_line_word_cnt = 0
this_line.append(w)
this_line_word_cnt += len(w)
# ljust(...)
# S.ljust(width[, fillchar]) -> string
# Return S left-justified in a string of length width. Padding is
# done using the specified fill character (default is a space).
# 注意!!! 使用ljust~
return result + [' '.join(this_line).ljust(maxWidth)]
def build():
return ["This", "is", "an", "example", "of", "text", "justification."], 16
if __name__ == "__main__":
s = Solution()
print(s.fullJustify(*build()))
print(s.rewrite(*build()))
|
3518cdb1dfc46e9248e59481d60bffa9e0ffcd9d | renu0028/PythonScripts | /upper.py | 137 | 3.75 | 4 | l=[]
print("Enter multiple lines: ")
while True:
line=input()
if line:
l.append(line)
else:
break
s="\n".join(l)
print(s.upper())
|
c69d8515bc4054873d41bfb1158909295d68168e | shangxiwu/services | /Module_10_DNN神經網路介紹/corelab_10.2_sol.py | 561 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # MNIST資料集的操作
# In[1]:
from tensorflow.examples.tutorials.mnist import input_data
# ## 請將MNIST資料集讀取進來,取出第一筆資料印出,並以簡單判斷式判斷該資料為哪個數字
# In[2]:
# Load mnist dataset
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
batch_xs, batch_ys = mnist.train.next_batch(1)
print(batch_ys)
num = 0
for i in batch_ys[0]:
if i != 1:
num += 1
else:
print("Number is: %d" % num)
break
# In[ ]:
|
00928bceaabe5fd4ebc691b89ef4e60bf114fbb4 | jekhokie/scriptbox | /python--learnings/coding-practice/key_with_max_dict_value.py | 367 | 4.1875 | 4 | #!/usr/bin/env python
#
# Find and print the dictionary key with the maximum same value.
#
def largest_value(my_dict):
print(max(my_dict.items(), key=lambda x: x[1])[0])
if __name__ == '__main__':
print("Should print: {}".format(1))
largest_value({1: 5, 2: 3, 3: 2})
print("Should print: {}".format(6))
largest_value({2: 1, 3: 2, 6: 15, 9: 7})
|
4d4ca4f3fa3e7bdcb90386245e60be758249f97e | srdoty/crypto-hw11 | /represent.py | 1,700 | 4.28125 | 4 | # Convert strings to integer representations and back again to
# strings. This is needed for implementing all public-key
# cryptosystems, which assume the plaintext is representated by
# some integer.
URADIX = 1114112 # The unicode upper range limit (CONSTANT)
def rep(string):
"""returns an integer representation of the input string string"""
k = 0; num = 0
for char in string:
num = num + ord(char) * URADIX**k
k = k+1
return num
def unrep(num):
"""returns the string that the input num represents"""
output = '' # empty string to start
q = num
while q > 0:
q,r = divmod(q,URADIX)
output = output + chr(r)
return output
# The above functions are inverses of one another, in the sense
# that
#
# unrep(rep(s)) == s
#
# returns True for any input string s of any length.
# Sometimes we have a restriction on the length of the input strings,
# called its blocksize (call it B for short). In that case, we convert
# each B characters of the string to its integer representation and
# return a list of the resulting integers. This leads to
def replist(str,blocksize):
"""returns a list of integer representations of blocks of
length given by the blocksize"""
B = blocksize
return [rep(str[i:i+B]) for i in range(0, len(str), B)]
def unreplist(lst):
"""returns the string that produced lst as its replist"""
out = '' # empty string to start
for item in lst:
out = out + unrep(item)
return out
# The above functions are inverses of one another, in the sense
# that
#
# unreplist(replist(s,B)) == s
#
# returns True for any input string s of any length, for a given
# blocksize B.
|
d2d4b26bad7a7c6a0e633b3d6dac0c5e6a9ee113 | suprajaarthi/Favourite-Snippets | /order of occurence.py | 411 | 3.59375 | 4 | def isSubSequence(str1,str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j<m and i<n:
if str1[j] == str2[i]:
j = j+1
i = i + 1
else:
i = i + 1
return j==m
# Driver Program
str1 = "skillrack"
str2 = "superkoolfillerack"
if isSubSequence(str1,str2) :
print("Yes")
else:
print("No")
|
b10619b16b03c0b849be4a232e8ae01184564f47 | Morael/CoffeeMachine | /Coffee Machine/task/machine/coffee_machine.py | 5,570 | 3.890625 | 4 | class CoffeeMachine:
def __init__(self):
self.machine_has = {"water": 400, "milk": 540, "coffee beans": 120, "disposable cups": 9, "money": 550}
self.espresso_needs = {"water": 250, "milk": 0, "coffee beans": 16, "disposable cup": 1, "cost": 4}
self.latte_needs = {"water": 350, "milk": 75, "coffee beans": 20, "disposable cup": 1, "cost": 7}
self.cappuccino_needs = {"water": 200, "milk": 100, "coffee beans": 12, "disposable cup": 1, "cost": 6}
self.action_choice()
def user_input(self):
user_input = input()
return user_input
def display_machine_content(self):
print(f"The coffee machine has: \n"
f"{str(self.machine_has['water'])} of water\n"
f"{str(self.machine_has['milk'])} of milk\n"
f"{str(self.machine_has['coffee beans'])} of coffee beans\n"
f"{str(self.machine_has['disposable cups'])} of disposable cups\n"
f"${str(self.machine_has['money'])} of money")
self.action_choice()
def action_choice(self):
print("\nWrite action (buy, fill, take, remaining, exit):")
action = str(input())
print("")
if action == "buy":
self.buy_menu()
elif action == "fill":
self.fill_machine()
elif action == "take":
self.take_money()
elif action == "remaining":
self.display_machine_content()
elif action == "exit":
global TURN_ON
TURN_ON = False
else:
print("Unrecognized command. Try again.")
self.action_choice()
def buy_menu(self):
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
choice = self.user_input()
if choice == "1":
if self.check_availability(choice):
self.machine_has["water"] -= self.espresso_needs["water"]
self.machine_has["milk"] -= self.espresso_needs["milk"]
self.machine_has["coffee beans"] -= self.espresso_needs["coffee beans"]
self.machine_has["disposable cups"] -= self.espresso_needs["disposable cup"]
self.machine_has["money"] += self.espresso_needs["cost"]
print("I have enough resources, making you a coffee!")
self.action_choice()
else:
print("Sorry, not enough water!\n")
elif choice == "2":
if self.check_availability(choice):
self.machine_has["water"] -= self.latte_needs["water"]
self.machine_has["milk"] -= self.latte_needs["milk"]
self.machine_has["coffee beans"] -= self.latte_needs["coffee beans"]
self.machine_has["disposable cups"] -= self.latte_needs["disposable cup"]
self.machine_has["money"] += self.latte_needs["cost"]
print("I have enough resources, making you a coffee!")
self.action_choice()
else:
print("Sorry, not enough water!\n")
self.action_choice()
elif choice == "3":
if self.check_availability(choice):
self.machine_has["water"] -= self.cappuccino_needs["water"]
self.machine_has["milk"] -= self.cappuccino_needs["milk"]
self.machine_has["coffee beans"] -= self.cappuccino_needs["coffee beans"]
self.machine_has["disposable cups"] -= self.cappuccino_needs["disposable cup"]
self.machine_has["money"] += self.cappuccino_needs["cost"]
print("I have enough resources, making you a coffee!")
self.action_choice()
else:
print("Sorry, not enough water!")
self.action_choice()
else:
print("Unrecognized command. Try again.")
self.action_choice()
def check_availability(self, choice):
if choice == "1":
for i in self.machine_has:
if self.machine_has[i] >= self.espresso_needs[i]:
return True
else:
return False
if choice == "2":
for i in self.machine_has:
if self.machine_has[i] >= self.latte_needs[i]:
return True
else:
return False
if choice == "3":
for i in self.machine_has:
if self.machine_has[i] >= self.latte_needs[i]:
return True
else:
return False
def fill_machine(self):
print("Write how many ml of water do you want to add:")
add_water = abs(int(self.user_input()))
self.machine_has["water"] += add_water
print("Write how many ml of milk do you want to add:")
add_milk = abs(int(self.user_input()))
self.machine_has["milk"] += add_milk
print("Write how many grams of coffee beans do you want to add:")
add_coffee_bns = abs(int(self.user_input()))
self.machine_has["coffee beans"] += add_coffee_bns
print("Write how many disposable cups do you want to add:")
add_cups = abs(int(self.user_input()))
self.machine_has["disposable cups"] += add_cups
self.action_choice()
def take_money(self):
print("I gave you $" + str(self.machine_has["money"]))
self.machine_has["money"] = 0
self.action_choice()
TURN_ON = True
while TURN_ON:
take = CoffeeMachine()
|
9807e8b9fcfc63246f1d287d6d5a6dd48efe3a91 | PacktPublishing/Mastering-Object-Oriented-Python-Second-Edition | /Chapter_10/ch10_ex1.py | 23,807 | 3.859375 | 4 | #!/usr/bin/env python3.7
"""
Mastering Object-Oriented Python 2e
Code Examples for Mastering Object-Oriented Python 2nd Edition
Chapter 10. Example 1. JSON
"""
# Persistence Classes
# ========================================
# A detail class for micro-blog posts
from typing import List, Optional, Dict, Any, DefaultDict, Union, Type
from pathlib import Path
import datetime
from dataclasses import dataclass
# Technically, this is the type supported by JSON serailization.
# JSON = Union[Dict[str, 'JSON'], List['JSON'], int, str, float, bool, Type[None]]
JSON = Union[Dict[str, Any], List[Any], int, str, float, bool, Type[None]]
@dataclass
class Post:
date: datetime.datetime
title: str
rst_text: str
tags: List[str]
def as_dict(self) -> Dict[str, Any]:
return dict(
date=str(self.date),
title=self.title,
underline="-" * len(self.title),
rst_text=self.rst_text,
tag_text=" ".join(self.tags),
)
# Here's a collection of these posts. This is an extension
# of list which doesn't work well with JSON.
from collections import defaultdict
class Blog_x(list):
def __init__(self, title: str, posts: Optional[List[Post]]=None) -> None:
self.title = title
super().__init__(posts if posts is not None else [])
def by_tag(self) -> DefaultDict[str, List[Dict[str, Any]]]:
tag_index: DefaultDict[str, List[Dict[str, Any]]] = defaultdict(list)
for post in self:
for tag in post.tags:
tag_index[tag].append(post.as_dict())
return tag_index
def as_dict(self) -> Dict[str, Any]:
return dict(
title=self.title,
entries=[p.as_dict() for p in self]
)
# An example blog
travel_x = Blog_x("Travel")
travel_x.append(
Post(
date=datetime.datetime(2013, 11, 14, 17, 25),
title="Hard Aground",
rst_text="""Some embarrassing revelation. Including ☹ and ⚓""",
tags=["#RedRanger", "#Whitby42", "#ICW"],
)
)
travel_x.append(
Post(
date=datetime.datetime(2013, 11, 18, 15, 30),
title="Anchor Follies",
rst_text="""Some witty epigram. Including < & > characters.""",
tags=["#RedRanger", "#Whitby42", "#Mistakes"],
)
)
# JSON
# ================================
# Example 1: Simple
# ####################
# Simple JSON dump
import json
test_json_1 = """
>>> print(json.dumps(travel_x.as_dict(), indent=4))
{
"title": "Travel",
"entries": [
{
"date": "2013-11-14 17:25:00",
"title": "Hard Aground",
"underline": "------------",
"rst_text": "Some embarrassing revelation. Including \u2639 and \u2693",
"tag_text": "#RedRanger #Whitby42 #ICW"
},
{
"date": "2013-11-18 15:30:00",
"title": "Anchor Follies",
"underline": "--------------",
"rst_text": "Some witty epigram. Including < & > characters.",
"tag_text": "#RedRanger #Whitby42 #Mistakes"
}
]
}
"""
# Example 2. JSON: Flawed Container Design
# ########################################
# Flawed Encoder based on flawed design of the class.
def blogx_encode(object: Any) -> Dict[str, Any]:
if isinstance(object, datetime.datetime):
return dict(
__class__="datetime.datetime",
__args__=[],
__kw__=dict(
year=object.year,
month=object.month,
day=object.day,
hour=object.hour,
minute=object.minute,
second=object.second,
),
)
elif isinstance(object, Post):
return dict(
__class__="Post",
__args__=[],
__kw__=dict(
date=object.date,
title=object.title,
rst_text=object.rst_text,
tags=object.tags,
),
)
elif isinstance(object, Blog_x):
# Will get ignored...
return dict(
__class__="Blog_x",
__args__=[],
__kw__=dict(title=object.title, entries=tuple(object)),
)
else:
return object
def blogx_decode(some_dict: Dict[str, Any]) -> Dict[str, Any]:
if set(some_dict.keys()) == set(["__class__", "__args__", "__kw__"]):
class_ = eval(some_dict["__class__"])
return class_(*some_dict["__args__"], **some_dict["__kw__"])
else:
return some_dict
test_json_2 = """
>>> text = json.dumps(travel_x, indent=4, default=blogx_encode)
>>> print(text)
[
{
"__class__": "Post",
"__args__": [],
"__kw__": {
"date": {
"__class__": "datetime.datetime",
"__args__": [],
"__kw__": {
"year": 2013,
"month": 11,
"day": 14,
"hour": 17,
"minute": 25,
"second": 0
}
},
"title": "Hard Aground",
"rst_text": "Some embarrassing revelation. Including \u2639 and \u2693",
"tags": [
"#RedRanger",
"#Whitby42",
"#ICW"
]
}
},
{
"__class__": "Post",
"__args__": [],
"__kw__": {
"date": {
"__class__": "datetime.datetime",
"__args__": [],
"__kw__": {
"year": 2013,
"month": 11,
"day": 18,
"hour": 15,
"minute": 30,
"second": 0
}
},
"title": "Anchor Follies",
"rst_text": "Some witty epigram. Including < & > characters.",
"tags": [
"#RedRanger",
"#Whitby42",
"#Mistakes"
]
}
}
]
The Blog structure overall? Vanished. It's only a list
>>> from pprint import pprint
>>> copy = json.loads(text, object_hook=blogx_decode)
>>> pprint(copy)
[Post(date=datetime.datetime(2013, 11, 14, 17, 25), title='Hard Aground', rst_text='Some embarrassing revelation. Including ☹ and ⚓', tags=['#RedRanger', '#Whitby42', '#ICW']),
Post(date=datetime.datetime(2013, 11, 18, 15, 30), title='Anchor Follies', rst_text='Some witty epigram. Including < & > characters.', tags=['#RedRanger', '#Whitby42', '#Mistakes'])]
"""
# Example 3 JSON: Better Design
# ###############################
# Consider this wrap-based design instead of an extension-based version
# Here's another collection of these posts.
# This wraps a list which works much better with JSON than extending a list.
import datetime
from collections import defaultdict
class Blog:
def __init__(self, title: str, posts: Optional[List[Post]]=None) -> None:
self.title = title
self.entries = posts if posts is not None else []
@property
def underline(self) -> str:
return '='*len(self.title)
def append(self, post: Post) -> None:
self.entries.append(post)
def by_tag(self) -> Dict[str, List[Dict[str, Any]]]:
tag_index: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
for post in self.entries:
for tag in post.tags:
tag_index[tag].append(post.as_dict())
return tag_index
def as_dict(self) -> Dict[str, Any]:
return dict(
title=self.title,
underline=self.underline,
entries=[p.as_dict() for p in self.entries],
)
# An example blog
travel = Blog("Travel")
travel.append(
Post(
date=datetime.datetime(2013, 11, 14, 17, 25),
title="Hard Aground",
rst_text="""Some embarrassing revelation. Including ☹ and ⚓︎""",
tags=["#RedRanger", "#Whitby42", "#ICW"],
)
)
travel.append(
Post(
date=datetime.datetime(2013, 11, 18, 15, 30),
title="Anchor Follies",
rst_text="""Some witty epigram. Including < & > characters.""",
tags=["#RedRanger", "#Whitby42", "#Mistakes"],
)
)
def blog_encode(object: Any) -> Dict[str, Any]:
if isinstance(object, datetime.datetime):
return dict(
__class__="datetime.datetime",
__args__=[],
__kw__=dict(
year=object.year,
month=object.month,
day=object.day,
hour=object.hour,
minute=object.minute,
second=object.second,
),
)
elif isinstance(object, Post):
return dict(
__class__="Post",
__args__=[],
__kw__=dict(
date=object.date,
title=object.title,
rst_text=object.rst_text,
tags=object.tags,
),
)
elif isinstance(object, Blog):
return dict(
__class__="Blog", __args__=[object.title, object.entries], __kw__={}
)
else:
return object
def blog_decode(some_dict: Dict[str, Any]) -> Dict[str, Any]:
if set(some_dict.keys()) == {"__class__", "__args__", "__kw__"}:
class_ = eval(some_dict["__class__"])
return class_(*some_dict["__args__"], **some_dict["__kw__"])
else:
return some_dict
test_json_3 = """
>>> text = json.dumps(travel, indent=4, default=blog_encode)
>>> print(text)
{
"__class__": "Blog",
"__args__": [
"Travel",
[
{
"__class__": "Post",
"__args__": [],
"__kw__": {
"date": {
"__class__": "datetime.datetime",
"__args__": [],
"__kw__": {
"year": 2013,
"month": 11,
"day": 14,
"hour": 17,
"minute": 25,
"second": 0
}
},
"title": "Hard Aground",
"rst_text": "Some embarrassing revelation. Including \u2639 and \u2693\ufe0e",
"tags": [
"#RedRanger",
"#Whitby42",
"#ICW"
]
}
},
{
"__class__": "Post",
"__args__": [],
"__kw__": {
"date": {
"__class__": "datetime.datetime",
"__args__": [],
"__kw__": {
"year": 2013,
"month": 11,
"day": 18,
"hour": 15,
"minute": 30,
"second": 0
}
},
"title": "Anchor Follies",
"rst_text": "Some witty epigram. Including < & > characters.",
"tags": [
"#RedRanger",
"#Whitby42",
"#Mistakes"
]
}
}
]
],
"__kw__": {}
}
>>> from pprint import pprint
>>> copy = json.loads(text, object_hook=blog_decode)
>>> print(copy.title)
Travel
>>> pprint(copy.entries)
[Post(date=datetime.datetime(2013, 11, 14, 17, 25), title='Hard Aground', rst_text='Some embarrassing revelation. Including ☹ and ⚓︎', tags=['#RedRanger', '#Whitby42', '#ICW']),
Post(date=datetime.datetime(2013, 11, 18, 15, 30), title='Anchor Follies', rst_text='Some witty epigram. Including < & > characters.', tags=['#RedRanger', '#Whitby42', '#Mistakes'])]
"""
# Sidebar: Demo of rendering 1
# ###############################
# Here's a template for an individual post
import string
# Here's a way to render the entire blog in RST
def rst_render(blog: Blog) -> None:
post = string.Template(
"""
$title
$underline
$rst_text
:date: $date
:tags: $tag_text
"""
)
# with contextlib.redirect_stdout("some_file"):
print(f"{blog.title}\n{blog.underline}\n")
for p in blog.entries:
print(post.substitute(**p.as_dict()))
tag_index = blog.by_tag()
print("Tag Index")
print("=========")
print()
for tag in tag_index:
print(f"* {tag}")
print()
for post_dict in tag_index[tag]:
print(f" - `{post_dict['title']}`_")
print()
test_string_template_render = """
>>> rst_render(travel)
Travel
======
<BLANKLINE>
<BLANKLINE>
Hard Aground
------------
<BLANKLINE>
Some embarrassing revelation. Including ☹ and ⚓︎
<BLANKLINE>
:date: 2013-11-14 17:25:00
<BLANKLINE>
:tags: #RedRanger #Whitby42 #ICW
<BLANKLINE>
<BLANKLINE>
Anchor Follies
--------------
<BLANKLINE>
Some witty epigram. Including < & > characters.
<BLANKLINE>
:date: 2013-11-18 15:30:00
<BLANKLINE>
:tags: #RedRanger #Whitby42 #Mistakes
<BLANKLINE>
Tag Index
=========
<BLANKLINE>
* #RedRanger
<BLANKLINE>
- `Hard Aground`_
- `Anchor Follies`_
<BLANKLINE>
* #Whitby42
<BLANKLINE>
- `Hard Aground`_
- `Anchor Follies`_
<BLANKLINE>
* #ICW
<BLANKLINE>
- `Hard Aground`_
<BLANKLINE>
* #Mistakes
<BLANKLINE>
- `Anchor Follies`_
<BLANKLINE>
"""
# Sidebar: Demo of rendering 2 (using Jinja2)
# ############################################
from jinja2 import Template
blog_template = Template(
"""{{title}}
{{underline}}
{% for e in entries %}
{{e.title}}
{{e.underline}}
{{e.rst_text}}
:date: {{e.date}}
:tags: {{e.tag_text}}
{% endfor %}
Tag Index
=========
{% for t in tags %}
* {{t}}
{% for post in tags[t] %}
- `{{post.title}}`_
{%- endfor %}
{% endfor %}
"""
)
test_jinja_temple_render = """
>>> print(blog_template.render(tags=travel.by_tag(), **travel.as_dict()))
Travel
======
<BLANKLINE>
<BLANKLINE>
Hard Aground
------------
<BLANKLINE>
Some embarrassing revelation. Including ☹ and ⚓︎
<BLANKLINE>
:date: 2013-11-14 17:25:00
<BLANKLINE>
:tags: #RedRanger #Whitby42 #ICW
<BLANKLINE>
<BLANKLINE>
Anchor Follies
--------------
<BLANKLINE>
Some witty epigram. Including < & > characters.
<BLANKLINE>
:date: 2013-11-18 15:30:00
<BLANKLINE>
:tags: #RedRanger #Whitby42 #Mistakes
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
Tag Index
=========
<BLANKLINE>
* #RedRanger
<BLANKLINE>
- `Hard Aground`_
- `Anchor Follies`_
<BLANKLINE>
* #Whitby42
<BLANKLINE>
- `Hard Aground`_
- `Anchor Follies`_
<BLANKLINE>
* #ICW
<BLANKLINE>
- `Hard Aground`_
<BLANKLINE>
* #Mistakes
<BLANKLINE>
- `Anchor Follies`_
<BLANKLINE>
"""
# Example 4. JSON: Refactoring Encoding
# ######################################
# Changes to the class definitions to add a ``_json`` method.
class Post_J(Post):
"""Not really essential to inherit from Post, it's simply a dataclass."""
@property
def _json(self) -> Dict[str, Any]:
return dict(
__class__=self.__class__.__name__,
__kw__=dict(
date=self.date, title=self.title, rst_text=self.rst_text, tags=self.tags
),
__args__=[],
)
class Blog_J(Blog):
"""Note. No explicit reference to Blog_J for entries."""
@property
def _json(self) -> Dict[str, Any]:
return dict(
__class__=self.__class__.__name__,
__kw__={},
__args__=[self.title, self.entries],
)
def blog_j_encode(object: Union[Blog_J, Post_J, Any]) -> Dict[str, Any]:
if isinstance(object, datetime.datetime):
return dict(
__class__="datetime.datetime",
__args__=[],
__kw__=dict(
year=object.year,
month=object.month,
day=object.day,
hour=object.hour,
minute=object.minute,
second=object.second,
),
)
else:
try:
encoding = object._json
except AttributeError:
encoding = json.JSONEncoder().default(object)
return encoding
travel3 = Blog_J("Travel")
travel3.append(
Post_J(
date=datetime.datetime(2013, 11, 14, 17, 25),
title="Hard Aground",
rst_text="""Some embarrassing revelation. Including ☹ and ⚓""",
tags=["#RedRanger", "#Whitby42", "#ICW"],
)
)
travel3.append(
Post_J(
date=datetime.datetime(2013, 11, 18, 15, 30),
title="Anchor Follies",
rst_text="""Some witty epigram.""",
tags=["#RedRanger", "#Whitby42", "#Mistakes"],
)
)
test_json_4 = """
>>> text = json.dumps(travel3, indent=4, default=blog_j_encode)
>>> print(text)
{
"__class__": "Blog_J",
"__kw__": {},
"__args__": [
"Travel",
[
{
"__class__": "Post_J",
"__kw__": {
"date": {
"__class__": "datetime.datetime",
"__args__": [],
"__kw__": {
"year": 2013,
"month": 11,
"day": 14,
"hour": 17,
"minute": 25,
"second": 0
}
},
"title": "Hard Aground",
"rst_text": "Some embarrassing revelation. Including \u2639 and \u2693",
"tags": [
"#RedRanger",
"#Whitby42",
"#ICW"
]
},
"__args__": []
},
{
"__class__": "Post_J",
"__kw__": {
"date": {
"__class__": "datetime.datetime",
"__args__": [],
"__kw__": {
"year": 2013,
"month": 11,
"day": 18,
"hour": 15,
"minute": 30,
"second": 0
}
},
"title": "Anchor Follies",
"rst_text": "Some witty epigram.",
"tags": [
"#RedRanger",
"#Whitby42",
"#Mistakes"
]
},
"__args__": []
}
]
]
}
"""
# Example 5: JSON: Super-Flexible Date Encoding
# #############################################
# Right at the edge of the envelope for dates. This may be too much flexibility.
# There's an ISO standard for dates, and using it is simpler.
# For other unique data objects, however, this kind of pattern may be helpful
# for providing a way to parse complex strings.
# Changes to the class definitions
def blog_j2_encode(object: Union[Blog_J, Post_J, Any]) -> Dict[str, Any]:
if isinstance(object, datetime.datetime):
return dict(
__class__="datetime.datetime.strptime",
__args__=[object.strftime("%Y-%m-%dT%H:%M:%S"), "%Y-%m-%dT%H:%M:%S"],
__kw__={},
)
else:
try:
encoding = object._json
except AttributeError:
encoding = json.JSONEncoder().default(object)
return encoding
test_json_5 = """
>>> text = json.dumps(travel3, indent=4, default=blog_j2_encode)
>>> print(text)
{
"__class__": "Blog_J",
"__kw__": {},
"__args__": [
"Travel",
[
{
"__class__": "Post_J",
"__kw__": {
"date": {
"__class__": "datetime.datetime.strptime",
"__args__": [
"2013-11-14T17:25:00",
"%Y-%m-%dT%H:%M:%S"
],
"__kw__": {}
},
"title": "Hard Aground",
"rst_text": "Some embarrassing revelation. Including \u2639 and \u2693",
"tags": [
"#RedRanger",
"#Whitby42",
"#ICW"
]
},
"__args__": []
},
{
"__class__": "Post_J",
"__kw__": {
"date": {
"__class__": "datetime.datetime.strptime",
"__args__": [
"2013-11-18T15:30:00",
"%Y-%m-%dT%H:%M:%S"
],
"__kw__": {}
},
"title": "Anchor Follies",
"rst_text": "Some witty epigram.",
"tags": [
"#RedRanger",
"#Whitby42",
"#Mistakes"
]
},
"__args__": []
}
]
]
}
>>> from pprint import pprint
>>> copy = json.loads(text, object_hook=blog_decode)
>>> print(copy.title)
Travel
>>> pprint(copy.entries)
[Post_J(date=datetime.datetime(2013, 11, 14, 17, 25), title='Hard Aground', rst_text='Some embarrassing revelation. Including ☹ and ⚓', tags=['#RedRanger', '#Whitby42', '#ICW']),
Post_J(date=datetime.datetime(2013, 11, 18, 15, 30), title='Anchor Follies', rst_text='Some witty epigram.', tags=['#RedRanger', '#Whitby42', '#Mistakes'])]
"""
with (Path.cwd()/"data"/"ch10.json").open("w", encoding="UTF-8") as target:
json.dump(travel3, target, separators=(",", ":"), default=blog_j2_encode)
__test__ = {name: value for name, value in locals().items() if name.startswith("test_")}
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=False)
|
da91a0b01674fd79aee23c93acd3e452a3d334d4 | 6306022610113/INEPython | /week3/if_elif3.py | 347 | 4.25 | 4 | inchar = input("Input one character:")
if inchar >= 'A' and inchar <= 'Z':
print("You input Upper case Letter ", inchar)
elif inchar >= 'a' and inchar <= 'z' :
print("You input Lower Case Letter" ,inchar)
elif inchar >= '0' and inchar <= '9':
print("You input Number" ,inchar)
else :
print("It's not a letter or number." , inchar) |
170047a8098af321aba57d75319bdd1524efa6fe | chenliu0831/Hackathon | /mergesortlist.py | 290 | 3.765625 | 4 | def mergeTwosortedlist(l1,l2):
res=[]
i1=0
i2=0
while i1<len(l1) and i2 <len(l2):
if l1[i1] <=l2[i2]:
res.append(l1[i1])
i1+=1
else:
res.append(l2[i2])
i2+=1
while i1<len(l1):
res.append(l1[i1])
i1+=1
while i2<len(l2):
res.append(l2[i2])
i2+=1
return res
|
f49654a90459ad6aafbd485c1c26cd8af9b6390f | gmlwndlaek/p1_201110251 | /w9Main.py | 286 | 3.53125 | 4 | def charCount(word):
w= word
d=dict()
for c in w:
if c not in d:
d[c]=1
else:
d[c]=d[c]+1
print d
def lab9():
charCount('sangmyung')
def main():
lab9()
if __name__=="__main__":
main()
|
8e4465f9254d7febf1990abfb7b4d55a8d76215e | rolika/quipu | /scripts/menu.py | 19,410 | 3.515625 | 4 | from tkinter import *
import szemelyurlap
import szervezeturlap
import projekturlap
import ajanlatkeresurlap
import ajanlaturlap
class Fomenu(Frame):
"""A főmenüből történik az alkalmazás kezelése."""
def __init__(self, master=None, kon=None, **kw) -> Frame:
"""A főmenü saját tkinter.Frame-ben kap helyet.
master: szülő widget
kon: adazbázis konnektorok gyűjtősztálya
**kw: tkinter.Frame tulajdonságát szabályozó értékek"""
super().__init__(master=master, **kw)
# főmenü
## ezek a pontok jelennek meg a főmenü sorában
szemelymb = Menubutton(self, text="Személy", width=10)
szervezetmb = Menubutton(self, text="Szervezet", width=10)
projektmb = Menubutton(self, text="Projekt", width=10)
raktarmb = Menubutton(self, text="Raktár", width=10)
# menük
## ezek keltik életre a főmenüt
szemelymenu = SzemelyMenu(szemelymb, kon)
szervezetmenu = SzervezetMenu(szervezetmb, kon)
projektmenu = ProjektMenu(projektmb, kon)
szemelymb.grid(row=0, column=0, sticky=W, ipadx=2, ipady=2)
szervezetmb.grid(row=0, column=1, sticky=W, ipadx=2, ipady=2)
projektmb.grid(row=0, column=2, sticky=W, ipadx=2, ipady=2)
raktarmb.grid(row=0, column=3, sticky=W, ipadx=2, ipady=2)
self.grid()
class SzemelyMenu(Menu):
"""Személymenü létrehozása és megjelenítése. A tkinter.Menu osztályból származtatva."""
def __init__(self, mb, kon) -> Menu:
"""Személymenü példányosítása.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, tearoff=0)
mb["menu"] = self
self.add("cascade", label="személy", menu=SzemelyAlmenu(mb, kon))
self.add("cascade", label="telefon", menu=SzemelyTelefonAlmenu(mb, kon))
self.add("cascade", label="email", menu=SzemelyEmailAlmenu(mb, kon))
self.add("cascade", label="cím", menu=SzemelyCimAlmenu(mb, kon))
self.add("cascade", label="kontaktszemély", menu=SzemelyKontaktAlmenu(mb, kon))
class SzervezetMenu(Menu):
"""Szervezetmenü létrehozása és megjelenítése. A tkinter.Menu osztályból származtatva."""
def __init__(self, mb, kon) -> Menu:
"""Szervezetmenü példányosítása.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, tearoff=0)
mb["menu"] = self
self.add("cascade", label="szervezet", menu=SzervezetAlmenu(mb, kon))
self.add("cascade", label="telefon", menu=SzervezetTelefonAlmenu(mb, kon))
self.add("cascade", label="email", menu=SzervezetEmailAlmenu(mb, kon))
self.add("cascade", label="cím", menu=SzervezetCimAlmenu(mb, kon))
self.add("cascade", label="kontaktszemély", menu=SzervezetKontaktAlmenu(mb, kon))
class ProjektMenu(Menu):
"""Projektmenü létrehozása és megjelenítése. A tkinter.Menu osztályból származtatva."""
def __init__(self, mb, kon) -> Menu:
"""Projektmenü példányosítása.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, tearoff=0)
mb["menu"] = self
self.add("cascade", label="projekt", menu=ProjektAlmenu(mb, kon))
self.add("cascade", label="ajánlatkérés", menu=AjanlatkeresAlmenu(mb, kon))
self.add("cascade", label="ajánlat", menu=AjanlatAlmenu(mb, kon))
class Alapmenu(Menu):
def __init__(self, mb, kon=None) -> Menu:
"""Minden menüpont alatt elvégezhető parancsok.
mb: tkinter.Menubutton példánya (amolyan szülő widget)"""
super().__init__(mb, tearoff=0)
self._mb = mb
self._kon = kon
self.add("command", label="új", command=self.uj)
self.add("command", label="törlés", command=self.torol)
self.add("command", label="módosítás", command=self.modosit)
def uj(self) -> None:
"""Új csomó létrehozása."""
raise NotImplementedError
def torol(self) -> None:
"""Meglévő csomó törlése."""
raise NotImplementedError
def modosit(self) -> None:
"""Meglévő csomó módosítása."""
raise NotImplementedError
class SzemelyAlmenu(Alapmenu):
"""Személykezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Személykezelő menüpontok élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése új személy létrehozására."""
szemelyurlap.UjSzemelyUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése meglévő személy törlésére."""
szemelyurlap.SzemelyTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése meglévő személy módosítására."""
szemelyurlap.SzemelyModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzemelyTelefonAlmenu(Alapmenu):
"""Személyek telefonos elérhetőségeit kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Személyek telefonkezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése személy új telefonos elérhetőségének létrehozására."""
szemelyurlap.UjTelefonUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése személy meglévő telefonos elérhetőségének törlésére."""
szemelyurlap.TelefonTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése személy meglévő telefonos elérhetőségének módosítására."""
szemelyurlap.TelefonModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzemelyEmailAlmenu(Alapmenu):
"""Személyek email elérhetőségeit kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Személyek emailkezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése személy új email elérhetőségének létrehozására."""
szemelyurlap.UjEmailUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése személy meglévő email elérhetőségének törlésére."""
szemelyurlap.EmailTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése személy meglévő email elérhetőségének módosítására."""
szemelyurlap.EmailModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzemelyCimAlmenu(Alapmenu):
"""Személyek cím elérhetőségeit kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Személyek címkezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése személy új cím elérhetőségének létrehozására."""
szemelyurlap.UjCimUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése személy meglévő cím elérhetőségének törlésére."""
szemelyurlap.CimTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése személy meglévő cím elérhetőségének módosítására."""
szemelyurlap.CimModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzervezetAlmenu(Alapmenu):
"""Szervezetkezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Szervezetkezelő menüpontok élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése új szervezet létrehozására."""
szervezeturlap.UjSzervezetUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése meglévő szervezet törlésére."""
szervezeturlap.SzervezetTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése meglévő szervezet módosítására."""
szervezeturlap.SzervezetModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzervezetTelefonAlmenu(Alapmenu):
"""Szervezetek telefonos elérhetőségeit kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Szervezetek telefonkezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése szervezet új telefonos elérhetőségének létrehozására."""
szervezeturlap.UjTelefonUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése szervezet meglévő telefonos elérhetőségének törlésére."""
szervezeturlap.TelefonTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése szervezet meglévő telefonos elérhetőségének módosítására."""
szervezeturlap.TelefonModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzervezetEmailAlmenu(Alapmenu):
"""Szervezetek email elérhetőségeit kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Szervezetek emailkezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése szervezet új email elérhetőségének létrehozására."""
szervezeturlap.UjEmailUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése szervezet meglévő email elérhetőségének törlésére."""
szervezeturlap.EmailTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése szervezet meglévő email elérhetőségének módosítására."""
szervezeturlap.EmailModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzervezetCimAlmenu(Alapmenu):
"""Szervezetek cím elérhetőségeit kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Szervezetek címkezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése szervezet új cím elérhetőségének létrehozására."""
szervezeturlap.UjCimUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése szervezet meglévő cím elérhetőségének törlésére."""
szervezeturlap.CimTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése szervezet meglévő cím elérhetőségének módosítására."""
szervezeturlap.CimModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class SzervezetKontaktAlmenu(Alapmenu):
"""Szervezet kontaktszemélyeit kezelő almenü."""
def __init__(self, mb, kon) -> Menu:
"""Szervezetek kontaktszemély-kezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése szervezethez új kontaktszemély hozzárendelésére."""
self._kon.szervezet.attach(szemely="szemely.db", kontakt="kontakt.db")
szervezeturlap.UjKontaktUrlap(self._mb.winfo_toplevel(), self._kon)
self._kon.szervezet.detach("szemely", "kontakt")
def torol(self) -> None:
"""Űrlap megjelenítése szervezet meglévő kontaktszemélyének törlésére."""
self._kon.szervezet.attach(szemely="szemely.db", kontakt="kontakt.db")
szervezeturlap.KontaktTorloUrlap(self._mb.winfo_toplevel(), self._kon)
self._kon.szervezet.detach("szemely", "kontakt")
def modosit(self) -> None:
"""Űrlap megjelenítése szervezethez meglévő kontaktszemélyének módosítására."""
self._kon.szervezet.attach(szemely="szemely.db", kontakt="kontakt.db")
szervezeturlap.KontaktModositoUrlap(self._mb.winfo_toplevel(), self._kon)
self._kon.szervezet.detach("szemely", "kontakt")
class SzemelyKontaktAlmenu(Alapmenu):
"""Kontaktszemélyhez rendelt szervezeteket kezelő almenü."""
def __init__(self, mb, kon) -> Menu:
"""Kontaktszemélyhez rendelt szervezetek kezelő menüpontjainak élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése kontaktszemélyhez új szervezet hozzárendelésére."""
self._kon.szemely.attach(szervezet="szervezet.db", kontakt="kontakt.db")
szemelyurlap.UjKontaktUrlap(self._mb.winfo_toplevel(), self._kon)
self._kon.szemely.detach("szervezet", "kontakt")
def torol(self) -> None:
"""Űrlap megjelenítése kontaktszemélyhez rendelt szervezet törlésére."""
self._kon.szemely.attach(szervezet="szervezet.db", kontakt="kontakt.db")
szemelyurlap.KontaktTorloUrlap(self._mb.winfo_toplevel(), self._kon)
self._kon.szemely.detach("szervezet", "kontakt")
def modosit(self) -> None:
"""Űrlap megjelenítése kontaktszemélyhez rendelt szervezet módosítására."""
self._kon.szemely.attach(szervezet="szervezet.db", kontakt="kontakt.db")
szemelyurlap.KontaktModositoUrlap(self._mb.winfo_toplevel(), self._kon)
self._kon.szemely.detach("szervezet", "kontakt")
class ProjektAlmenu(Alapmenu):
"""Projektkezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Projektkezelő menüpontok élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
self.add("cascade", label="munkarész", menu=MunkareszAlmenu(mb, self._kon))
def uj(self) -> None:
"""Űrlap megjelenítése új projekt létrehozására."""
projekturlap.UjProjektUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése meglévő projekt törlésére."""
projekturlap.ProjektTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése meglévő projekt módosítására."""
projekturlap.ProjektModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class MunkareszAlmenu(Alapmenu):
"""Munkarész-kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Munkarész-kezelő menüpontok élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése új munkarész létrehozására."""
projekturlap.UjMunkareszUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése meglévő munkarész törlésére."""
projekturlap.MunkareszTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése meglévő munkarész módosítására."""
projekturlap.MunkareszModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class AjanlatkeresAlmenu(Alapmenu):
"""Ajánlatkérés-kezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Ajánlatkérés-kezelő menüpontok élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése új ajánlatkérés létrehozására."""
self._kon.szervezet.attach(szemely="szemely.db", kontakt="kontakt.db")
ajanlatkeresurlap.UjAjanlatkeresUrlap(self._mb.winfo_toplevel(), self._kon)
self._kon.szervezet.detach("szemely", "kontakt")
def torol(self) -> None:
"""Űrlap megjelenítése meglévő ajánlatkérés törlésére."""
self._kon.szervezet.attach(szemely="szemely.db", kontakt="kontakt.db")
self._kon.projekt.attach(ajanlat="ajanlat.db")
# ha nincs megjeleníthető ajánlatkérés, a hibát itt elkapom
try:
ajanlatkeresurlap.AjanlatkeresTorloUrlap(self._mb.winfo_toplevel(), self._kon)
except AttributeError:
print("Nincs törölhető árajánlatkérés.")
self._kon.szervezet.detach("szemely", "kontakt")
self._kon.projekt.detach("ajanlat")
def modosit(self) -> None:
"""Űrlap megjelenítése meglévő ajánlatkérés módosítására."""
ajanlatkeresurlap.AjanlatkeresModositoUrlap(self._mb.winfo_toplevel(), self._kon)
class AjanlatAlmenu(Alapmenu):
"""Ajánlatkezelő alapmenü."""
def __init__(self, mb, kon) -> Menu:
"""Ajánlatkezelő menüpontok élesítése.
mb: tkinter.Menubutton példánya (amolyan szülő widget)
kon: konnektor.Konnektor adatbázis-gyűjtőkapcsolat"""
super().__init__(mb, kon)
def uj(self) -> None:
"""Űrlap megjelenítése új ajánlat létrehozására."""
ajanlaturlap.UjAjanlatUrlap(self._mb.winfo_toplevel(), self._kon)
def torol(self) -> None:
"""Űrlap megjelenítése meglévő ajánlat törlésére."""
ajanlaturlap.AjanlatTorloUrlap(self._mb.winfo_toplevel(), self._kon)
def modosit(self) -> None:
"""Űrlap megjelenítése meglévő ajánlat módosítására."""
ajanlaturlap.AjanlatModositoUrlap(self._mb.winfo_toplevel(), self._kon)
if __name__ == "__main__":
Fomenu(Tk()).mainloop()
|
54c174d41a205e20c5e428b93234c4bd7e3c2a45 | ahmad-elkhawaldeh/ICS3U-Unit6-03-py | /small.py | 658 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Ahmad
# Created on: Jan 2021
# This program uses an array
from random import randint
def find_smallest(array):
smallest = array[0]
for num in array:
if num < smallest:
smallest = num
return smallest
def main():
array = []
for loop in range(10):
array.append(randint(0, 99))
print("Here is a list of random numbers:")
print("\n")
for loop in range(len(array)):
print("The random number {} is: {}".format(loop + 1, array[loop]))
print("\nThe smallest number is", find_smallest(array))
print("Done.")
if __name__ == "__main__":
main()
|
4683696d065d888e9a452c6340437b43fc71d74b | jz33/LeetCodeSolutions | /T-1055 Shortest Way to Form String.py | 2,160 | 4.0625 | 4 | '''
1055. Shortest Way to Form String
https://leetcode.com/problems/shortest-way-to-form-string/
From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).
Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals
target. If the task is impossible, return -1.
Example 1:
Input: source = "abc", target = "abcbc"
Output: 2
Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".
Example 2:
Input: source = "abc", target = "acdbc"
Output: -1
Explanation: The target string cannot be constructed from the subsequences of source string due to the character "d" in target string.
Example 3:
Input: source = "xyz", target = "xzyxz"
Output: 3
Explanation: The target string can be constructed as follows "xz" + "y" + "xz".
Constraints:
Both the source and target strings consist of only lowercase English letters from "a"-"z".
The lengths of source and target string are between 1 and 1000.
'''
from copy import deepcopy
class Solution:
def shortestWay(self, source: str, target: str) -> int:
'''
O(M+N) method
'''
# Preprocesing: build the index map on source.
# dp[i] is a {char : index} dict where index is the
# closest index of char which appears on i or later than i
sourceSize = len(source)
dp = [None] * sourceSize
dp[-1] = {source[-1] : sourceSize - 1}
for i in range(sourceSize-2, -1, -1):
dp[i] = deepcopy(dp[i+1])
dp[i][source[i]] = i
i = sourceSize # iterater for dp (aka, source)
cycleCount = 0
for t in target:
# No appearance of t in source[i:],
# or i is at sourceSize,
# reset i to 0
if i == sourceSize or t not in dp[i]:
i = 0
cycleCount += 1
togo = dp[i].get(t)
if togo is None:
return -1
i = togo + 1
return cycleCount
|
3b46a3202e489991a16d81f98c329c3e67a6fe45 | gonchigor/ormedia | /lesson5/orange.py | 497 | 3.84375 | 4 | class Orange:
def __init__(self, w, c):
self.weight = w
self.color = c
self.mold = 0
print('Создано')
def rot(self, days, temp):
self.mold = days * temp
or1 = Orange(10, 'dark orange')
print(or1)
or1.weight = 228
or1.color = 'pink orange'
print(or1.weight)
print(or1.color)
or2 = Orange(12, 'black orange')
or3 = Orange(23, 'white orange')
or4 = Orange(5, 'red orange')
orange = Orange(6, 'pickle')
orange.rot(10, 33)
print(orange.mold)
|
84cfd6d481be7f9acd576b6ef9be231aa1cfdf40 | AKHeit/LeetCode | /Algorithms_LinkedLists/Code/143_ReorderList/v0_save0.py | 2,937 | 3.734375 | 4 | """
Problem: 143 Reorder List
Level: Medium
Tags: Linked List
Technique:
Status:
Problem Description:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example: Given {1,2,3,4}, reorder it to {1,4,2,3}
Lesson:
"""
###########################################
#
# LeetCode solution class
#
###########################################
class Solution(object):
def reorderlist():
"""
brute force store pointers in a list
Time (O(n))
Space (O(n))
"""
pointers = []
return []
###########################################
#
# linked list helpers for local testing
#
###########################################
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def addNode_head(node_h, val):
"""
adds node to head
:type node_h: ListNode (original head)
:type val: ListNode (new head)
:rtype : ListNode
:method calls: NONE
"""
nn = ListNode(val)
nn.next = node_h
return nn
def list_tolinkedlist(list):
"""
converts lists to linked lists
use to make easy test code
"""
head = ListNode(None)
tail = head
for v in list:
tail.next = ListNode(v)
tail = tail.next
return head.next
def linkedlist_tolist(linkedlist):
"""
converts linkedlists to lists
"""
list = []
tail = linkedlist
while tail != None:
list.append(tail.val)
tail = tail.next
return list
def print_test(ans_e,ans_o,name):
"""
prints tests in standardized format
:type ans_e: expected answer in printable format
:type ans_o: observed answer in printable format
"""
print('~'*40)
if ans_o != ans_e:
error = 1
print("########## FAIL ##########")
print("TEST: {} :: Status: FAIL".format(name))
else:
error = 0
print("TEST: {} :: Status: PASS".format(name))
print('TEST: {} :: Expected: {}'.format(name, ans_e))
print('TEST: {} :: Observed: {}'.format(name, ans_o))
return error
###########################################
#
# code for local testing
#
###########################################
if __name__== "__main__":
"""
test code
"""
err = 0
# test 0 linked list helpers
name = 'test helpers: list to linkedlist converters'
input = [1,2,3,4]
expected = input
observed = linkedlist_tolist(list_tolinkedlist(input))
err = err + print_test(expected, observed, name)
# test 1 simple even count
name = 'reorderlist: length of four'
input = [1,2,3,4]
# Final pass/fail readout
print('')
if err == 0:
print('PASSED ALL TESTS')
else:
print('FAILED A TEST: DEBUG!!!')
|
15c7cd091e8f9fed767ceb2fabd8fb053a66b85a | tares003/CWVotingSystem | /voting_system/models.py | 4,522 | 3.6875 | 4 | """
class of student
Students eligible to vote are also stored on a simple text file called StudentVoters.txt. The contents of this file are
simply records, on separate lines, each containing the student user login ID and password name and separated by a
single space or comma.
"""
class login_management:
def __init__(self):
self.authenticated = False;
self._login_id = None
# https://flask-login.readthedocs.io/en/latest/#how-it-works Doc
def is_active(self):
"""Returns True as all the users in text file is active"""
return True
def get_id(self):
"""Return the Student id- required by the module"""
return self._login_id
def is_authenticated(self):
"""Return True if the user is authenticated."""
return self.authenticated
def is_anonymous(self):
"""False, as anonymous Student aren't supported."""
return False
class Student(login_management):
def __init__(self, name, login_id, password, dob, faculty, directory_to_user_image=None, has_registered=False):
self.first_name = name.split()[0]
self.middle_name = " ".join(name.split()[1:len(name.split()) - 1]) # gets all the middle names
self.last_name = name.split()[-1]
self._login_id = login_id
self._faculty = faculty
self.email_name = self.first_name[
0] + self.last_name # This property could be used to send out email after vote been casted
self.__pwd = password
self.dob = dob
self.image = directory_to_user_image # directory ref to user img
self.__has_registered = has_registered
# check if user is registered
def is_registered(self):
if self.__has_registered:
print("The student %s %s has registered" % (self.first_name, self.last_name))
return True
else:
print("The student %s %s has not registered" % (self.first_name, self.last_name))
return False
def get_user_id(self):
# return users login id
return self._login_id
@property
def full_name(self):
"""
:return: Full name of that person
"""
return " ".join([self.first_name, self.middle_name, self.last_name])
@full_name.setter
def full_name(self, name):
names = name.split()
self.first_name = names[0]
self.middle_name = " ".join(names[1:len(names) - 1]) # gets all the middle names
self.last_name = names[-1]
def get_user_email(self):
# Return user email
return '{}@gre.ac.uk'.format(self.email_name)
def set_has_registered(self, has_registered):
self.__has_registered = has_registered
def verify_password(self, password):
"""
To verify the users password
:param password:
:return:
"""
if self.__pwd == password:
return True
else:
return False
def get_user_faculty(self):
"""
:return:Returns users faculty
"""
return self._faculty
def __eq__(self, other):
"""
Check weather the other object with similar attributes
"""
if not isinstance(other, Student):
return NotImplemented
return (self.full_name.lower(), self._login_id, self.dob) == (
other.full_name.lower(), other._login_id, other.dob)
def __hash__(self):
"""
Returns hash for this object
"""
return hash((self.full_name, self._login_id, self.dob))
def get_user_ppi_info(self):
"""
Returns user's Full name, dob and loginid
"""
return (self.first_name, self.dob, self._login_id, self._faculty)
class Candidate(Student):
def __init__(self, name, login_id, password, dob, faculty, position, logoref=None, campaign=None, promises=None,
has_registered=False, group=None):
super().__init__(name, login_id, password, dob, faculty, has_registered)
self.position = position
self.campaign_name = campaign # candidates campaigning name
self.campaign_promises = promises
self.logo = logoref
self.group = group
def get_user_ppi_info(self):
"""
Returns user's Full name, dob and loginid
"""
return (self.first_name, self.dob, self._login_id, self._faculty, self.position)
class gsu_officers(Student):
def __init__(self, petitionRunng):
pass
|
9a5c2495e7f7fca9a8d269c97928e98c1f0971ad | HesterHuisman/BasicTrack | /Week 4/4.9/Assignment 4.3.py | 289 | 3.65625 | 4 | import turtle
def draw_poly(t, n, sz):
for _ in range(n):
t.forward(sz)
angle = 360/n
t.left(angle)
paper = turtle.Screen()
paper.bgcolor("lightgreen")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
draw_poly(tess, 8, 50)
paper.mainloop()
|
c0332ac07f302ba921233f2ba5beb0b53dbd4497 | alirezaaali/LearnPyhthon | /Begginer/forLoop_samples.py | 443 | 4.125 | 4 | '''
Here is some useful methods
You can find more information in
https://www.w3schools.com/python/python_for_loops.asp
'''
# Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
# simple
# for x in range(11):
# print(x)
# complex
# for x in range(0, 11, 1):
# print(x)
# Jadval zarb
result = ''
for x in range(11):
for y in range(11):
result = '{0} X {1} = ' + str(x*y)
print(result.format(x, y))
|
c2ee2574cfec20002dffafd8a5bc8f56b8b06381 | goragottsen/python-data-structures | /LinkedList/ll.py | 1,964 | 4.03125 | 4 | class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def getPosition(self, position):
counter = 1
if position < 1:
return None
current = self.head
while current and counter <= position:
if counter == position:
return current
counter += 1
current = current.next
return None
def insertAt(self, new_element, position):
previous = self.getPosition(position - 1)
if position > 1:
new_element.next = previous.next.next
previous.next = new_element
elif position == 1:
new_element = self.head
def delete(self, value):
current = self.head
previous = None
while current.next and current.value != value:
previous = current
current = current.next
if current.value == value:
if previous:
previous.next = current.next
else:
self.head = current.next
# Test the LinkedList implementation
el1 = Element('A')
el2 = Element(10)
el3 = Element(20)
el4 = Element("Hello")
el5 = Element("World")
ll = LinkedList(el1)
ll.append(el2)
ll.append(el3)
# Should print 20
print(ll.head.next.next.value)
# Get position: should print 20
print(ll.getPosition(3).value)
ll.insertAt(el4, 3)
print(ll.getPosition(3).value) # Should print "Hello"
print(ll.getPosition(2).value) # Should print 10
ll.delete(10)
print(ll.getPosition(2).value) # Should print "Hello"
|
b7533f3e162ebae9888ee324398664875d142d75 | amberno1111/Data_Structure_and_Algorithm | /LeetCode/Python/Power_of_Three.py | 425 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# -------------------------------------------------------------------
# 给定一个整数,编写一个函数判断它是否是3的幂
# -------------------------------------------------------------------
import math
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and n == 3 ** round(math.log(n, 3))
|
ca61dcd177b393e04153b09873be709582412a83 | PacktPublishing/big-data-analytics | /Chapter 4/DataSourceJson.py | 662 | 3.515625 | 4 | # Copy input dataset(people.json) to HDFS and then get into PySpark Shell. To read json file, use format to specify the type of datasource.
df_json = spark.read.load("people.json", format="json")
df_json = spark.read.json("people.json")
df_json.printSchema()
df_json.show()
# To write data to another JSON file, use below command.
df_json.write.json("newjson_dir")
df_json.write.format("json").save("newjson_dir2")
# To write data to any other format, just mention format you want to save. Below example saves df_json DataFrame in Parquet format.
df_json.write.parquet("parquet_dir")
df_json.write.format("parquet").save("parquet_dir2")
|
7d1521d75b16224384081722d8ce9f28adbba32c | Pallapupoojitha/guvi | /pooji6.py | 96 | 3.5625 | 4 | N=int(input())
if("n<0" or "n%1!=0"):
print("no")
else:
k=0
while(n!=0):
k=k+n
n=n-1
print("k")
|
a7be2bcd7e84109b50e169d37a42d113298d3f96 | nejads/aoc-2020 | /aoc1.py | 4,045 | 3.8125 | 4 | def getInputAsArray():
input = """1945
2004
1520
1753
1463
1976
1994
1830
1942
1784
1858
1841
1721
1480
1821
1584
978
1530
1278
1827
889
1922
1996
1992
1819
1847
2010
2002
210
1924
1482
1451
1867
1364
1578
1623
1117
1594
1476
1879
1797
1952
2005
1734
1898
1880
1330
1854
1813
1926
1686
1286
1808
1876
1366
1995
1632
1699
2001
1365
1343
1979
1868
1815
820
1966
1888
1916
1852
1932
1368
1606
1825
1731
1980
1990
1818
1702
1419
1897
1970
1276
1914
1889
1953
1588
1958
1310
1391
1326
1131
1959
1844
1307
1998
1961
1708
1977
1886
1946
1516
1999
1859
1931
1853
1265
1869
1642
1740
1467
1944
1956
1263
1940
1912
1832
1872
1678
1319
1839
1689
1765
1894
1242
1983
1410
1985
1387
1022
1358
860
112
1964
1836
1838
1285
1943
1718
1351
760
1925
1842
1921
1967
1822
1978
1837
1378
1618
1266
2003
1972
666
1321
1938
1616
1892
831
1865
1314
1571
1806
1225
1882
1454
1257
1381
1284
1907
1950
1887
1492
1934
1709
1315
1574
1794
1576
1883
1864
1981
1317
1397
1325
1620
1895
1485
1828
1803
1715
1374
1251
1460
1863
1581
1499
1933
1982
1809
1812"""
return input.splitlines()
def main():
array = getInputAsArray()
first_digit = 0
second_digit = 0
third_digit = 0
for i in array:
first_digit = int(i)
for j in array:
second_digit = int(j)
for k in array:
if 2020 - first_digit - second_digit == int(k):
third_digit = int(k)
print(first_digit + second_digit + third_digit)
print(first_digit * second_digit * third_digit)
if __name__ == '__main__':
main()
"""
--- Day 1: Report Repair ---
After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. Surely, Christmas will go on without you.
The tropical island has its own currency and is entirely cash-only. The gold coins used there have a littleicture of a starfish; the locals just call them stars. None of the currency exchanges seem to have heard of them, but somehow, you'll need to find fifty of these coins by the time you arrive so you canay the deposit on your room.
To save your vacation, you need to get all fifty stars by December 25th.
Collect stars by solvinguzzles. Twouzzles will be made available on each day in the Advent calendar; the seconduzzle is unlocked when you complete the first. Eachuzzle grants one star. Good luck!
Before you leave, the Elves in accounting just need you to fix your expense report (youruzzle input); apparently, something isn't quite adding up.
Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together.
For example, suppose your expense report contained the following:
1721
979
366
299
675
1456
In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying them togetherroduces 1721 * 299 = 514579, so the correct answer is 514579.
Of course, your expense report is much larger. Find the two entries that sum to 2020; what do you get if you multiply them together?
Youruzzle answer was 1005459.
--- Part Two ---
The Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had left over from aast vacation. They offer you a second one if you can find three numbers in your expense report that meet the same criteria.
Using the above example again, the three entries that sum to 2020 are 979, 366, and 675. Multiplying them togetherroduces the answer, 241861950.
In your expense report, what is theroduct of the three entries that sum to 2020?
Youruzzle answer was 92643264.
Botharts of thisuzzle are complete! Theyrovide two gold stars: **)
"""
|
27a08e7e31b5d88e7dbde53f9f42d15aed74c02c | sanket-qp/codepath-interviewbit | /week4/bit_manipulation/reverse_bits.py | 566 | 3.84375 | 4 | """
https://www.interviewbit.com/problems/number-of-1-bits/
"""
def reverse_bits(n):
result = 0
counter = 32
while counter >= 1:
counter -= 1
right_most_bit = n & 1
print result, bin(result)
print n, bin(n)
result = (result << 1) + right_most_bit
n = n >> 1
return result
def main():
#assert reverse_bits(int('1000', 2)) == int('0001', 2)
#assert reverse_bits(int('1111', 2)) == int('1111', 2)
assert reverse_bits(int('0011', 2)) == int('1100', 2)
if __name__ == "__main__":
main()
|
846deb83384e0dffdeefb76982fc2f16ed36f1f7 | tantakotan/PIKUMIN | /module/csv_process.py | 546 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import csv
def columns_of_index(arg1, arg2):
with open(arg1, 'r', encoding='utf-8_sig') as f:
tpl = csv.reader(f, delimiter=',')
tpl_list = []
index_list = next(tpl)
index_num = [i for i, x in enumerate(index_list) if x == arg2]
if len(index_num) >= 2:
print(arg2 + ' is ' + str(index_num) + ' count from ' + arg1)
exit()
for x in tpl:
if x[index_num[0]]:
tpl_list.append(x[index_num[0]])
return tpl_list
|
1f4f0313c1a26503185fe3a916c8e15072ef7a89 | jmavis/CodingChallenges | /Python/CompressedSequence.py | 817 | 3.875 | 4 | import sys
def ReadFile(file):
""" Reads in and parses the lines of the given file."""
for line in file.readlines():
line = line.rstrip() #remove endline
numbers = line.split(' ');
currentNumber = numbers[0];
countOfCurrentNumber = 0;
for number in numbers:
if number == currentNumber:
countOfCurrentNumber += 1;
else:
print str(countOfCurrentNumber) + " " + str(currentNumber),
countOfCurrentNumber = 1
currentNumber = number
print str(countOfCurrentNumber) + " " + str(currentNumber)
#---------------------------------------------------------
# Running Test Cases
#---------------------------------------------------------
test_cases = open(sys.argv[1], 'r')
ReadFile(test_cases)
test_cases.close() |
1db08839ef6ca99d746327ac2ede2deb253c6fae | sashakrasnov/datacamp | /14-interactive-data-visualization-with-bokeh/2-layouts-interactions-and-annotations/11-adding-a-hover-tooltip.py | 2,042 | 4.0625 | 4 | '''
Adding a hover tooltip
Working with the HoverTool is easy for data stored in a ColumnDataSource.
In this exercise, you will create a HoverTool object and display the country for each circle glyph in the figure that you created in the last exercise. This is done by assigning the tooltips keyword argument to a list-of-tuples specifying the label and the column of values from the ColumnDataSource using the @ operator.
The figure object has been prepared for you as p.
After you have added the hover tooltip to the figure, be sure to interact with it by hovering your mouse over each point to see which country it represents.
'''
import pandas as pd
from bokeh.plotting import figure
from bokeh.io import output_file, show
from bokeh.layouts import gridplot
from bokeh.plotting import ColumnDataSource
df = pd.read_csv('../datasets/gapminder_tidy.csv').dropna()
america_df = df[df.region.str.contains('America')].groupby('Country').mean()
africa_df = df[df.region.str.contains('Africa')].groupby('Country').mean()
america = ColumnDataSource(america_df)
africa = ColumnDataSource(africa_df)
p = figure(
x_axis_label='fertility (children per woman)',
y_axis_label='life')
p.circle('fertility', 'life', source=america, size=10, color='red', legend='America')
p.circle('fertility', 'life', source=africa, size=10, color='blue', legend='Africa')
p.legend.location = 'bottom_left'
p.legend.background_fill_color = 'lightgray'
'''
INSTRUCTIONS
* Import the HoverTool class from bokeh.models.
* Use the HoverTool() function to create a HoverTool object called hover and set the tooltips argument to be [('Country','@Country')].
* Use p.add_tools() with your HoverTool object to add it to the figure.
'''
# Import HoverTool from bokeh.models
from bokeh.models import HoverTool
# Create a HoverTool object: hover
hover = HoverTool(tooltips=[('Country', '@Country')])
# Add the HoverTool object to figure p
p.add_tools(hover)
# Specify the name of the output_file and show the result
output_file('hover.html')
show(p)
|
15e09951c7218d856379162f4e7e1515a016e3fc | Kushal997-das/Hackerrank | /Hackerrank_python/3.string/26.The Minion Game.py | 424 | 3.75 | 4 | def minion_game(string):
# your code goes here
sum1=0
sum2=0
vowel="AEIOU"
for i in range(len(s)):
if s[i] in vowel:
sum1=sum1+(len(s)-i)
else:
sum2=sum2+(len(s)-i)
if sum1>sum2:
print("Kevin",sum1)
elif sum2>sum1:
print("Stuart",sum2)
else:
print("Draw")
if __name__ == '__main__':
s = input()
minion_game(s)
|
cce8e43602932adf5985e8eaa02e70b2dcaa2583 | jakehoare/leetcode | /python_1_to_1000/214_Shortest_Palindrome.py | 1,497 | 3.984375 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/shortest-palindrome/
# Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it.
# Find and return the shortest palindrome you can find by performing this transformation.
# Least number of characters added implies finding the longest prefix palindrome. Use KMP failure function
# algorithm to find the longest prefix of s that is also a suffix of s[::-1].
# Time - O(n)
# Space - O(n)
class Solution(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest_prefix_suffix = self.kmp_table(s + '*' + s[::-1])
return s[:longest_prefix_suffix:-1] + s
def kmp_table(self, word):
failure = [-1] + [0 for _ in range(len(word)-1)]
pos = 2 # the next index of failure table to be computed
candidate = 0
while pos < len(word):
if word[pos-1] == word[candidate]: # prefix/suffix of word[:i] extends the previous prefix/suffix by 1 char
failure[pos] = candidate + 1
candidate += 1
pos += 1
elif candidate > 0: # no extension, update candidate to earlier prefix/suffix
candidate = failure[candidate]
failure[pos] = 0
else: # candidate == 0
failure[pos] = 0
pos += 1
return failure[-1] |
2519dae9444fa810582ef8f66da69286b94ab28f | zhenghaoyang/PythonCode | /ex19.py | 819 | 3.75 | 4 | # --coding: utf-8 --
#定义函数
def cheese_and_crackers(cheese_count,boxes_of_crackers):
print "You have %d cheese!" %cheese_count
print "You have %d boxes of cracker!" %boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
#直接传参
cheese_and_crackers(20,30)
print "OR,We can use variables from our script:"
#给变量赋值
amount_of_cheese = 10
amount_of_crackers = 50
#用变量传参
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
print "We can even do math inside too:"
#计算完直接传参
cheese_and_crackers(10+20,5+6)
print "And we combine the two,variables and math:"
#变量计算后,传参
cheese_and_crackers(amount_of_cheese + 100,amount_of_crackers +1000)
#加分题
|
5d9b8e4cc24ff766be67c1d0369539076b91ef5b | mwrouse/Python | /Design Exercises/die_roller.py | 392 | 3.765625 | 4 | """
Program: die_roller.py
Author: Michael Rouse
Date: 11/4/13
Description: Dice rolling function
"""
import random
def die_roller (sides, modifier=0):
""" Function to similater dice rolling """
# Generate random number between 1 and the sides of the dice
roll = random.randint(1, sides)
# Add the modifier to the roll
roll += modifier
return roll
|
72aeac11ea58d82179513b5c97dc8e392af3ef39 | pavananms/lp3thw | /ex5.py | 329 | 3.765625 | 4 |
name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'blue'
teeth = 'white'
hair = 'Brown'
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair.")
|
47cdad3f51c6724a11cb435cd49e13ec4d02b7a3 | LiangZZZ123/algorithm_python | /1/02_linked_list.py | 6,022 | 4.03125 | 4 | """
LinkedList: addleft, addright, popleft o(1)
popright o(n), because must traverse to the second-last node
LinkedList是便于FIFO(addright, popleft)的o(1), 所以本身就是一个queue的最优实现
如果要做到LIFO的o(1),即stack的最优实现, 必须借助DoublyLinkedList.
因为LinkedList的popright 是o(n)
Array: addright, popright, o(1), when the assigned memory block is not changed;
addleft, popleft, add/pop in the middle, o(n)
Array在不扩容/缩容的情况下,LIFO(addright, popright)是o(1)
"""
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __repr__(self):
return f"<Node: value={self.value}, "
class LinkedList():
"""
We regulate that there's no root points to headnode, when the linkedlist is empty,
we just use head=None to represent.
"""
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def __len__(self):
return self.length
def addright(self, value): # o(1)
node = Node(value)
if self.length == 0:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
self.length += 1
def addleft(self, value): # o(1)
node = Node(value)
if self.length == 0:
self.head = node
self.tail = node
else:
node.next = self.head
self.head = node
self.length += 1
def __iter__(self):
# for node in self.iter_factory():
# yield node.value
return self.iter_factory()
def iter_factory(self):
current = self.head
if len(self) > 0:
# while current is not self.tail.next:
for _ in range(len(self)):
yield current
# finally current will become none, then it should not have current.next
if current is not None:
current = current.next
def remove(self, value): # o(1) if remove head, o(n) if remove tail
if len(self) == 0:
raise IndexError("this is an empty linkedlist, no node to remove")
previous = self.head
for current in self:
if current.value == value:
previous.next = current.next
if current is self.head:
self.head = current.next
if current is self.tail:
self.tail = previous
del current
self.length -= 1
return 1
else:
previous = current
return -1
def popright(self): # o(n)
if len(self) == 0:
raise Exception("Cannot pop from empty linkedlist")
right = self.tail
self.remove(right.value)
return right.value
def popleft(self): # o(1)
if len(self) == 0:
raise Exception("Cannot pop from empty linkedlist")
left = self.head
self.remove(left.value)
return left.value
def find(self, value): # o(n)
"""
:para
value: the value this node stores
:return
the index of this node, -1 if not found
"""
index = 0
for node in self:
if node.value == value:
return index
index += 1
return -1
def clear(self):
for node in self:
del node
self.head = None
self.tail = None
self.length = 0
def reverse(self):
if len(self) in (0, 1):
return None
n1 = None # n1 represents the node before the headnode
n2 = self.head
self.tail = n2
# head = self.switch_position(n1, n2)
# print(f"head is {head}")
# self.head = head
while n2 is not None:
n3 = n2.next
n2.next = n1
n1 = n2
n2 = n3
# print(n1, n2, n3)
self.head = n1
def test():
# assert 0
import pytest
# test __len__(), addright(value), addleft(value)
l1 = LinkedList()
l1.addright(0)
l1.addright(1)
l1.addright(2)
l1.addright(3)
l1.addleft(-1)
l1.addleft(-2)
assert len(l1) == 6
assert [x.value for x in l1] == list(range(-2, 4))
# test __iter__()
l2 = LinkedList()
assert [x.value for x in l2] == list()
# test remove(value)
l3 = LinkedList()
for x in range(5):
l3.addright(x)
assert [x.value for x in l3] == list(range(5))
l3.remove(0)
l3.remove(2)
l3.remove(4)
assert [x.value for x in l3] == [1, 3]
# test find(value)
l4 = LinkedList()
for x in range(5):
l4.addright(x)
assert l4.find(0) == 0
assert l4.find(3) == 3
assert l4.find(-1) == -1
assert l4.find(6) == -1
# Again: test remove(value)
l5 = LinkedList()
with pytest.raises(Exception) as info:
l5.remove('aaa')
l5.addright('aaa')
l5.addright('bbb')
l5.remove('bbb')
assert [x.value for x in l5] == ['aaa']
assert l5.remove('bbb') == -1
assert l5.remove('aaa') == 1
assert [x.value for x in l5] == []
# test popright(), popleft()
l6 = LinkedList()
l6.addright('aaa')
l6.addright('bbb')
l6.addright('ccc')
l6.addright('ddd')
assert l6.popright().value == 'ddd'
assert l6.popleft().value == 'aaa'
assert [x.value for x in l6] == ['bbb', 'ccc']
# test clear()
l7 = LinkedList()
l7.addright('1')
l7.addright('2')
l7.clear()
assert len(l7) == 0
assert [x.value for x in l7] == []
# test reverse()
# assert(0)
l8 = LinkedList()
for x in range(5):
l8.addright(x)
l8.reverse()
assert [x.value for x in l8] == list(reversed(range(5)))
# l8 = LinkedList()
# for x in range(5):
# l8.addright(x)
# l8.reverse()
# print(list(l8))
|
c4b45de3330b79ef221befcaa3811a4300f2f9bc | CCommandoApero/Javascript-Python | /MotLePlusLong.py | 198 | 3.53125 | 4 | texte = input ("Mets ta phrase wesh :")
mot_long = ""
mots = texte.split()
for mot in mots:
if len(mot) > len(mot_long):
mot_long = mot
print (mot_long)
|
6fd8cb0e737090e1c7d790193e4e975fd7ee7836 | nirvaychaudhary/Python-Assignmnet | /data types/question9.py | 228 | 4.40625 | 4 | # write a python program to change a given string to a new string
# where the first and last chars have been exchanged.
def exchange(str1):
swap = str1[-1:] + str1[1:-1] + str1[:1]
return swap
print(exchange("Hello")) |
c70243b6a1efa887c7908a60eabe0ae51d02d1c4 | Athithya6/MyCaptain-Python | /Task1.py | 120 | 4.125 | 4 | r=float(input("Enter the radius of the circle"));
print(r);
a=3.14*r*r;
print("Area of the circle is:");
print(a);
|
7d60df5b6e2db447b854a00549b04d99faebd757 | Wiinterfell/adventofcode2k19 | /day1.py | 196 | 3.640625 | 4 | import sys
total_fuel = 0
with open("input1.txt") as fp:
for line in fp:
fuel = int(line)
while (fuel > 0):
fuel = fuel / 3 - 2
if (fuel > 0):
total_fuel += fuel
print(total_fuel) |
b0b197832c7784f31bed8208e1b3127a116bc5e4 | redline-collab/Python-Basic-Programs | /Compound_Interest.py | 268 | 3.96875 | 4 | # To Finf Simple Intrest
print("Lets Find Compound Interest!")
p = int(input("Enter Principal Ammount:"))
r = float(input("Enter Rate of interest:"))
t = int(input("Time Interval of Interest in Terms of Year:"))
pi = p*(1+r/100)**t
print("Compound Interest is:",pi) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.