blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
ba06cffa8e5a51216985271211cb8faba8395990 | shubhamingle/Data-Structures | /Searching Algorithms/Binary Search.py | 1,693 | 4.28125 | 4 | # For performing Binary Search we need the array to be sorted either in ascending or descending order
# We will make use of Quick Sort to sort the array in ascending order and then perform binary search on it
def Partition(a, start, end):
pivot = a[end]
pIndex = start
for i in range(start, end):
if a[i] <= pivot:
temp = a[i]
a[i] = a[pIndex]
a[pIndex] = temp
pIndex += 1
a[end] = a[pIndex]
a[pIndex] = pivot
return pIndex
def QuickSort(a, start, end):
if start < end:
pIndex = Partition(a, start, end)
QuickSort(a, start, pIndex-1)
QuickSort(a, pIndex+1, end)
print("Enter array elements")
a = list(map(int, input().split()))
QuickSort(a, 0, len(a)-1)
'''
# Iterative Method
def BinarySearch(start, end, element):
while start <= end:
mid = (start + end) // 2 # you can also write start + (start - end) // 2 to avoid overflow. Since max size of integer is 2^31 - 1 for 32 bit processor
if element == a[mid]:
return mid
elif element < a[mid]:
end = mid - 1
else:
start = mid + 1
return False
'''
# Recursive Method
def BinarySearch(start, end, element):
mid = (start + end) // 2
if element == a[mid]:
return mid
elif element < a[mid]:
BinarySearch(start, mid-1, element)
else:
BinarySearch(mid+1, end, element)
return False
print(a)
element = int(input("Enter element to search >> "))
found = BinarySearch(0, len(a)-1, element)
if found is False:
print("{} not found!".format(element))
else:
print("{} is present at index {}".format(element, found)) |
538a50e50debab2bbfcbeab84ee34e73e2fa6358 | MarcosPX1/URI_Python | /EX_1071- soma de impares.py | 211 | 3.6875 | 4 | x = int(input())
y = int(input())
maior = x if x > y else y
menor = y if y < x else x
menor += 1
soma = 0
while (menor < maior):
if(menor % 2 != 0):
soma+=menor
menor+=1
print(soma) |
94c3f4b88a376928459df5fbc9d6304a50bc07cb | SilvesSun/learn-algorithm-in-python | /tree/235_二叉搜索树的公共祖先.py | 1,672 | 3.5625 | 4 | # 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
#
# 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(
# 一个节点也可以是它自己的祖先)。”
#
# 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
#
#
#
#
#
# 示例 1:
#
# 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
# 输出: 6
# 解释: 节点 2 和节点 8 的最近公共祖先是 6。
#
#
# 示例 2:
#
# 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
# 输出: 2
# 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
#
#
#
# 说明:
#
#
# 所有节点的值都是唯一的。
# p、q 为不同节点且均存在于给定的二叉搜索树中。
#
# Related Topics 树 深度优先搜索 二叉搜索树 二叉树
# 👍 670 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root: return root
if p.val > q.val: return self.lowestCommonAncestor(root, q, p)
if p.val <= root.val <= q.val: return root
if root.val < p.val: return self.lowestCommonAncestor(root.right, p, q)
if root.val > q.val: return self.lowestCommonAncestor(root.left, p, q)
|
737839785a98ec2d5e0ccf00d29f88c2941ce11a | ragarsa/Django_Python | /my_name.py | 73 | 3.515625 | 4 | nombre = input("Introduce tu nombre: ")
print("Tu nombre es: " + nombre)
|
514592532fcb6c594fc0a23b05d05fbc95ceadb5 | SnowMasaya/python-algorithm | /python_algorithm/LinkedList/kth_last.py | 1,091 | 3.765625 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from LinkedList import LinkedList
def printKthToLast(head: LinkedList=None, k: int=0) -> int:
if head is None:
return 0
index = printKthToLast(head.next, k) + 1
if index == k:
print("{0} th to last node is {1}".format(k, head.current))
return index
class Index(object):
def __init__(self):
self.value = 0
def kthToLast(*args):
if len(args) == 2:
idx = Index()
return kthToLast(args[0], args[1], idx)
elif len(args) == 3:
if args[0] == None:
return None
node = kthToLast(args[0].next, args[1], args[2])
args[2].value = args[2].value + 1
if args[2].value == args[1]:
return args[0]
return node
def nthToLast(head: LinkedList, k: int) -> LinkedList:
p1 = head
p2 = head
for i in range(k):
if p1 == None:
return None
p1 = p1.next
while p1 != None:
p1 = p1.next
p2 = p2.next
return p2
|
b3c9bb0ecab18492abc4e4129dbf3048966dd6c9 | UX404/Leetcode-Exercises | /#874 Walking Robot Simulation.py | 2,021 | 4.5 | 4 | '''
A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:
-2: turn left 90 degrees
-1: turn right 90 degrees
1 <= x <= 9: move forward x units
Some of the grid squares are obstacles.
The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])
If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)
Return the square of the maximum Euclidean distance that the robot will be from the origin.
Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)
Example 2:
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)
Note:
0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
The answer is guaranteed to be less than 2 ^ 31.
'''
class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
left = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
right = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}
pack = {'N': (1, 1), 'E': (0, 1), 'S': (1, -1), 'W': (0, -1)} # (coordinate, direction)
direction = 'N'
location = [0, 0]
result = 0
for i in commands:
if i == -2:
direction = left[direction]
elif i == -1:
direction = right[direction]
else:
for n in range(i):
location[pack[direction][0]] += pack[direction][1]
if location in obstacles:
location[pack[direction][0]] -= pack[direction][1]
break
result = max(result, location[0] * location[0] + location[1] * location[1])
return result |
a148a868d09b5eb138f620c13cdfa748f13aebe6 | jmiqra/learn_python | /modules_and_packages.py | 135 | 3.78125 | 4 | import re
# Your code goes here
lists = []
for list in dir(re):
if "find" in list:
lists.append(list)
print sorted(lists) |
2f3e95c2cc84fe82eccf4b584b649c5849d1faca | WangYuanting/leetcode_problem | /outofdate/4Median_of_Two_Sorted_Arrays/test20180107.py | 1,986 | 4.21875 | 4 | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
'''
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
max1=len(nums1)
max2=len(nums2)
n1=0
n2=0
list=[]
if nums1==[]:
list=nums2
elif nums2==[]:
list=nums1
else:
while True:
if n1==max1:
for i in xrange(n2,max2):
list.append(nums2[i])
break
elif n2==max2:
for i in xrange(n1,max1):
list.append(nums1[i])
break
elif nums1[n1]<nums2[n2]:
list.append(nums1[n1])
n1+=1
else:
list.append(nums2[n2])
n2 += 1
n=len(list)
if n%2==0:
return (list[n/2-1]+list[n/2])/float(2)
else:
return list[(n-1)/2]
a=Solution()
b=a.findMedianSortedArrays([],[2,3])
print b
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
all_nums = nums1 + nums2
len_all = len(all_nums)
all_nums.sort()
if len_all == 0:
return None
elif len_all == 1:
return all_nums[0]
elif len_all == 2:
return ((all_nums[0] + all_nums[1]) / 2.0)
if len_all % 2 == 0:
median = (all_nums[(len(all_nums) / 2)] + all_nums[(len(all_nums) / 2) - 1]) / 2.0
else:
median = all_nums[(len(all_nums) / 2)]
return median |
760c99030a0248ceab392ce2bb2b0c1b6b6f64d7 | nikonst/filesPythonCourse | /Section9Examples/1-ReadEvenOddLines/6-countWords.py | 437 | 3.53125 | 4 | str = "sculptor"
fin = open("finn.txt")
print(fin.read())
fin.close()
count = 0
with open("finn.txt") as fin:
for l in fin:
for word in l.split(' '):
count +=1
print("Total Word Count =", count)
count = 0
wordToCount = "Huck"
with open("finn.txt") as fin:
for l in fin:
if wordToCount in l.split(' '):
count +=1
print("Total count for the word '{}' is {}".format(wordToCount, count))
|
17515e6b608c08bcf9f09f6b4316bb6e472fef32 | NORR312/Portfolio | /Person__init__class.py | 670 | 3.671875 | 4 | class Person:
qualit: int
def __init__(self, n, s, qu=1):
self.name = n
self.surname = s
self.qualit = qu
def get_info(self):
print(self.name, self.surname, self.qualit)
def __del__(self):
print('Goodbye Mr. ', self.surname)
# --------------------------------------------------
p1 = Person("John", "Smith")
p2 = Person("Matt", "Swan", 4)
p3 = Person("Edd", "Collins", 2)
p1.get_info()
p2.get_info()
p3.get_info()
quallist = []
for skill in p1.qualit, p2.qualit, p3.qualit:
quallist.append(skill)
weak = min(quallist)
for pers in p1, p2, p3:
if pers.qualit == weak:
pers.__del__()
input()
|
4a27899f8199536a41c7d57db34779add6df7fdc | bayusamudra5502/Daspro | /Prosedural/Responsi 3/luassegitiga.py | 265 | 3.53125 | 4 | # Bayu Samudra (16520420) - 2 April 2021
# program luasSegitiga
# Program ini akan menerima dua buah bilangan
# float (a, t) lalu menggeluarkan hasil perhitungan
# L = .5 * a * t
# KAMUS
# a, t : real
a = float(input())
t = float(input())
print("%.3f" % (.5 * a * t)) |
6c6fea06c6093b48941f7517f77ab71e3002e664 | nathsotomayor/cab_hippo | /cab_app.py | 1,267 | 4 | 4 | #!/usr/bin/python3
import random
cab_num = 20
prob_trunk = 0.2
cab_list = [1 if x < cab_num * prob_trunk else 0 for x in range(cab_num)]
random.shuffle(cab_list)
def add_cab():
cab = input("Big Trunk?: 0(not), 1(yes)\n")
cab = int(cab)
if (len(cab_list) == 73):
print("=================== Warning!! ====================")
print("Not possible to add any more cabs to this station")
print("Max cap: 73")
print("Cab not added")
print("==================================================")
return
cab_list.append(cab)
cab_count()
def cab_request():
request = input("Do you need big trunk?: 0(not), 1(yes)\n")
request = int(request)
if request is 0:
cab_list.pop(0)
else:
cab_list.remove(1)
cab_count()
def cab_count():
count = len(cab_list)
print ("The number of taxis in queue is: {:d}".format(count))
if count <= 10:
print("Please request more Taxis to this location")
def run_station():
print()
wait = input("Enter: (0) to exit\n\t(1) if a cab arrived\n\t(2) if requesting a cab from queue:\n")
wait = int(wait)
if wait is 1:
add_cab()
elif wait is 2:
cab_request()
elif wait is 0:
return 0
|
5650b17874ec202f6e08731349c3ee6a58008f3b | deepak07031999/MongoPython | /create.py | 1,213 | 3.78125 | 4 | import pymongo
from pymongo import MongoClient
from random import randint
#Step 1: Connect to MongoDB
client = MongoClient("mongodb://Username:password@HOSTNAME:NODEPORT")
db=client.newdb
#Step 2: Create sample data
#Here we are creating 100 business reviews data randomly
names = ['Spoon','Tree','Country', 'Delecious', 'Large','City','Pond', 'Mozzarella','Elephant', 'Salty','Burger','Energetic', 'Funny']
company_type = ['LLC','Inc','Company','Corporation']
company_cuisine = ['Pizza', 'Indian', 'Indonesian', 'Italian', 'Mexican', 'American', 'Japanese', 'Vegetarian']
for x in range(1, 101):
business = {
'name' : names[randint(0, (len(names)-1))] + ' ' + names[randint(0, (len(names)-1))] + ' ' + company_type[randint(0, (len(company_type)-1))],
'rating' : randint(1, 5),
'cuisine' : company_cuisine[randint(0, (len(company_cuisine)-1))]
}
#Step 3: Insert business object directly into MongoDB via insert_one
result=db.reviews.insert_one(business)
#Step 4: Print to the console the ObjectID of the new document
print('Created {0} of 100 as {1}'.format(x,result.inserted_id))
#Step 5: Tell us that you are done
print('finished creating 100 business reviews')
|
bee1c6bfb80330fdb50a2f6246946945bb144fe0 | adelinedepaepe/perso_m2i | /3-Python/Matplotlib/matplotlib_playground.py | 1,264 | 3.84375 | 4 | ##matplotlib est un package, un package est un ensemble de classes. pyplot est une class. C'est la plus utilisée dans matplotlib
import matplotlib.pyplot as plt # ou 'from matplotlib import pyplot as plt'
# Numpy = numerical python, permet d'utiliser des fonctions numériques de manière plus rapide
import numpy as np
#arange ~ range de vanilla python,
# mais on utilise numpy car certaines fontions n'existent pas sur python, et le fonctions de python encombrent plus de mémroire
data = np.arange(10)
print(data)
print(type(data))
plt.plot(data)
#Pour accéder à l'aide, aller sur le terminal, taper
#ipython
#puis plt.plot?
#pour afficher le résultat
#plt.show()
#Pour subdiviser les graph
#POur l'aide sur les options plt.figure?
#On crée l'objet figure
fig = plt.figure(figsize=(12,10))
#Puis, au sein de cette fig, on créé pusieurs sous-tracés
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
# 2: nombre total de tracés verticalement,
# 2:nombre de tracés total horizontalement,
# 1: position ciblé pour le tracé en cours
plt.plot(np.random.randn(1200).cumsum(),'k--') #random.randn(50) va créer 50 point random, cumsum() fait un cumul
ticks = ax3.set_xticks([0, 250, 500, 750, 1000])
plt.show()
|
5a516c7ce55f8cd44b42e7ae418d90dd57228b97 | skidmarker/ferrari | /heap/디스크_컨트롤러.py | 626 | 3.578125 | 4 | import heapq
def solution(jobs):
answer = 0
time = 0
last = -1
waiting_list = []
count = 0
while count < len(jobs):
for start_sec, working_sec in jobs:
if last < start_sec <= time:
heapq.heappush(waiting_list, (working_sec, start_sec))
# 대기중인 작업이 없으면 다음으로
if not waiting_list:
time += 1
continue
count += 1
last = time
working_sec, start_sec = heapq.heappop(waiting_list)
time += working_sec
answer += (time - start_sec)
return answer // len(jobs)
|
689e91b100b8b25b352dfb04d7e890d287bd078f | SagarKulk539/Code_Repository | /CodeChef/DECODEIT.py | 1,036 | 3.734375 | 4 | '''
Problem Description, Input, Output : https://www.codechef.com/JAN21C/problems/DECODEIT
Code by : Sagar Kulkarni
'''
def getEncodedCharacter(str1):
if str1=="0000":
return 'a'
elif str1=="0001":
return 'b'
elif str1=="0010":
return 'c'
elif str1=="0011":
return 'd'
elif str1=="0100":
return 'e'
elif str1=="0101":
return 'f'
elif str1=="0110":
return 'g'
elif str1=="0111":
return 'h'
elif str1=="1000":
return 'i'
elif str1=="1001":
return 'j'
elif str1=="1010":
return 'k'
elif str1=="1011":
return 'l'
elif str1=="1100":
return 'm'
elif str1=="1101":
return 'n'
elif str1=="1110":
return 'o'
elif str1=="1111":
return 'p'
for _ in range(int(input())):
n=int(input())
str1=input()
list1=list(str1)
newStr=""
for i in range(0,n,4):
ch=getEncodedCharacter("".join(list1[i:i+4]))
newStr+=ch
print(newStr)
|
558ff52200763b6df663b1bc32ec84fd41d45614 | jorgeteixe/algorithms | /algebra/euclidean_algorithm/euclidean_algorithm.py | 279 | 3.8125 | 4 | def euclidean_algorithm(a, b):
while b != 0:
tmp = b
b = a % b
a = tmp
return a
def main():
a = 252
b = 105
gcd = euclidean_algorithm(a, b)
print(f'gcd({a}, {b}) = {gcd}')
if __name__ == '__main__':
main()
|
42ee5ba62a359bd5d29ae725cf24e3ae3568669d | harryw2427/2_to_the_nth_power | /2_to_the_nth_power.py | 125 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
ans=1
n=6
for a in range(n):
ans=ans*2
print(a,ans)
# In[ ]:
|
9361dac667462b2b63998f5709471732bb37ce9f | wweihang/study | /python/threading/threading_lock.py | 1,121 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import threading
"""
lock在不同线程使用同一共享内存时,能够确保线程之间互不影响,使用lock的方法是, 在每个线程执行运算修改共享内存之前,
执行lock.acquire()将共享内存上锁, 确保当前线程执行时,内存不会被其他线程访问,执行运算完毕后,使用lock.release()
将锁打开, 保证其他的线程可以使用该共享内存。
"""
#函数一:全局变量A的值每次加1,循环10次,并打印
def job1():
global A, lock
lock.acquire()
for i in range(10):
A += 1
print('job1', A)
lock.release()
#函数二:全局变量A的值每次加10,循环10次,并打印
def job2():
global A, lock
lock.acquire()
for i in range(10):
A += 10
print('job2', A)
lock.release()
#主函数:定义两个线程,分别执行函数一和函数二
if __name__ == '__main__':
lock = threading.Lock()
A = 0
t1 = threading.Thread(target=job1)
t2 = threading.Thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()
|
6027b461feaed6ce12b80ec0467a15b5133452c8 | ayush9200/Week1 | /ReverseNameString.py | 495 | 4.1875 | 4 | full_name = ""
def main():
takeUserName()
printReversedName()
def takeUserName():
global full_name
first_name = input("Enter your first name : ")
last_name = input("Enter your last name : ")
full_name = first_name + " " + last_name
def printReversedName():
reversed_name = ""
# Executing loop in reversed
for count in range(len(full_name),0,-1):
reversed_name = reversed_name + full_name[count-1]
print(reversed_name)
# Adding coment
main() |
702eab96a82cd70fd3b8822f9a6bee4f0d3b1ca2 | kaat0/OpenLinTim | /src/tools/visum-transformer/fixed_times/src/fixed_times/io/lines.py | 526 | 3.640625 | 4 | from typing import Dict, Tuple
def read_line_names(filename: str) -> Dict[int, Tuple[str, str, str]]:
names = {}
with open(filename) as input_file:
for line in input_file:
line = line.split("#")[0].strip()
if not line:
continue
values = line.split(";")
line_id = int(values[0].strip())
name = values[1].strip()
names[line_id] = ("-".join(name.split("-")[:-2]), name.split("-")[-2], name.split("-")[-1])
return names
|
158c8d537448229b00061662dfa1f5d14032d92d | rahulon001/python_programs | /stringContainsOnlyDigits.py | 185 | 3.875 | 4 | def string_contains_digits(string: str) -> bool:
for s in string:
if not (s.isdigit()):
return False
return True
print(string_contains_digits("1234"))
|
bb3e8aea06f6a3a88884529a15834b053272e69b | sarana-25/Pocket | /Queue.py | 338 | 3.859375 | 4 | queue=[]
x=True
while x==True:
print("Menu","1.Push","2.Pop","3.Size","4.Print","5.Exit")
n=int(input("Enter Choice:"))
if n==1:
queue.insert(0,input("Enter data:"))
elif n==2:
queue.pop()
elif n==3:
print(len(queue))
elif n==4:
print(queue)
else:
x=False
break
|
e744860b9853a3d0ea7323ce2c81d79bf4cad674 | bopopescu/projects-2 | /cs581/ackermann.py | 561 | 3.875 | 4 | import sys
# global variable to count number of recursive calls
count = 0
def ackermann(m, n):
global count
count+= 1
if m == 0:
# printf "A(%d,%d)" % (m, n+1)
return n+1
elif n == 0:
# printf "A(%d,%d)" % (m-1, 1)
return ackermann(m-1, 1)
else:
# printf "A(%d,A(%d,%d))" % (m-1, m, n-1)
return ackermann(m-1, ackermann(m, n-1))
if __name__ == "__main__":
m = long(sys.argv[1])
n = long(sys.argv[2])
count = 0
rv = ackermann(m, n)
print "Result: %d (%d recursive calls)" % (rv, count)
|
797f2c69db16969ae600550398a5a72603752e6a | ck564/HPM573S18_Kong_HW4 | /HW4_P2_Run.py | 551 | 3.640625 | 4 | """
Problem 2: A Game of Chance with an Unfair Coin (Weight 1). Modify your model
for Problem 1 so that you can specify the probability that a coin flip results
in head. What is the average reward when this probability is 0.4?
"""
import HW4_P1 as G
TOSSES = 20
PROBABILITY = 0.4
GAMES = 1000
# Create game
myRepeatedGame = G.RepeatedGame(id=1, prob=PROBABILITY, iterations=GAMES)
# Simulate game
myRepeatedGame.simulate(n_times=TOSSES)
# Print the expected value of game
print("Expected value of game: $", myRepeatedGame.get_expected_value())
|
4a8f340212882e41121e31ddb148c6d18e1ef5b6 | Nojdaz/Linneuniversitetet-Introduction_to_programming-Assignment-1_Python_ | /G/shortname.py | 152 | 3.71875 | 4 | firstName = input("First name: ")
lastName = input("Last name: ")
print(firstName[0].capitalize() + ". " + lastName[0].capitalize() + lastName[1:4])
|
697c9ca8a9c022a75f91bec12099af99b4177924 | GhostDovahkiin/Introducao-a-Programacao | /Monitoria/Estruturas de Repetição/25.py | 329 | 3.921875 | 4 | cont = 0
pessoas = int(input("Digite a quantidade de pessoas: "))
for i in range(pessoas):
idade = int(input("Digite sua idade: "))
cont += idade
media = cont / pessoas
if media >= 0 and media <= 25:
print("Turma jovem")
elif media >= 26 and media <= 60:
print("Turma adulta")
else:
print("Turma idosa")
|
b5fdfe6a89b9d593eddf61911c5d309a16ae284a | Banktts/complog2018_2 | /week6/06_P18.py | 221 | 3.5 | 4 | n=int(input().strip())
data1=[]
data2=[]
for i in range(n):
data2.append(int(input().strip()))
data1.append(i+1)
tmp=1
print(tmp,end=" ")
for i in range(n-1):
tmp=data2[data1.index(tmp)]
print(tmp,end=" ") |
5bcaabcc8f03b370674794b9ab08b871b4f8abca | DLSK-study/letzgorats | /Sorting/14-26_Sorting cards.py | 3,503 | 3.5625 | 4 | # 내가 처음 푼 방법에서는 반례가 발견되었다.
'''
먼저 풀었던 로직
1) 카드덱을 오름차순으로 정렬한다.
2) 2개씩 묶어서 쭉쭉 더한다.
반례 1)
3 3 4 5
=> (3 + 3) = 6
=> (6 + 4) = 10
=> (10 + 5) = 15
최종 : 6 + 10 + 15 = 31
=> (3 + 3) = 6
=> (4 + 5) = 9
=> (6 + 9) = 15
최종 : 6 + 9 + 15 = 30 => 얘가 더 최소값
반례 2)
3 3 3 3
=> (3+3) = 6
=> (6+3) = 9
=> (9+3) = 12
최종 : 6 + 9 + 12 = 27
=> (3+3) = 6
=> (3+3) = 6
=> (6+6) = 12
최종 : 6 + 6 + 12 = 24 => 얘가 더 최소값
이러한 반례들이 너무 많이 존재하기 때문에, 최소값부터 더하면 안된다!
너무 단순했던 생각이기에 아닐 것을 알았다..방법이 안떠올랐다.
'''
# 질문검색을 참고해서 리스트로 풀었는데, 시간초과가 났다.
import sys
input = sys.stdin.readline
n = int(input())
card_list = []
for _ in range(n):
card_list.append(int(input()))
card_list = sorted(card_list)
answer = 0
if(len(card_list)==1):
print(0)
else:
answer = 0
while len(card_list) >1 : # 1개 일경우는 비교 안해도 된다.
one = card_list.pop(0)
two = card_list.pop(0)
answer += one+two
card_list.append(one+two)
card_list = sorted(card_list)
print(answer)
# <알게 된 사실>
# 덱을 사용하려는데, 덱을 정렬하는 방법이 마땅히 없어, 우선순위 큐로 풀어야 했다. 우선순위 큐는 그 자체로 min_heap 구조이기 때문에, 정렬이 되어있다.
# 1) 덱만 잘 활용하면 큐는 사용하지 않아도 되는 줄 알았는데, 이러한 정렬을 최신화해야 하는 문제에서는 힙큐말고는 마땅한 자료구조가 없더라..
# (덱을 sorted 하면 type이 리스트로 바뀐다.)
# 2) pop(0)을 하는 것은 시간적으로 많은 비용을 발생시킨다. 다른 원소들을 앞으로 다 땡기기 때문에, 또한 사용할때도 주의해야 하므로, 이럴땐 덱을 사용하자.
'''
test1 = [0, 0, 0, 1, 2, 3, 4, 5, 6]
for _dummy in test1:
if(_dummy == 0):
test1.pop(0)
print(test1)
[0, 0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
출력값 : [0, 1, 2, 3, 4, 5, 6]
인덱스도 고려해줘야 하므로, 의도했던바와는 다르게 오류가 발생할 여지가 있다. 지양하자.
'''
# 3) append의 리턴값도 sort()와 같이 None 이더라
'''
card_list = card_list.append(something)
과 같이 코드를 작성하면, card_list에 None 이 할당되기 때문에, 더 이상의 진행에 오류가 발생한다.
append는 그냥
card_list.append(something) 과 같이 append문 자체만 써주자.
'''
# 우선순위 큐를 이용한 최종 코드 ( 1068ms)
from queue import PriorityQueue
import sys
input = sys.stdin.readline
n = int(input())
card_list = PriorityQueue()
answer = 0
for _ in range(n):
card_list.put(int(input()))
while card_list.qsize() >=2:
one = card_list.get()
two = card_list.get()
answer += one+two
card_list.put(one+two)
print(answer)
# 힙큐를 이용한 최종 코드 --> 가장 빨랐다.(252ms)
import heapq
import sys
input = sys.stdin.readline
n = int(input())
card_list = []
answer = 0
for _ in range(n):
heapq.heappush(card_list,int(input()))
while len(card_list) >=2:
one = heapq.heappop(card_list)
two = heapq.heappop(card_list)
answer += one+two
heapq.heappush(card_list,one+two)
print(answer)
|
184481166821e5e94cfe3405f834bc6b8f5666c8 | peterson-dev/pathfinder-django | /core/pathfinder.py | 7,792 | 3.515625 | 4 | from PIL import Image
from random import choice
import argparse
class ElevationMap:
def __init__(self, data_file=None, data=None):
"""
Opens data file and stores contents into a nested list.
Data file default is a test set.
"""
if data_file is not None:
data = open(data_file).readlines()
self.data = []
for row in data:
lines = row.split()
lines = [int(item) for item in lines]
self.data.append(lines)
def get_max(self) -> int:
"""
Returns the max value in the elevation map data set
"""
return max([max(row) for row in self.data])
def get_min(self) -> int:
"""
Returns the min value in the elevation map data set
"""
return min([min(row) for row in self.data])
class MapImage:
def __init__(self, map_data, pathfinder):
"""
Parameters
map_data = ElevationMap Instance
pathfinder = PathFinder Instance
width/height = based on data set
canvas = image instance
"""
self.map_data = map_data
self.pathfinder = pathfinder
self.width = len(self.map_data.data[0])
self.height = len(self.map_data.data)
self.canvas = Image.new('RGBA', (self.width, self.height))
def greyify(self) -> list:
"""
Return nested list of colors corresponding to
the elevations
"""
max_elevation = self.map_data.get_max()
min_elevation = self.map_data.get_min()
def grey_a_point(elevation_value):
return int(((elevation_value - min_elevation) /
(max_elevation - min_elevation)) * 255)
colors = [
[grey_a_point(item) for item in row] for row in self.map_data.data
]
return colors
def draw_image(self, file_name=None):
"""
Plots the list of colors onto the canvas
"""
colors = self.greyify()
for x in range(self.width):
for y in range(self.height):
self.canvas.putpixel((x, y),
(colors[y][x], colors[y][x], colors[y][x]))
if file_name:
self.canvas.save(file_name)
return self.canvas
def draw_path(self, file_name=None, color=(206, 158, 255)):
"""
Plots path points onto the canvas
"""
for point in self.pathfinder.path:
self.canvas.putpixel((point[2], point[1]), color)
for point in self.pathfinder.optimal_path:
self.canvas.putpixel((point[2], point[1]), (0, 255, 0))
if file_name:
self.canvas.save(file_name)
return self.canvas
class PathFinder:
def __init__(self, map_data):
"""
Parameters
map_data = ElevationMap instance
current_location = current location as a tuple (elevation, y, x)
path = list of coordinates that are paths
optimal_path = list of coordinates that is the optimal path
"""
self.map_data = map_data
self.current_location = None
self.path = []
self.optimal_path = []
def navigate(self):
"""
Compares the north, south, and straight locations to the current
location and returns the greediest one with minimal change. If there is a tie then
the choice function is called to randomize the output
"""
current = self.current_location[0]
north = self.get_north_location()
south = self.get_south_location()
closest = self.get_straight_location()
if north is not None:
north = north[0]
if abs(current - north) < abs(current - closest[0]):
closest = self.get_north_location()
elif abs(current - north) == abs(current - closest[0]):
closest = choice([self.get_north_location(), closest])
if south is not None:
south = south[0]
if abs(current - south) < abs(current - closest[0]):
closest = self.get_south_location()
elif abs(current - south) == abs(current - closest[0]):
closest = choice([self.get_south_location(), closest])
return closest
def get_north_location(self):
"""
Returns a tuple with the elevation
and coordinates of the northern next step
"""
y = self.current_location[1] - 1
x = self.current_location[2] + 1
if y < 0 or x < 0:
return None
return (self.map_data.data[y][x], y, x)
def get_south_location(self):
"""
Returns a tuple with the elevation
and coordinates of the southern next step
"""
y = self.current_location[1] + 1
x = self.current_location[2] + 1
if y < 0 or x < 0:
return None
if y > len(self.map_data.data) - 1:
return None
return (self.map_data.data[y][x], y, x)
def get_straight_location(self):
"""
Returns a tuple with the elevation
and coordinates of the straight next step
"""
y = self.current_location[1]
x = self.current_location[2] + 1
if y < 0 or x < 0:
return None
if x > len(self.map_data.data[0]) - 1:
return None
return (self.map_data.data[y][x], y, x)
def find_path(self, current_location, path_data):
"""
Runs navigate from a set location towards the east
"""
start = current_location
self.current_location = current_location
path_data.append(self.current_location)
total_change_in_elevation = 0
while self.get_straight_location():
next_point = self.navigate()
total_change_in_elevation = (
total_change_in_elevation +
abs(current_location[0] - next_point[0]))
path_data.append(next_point)
self.current_location = next_point
return (total_change_in_elevation, start[0], start[1], start[2])
def find_optimal_path(self):
"""
Finds all possible routes on the map and
saves the one with least change in elevation
"""
path_with_least_change = (5000000, 0, 0, 0)
x = 0
for route in self.map_data.data:
temp_path = []
start = (route[len(route) // 2], x, 0)
route_effort = self.find_path(start, temp_path)
if route_effort[0] < path_with_least_change[0]:
path_with_least_change = route_effort
self.optimal_path = temp_path
else:
for point in temp_path:
self.path.append(point)
x += 1
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("file", help="Enter data file")
parser.add_argument("file_name", help="Enter file name to save as")
parser.add_argument("path_color",
nargs='?',
help="Color for all the\
paths in this format - [255 255 255]",
type=int)
args = parser.parse_args()
map = ElevationMap(args.file)
pathfinder = PathFinder(map)
map_image = MapImage(map, pathfinder)
map_image.draw_image(args.file_name + ".png")
map_image.pathfinder.find_optimal_path()
try:
map_image.draw_path(args.file_name + "_path.png",
tuple(args.path_color))
except TypeError:
args.path_color = (206, 158, 255)
map_image.draw_path(args.file_name + "_path.png", args.path_color)
|
de94d0dfcbe5281a3d01a79e6fff8d01bac206a6 | quantum-guy7/algoDs | /sorting/python/selectionsort.py | 894 | 4.25 | 4 | # Implementation of Selection Sort
def main():
''' Script entrypoint.'''
numbers = [4877, 5280, 9977, 2105, 816, 7430, 8524, 4212, 8371, 8177]
print_numbers(numbers)
selection_sort(numbers)
print_numbers(numbers)
def selection_sort(numbers: list):
''' Returns sorted list of numbers. '''
# Traverse through all array elements
for i in range(len(numbers)):
minimum_index = i
# Find the minimum element in remaining unsorted array
for j in range(i + 1, len(numbers)):
if numbers[minimum_index] > numbers[j]:
minimum_index = j
# Swap the minimum element with current index
numbers[i], numbers[minimum_index] = numbers[minimum_index], numbers[i]
def print_numbers(numbers: list):
''' Print elements in a list seperated by comma.'''
print(*numbers, sep = ", ")
main()
|
8c71b2ea3cc1f3df7a9e22ac005d4b6a1c6408ec | ankitsoni5/python | /course_python/Python/search_student.py | 1,073 | 3.859375 | 4 | from com.ankit.collage.student import Student
'''
# It is using list.
slist = [
Student(name='Ankit', gender='M', roll=1, marks=90),
Student(name='Soni', gender='M', roll=2, marks=80),
Student(name='Anjani', gender='F', roll=3, marks=70)
]
roll_no = int(input('Enter the roll number: '))
#student_found = False
for s in slist:
if roll_no == s.roll:
print(Student.getdetails(s))
#student_found=True
break
else:
# execute when the 'for' loop ran completely and result not found then for we have else block for this.
print('Student not found')
#if not student_found:
print('Student not found')
#
'''
# It is using list.
dlist = {
1: Student(name='Ankit', gender='M', roll=1, marks=90),
2: Student(name='Soni', gender='M', roll=2, marks=80),
3: Student(name='Anjani', gender='F', roll=3, marks=70)
}
roll_no_1 = int(input('Enter the roll number: '))
if roll_no_1 in dlist:
student = dlist[roll_no_1]
print(student.getdetails())
else:
print('Student not found.') |
6b01fe09f61d4b22c640df965a8f4f2889d7e4c1 | vpc20/python-data-structures | /DisjointSetNaive.py | 2,414 | 3.828125 | 4 | from collections import defaultdict
class DisjointSet:
# def __init__(self):
# self.disj_list = list()
#
# def make_set(self, e):
# self.disj_list.append({e})
#
# def find_set(self, e):
# for disj_set in self.disj_list:
# if e in disj_set:
# return disj_set
# return None
#
# def union(self, set1, set2):
# self.disj_list.append(set().union(set1, set2))
# self.disj_list.remove(set1)
# self.disj_list.remove(set2)
def __init__(self):
self.parent = {}
def make_set(self, x):
self.parent[x] = x
def find_set(self, x):
return self.parent[x]
def union(self, x, y):
py = self.parent[y] # save value as this could be updated in loop below
for k in self.parent:
if self.parent[k] == py:
self.parent[k] = self.parent[x]
def get_set(self):
conn_comps = defaultdict(set)
for k, v in self.parent.items():
conn_comps[v].add(k)
return list(conn_comps.values())
if __name__ == '__main__':
djset = DisjointSet()
djset.make_set(1)
djset.make_set(2)
djset.make_set(3)
djset.make_set(4)
djset.make_set(5)
djset.make_set(6)
djset.make_set(7)
# print(djset.parent)
print(djset.get_set())
djset.union(1, 2)
print(djset.get_set())
djset.union(4, 5)
print(djset.get_set())
djset.union(1, 5)
print(djset.get_set())
djset.union(6, 7)
print(djset.get_set())
djset.union(4, 6)
print(djset.get_set())
# for edge1, edge2 in [('b', 'd'), ('e', 'g'), ('a', 'c'), ('h', 'i'),
# ('a', 'b'), ('e', 'f'), ('b', 'c')]:
# set1 = djset.find_set(edge1)
# set2 = djset.find_set(edge2)
# if set1 != set2:
# djset.disj_list.append(djset.union(set1, set2))
# djset.disj_list.remove(set1)
# djset.disj_list.remove(set2)
# print(djset.disj_list)
# disjoint_list = [{1}, {2}, {3}, {4}, {5}]
# x = find_set(disjoint_list, 3)
# disjoint_list.remove(x)
# print(disjoint_list)
# disjoint_list = [{1}, {2}, {3}, {4}, {5}]
# set1 = disjoint_list[0]
# set2 = disjoint_list[2]
# disjoint_list.append((set1.union(set2)))
# disjoint_list.remove(set1)
# disjoint_list.remove(set2)
# print(disjoint_list)
|
2979ab74b6fca1690a71321ebb3c2223a7b2e3a0 | operation-lakshya/BackToPython | /MyOldCode-2008/JavaBat(now codingbat)/Strings1/Hello name.py | 420 | 3.640625 | 4 |
#********************************************************************
# Description: This Python script and this is for Hello Name
#********************************************************************
#Take a name from user to say hello
s=raw_input("\nEnter a person name to say hello to that person:\t")
#Print the given name with hello
print "\nHello",s
#Prompt user to finish
raw_input("\nPress enter to finish") |
6286568e3e8aa850500ee3f57353aba2ac7dc854 | EuphosiouX/Assignment-Week-6 | /AssignmentWeek6/Assignment 8/Assignment8.py | 1,619 | 3.65625 | 4 | pokemon = '''audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask'''
# Split to list
pokemon_list = pokemon.split(" ")
# Put each of them inside dictionary
pokemon_dict = {}
for names in pokemon_list:
if names[0] not in pokemon_dict:
pokemon_dict[names[0]] = [names]
else:
pokemon_dict[names[0]].append(names)
# Variables
count = 0
longest_combi = []
# Main function
def longest_combination(combination):
global count
global longest_combi
# Check the longest combination
if len(combination) > count:
count = len(combination)
longest_combi = combination
# The code snippet to find the next value in the chain
if combination[-1][-1] in pokemon_dict:
for name in pokemon_dict[combination[-1][-1]]:
if name not in combination:
longest_combination(combination + [name])
# Search all possible combinations
for names in pokemon_list:
longest_combination([names])
# Print
print(longest_combi,"\n"+"The Length:",count)
|
3db370ca624b4616e1278e4ad2cb15ae45ac3b08 | borislavstoychev/Soft_Uni | /soft_uni_OOP/Attributes and Methods/lab/integer_2.py | 1,218 | 3.875 | 4 | class Integer:
def __init__(self, value: int):
self.value = value
@staticmethod
def from_float(value):
if not isinstance(value, float):
return "value is not a float"
return Integer(int(value))
@staticmethod
def from_roman(value):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(value)):
if i > 0 and rom_val[value[i]] > rom_val[value[i - 1]]:
int_val += rom_val[value[i]] - 2 * rom_val[value[i - 1]]
else:
int_val += rom_val[value[i]]
return Integer(int_val)
@staticmethod
def from_string(value):
if not isinstance(value, str):
return "wrong type"
return Integer(int(value))
def add(self, integer):
if not isinstance(integer, Integer):
return "number should be an Integer instance"
return self.value + integer.value
def __str__(self):
return f"{self.value}"
first_num = Integer(10)
second_num = Integer.from_roman("IV")
x = Integer.from_float(3.5)
print(x)
y = Integer.from_string("2")
print(y)
print(first_num.add(second_num)) |
3cdb84fc84496462ac8afb230c82e10f858cbbe5 | rbenjos/nand2tetris | /tokenizer2.py | 3,970 | 4.15625 | 4 | import re
class Tokenizer:
def __init__(self, input_file):
"""
A constructor of a tokenizer. Mainly prepares the input as
a list to work with.
:param input_file: a jack file to read the jack code from
"""
file_content = None
self.input_file_name = input_file
# opening the input jack file
print("file is "+input_file)
file = open(input_file, "r")
if file.mode == "r":
# extracting the entire text
self.file_content = file.read()
# removing jack documentation
self.file_content = re.sub(r"(/{2}.*?\n)", "",file_content)
self.file_content = re.sub(r"/\*{1,2}(.|\n)*?\*/", "", file_content, re.DOTALL)
print(file_content)
file.close()
# creating a list and filtering the list from empty strings
if self.file_content is not None:
# setting other variables
self.token_type = None
self.token = None
self.inside_string = False
self.word = ""
self.key_words = {"class", "constructor", "function", "method",
"field", "static", "var", "int", "char", "true",
"boolean", "void", "false", "null", "this",
"let", "do", "if", "else", "while", "return"}
self.symbols = {"{", "}", "(", ")", "[", "]", ".", ",", ";", "+",
"-", "*", "/", "&", "|", "<", ">", "=", "~"}
self.double_symbols = {"<=", ">=", "!="}#todo
def get_token(self):
return self.token
def get_token_type(self):
return self.token_type
def has_more_tokens(self):
"""
:return: true if there are more tokens in the file,
false otherwise
"""
return self.file_content != ""
def set_word(self, cut):
self.token = self.word[:cut]
self.word = self.word[cut:]
def extract_token(self):
if self.symbols.__contains__(self.word[0]):
if self.double_symbols.__contains__(self.word[:2]):
cut_index = 2
else:
cut_index = 1
self.token_type = "symbol"
else:
text = re.search("^[a-zA-Z_][a-zA-Z_\\d]*", self.word, re.MULTILINE)
if text is not None:
if self.key_words.__contains__(text.group()):
self.token_type = "keyword"
else:
self.token_type = "identifier"
cut_index = text.span()[1]+1
else:
text = re.search("^\\d+", self.word, re.MULTILINE)
if text is not None:
self.token_type = "integerConstant"
cut_index = text.span()[1]+1
self.set_word(cut_index)
def advance(self):
if self.word != "" or self.word != " " or self.word != "\n":
self.extract_token()
else:
if self.inside_string and self.token == "\"":
string_content = re.search("[^\"]*", self.file_content)
self.token = string_content.group()
self.token_type = "stringConstant"
self.file_content = self.file_content[string_content.span()[1]:]
elif self.has_more_tokens():
separator = re.search(" |\n|\"", self.file_content)
if separator.group() == "\"":
self.inside_string = not self.inside_string
cut_at = separator.span()[0]+1
self.word = self.file_content[:cut_at]
self.file_content = self.file_content[cut_at:]
else:
cut_at = separator.span()[0]
self.word = self.file_content[:cut_at]
self.file_content = self.file_content[cut_at+1:]
self.extract_token()
|
77fc63e1a55037dd1b39fc1ee329663f8d3888d0 | PrithviSathish/SchoolProjects | /triangleType.py | 361 | 4.25 | 4 | # Find the type of triangle
s1 = int(input("Enter the length of side 1: "))
s2 = int(input("Enter the length of side 2: "))
s3 = int(input("Enter the length of side 3: "))
if s1 == s2 == s3:
print("The triangle is Equilateral")
elif (s1 == s2) or (s2 == s3) or (s3 == s1):
print("The triangle is isoscles")
else:
print("The triange is scalene")
|
58e393207aca31fe19d52cfbddc57cdb0094968f | RomanSC/Introduction-to-Programming-with-Python | /strings/how-quotes-work.py | 333 | 4.09375 | 4 | # this demonstrates syntax for strings
# in python there is no difference, except for style
# between "string" and 'string'
# double quotes, \n prints a new line
print("This string uses double quotes: ")
print("Hello world!\n")
# single quotes, \n prints a new line
print('This string uses single quotes: ')
print('Suh dude!\n')
|
f5d05c65eaee246537ba1dc34c80d5853e469f2b | duyvuleo/scientific-paper-summarisation | /Summarisers/Summariser.py | 1,317 | 3.984375 | 4 | import abc
class Summariser:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def summarise(self, filename):
"""
Generates a summary of a paper.
:param filename: the filename of the paper to summarise. The paper is in a specific form: it is a text file
where each section is delineated by @&#SECTION-TITLE@&#.
:return: a summary of the paper.
"""
pass
@abc.abstractmethod
def prepare_paper(self, filename):
"""
Takes the filename of the paper to summarise and reads the paper into memory. It also puts it into the requisite
form for summarising the paper, that is it splits the paper on the symbol "@&#" and then puts the paper into a
dictionary where the keys are the section titles and the values are the text in that section. The values, i.e.
the section text, will be in the form of a list of lists, where each list is a list of words corresponding to
a sentence in that section. Depending on the model, this may be augmented in some way e.g. the sentences may
be read in as averaged word vectors or feature vectors rather than raw words.
:return: the scientific paper in a form suitable fo the summarisation algorithm to run on.
"""
pass |
02e75b45374d35a2a8862dee62f817cc4850cedd | DKU-STUDY/Algorithm | /BOJ/solved.ac_class/Class02/11050. 이항계수/sAp00n.py | 146 | 3.5 | 4 | from math import factorial as f
n, k = map(int, input().split())
if k < 0 or k > n:
print(0)
else:
print(int(f(n) / (f(k) * f(n - k))))
|
809518979a117af21bae227e0bfbb7224a4eddc2 | BIDMAL/codewarsish | /HackerRank/Data Structures/Arrays/Arrays - DS.py | 153 | 3.78125 | 4 | inp = ['4',
'1 4 3 2']
def reverseArray(a):
return a[::-1]
N = int(inp[0])
arr = list(map(int, inp[1].split()))
print(*reverseArray(arr))
|
5aa6d2f4d5029baa01953fb74dc760ece168307d | Syntaf/Challenge | /DEVELOP_scripts/arizona/format_data.py | 1,078 | 3.546875 | 4 | """
@author: Grant Mercer
gmercer015@gmail.com
Script designed to read in a data file of a specific format as
dat.txt shows, and display information on each station formatted
according to format.dat .
"""
import re
import string
from itertools import groupby
bad_chars = '(){}"<>[] ' # characers we want to strip from the string
key_map = []
# parse file
with open("dat.txt") as f:
data = f.read()
data = data.strip('\n')
data = re.split('}|\[{', data)
# format file
with open("format.dat") as f:
formatData = [x.strip('\n') for x in f.readlines()]
data = filter(len, data)
# strip and split each station
for k in range(1, len(data)-1):
# perform black magic, don't even try to understand this
dat = filter(None, data[k].translate(string.maketrans("", "", ), bad_chars).split(','))
key_map.append(dict(x.split(':') for x in dat if ':' in x))
if ':' not in dat[4] : key_map[k-1]['NAME']+=str(", " + dat[4])
for station in range(0, len(key_map)):
for opt in formatData:
print opt,":",key_map[station][opt]
print ""
|
b6523a22a589df6f5153a30524e0cf7f3b93472b | Danny7226/MyLeetcodeJourney | /normal_order_python/7.ReverseInteger.py | 1,009 | 4.0625 | 4 | '''
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within
the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem,
assume that your function returns 0 when the reversed integer overflows.
'''
# sth[i:j:s] from i(included) to j(excluded) by step s(defaults 1)
i = 123
class Solution:
def reverse(x: int) -> int:
if (x >= 0):
toStringR = reversed(str(x))
out = int(''.join(list(toStringR)))
# or: out = str(x)[::-1]
else:
toStringR = reversed(str(x).lstrip('-'))
out = -int(''.join(list(toStringR)))
# or: out = str(x)[1:][::-1]
if (out > (2**31 - 1)) or (out < -(2**31)):
return 0
else: return out
print(Solution.reverse(i))
|
79ac40fa70feaaec86fdc5df7df38747c0927081 | simzhi/PY4E-Assignments | /chapter8_1_assignment.py | 107 | 3.546875 | 4 | fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
print(line.rstrip())
|
99fa6e0f8c1dd787d15147175b6cb778923abba1 | andrewghaddad/OOP | /OOP/Notes/Week5/number_guessing_game.py | 894 | 4.28125 | 4 | # Generate a random integer in the range [1,10]
# Ask the user to guess the number until they guess correctly
import random
play = ""
while play != "no":
lower_bound = 1
upper_bound = 10
secret_number = random.randint(lower_bound, upper_bound)
guess = 0
while True:
guess = int(input("Please enter your guess: "))
if guess == secret_number:
print("Congratulations!")
break
else:
if guess < secret_number:
print("Your guess was too low")
else:
print("Your guess was too high")
play = input("Do you want to keep playing? Enter 'no' to stop: ")
# 1. Write code to solve the problem once
# 2. Place the code into a loop
# 3. Figure out the exit condition
# 4. Double check your work
# a) check before the loop
# b) check during the loop
# c) check after the loop |
4753b7004988dfef5d26f7ddce38061b9f961f67 | pavankumar2203/InterviewcakeSolutions | /25.py | 267 | 3.625 | 4 | def ktolast(node, k):
if node is None:
raise Exception("Node cannot be None")
start = head
i = 0
while(i < k):
start = start.next
while(start is not None):
start = start.next
head = head.next
return head
|
0d2a71818211f0941f5f2abef757e0ab9d1fe162 | tudor-alexa99/fp | /Movie_rental/domain/movie_validator.py | 1,190 | 3.84375 | 4 | import unittest
from domain.movie import Movie
class ValidateMovie:
def validate(self, movie):
_errors = []
if isinstance(movie, Movie) == False:
_errors.append("Instance error! The object 'movie' does not belong to the 'Movie' Class")
if len(movie.title) == 0:
_errors.append("The title should not be empty")
if len((movie.descr)) == 0:
_errors.append("The description should not be empty")
if len((movie.genre)) == 0:
_errors.append("The genre should not be empty")
if len(_errors) != 0:
raise ValueError(_errors)
return True
class TestValidate(unittest.TestCase):
def setUp(self):
self.validator = ValidateMovie()
def test_title(self):
self.assertEqual(self.validator.validate(Movie(1, "T1", "D1", "G1")), True)
self.assertRaises(ValueError, self.validator.validate, Movie(1, '', 'D1', 'G1'))
def test_descr(self):
self.assertEqual(self.validator.validate(Movie(1, "T1", "D1", "G1")), True)
self.assertRaises(ValueError, self.validator.validate, Movie(1, 'T1', '', 'G1')) |
7a59af12b94dd87a24e78691d90bbc6cdd49984d | larad5/python-exercises | /functions/max_two_values.py | 330 | 4.09375 | 4 | # 12. Maximum of Two Values
# functions
def maximum(a,b):
if a > b :
return a #the value that is returned can be within a decision structure
else:
return b
# program
num1 = int(input("First number: "))
num2 = int(input("Second number: "))
print("The greater number is",maximum(num1,num2))
|
b8940d9bec5640a343bbec3a6437946c6f91fe13 | Thunderbirrd/algs-structures | /lesson2/2.py | 272 | 4.125 | 4 | number = int(input("Ведите число: "))
even = 0
odd = 0
while number > 0:
last = number % 10
if last % 2 == 0:
even += 1
else:
odd += 1
number //= 10
print(f"Количество чётных - {even}, нечётных - {odd}")
|
e8027a0ac53fda955115ef5b3b8b817ff36e72b0 | DENNIS-CODES/Stack-Machine | /Stack1.py | 570 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 12 19:21:16 2021
@author: user
"""
def check_palindrome(string):
length = len(string)
first = 0
last = length -1
status = 1
while(first<last):
if(string[first]==string[last]):
first=first+1
last=last-1
else:
status = 0
break
return int(status)
string = input("Enter the string: ")
print("Method 1")
status= check_palindrome(string)
if(status):
print("It is a palindrome")
else:
print("Sorry! Try again")
|
0d99a5dc6fde9184c24c38204e40fc74ff306d98 | elvinrasul/Python | /lecture1/lambda.py | 202 | 3.8125 | 4 | people = [
{"name": "Harry", "house": "arlington"},
{"name": "Rachel", "House": "Fairfax"},
{"name": "Ahmet", "house": "DC"}
]
people.sort(key=lambda person: person["name"])
print(people) |
c18d0dd6eefa327774100919727ecafb5346e73c | loveQt/PythonWebSourceCode | /02/01.py | 178 | 3.8125 | 4 | time=12
if(time==12):
print '12' #
else:
print '18' #
time=time+6 #
print str(time) # |
e1bf1e196baac1bdff4d2793dfc7ed591a8e26ea | er-aditi/Learning-Python | /Practice_Programs/While_NumberSum.py | 119 | 3.875 | 4 | num = int(input("Enter Number: "))
var = 0
while num > 1:
var = var + (num % 10)
num = num // 10
print(var)
|
3b415581401c23284d5b730f8e0040754630e399 | Scott-Huston/Algorithms | /stock_prices/stock_prices.py | 889 | 4.0625 | 4 | #!/usr/bin/python
import argparse
def find_max_profit(prices):
# Check that there are at least 2 prices
if len(prices) < 2:
raise Exception('Price array does not contain 2 or more prices')
# initialize max profit
max_profit = prices[1] - prices[0]
for i, price_1 in enumerate(prices):
for price_2 in prices[i+1:]:
profit = price_2 - price_1
if profit > max_profit:
max_profit = profit
return max_profit
if __name__ == '__main__':
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
args = parser.parse_args()
print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers)) |
2c7a474dbe451327a9b6ffc55e9e2ca18663a9f8 | boknowswiki/mytraning | /lc/python/441_arranging_coins.py | 1,039 | 3.546875 | 4 | #!/usr/bin/python -t
# binary search
# time O(logn)
# space O(1)
class Solution:
def arrangeCoins(self, n: int) -> int:
l = 0
r = n
while l + 1 < r:
mid = l + (r-l)//2
coin_needed = self.coin_num(mid)
if coin_needed == n:
return mid
elif coin_needed < n:
l = mid
else:
r = mid
if self.coin_num(r) <= n:
return r
return l
def coin_num(self, num):
return (1+num)*num//2
#time O(log2^n) space O(1)
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0 or n == 1:
return n
l = 1
r = n
while l < r:
m = l + (r-l)/2
need = (1+m)*m/2
if need <= n:
l = m+1
else:
r = m
return l-1
|
d36845b19a861a9433d54e023d051e7e556defc9 | ymccarter/flashcard_project | /working_mihon/automationPython/lesson44PDF.py | 2,326 | 3.796875 | 4 | #! /usr/bin/env Python3
import PyPDF2
import os
"""
#print(os.getcwd())
os.chdir('/Users/ymccarter/PycharmProjects/Mihon/working_mihon/Renshu_folder/automationPython/FileDirectory')
pdfFile=open('/Users/ymccarter/Downloads/meetingminutes1.pdf','rb')
reader=PyPDF2.PdfFileReader(pdfFile)
reader.numPages
page=reader.getPage(0)
print(page.extractText())
for pageNum in range(reader.numPages): #shows contents of PDF
print(reader.getPage(pageNum).extractText())
#SAY WE WANT TO COMBINE MULTIPE PDF FILE. IN THIS SCENARIO MEETINGMINUTE 1 AND 2:
os.chdir('/Users/ymccarter/PycharmProjects/Mihon/working_mihon/Renshu_folder/automationPython/FileDirectory')
pdfFile1=open('/Users/ymccarter/Downloads/meetingminutes1.pdf','rb')
pdfFile2=open('/Users/ymccarter/Downloads/meetingminutes2.pdf','rb')
reader1=PyPDF2.PdfFileReader(pdfFile1)
reader2=PyPDF2.PdfFileReader(pdfFile2)
print(reader1.numPages) # numPages in PyPDF2 will count the number of page
print(reader2.numPages)
# and you can use 'reader.getPage('page#') ' to take the object of specified page
#page.extractText() will show the text format of content
page=reader1.getPage(0)
print(page.extractText())
#you can create a loop to extract page contents too:
for pageNum in range(reader1.numPages):
print(reader1.getPage(pageNum).extractText())
"""
#writer function
#create the loop and add each page to add each page of two PDFs
pdfFile1=open('/Users/ymccarter/Downloads/meetingminutes1.pdf','rb')
pdfFile2=open('/Users/ymccarter/Downloads/meetingminutes2.pdf','rb')
reader1=PyPDF2.PdfFileReader(pdfFile1)
reader2=PyPDF2.PdfFileReader(pdfFile2)
writer = PyPDF2.PdfFileWriter() #creating written object
for pageNum in range(reader1.numPages):
page = reader1.getPage(pageNum)
writer.addPage(page) #adding the file1 to written object
for pageNum in range(reader2.numPages):
page = reader2.getPage(pageNum)
writer.addPage(page) #adding the file2 on the top of file1 to the written object.
outputfile=open('combinedminutes.pdf','wb')
writer.write(outputfile)
pdfFile2.close()
pdfFile1.close()
outputfile.close()
pdfFile3=open('combinedminutes.pdf','rb')
reader3=PyPDF2.PdfFileReader(pdfFile3)
print(reader3.numPages)
for pageNum in range(reader3.numPages): #shows contents of PDF
print(reader3.getPage(pageNum).extractText()) |
f857a1bf30f614bbd64693f32e9e78d85dca3575 | osama-mohamed/python_projects | /python projects 3.6/إدخال رقم وجمعه مع الأرقام الفرديه الأصغر منه.py | 448 | 4.1875 | 4 | while True :
n = int(input('Enter a number : '))
def sum_odd(n):
total = 0
for i in range(1, n+1, 2):
total += i
return total
print(sum_odd(n))
'''
while True :
n = int(input('Enter a number : '))
def sum_odd(n):
if n < 2 :
return 1
elif n % 2 == 0 :
return sum_odd(n -1)
else :
return n + sum_odd(n - 2)
print(sum_odd(n))
'''
|
8f5a80bf0aad80371cbc30c8eaecd529390e9765 | yingcuhk/LeetCode | /Algorithms/#128 Longest Consecutive Sequence/PythonCode.py | 2,414 | 3.78125 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.recursiveSolution(nums)
def recursiveSolution(self,nums):
# a solution that is fast on the testing set but seems not O(N)
# this solution use the naive method implemented below
L = len(nums)
if L == 1:
return 1
minval = nums[0]
maxval = nums[0]
for num in nums:
if num < minval:
minval = num
if num > maxval:
maxval = num
Interval = maxval-minval+1
if Interval < L**2:
return self.naiveSolution(nums)
SegL = Interval/(L-1)
SubLists = [[] for k in xrange(L+1)]
for num in nums:
pos = int((num-minval)/SegL)
SubLists[pos].append(num)
SubLists[pos+1].append(num)
LongL = 0
for sublist in SubLists:
if len(sublist) > 0:
temp = self.recursiveSolution(sublist)
LongL = max(LongL,temp)
return LongL
def naiveSolution(self,nums):
# a naive solution to utilize too much memory
#print nums
if len(nums) == 1:
return 1
minval = nums[0]
maxval = nums[0]
for num in nums:
if num < minval:
minval = num
if num > maxval:
maxval = num
ListLen = maxval-minval+1
Markers = list([0]*ListLen)
for num in nums:
Markers[num-minval] = 1
LongestL = 1
curL = 1
for m in range(1,ListLen):
if Markers[m] == 1:
curL += 1
else:
if curL > LongestL:
LongestL = curL
curL = 0
if curL > LongestL:
LongestL = curL
return LongestL
# [2147483646,-2147483647,0,2,2147483644,-2147483645,2147483645]
|
5a050e480a143daafcbe364c9e338397bf7d08ca | rtountch/python-challenge | /PyBank/.ipynb_checkpoints/main-checkpoint.py | 1,817 | 3.640625 | 4 | #final file
import os
import csv
c_csv = os.path.join("budget_data.csv")
lines = []
with open(c_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
NumMonths = 0 # variable to hold the # of months
TotalProfitLoss = 0 # variable to hold the total Profit / Loss
AvgProfitLoss = 0 # variable to hold the average Profit / Loss over the period
MaxProfit = 0
MinLoss = 0
MaxDate = "Jan-2010"
MinDate = "Jan-2010"
for row in csvreader:
NumMonths = NumMonths + 1
Amount = int(row[1])
TotalProfitLoss = TotalProfitLoss + Amount
if MaxProfit < Amount:
MaxProfit = Amount
MaxDate = row[0]
if MinLoss > Amount:
MinLoss = Amount
MinDate = row[0]
AvgProfitLoss = TotalProfitLoss / NumMonths
lines.append("There are a total of "+ str(NumMonths) + "months in this data set")
print("There are a total of ", NumMonths, "months in this data set")
lines.append("The total Profit / Loss over the period is $" + str(TotalProfitLoss))
print("The total Profit / Loss over the period is $",TotalProfitLoss)
lines.append("The average monthly Profit / Loss is $" + str("%.2f" % AvgProfitLoss))
print("The average monthly Profit / Loss is $", "%.2f" % AvgProfitLoss)
lines.append("The Max Profit is $" + str(MaxProfit) + " " + MaxDate)
print("The Max Profit is $" + str(MaxProfit)+ " " + MaxDate)
lines.append("The Min Profit is $" + str(MinLoss)+ " " + MinDate)
print("The Min Profit is $" + str(MinLoss)+ " " + MinDate)
with open('solution_data.txt', mode='wt', encoding='utf-8') as myfile:
myfile.write('\n'.join(lines)) |
932691dc5f4325f84684f89d36e4d3686e4857b3 | jackalsin/Python | /15112/Quiz/H5P.PY | 6,768 | 3.6875 | 4 | import copy
def isLatinSquare(a):
(rows,cols)=(len(a),len(a[0]))
aa=copy.copy(a)
if rows * cols==0:
return False
for i in range(cols):
target=a[0][i:]+a[0][:i]
if target in aa:
aa.remove(target)
else:
return False
return True
def testIsLatinSquare():
print("Testing isLatinSquare()...", end="")
assert(isLatinSquare([['A','B','C'],['B','A','C'],['C','A','B']]) == False)
assert(isLatinSquare([['A','B','C'],['B','C','A'],['C','A','B']]) == True)
assert(isLatinSquare([['B','C','A'],['A','B','C'],['C','A','B']]) == True)
assert(isLatinSquare([[],[],[]]) == False)
print("Passed. (Add more tests to be more sure!)")
testIsLatinSquare()
# Write the function matrixAdd(m1, m2) that takes two 2d lists
# (that we will consider to be matrices, in the linear algebra sense)
# and returns a new 2d list that is the result of adding the two matrices.
# Return None if the two matrices cannot be added for any reason.
def matrixAdd(m1,m2):
(rows1,cols1)=(len(m1),len(m1[0]))
(rows2,cols2)=(len(m2),len(m2[0]))
if (rows1!=rows2) or (cols1!=cols2) or (rows1*cols1*cols2*rows2==0):
return False
sum=[[0]*cols1 for row in range(rows1)]
for row in range (rows1):
for col in range(cols1):
sum[row][col]=m1[row][col]+m2[row][col]
return sum
def testMatriAdd():
print("Testing matrixAdd()...", end="")
A=[[1,2,3],[4,5,6],[7,8,9]]
B=[[5,6,7],[8,4,3],[3,4,6]]
C=[[3,5],[3,4]]
D=[[],[]]
assert(matrixAdd(A,B) == [[6,8,10],[12,9,9],[10,12,15]])
assert(matrixAdd(A,C) == False)
assert(matrixAdd(D,D) == False)
print("Passed. (Add more tests to be more sure!)")
testMatriAdd()
def matrixMultiply(m1,m2):
(rows1,cols1)=(len(m1),len(m1[0]))
(rows2,cols2)=(len(m2),len(m2[0]))
if (rows1!=cols2) or (rows1*cols1*cols2*rows2==0):
return False
else:
rows=rows1
cols=cols2
sum=[[0]*cols for row in range (rows)]
for row in range(rows):
for col in range(cols):
sum[row][col]=getSum(m1,m2,row,col)
print(sum)
return sum
def getSum(m1,m2,row,col):
(rows1,cols1)=(len(m1),len(m1[0]))
(rows2,cols2)=(len(m2),len(m2[0]))
unit=0
# for (iCol,iRow) in zip (cols1,rows2):
# unit+=m1[row][iCol]*m2[col][iRow]
iRow=iCol=0
while(iCol<cols1):
unit+=m1[row][iCol]*m2[iRow][col]
iRow+=1
iCol+=1
return unit
def testMatrixMultiply():
print("Testing matrixMultiply()...", end="")
A=[[1,2,3],[4,5,6],[7,8,9]]
B=[[5,6,7],[8,4,3],[3,4,6]]
C=[[3,5],[3,4]]
D=[[],[]]
assert(matrixMultiply(A,B) == [[30,26,31],[78,68,79],[126,110,127]])
assert(matrixMultiply(A,C) == False)
assert(matrixMultiply(D,D) == False)
print("Passed. (Add more tests to be more sure!)")
testMatrixMultiply()
# Helper function for print2dList.
# This finds the maximum length of the string
# representation of any item in the 2d list
def maxItemLength(a):
maxLen = 0
rows = len(a)
cols = len(a[0])
for row in range(rows):
for col in range(cols):
maxLen = max(maxLen, len(str(a[row][col])))
return maxLen
# Because Python prints 2d lists on one row,
# we might want to write our own function
# that prints 2d lists a bit nicer.
def print2dList(a):
if (a == []):
# So we don't crash accessing a[0]
print([])
return
rows = len(a)
cols = len(a[0])
fieldWidth = maxItemLength(a)
print("[ ", end="")
for row in range(rows):
if (row > 0): print("\n ", end="")
print("[ ", end="")
for col in range(cols):
if (col > 0): print(", ", end="")
# The next 2 lines print a[row][col] with the given fieldWidth
formatSpec = "%" + str(fieldWidth) + "s"
print(formatSpec % str(a[row][col]), end="")
print(" ]", end="")
print("]")
def playMemoryGame(rows, cols):
board=makeABoard(rows,cols)
displayBoard=[['-']*cols for row in range (rows)]
(score1,score2)=(0,0)
count=0
player=0
while(count<=rows*cols/2):
player=player%2+1# so player 1 and player 2
guessPosition=getGuessPosition(player,board,displayBoard)
# example [(1,2),(3,4)]
if (takeGuess(board,displayBoard,guessPosition)):
count+=1
if player==1:
score1+=1
else:
socre2+=1
player+=1
print2dList(displayBoard)
def takeGuess(board,displayBoard,guessPosition):
(rows,cols)=(len(board),len(board[0]))
guess1Row=guessPosition[0][0]
guess1Col=guessPosition[0][1]
guess2Row=guessPosition[1][0]
guess2Col=guessPosition[1][1]
if (board[guess1Row][guess1Col]==board[guess2Row][guess2Col]):
displayBoard[guess1Row][guess1Col]=board[guess1Row][guess1Col]
displayBoard[guess2Row][guess2Col]=board[guess2Row][guess2Col]
return True
else:
return False
def getGuessPosition(player,board,displayBoard):
(rows,cols)=(len(board),len(board[0]))
while True:
response=input("Enter player %d's move ([[row1,col1],[row2,col2]]) --> "
% (player))
inputResult=[]
try:
for item in response.split(' '):
inputResult+=[item]
print(inputResult)
(row1,col1,row2,col2)=(int(inputResult[0])-1,int(inputResult[1])-1,
int(inputResult[2])-1,int(inputResult[3])-1)
# so that get the normal Value
if ((col1<0 or row1<0 or col2 <0 or row2<0)
or (col1>cols or row1>rows or col2>cols or row2>rows)):
print("Columns must be between 1 and %d\n Rows must be between 1 and %d "
% (cols,rows), end="")
elif(col1==col2 and row1==row2):
print("You're entering the same position")
elif (displayBoard[row1][col1]!='-') or (displayBoard[row2][col2]!='-'):
print("That position has been occupied ", end="")
else:
print("we enter the return statement")
return [[row1,col1],[row2,col2]]
except:
print("You must enter integer values! ", end="")
print("Please try again.")
def makeABoard(rows,cols):
result=[[0]*cols for row in range (rows)]
count=0
for row in range(rows):
for col in range(cols):
result[row][col]=round((count)%((rows*cols)/2))
count+=1
return result
cols=4
rows=4
# displayBoard=[['-']*cols for row in range (rows)]
# board=makeABoard(cols,rows)
# print(getGuessPosition(1,board,displayBoard))
playMemoryGame(rows, cols) |
1b12b5769ec2b7f17882b5c939d4303afa04c24b | dardevetdidier/blitz | /models/rounds.py | 1,371 | 3.75 | 4 | from time import strftime, localtime
from os import system
class Round:
def __init__(self, players_pairs):
self.name = ''
self.start_time = None # modified when round is created
self.end_time = None # modified when round is over
self.players_pairs = players_pairs
self.scores = None
self.round_list = []
def starts_round(self, round_number, tournament):
"""
Modifies 'name' and 'start_time' attributs, used by the new instance creation when user creates a new round.
Returns a list containing round information
"""
self.name = f"round_{round_number}"
self.start_time = strftime('%a %d %b %Y %H:%M:%S', localtime())
self.round_list.extend([self.name, self.start_time, self.end_time, self.players_pairs, self.scores])
system('cls')
print(f"\n\tLe round {round_number} du tournoi '{tournament}' a bien été créé.")
return self.round_list
def ends_round(self, scores):
"""
modifies the date of the end of the round. Modifies end date of the round and scores entered by user in round
list. Returns this list.
"""
self.end_time = strftime('%a %d %b %Y %H:%M:%S', localtime())
self.round_list[2] = self.end_time
self.round_list[-1] = scores
return self.round_list
|
6f3a36143e4eb60b81684af6699ec87f13a7ae7f | rexayt/Meu-Aprendizado-Python | /Aula13/ex52.py | 403 | 3.828125 | 4 | p=int(input('Digite um número: '))
t = 0
for c in range(1, p + 1,):
if p % c == 0:
print('\033[33m', end=' ')
t += 1
else:
print('\033[31m', end=' ')
print('{}'.format(c), end=' ')
print('O número {}, foi divísivel {} vezes'.format(p, t))
if t == 2:
print('O número {} é PRIMO'.format(p))
else:
print('O número {} não é primo.'.format(p)) |
47adc969aaba5e19a640714387f0c9d65a879cc6 | yyyuaaaan/python7th | /crk/1.2.py | 1,018 | 3.984375 | 4 |
"""
__author__ = 'anyu'
Implement a function void reverse (char* str) in C or C++
which reverses a null-terminated string.
Just reverse a string.
"""
# if we recursively do this problem, it will take too much space, not in place,
# because everytime the python interpreter calls a recursive function, it set
# a new stack frame, it is too costly, in other languges surporting CPS transformation
# we can use recursive way.
def reverse(s):
if not s:
return s
return reverse(s[1:])+s[0]
def reversestr(s):
"""
:param s: input string
:return: reversed string
"""
if not s or len(s) ==1:
return s
else:
return ''.join(s[-1]+reversestr(s[1:-1])+s[0])
print reversestr('fsasdf')
def reverse2(s):
if not s:
return s
if len(s)==1:
return s
else:
l = list(s)
for i in range(len(s)/2):
# switch two chars
l[i], l[len(s)-i-1] = l[len(s)-i-1], l[i]
return ''.join(l)
print reverse2("asdf")
|
0113ea7cfa071fdf4d31f0dfaeeae4e68cb2d833 | GuhanSGCIT/Trees-and-Graphs-problem | /special arrangement.py | 1,672 | 4.21875 | 4 | """
An operation on an array of size n shifts each of the array's elements 1 unit to the left.
Given an array of n integers and a number, d, perform d operations on the array. Then print the updated array as a single
line of space-separated integers.
timng:1sec
level:4
Input Format:
The first line contains two space-separated integers denoting the respective values of n (the number of integers) and d
(the number of operations you must perform).
The second line contains n space-separated integers describing the respective elements of the array's initial state.
Constraints:
1≤n≤105
1≤d≤n
1≤ai≤106
where ai is the ith element of array
Output Format:
Print a single line of n space-separated integers denoting the final state of the array after performing d operations.
Sample Input:
5 4
1 2 3 4 5
Sample Output:
5 1 2 3 4
Explanation:
When we perform d=4 operations, the array undergoes the following sequence of changes:
[1,2,3,4,5]→[2,3,4,5,1]→[3,4,5,1,2]→[4,5,1,2,3]→[5,1,2,3,4]
Thus, we print the array's final state as a single line of space-separated values, which is 5 1 2 3 4.
Input:
6 3
19 4 6 5 2 1
output:
5 2 1 19 4 6
Input:
9 8
8 4 6 5 1 2 3 7 9
output:
9 8 4 6 5 1 2 3 7
Input:
4 2
5 8 6 1
output:
6 1 5 8
Input:
5 2
8 5 2 6 3
output:
2 6 3 8 5
hint:
Instead of shifting the elements one by one, we first print elements from index ddd to index n−1.
Then from 0 to index d−1.
"""
n,k = map(int,input().split())
arr = list(map(int,input().split()))
if len(arr) == n:
arr = arr[k:] + arr[:k]
for i in arr:
print(i,end=" ")
print()
|
d1a12efd4ded5c06af36121a4f8f83569702b341 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140924W.py | 1,728 | 3.65625 | 4 | """
[Weekly #12] Learning a new language
https://www.reddit.com/r/dailyprogrammer/comments/2h5u7q/weekly_12_learning_a_new_language/
There are many ways to learn a new language. Books. Online videos. Classes. Virtual online Classes. In addition there
are many supports to learning the language. Google searching questions you have to find answers (lot of them list hits
on stackoverflow.com)
This we week we share these methods/books/websites/suggestions on learning that new language or a language you post to
get some daily programmer user tips for.
Before posting - search for the language first in this topic and add to that thread of discussion. So try to avoid 20
threads about "python" for example. Add to the python one.
* Pick 1 language - start a thread on it with just the name of that language (could be one you know or one you want to
know.
* Add to that thread (reply to the 1st comment on the language) list some good tips on learning that language. Maybe a
book. Classes. Website. subreddit. Whatever.
* Shared experience. For example learning objective C I would list some websites/books that help me but I might add a
story about how I found always having the api documentation up and ready to use in front of me as I did classes/read
books was very helpful.
* Or if you have a "in general" tip - go ahead and add a general tip of learning languages. Insight shared is very
valued
#Last week's Topic:
[Weekly 11] (http://www.reddit.com/r/dailyprogrammer/comments/2ggunp/weekly_11_challenges_you_want/)
#2nd Week
I will keep this up another week. Thank you for everyone for donating to this thread so far. Lots of great replies and
sharing.
"""
def main():
pass
if __name__ == "__main__":
main()
|
000b0ecd7ec3c9eb7346232a668bbacdde10f4a7 | scr44/PyBev | /PyBev/Old Versions/pyBev_0-4/pyBev_0-4-6/pybev/datecheck.py | 2,890 | 4.625 | 5 | """Functions to turn user input dates into valid datetime objects."""
import datetime as dtt
def date_stripper(date):
"""Takes a given date or datetime object and strips out all information besides
the day, month, and year, then returns as a datetime object. Can be used to
turn dates into datetimes."""
# the fact that there's no native dtt.date.to_datetime() method is just mind-
# bogglingly dumb
return dtt.datetime(
year=date.year,
month=date.month,
day=date.day
)
def date_from_str(datestring=None):
"""Turns a string into a datetime. Takes date string using the format
'MM/DD/YYYY'. If given 'default' as the string, it will return today as a
datetime."""
if datestring is None:
today_date = dtt.datetime.today()
today_datetime = date_stripper(today_date)
return today_datetime
else:
try:
date = dtt.datetime.strptime(datestring,'%m/%d/%Y')
except ValueError:
print('Unrecognized date format, please try again.')
date = None
return date
def choose_week(weeksago_init=None):
"""Asks for the week you wish to check. Using the default will return the
current week. Accepts either a date in the format MM/DD/YYYY or an integer
of a week difference (one week ago would be -1, for example)."""
prompt = '''Input date to check.
Format as MM/DD/YYYY or negative integer of weeks ago:
(Defaults to current week)\n\n'''
if weeksago_init is None:
datestring = weeksago_init
elif weeksago_init is not None:
datestring = input(prompt) or None
try:
weeksago = int(datestring)
week_date = dtt.datetime.today() + (dtt.timedelta(days=7) * weeksago)
week_date = date_stripper(week_date.date()) # strip out the hh:mm:ss data
except (NameError,ValueError,TypeError):
week_date = date_from_str(datestring)
if week_date is None:
return None
if week_date.weekday() != 6: # if it's not a Sunday
monday_difference = dtt.timedelta(days=week_date.weekday())
# -1 since Monday == 0 for some reason
week_date = (week_date - monday_difference - dtt.timedelta(days=1))
if week_date > dtt.datetime.today():
print('Warning: Future dates may not function correctly with other stages.')
return week_date
def choose_cutoff():
"""Asks for a cutoff date for the comparison checking. Returns a datetime
object."""
prompt = '''Input comparison check cutoff date (MM/DD/YYYY):
(Defaults to current day)\n'''
datestring = input(prompt) or None
return date_from_str(datestring) |
1cbafa3541a8db74f27b1647377629d8d27b6124 | mvarnold/CS287 | /HW01/problem3_mvarnold.py | 2,043 | 3.734375 | 4 | # STAT/CS 287
# HW 01
#
# Name: Michael Arnold
# Date: 09-12-18
import urllib.request
from string import punctuation
def words_of_book():
"""Download `A tale of two cities` from Project Gutenberg. Return a list of
words. Punctuation has been removed and upper-case letters have been
replaced with lower-case.
"""
try:
f = open("two_cities.txt")
raw = f.read()
except FileNotFoundError:
# DOWNLOAD BOOK:
url = "http://www.gutenberg.org/files/98/98.txt"
req = urllib.request.urlopen(url)
charset = req.headers.get_content_charset()
raw = req.read().decode(charset)
f = open('two_cities.txt', 'w')
f.write(raw)
f.close()
# PARSE BOOK
raw = raw[750:] # The first 750 or so characters are not part of the book.
# Loop over every character in the string, keep it only if it is NOT
# punctuation:
exclude = set(punctuation) # Keep a set of "bad" characters.
list_letters_noPunct = [ char for char in raw if char not in exclude ]
# Now we have a list of LETTERS, *join* them back together to get words:
text_noPunct = "".join(list_letters_noPunct)
# (http://docs.python.org/3/library/stdtypes.html#str.join)
# Split this big string into a list of words:
list_words = text_noPunct.strip().split()
# Convert to lower-case letters:
list_words = [ word.lower() for word in list_words ]
return list_words
def count_most_common(word_list):
"""Count the words in the word list"""
word_counts = {}
for word in word_list:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
sort_list = sorted(list(word_counts.items()), key = lambda x: x[1],reverse=True)
return sort_list
print("word".ljust(10),"count".ljust(6))
print("-"*20)
words = words_of_book()
word_counts = count_most_common(words)
for word,count in word_counts[:100]:
print(word.ljust(10),str(count).ljust(6))
|
0486944594ef51004a80960260e426f2280f7a89 | nahida47/student_projects | /Self_IntroductionPy/Week6/001.py | 255 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 19 13:33:28 2016
@author: consT_000
"""
if type(varA)==str or type(varB)==str:
print('string involved')
elif varA>varB:
print('bigger')
elif varA==varB:
print('equal')
else:
print('smaller') |
d21554503d5f59966509c9c9a835903bfdf5eb38 | maksim-verzbitski/ConsoleMenuPython | /main.py | 5,532 | 3.625 | 4 | import keyboard
actions_menu = {
1: 'List all users - 1',
2: 'Edit user/s - 2',
3: 'Add new user - 3',
4: "Average(Medium) user's age - 4",
5: "Delete user - 5",
6: "Exit - 6"
}
def average_age(db):
sum=0
for i in range(0, len(db)):
row= db[i]
sum = sum + int(row[2])
print(i, row[2])
print(sum/i)
def deleting_user(db):
print('Deliting user')
print_out_database(db)
delete_user = int(input("What user you want to delete user's index number: "))
del db[delete_user]
write_database(db)
def strip(string):
return string.strip()
def read_database():
file = open("C:/Users/akell/Desktop/Tick-tac-toe/contacts.txt", encoding="utf-8")
rows = []
for row in file:
rows.append(list(map(strip, row.split(", "))))
return rows
def write_database(db):
file = open("C:/Users/akell/Desktop/Tick-tac-toe/contacts.txt", mode="w", encoding="utf-8")
rows = []
for row in db:
rows.append(", ".join(row))
file.write("\n".join(rows),)
file.close()
def print_out_menu_options():
for i in actions_menu:
print(actions_menu[i])
def print_out_database(db):
print("Index \t Name \t\t\t Phone \t\t\t Age \t Email")
for i in range(0, len(db)):
row = db[i]
print(i, "\t\t", row[0], "\t", row[1], "\t", row[2], "\t", row[3], "\t")
def listing_users(db):
print('Listing users...')
db = read_database()
# i Have fixed None issue
print_out_database(db)
def editing_users(db):
print('Editing users...')
# index name Phone Age Email
db = read_database()
listing_users(db)
index_inpt = int(input("Enter which user' index(exp: 1,2,3...) you would like to improve: "))
if index_inpt == 0:
print(db[index_inpt])
#print(i, "\t\t", row[0], "\t", row[1], "\t", row[2], "\t", row[3], "\t")
elif index_inpt == 1:
print(db[index_inpt])
elif index_inpt == 2:
print(db[index_inpt])
#elif index_inpt == len(db[index_inpt-1]):
#print(db[index_inpt-1])
else:
print("User's List is Out of range")
inpt = input("What field you would like to change: ")
if inpt.lower() == "Name":
add_name = input("Enter your desired name: ")
# db.write(db[0][0].replace())
db[index_inpt][0] = add_name
print(db[index_inpt][0])
elif inpt == "Phone":
add_number = input("Enter mobile number using only numbers and '+': ")
db[index_inpt][1] = add_number
print(db[index_inpt][1])
elif inpt == "Age":
add_age = input("Enter numeric value: ")
db[index_inpt][2] = add_age
print(db[index_inpt][2])
elif inpt.lower == "Email" or input.lower() == "@":
add_email = input("Enter email using letters numbers and @: ")
db[index_inpt][3] = add_email
print(db[index_inpt][3])
else:
print("Wrong input: => Try {Name, Phone, Age, Email}")
editing_users(db)
write_database(db)
def adding_user(db):
print('Adding users...')
db = read_database()
add_name = input("Add name:")
if add_name.isnumeric():
print("Only string are allowed!")
return
add_number = input("Add Phone number:")
if add_number.isalpha():
print("Only string are allowed!")
return
add_age = input("Add Age:")
if add_age.isalpha():
print("Only string are allowed!")
return
add_email = input("Add Email:")
db.append([add_name, add_number, add_age, add_email])
write_database(db)
# Press the green button in the gutter to run the script.
# As im using Pycharm here is main method
if __name__ == '__main__':
print("Welcome to main method"+"\nPress space to continue")
while True:
db = read_database()
try:
if keyboard.is_pressed('space'):
print('*******************************')
print_out_menu_options()
print('*******************************')
operation = int(input("Enter option you would like to choose:"))
if operation == 1:
#print("Listing your users...")
listing_users(db)
print("Press space")
elif operation == 2:
editing_users(db)
print("Press space")
elif operation == 3:
print("Adding new user to your contacts.txt...")
adding_user(db)
print("Press space")
elif operation == 4:
print("Calculating average user's age...")
average_age(db)
print("Press space")
elif operation == 5:
print("Deliting excisting user...")
deleting_user(db)
print("Press space")
elif operation == 6:
print("Exiting....")
break
exit()
else:
print("Invalid action. Try(1,2,3,4,5")
except:
print("you have entered incorrect information")
print("Press space")
def main():
db=read_database()
#print_out_database(db)
#print_out_menu_options()
main()
|
76236e2935fca917c5c952f14527607e6a3d78d5 | PiWingo/URI-Online-Judge | /Exercícios/1015/1015.py | 217 | 3.609375 | 4 | import math
line = input()
x1, y1 = line.split()
x1, y1 = [float(x1), float(y1)]
line2 = input ()
x2, y2 = line2.split()
x2, y2 = [float(x2), float(y2)]
Dist= math.sqrt ((x2-x1)**2+(y2-y1)**2)
print ("%.4f" %Dist) |
91dbac050284be497951bff95906a76d754c1e21 | faizygithub/-Database-Appplication-Demo-using-tkinter | /Database Application/account/acc.py | 1,227 | 3.640625 | 4 | class Account:
def __init__(self,filepath):
self.filepath=filepath
with open (filepath,'r') as file:
self.balance=int(file.read())
def withdraw(self,amount):
self.balance=self.balance-amount
def deposit(self,amount):
self.balance=self.balance+amount
def commit(self):
with open(self.filepath,'w') as file:
file.write(str(self.balance))
class Checking(Account):
""" This class generates Checking accounts"""
type="checking"
def __init__(self,filepath,fee):
Account.__init__(self,filepath)
self.fee=fee
def transfer(self,amount):
self.balance=self.balance-amount-self.fee
jacks_checking=Checking("account\\jack.txt",1)
jacks_checking.transfer(100)
print(jacks_checking.balance)
jacks_checking.commit()
print(jacks_checking.type)
jhons_checking=Checking("account\\jhon.txt",1)
jhons_checking.transfer(100)
print(jhons_checking.balance)
jhons_checking.commit()
print(jhons_checking.type)
print(jhons_checking.__doc__)
#checking.deposit(10)
#account=Account("account//balance.txt")
#print(account.balance)SS
#print(account.balance)
#print(account.balance)
|
e1d797790d72897699ed7a695212ab97f7dc9e3b | kailinxie/Tencent-50 | /Merge k Sorted Lists.py | 870 | 3.96875 | 4 | """
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
Sorted_List = []
for i in lists:
while i != None:
Sorted_List.append(i.val)
i = i.next
Sorted_List.sort()
#Merge the sorted lists into one list and sort it.
Head_Node = ListNode(None)
#Create the first node.
Node = Head_Node
#Copy the first node for moving the pointer.
for j in Sorted_List:
Node.next = ListNode(j)
#Assign values to nodes.
Node = Node.next
#Link the nodes.
return Head_Node.next
#Return all the nodes except the first node. |
3bcf98b4d12d684df00b318768acf3e2a776ac2e | BlackWolf95/Labelled-trees-Maths-homework | /check.py | 2,096 | 3.59375 | 4 | import networkx as nx
from random import randint
n=8
G1=nx.complete_graph(n)
G2=nx.Graph()
G2=G1
#G will be the output Graph
G=nx.Graph()
E=G.edges()
E2=G2.edges()
V2=G2.nodes()
len_V2=G2.number_of_nodes()
len_E2=G2.number_of_edges()
#V1 not needed, not available
#print(E2)
#print(V2)
#print(len_E2)
#print(len_V2)
#from 0 to n-1 we find the nodes
#and its corresponding vertices
x=0
#while (x<=n-1 and ):
while (len(G.nodes)!=n):
#select a vertex randomly
temp=randint(0,n-1)
#print(temp)
found=list(G2.edges(temp))
#from 1the edges connected to the vertex
#we randomly choose an edge
temp2=randint(0,len(found)-1)
rand_edge=found[temp2]
#print(rand_edge)
#get the start and ending nodes of the random edge obtained
u=rand_edge[0]
v=rand_edge[1]
#now check if u is not equal to v that is no self loop
#now add the nodes if it is not present
if (G.has_node(u)==False):
G.add_node(u)
if (G.has_node(v)==False):
G.add_node(v)
# and see if there exists an ed
if (u!=v) and (G.has_edge(u,v)==False):
G.add_edge(u,v)
#now check for cycles in G
list1=list(nx.cycle_basis(G))
#if length of list1 is 0, then there are no cycles
if((len(list1)==0)and (nx.is_connected(G)==True)):
x=x+1
#print("Go ahead!")
else:
#x=0
#reinitialize graph G
#G=nx.Graph()
G.remove_edge(u, v)
G.remove_node(u)
G.remove_node(v)
E=G.edges()
#print("RESTART!",len(list1),x)
#print(G.nodes())
#print(G.edges())
print("NUMBER OF NODES IN G")
print(len(G.nodes()))
print("NUMBER OF EDGES IN G")
print(len(G.edges()))
#print("DEGREES OF EACH NODE")
leaves=0;
avg=0
print("Degrees of each vertex:")
for i in range(0,n):
deg=G.degree(i)
print(deg)
avg=avg+deg
if deg==1:
leaves=leaves+1
print("LEAVES")
print(leaves)
print("DIAMETER")
d=nx.diameter(G)
print(d)
print("TOTAL DEGREE")
print(avg)
print("AVERAGE DEGREE")
avg=float(avg/n)
print(deg)
|
aed0dd7a96b6ac58818b2c3b44d8ddbdf25f1a8f | Ragini08/PPL-ASSIGNMENTS | /ASSIGNMENT 1/4guess.py | 479 | 4.1875 | 4 | import random
print("-----GUESS THE NUMBER GAME-----")
num = random.randint(1,25)
chance = 0
print("Guess a number between 1 and 25 : ")
while chance < 7:
guess = int(input())
if guess == num:
print("Congratulations! You got the number!")
break
elif guess < num:
print("Guess a high number! ")
else:
print("Guess a low number! ")
chance = chance + 1
if not chance < 7:
print("No more chances to guess, the number is ",num) |
96b762ba1cafa01b4d2b355edbc9fd7d35044eff | impraveen96/praveenkumar96 | /change.py | 509 | 4.09375 | 4 | def num_guess():
guess_number = 9
guess_count = 0
while guess_count < 3:
guess = int(input("guess a number : "))
guess_count += 1
if guess == guess_number:
print("well done 👏")
break
else:
print("You lost !")
print("Try again 😉")
num_guess()
while 1:
x = input("Do you want to continue(Y/N): ")
if x == 'Y' or x == 'y':
num_guess()
else:
break
print("thanks for choosing hope you enjoyed...")
|
d63b67fcead05a4be193cd38d34deeb4a3b8b83e | Awxi/Hangman | /Hangman.py | 1,112 | 4.125 | 4 | #Hangman:Beginner level
#welcome the user
name = input("What is your name: ")
print("Welcome "+ name + ", can you guess my word" )
#Secret Word
word = "amazing"
#number of guesses
guesses = ""
#number of turns
turns = 10
while turns > 0:
#make a counter that starts with zero.Just a flag.
failed = 0
#for every character in secret_word
for char in word:
#print tif the character is in the players guess
if char in guesses:
#print the character on the screen
print(char)
#if not
else:
#print nothing and add to failed attempts
print("_")
failed += 1
#if you failed 0 times you won
if failed == 0:
print("You won")
break
print()
guess = input("guess a character:")
guesses += guess
#if the geuss is not in word
if guess not in word:
turns -= 1
print("Wrong Guess")
print("You have", + turns,'more guesses')
if turns == 0:
print("You Lose")
|
0039dcb880b9574fad5526960d516ced50d48da2 | matchallenges/Portfolio | /2021/PythonScripts/intro.py | 183 | 3.875 | 4 | #for loop
for i in range(10):
print("Wow")
'''
multi-line
comment
'''
country = "Canada"
if(country == "Canada"):
print("Hello, Canada")
else:
print("Hello, America") |
bcc96e01c92ef6e122170019c36da72e8d7417ac | daniel-reich/ubiquitous-fiesta | /AeWbFdxSwAf5nhQpG_10.py | 172 | 3.5 | 4 |
def aux(num):
if not int(num/10):
return num%10
return num%10*aux(int(num/10))
def persistence(num):
return 1+persistence(aux(num)) if int(num / 10) else 0
|
6147fffd71ef5d4666a4a94354bef1b32d6e2cce | JMW0503/CSCI_4 | /betterVariables.py | 821 | 4.25 | 4 | """
pizzaSize = "medium"
pizzaNumToppings = 3
pizzaCost = 4.99
print("Pizza 1:")
print("The pizza size is", pizzaSize)
print("The number of toppings is", pizzaNumToppings)
print("THe pizza price is", pizzaCost)
pizzaSize2 = "Large"
pizzaNumToppings2 = 2
pizzaCost2 = 7.99
print("Pizza 2:")
print("The pizza size is", pizzaSize2)
print("The number of toppings is", pizzaNumToppings2)
print("THe pizza price is", pizzaCost2)
"""
class Pizza:
def __init__(self):
size = ""
numToppings = ""
cost = 0.0
pizza1 = Pizza
pizza1.size = "Medium"
pizza1.cost = 5.99
pizza1.numToppings = 3
print("Pizza 1:")
print("The pizza size is", pizza1.size)
print("The number of toppings is", pizza1.numToppings)
print("THe pizza price is", pizza1.cost)
|
adde446af3396838ec9254f305d0609de5ea3ca8 | SHASHANK992/Python_Hackerrank_Challenges | /HACKERRANK_FIND_STRING.py | 574 | 3.625 | 4 | def occurence_counter(source,target):
palin=0
flag = source.count(target)
location = source.find(target)
target2=target[::-1]
if(target2==target):
palin=1
if(palin==1):
location=location+len(target)-1
print(len(source))
flag=flag+source.count(target)
return flag
str = input()
search = input()
if (len(str)>=1 and len(str)<=200):
for i in range(len(str)):
if(isinstance(str[i],type('string'))):
flag=0
else: flag=1
if(flag==0):
print(occurence_counter(str,search)) |
60cf941cdac8129bf0778f2f7f9a19f30ad56e2a | chesterlee0722/hackerrank | /challenges/birthday-cake-candles/Birthday Cake Candles.py | 625 | 3.78125 | 4 | #!/bin/python3
#https://www.hackerrank.com/challenges/birthday-cake-candles/problem
import os
import sys
from functools import reduce
#
# Complete the birthdayCakeCandles function below.
#
def birthdayCakeCandles(n, ar):
#
# Write your code here.
#
arrSort = sorted(ar,reverse=True)
resultArr = [x for x in arrSort if x == arrSort[0]]
return(len(resultArr))
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = birthdayCakeCandles(n, ar)
f.write(str(result) + '\n')
f.close()
|
4a24dccc9a21fe6df5826b1b913b5af59363aa3d | aRToLoMiay/Special-Course | /Основные инструкции/game_21.py | 909 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# Упражнение 14. Игра 21
from random import randint
S = 0
S += randint(0, 10)
f = 0
print "Ваше стартовое значение = %d" % (S)
f = raw_input("Введите Y для генерации ещё одного числа или любой другой символ для прекращения игры: ")
while f == 'Y':
if S > 21:
f = 'N'
else:
S += randint(0, 10)
print "Ваше текущее значение - %d" % (S)
f = raw_input("Введите Y для генерации ещё одного числа или любой другой символ для прекращения игры: ")
if S > 21:
print "Вы проиграли! Ваш результат = %d" % (S)
elif S == 21:
print "Поздравляем! Вы победили и набрали 21 очко!"
else:
print "Ваш результат = %d" % (S) |
1b98edd1533c8cd61a5366a5b0bd6510f693bbd4 | resb53/advent | /2020/src/day-07.py | 2,670 | 3.53125 | 4 | #!/usr/bin/python3
import argparse
import sys
import re
# Check correct usage
parser = argparse.ArgumentParser(description="Check your Bags.")
parser.add_argument('input', metavar='input', type=str,
help='Bag rule list input.')
args = parser.parse_args()
rules = {}
holdsgold = []
countcont = 0
def main():
global holdsgold, countcont
parseInput(args.input)
# Part 1
# Check for directly holding
holdsgold = findBags("shiny gold")
# Check for indirectly holding
new = holdsgold.copy()
redo = True
while redo:
newnew = []
# print(f"Checking... {new}")
for item in new:
check = findBags(item)
for test in check:
if test not in holdsgold:
newnew.append(test)
holdsgold.append(test)
if len(newnew) == 0:
redo = False
else:
new = newnew
print(f"Total in holdsgold: {len(holdsgold)}.")
# Part 2
countBags("shiny gold", 1)
print(f"Total bags in gold bag: {countcont}")
# Debug
# printRules()
# Parse the input file
def parseInput(inp):
global passes
try:
rules_fh = open(inp, 'r')
except IOError:
sys.exit("Unable to open input file: " + inp)
for line in rules_fh:
line = line.strip("\n")
match = re.match(r"^(\w+ \w+) bags contain (.+)\.$", line, re.I)
if not match:
print(f"Error: Can't parse line: {line}")
else:
container = match.group(1)
contents = match.group(2)
# print(f"Container: {container}, Content: {content}")
# Parse the contents
itin = {}
if contents != "no other bags":
match = re.findall(r"(\d+) (\w+ \w+) bag", contents, re.I)
if not match:
print(f"Error: Can't parse contents: {contents}")
else:
# Include number of each
for hit in match:
hit = list(hit)
itin[hit[1]] = int(hit[0])
rules[container] = itin
# For specified bag, how many can contain it?
def findBags(bagtype):
holds = []
for item in rules:
if bagtype in rules[item]:
holds.append(item)
return(holds)
def printRules():
for item in rules:
print(f"{item}: {rules[item]}")
def countBags(bagtype, multi):
global countcont
contains = rules[bagtype].copy()
for val in contains:
contains[val] *= multi
countcont += contains[val]
countBags(val, contains[val])
if __name__ == "__main__":
main()
|
68914b1d2a3ddc37b19f9ddfbae04096452bbf6e | thisguycodez/python-number-guessing | /test2.py | 6,145 | 4.40625 | 4 | import random
from random import randint
'''
_____________________________________________________________________________________________________________________
>>> If/else statements - is a conditional statement that runs code depending on whether an expression is true or false:
---------------------------------------------------------------------------------------------------------------------
* if - the statement that will allow code ITS HOLDING to run if the condition is True
-----------------------------------------------------------------------------------
if 1 == 1:
print('this code is running because 1 is equal to 1',True)
print('this code will run regardless. Its not apart of the if statement')
___________________________________________________________________________________
* elif - this statement will allow code ITS HOLDING to run if the condition is True and if the 'If' statement before it was False.
-----------------------------------------------------------------------------------
# statement checked 1st
if 1 > 2:
print('this code is running because 1 is GREATER than 2',True)
# statement checked if 1st statement is false
elif 1 < 2:
print('this code is running because 1 is LESS than 2',True)
___________________________________________________________________________________
* else - the statement that will allow code ITS HOLDING to run if no other statement before it was True (if,elif).
-----------------------------------------------------------------------------------
# statement checked 1st
if 100 < 0:
print('this code is running because 100 is less than 0',True)
# statement checked if 1st statement is false
elif 100 < 50:
print('this code is running because 1 is LESS than 2',True)
# statement checked if all statements before this were also false
else:
print('this will run by default....ELSE')
___________________________________________________________________________________
_____________________________________________________________________________________________________________________
>>> Random Module (random) - Used for random value returns from a list(array) or generates random numbers based on ranges given as arguements(parameters). We Will only use the 'randint' method built into this module: See More Here: https://docs.python.org/3/library/random.html
---------------------------------------------------------------------------------------------------------------------
* - import this module into your script.- *
* - We are only using 'randint' so this Can be imported in different ways - *
* 1....just pull the method its self out alone
_____________________________________________________________________________________________________________________
from random import randint
# prints a random number between 1-100
print(randint(1,100))
---------------------------------------------------------------------------------------------------------------------
* 2....pull the method its self out alone and rename it to whatever you want 'rando'
_____________________________________________________________________________________________________________________
from random import randint as rando
# prints a random number between 1-100
print(rando(1,100))
---------------------------------------------------------------------------------------------------------------------
* 3....import random and use the method randInt as the 'random' modules attribute
_____________________________________________________________________________________________________________________
import random
# prints a random number between 1-100
print(random.randint(1,100))
---------------------------------------------------------------------------------------------------------------------
____________________________________________________________________________________________________________________
>>> Functions (def) - A block of code that only runs when its called. A function can return data as a result , you can pass data into the function and this is known as a 'parameter': (See more here) https://www.learnpython.org/en/Functions
---------------------------------------------------------------------------------------------------------------------
# A function is declared with the word 'def', followed by the name you choose to use for the function, and then parentheses.- *
def name_of_function():
pass
# If you declare a function and do not have code written inside of it yet, then simply add pass statement so the it does not cause errors. Pass is just a null statement, see more here > https://www.educative.io/edpresso/what-is-pass-statement-in-python- *
_____________________________________________________________________________________________________________________
---------------------------------------------------------------------------------------------------------------------
# Ex: Make a function return True ( this funciton now also equals True) especially if this is the only thing it does.
def func():
return True
_____________________________________________________________________________________________________________________
# Info - An entire script 'file.py' carries a global scope and a function carries its own within it. More on scopes here > https://www.w3schools.com/python/python_scope.asp
'''
# Try it your self......
# Answer all the questions below, then move on to num_guess.py
#1.)print 2 conditions using Comparing operators...
# 2.) print 3 random numbers between 55-89...
# 3.) print the Boolean of 2 random numbers between 1-8 being compared using Comparing operators...:)
# 4.) create a function and add 1-3 inside of it. Call the function.
''' 5.) save 2 random numbers between 15-30 into variables.
Run an if statement with those 2 variables being compared
using Comparing operators as the condition. If True,
run "print('This time its true')". If False,
run "print('this time its false')"...:)
'''
# 6 .) create a function and add 5 inside of it. Call the function.
|
ca0cdde561e243579594d11f9cacc3ecb027edf4 | nikitiwari/Learning_Python | /sum_nrecurson.py | 194 | 4.125 | 4 | print "Sum of n natural numbers using recursion"
n = (int)(raw_input("Enter a number :"))
def sum_n( x) :
if x == 1 :
return 1
else :
return (x+sum_n(x-1))
print sum_n(n) |
7c9bebebdde9788050235a65f6989ad5253b8ab4 | xili-h/PG | /Python/ch3/Rock,Paper,Seissor.py | 1,465 | 4.125 | 4 | import random
money = 25
print('You start with $25\n')
print('Every game is worth a $5')
while money >= 5 :
computer_choice = random.choice(('rock','paper','scissors'))
#if random_choice == 0:
# computer_choice = 'rock'
#elif random_choice == 1:
# computer_choice = 'paper'
#else:
# computer_choice = 'scissors'
#print('The computer chooses',computer_choice)
user_choice = ''
while (user_choice != 'rock' and
user_choice != 'paper' and
user_choice != 'scissors'):
user_choice = input('rock, paper or scissors? ').lower()
money -= 5
#print('You chose',user_choice,'and the computer chose', computer_choice)
if user_choice == computer_choice:
winner = 'Tie'
elif computer_choice == 'paper' and user_choice == 'rock':
winner = 'Computer'
elif computer_choice == 'rock' and user_choice == 'scissors':
winner = 'Computer'
elif computer_choice == 'scissors' and user_choice == 'paper':
winner = 'Computer'
else:
winner = 'User'
if winner == 'Tie':
print('We both chose',computer_choice + ', play again.')
elif winner == 'Computer':
print(winner,'won. The computer chose',computer_choice + ', you lost $5.')
elif winner == 'User':
print(winner,'won. The computer chose',computer_choice + ', you got $5.')
money += 10
print('You have $%.d\n'%money)
print('You lost all tour money') |
5fcb2657ad91753573db28e767d84bc09e5e1539 | savva-kotov/python-prog | /3-2-2.py | 866 | 4.03125 | 4 | """
Программа должна считывать одну строку со стандартного ввода и выводить для каждого уникального слова в этой строке
число его повторений (без учёта регистра) в формате "слово количество" (см. пример вывода).
Порядок вывода слов может быть произвольным, каждое уникальное слово должно выводиться только один раз.
Sample Input 1:
a aa abC aa ac abc bcd a
Sample Output 1:
ac 1
a 2
abc 2
bcd 1
aa 2
Sample Input 2:
a A a
Sample Output 2:
a 3
"""
import collections
c = collections.Counter()
l = input().lower().split()
for word in l:
c[word] +=1
for key,value in c.items():
print(key,value)
|
7aced09d4a5c60946f83ce5a893f8c10aa2f3a0c | antoniocolucci/TW6 | /10-Tecnologie_Web-Introduzione_a_Python/esempio01.py | 182 | 3.75 | 4 | # Variables definitions
message = "This is a string"
a = 5
x = 3.14
print("message:", type(message))
print("a:", type(a))
print("x:", type(x))
a = 5.0
print("a:", type(a))
|
5ec88176538e2cddd11d3c2c3b898abc96eddefc | jgondin/dsp | /python/advanced_python_regex.py | 1,427 | 3.90625 | 4 | import csv
def read_data(file):
return(list(csv.reader(open(file))))
facu = read_data('/home/gondin/metis/bootcamp/dsp/python/faculty.csv')
# Crete list dictionary with the degrees.
deg_freq = {'PhD': 0, 'ScD': 0, 'MD':0, 'MPH':0, 'BSEd':0, \
'MS':0, 'JD':0,}
#Q1 Calculate frequecy
for i in range(1,len(facu)):
key = facu[i][1]
key = key.replace('.','')
key = key.replace(' ','', 1)
if key in deg_freq.keys():
deg_freq[key] += 1
else:
keys = key.split(' ')
keys = [k for k in keys if k!='']
for k in keys:
if k in deg_freq.keys():
deg_freq[k] += 1
deg_freq[key] = 1
#Degree frequency:
print('----')
for k, v in deg_freq.items():
print(k, v)
#Q2 Titles:
titles = {}
for i in range(1, len(facu)):
key = facu[i][2]
key = key.replace(' ','',1)
if key in titles.keys():
titles[key] +=1
else:
titles[key] = 1
#Print titles frequency:
print('------')
for k, v in titles.items():
print(k, v)
#Q3 emails:
emails = []
for i in range(1, len(facu)):
emails.append( facu[i][3])
#Print emails list:
print('------')
for v in emails:
print(v)
#Q4 emails domain:
domains = []
for e in emails:
d = e.split('@')[1]
d = d.replace(' ', '')
if d not in domains:
domains.append(d)
#print domains
print('----')
for v in domains:
print(v)
|
440ce2a5326c2c8d7d5272602e9b5f3adc5989dd | schadock/route_script | /road.py | 1,669 | 4 | 4 | from math import radians, cos, sin, asin, sqrt
import datetime
class Road:
"""
Count ride time based on geographic coordinate.
:param City from_city: City class object
:param City to_city : City class object
:param float maxspeed : Max ride speed on road.
"""
def __init__(self, from_city, to_city, maxspeed):
self.from_city = from_city
self.to_city = to_city
self.maxspeed = maxspeed
def calculate_ride_time(self):
"""
Calculate ride time between cities in hours.
:rtype: datetime
"""
distance = self._distance(self.from_city, self.to_city)
ride_time_not_converted = distance / self.maxspeed
ride_time = self._datetime_from(ride_time_not_converted)
return ride_time
def _datetime_from(self, hours):
"""
Convert float to datetime.
:param float hours: Ride time in hours in float type.
:rtype: datetime
"""
return datetime.timedelta(hours=hours)
def _distance(self, from_city, to_city):
"""
Calculate the great _by_haversine circle distance between two points
on the earth (specified in decimal degrees)
:rtype: float
"""
lon1, lat1, lon2, lat2 = map(radians,
[from_city.longitude, from_city.latitude, to_city.longitude, to_city.latitude])
delta_longitude = lon2 - lon1
delta_latitude = lat2 - lat1
distance = 2 * asin(
sqrt(sin(delta_latitude / 2) ** 2 + cos(lat1) * cos(lat2) * sin(delta_longitude / 2) ** 2)) * 6371
return round(distance, 2)
|
2c98b70fa024cb9e551885621e872653ccbb66a7 | AndreyIh/Solved_from_chekio | /Elementary/remove_all_before.py | 754 | 4.375 | 4 | #!/usr/bin/env checkio --domain=py run remove-all-before
# Not all of the elements are important. What you need to do here is to remove from the list all of the elements before the given one.
#
#
#
# For the illustration we have a list [3, 4, 5] and we need to remove all elements that go before 3 - which is 1 and 2.
#
# We have two edge cases here: (1) if a cutting element cannot be found, then the list shoudn't be changed. (2) if the list is empty, then it should remain empty.
#
# Input:List and the border element.
#
# Output:Iterable (tuple, list, iterator ...).
#
#
# END_DESC
from typing import Iterable
def remove_all_before(items: list, border: int) -> Iterable:
return items[items.index(border):] if border in items else items |
0c3cf3e48689f4aebf7be8f7679d312d3574c9a5 | euxuoh/leetcode | /python/two-pointer/remove-duplicates-sorted-array.py | 1,007 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
80. Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3.
It doesn't matter what you leave beyond the new length.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2016/12/1
"""
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
last, i, same = 0, 1, False
while i < len(nums):
if nums[last] != nums[i] or not same:
same = nums[last] == nums[i]
last += 1
nums[last] = nums[i]
i += 1
return last + 1
if __name__ == "__main__":
solution = Solution()
test1 = [1, 1, 1, 2, 2, 3, 3]
|
c5141030204e2316ecd48e3549fdc6f200ea4dd7 | ShivendraAgrawal/coding_2016 | /ib-colorful-number.py | 539 | 3.5625 | 4 | def colorful(A):
all_muls = {}
num_list = []
while A > 0:
num_list.append(A % 10)
A = A // 10
j = 1
while j <= len(num_list):
for i in range(0, len(num_list) - j + 1):
mul = 1
for k in range(i, i+j):
mul *= num_list[k]
# print(i,j ,k,mul)
if mul in all_muls:
# print(all_muls)
return 0
else:
all_muls[mul] = 1
j += 1
return 1
A = 3245
print(colorful(A)) |
8400c188caad499d4bdb8d1bbd89020564015610 | FuJieHao/MachineLearn | /numpy/文件操作/file.py | 635 | 3.65625 | 4 |
#读文件
txt = open('./fj.txt')
txt_read = txt.read()
print(txt_read)
txt.close()
txt = open('./fj.txt')
lines = txt.readlines()
print(lines)
for line in lines:
print('cur_line:',line)
txt.close()
#写文件 w 覆盖 a 追加
txt = open('fj_write.txt','w')
txt.write('jin tian tian qi bu cuo\n')
txt.write('hao fu jie')
txt.close()
txt = open('fj_write.txt','w')
try:
for i in range(10):
10/(i-5)
txt.write(str(i) + '\n')
except Exception:
print('error:',i)
finally:
txt.close()
# 自动执行except 和 finally
with open('fj_write.txt','w') as f:
f.write('jin tian tian qi bu cuo') |
4174c437586da4d89637f252d40cdcbf973d6d34 | geoxliu/Python_Crash_Course_all | /part_8/make_album_8_8.py | 693 | 4.0625 | 4 | # coding=utf-8
# ϸ˵P125
# ֵΪֵ
def make_album(singer, album, number = ''):
"""return to album's information"""
full_album = {'singer': singer, 'album': album}
if number:
full_album['number'] = number
return full_album
while True:
print("Please tell me something about album:")
print("(Enter 'q' at any time to quit)")
singer = input("Singer name: ")
if singer == 'q':
break
album = input("Album name: ")
if album == 'q':
break
number = input("Nmuber: ")
if number == 'q':
break
full_album = make_album(singer, album, number)
print(full_album)
|
cc2f38b7a27f2a7088b4fcc96bc6ce3b25ec4292 | jay6413682/Leetcode | /Path_Sum_112.py | 2,735 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
""" recursive/dfs
https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-by-leetcode-solution/
时间复杂度:O(N)O(N),其中 NN 是树的节点数。对每个节点访问一次。
空间复杂度:O(H)O(H),其中 HH 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为 O(\log N)O(logN)。
"""
# empty
if not root:
return False
# leaf
if not root.left and not root.right:
if targetSum == root.val:
return True
else:
return False
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
class Solution2:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
"""
bfs/iterative/queue: https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-by-leetcode-solution/
时间复杂度:O(N)O(N),其中 NN 是树的节点数。对每个节点访问一次。
空间复杂度:O(N)O(N),其中 NN 是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。
"""
if not root:
return False
queue = [root]
sum_queue = [root.val]
while queue:
node = queue.pop(0)
s = sum_queue.pop(0)
if not node.left and not node.right and s == targetSum:
return True
if node.left:
queue.append(node.left)
sum_queue.append(node.left.val + s)
if node.right:
queue.append(node.right)
sum_queue.append(node.right.val + s)
return False
'''
# or
if not root:
return False
queue = deque([(root, targetSum)])
while queue:
root, targetSum = queue.popleft()
if root.left:
queue.append((root.left, targetSum - root.val))
if root.right:
queue.append((root.right, targetSum - root.val))
if not root.left and not root.right:
# leaf
if root.val == targetSum:
return True
return False
'''
|
8b2ebe0d1741f9acb06323ce4a6270b4ffe6a684 | momomojiang/Python | /User.py | 1,456 | 3.8125 | 4 | class User:
def __init__(self,name,email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
def make_withdrawl(self, amount):
self.account_balance -= amount
def display_user_balance(self):
print(self.account_balance)
Joe = User("Joe","Joe@mail.com")
Monty = User("Monty", "monty@mail.com")
Peter = User("Peter", "peter@mail.com")
# Joe.make_deposit(10)
# Joe.make_deposit(10)
# Joe.make_deposit(10)
# Joe.make_withdrawl(10)
# Joe.display_user_balance()
# Monty.make_deposit(10)
# Monty.make_deposit(10)
# Monty.make_withdrawl(10)
# Monty.display_user_balance()
class BankAccount:
def __init__(self,interest_rate, balance):
self.interest_rate = interest_rate
self.balance = balance
def deposite(self, amount):
self.balance += amount
print(self.balance)
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print("Balance: $"+self)
return self
def yield_interest(self):
if self.balance>0:
self.balance = self.balance + self.balance * self.interest_rate
print(self.balance)
# goldAccount = BankAccount(0.02,200)
silverAccount = BankAccount(0.03, 300)
# goldAccount.deposite(20).yield_interest()
silverAccount.deposite(20).deposite(20).yield_interest() |
5a9d3cd88087cb139e2269eb8046409ef7e629ac | RedheatWei/python-study | /实验/5-3判断成绩.py | 345 | 3.71875 | 4 | #!/usr/bin/env python
import sys
A = int(raw_input('A=\n>'))
if 90 <= A <= 100:
print 'A'
elif 80 <= A <= 89:
print 'B'
elif 70 <= A <= 79:
print 'C'
elif 60 <= A <= 69:
print 'D'
elif A < 60:
print 'F'
else:
print 'Go away!'
sys.exit()
#try:
# 0 < A < 100
#except Exception ,e:
# sys.exit()
#else:
# print A |
93a625b75c3f19703376053d6f755cb35eff4ad4 | deanscameron/Greengraph | /greengraph/create_png.py | 1,187 | 3.828125 | 4 | """png creation file"""
# Module counts the green parts of a image, and creates a image diaplaying them
# Define the green areas of an image
def is_green(r,g,b):
threshold=1.1
return g>r*threshold and g>b*threshold
import png
from itertools import izip
# Counts the green parts of a png image
def count_green_in_png(data):
image=png.Reader(file=StringIO(data.content)).asRGB()
count = 0
for row in image[2]:
pixels=izip(*[iter(row)]*3)
count+=sum(1 for pixel in pixels if is_green(*pixel))
return count
from StringIO import StringIO
# Creates a png image displaying the green parts of the image
def show_green_in_png(data):
image=png.Reader(file=StringIO(data.content)).asRGB()
count = 0
out=[]
for row in image[2]:
outrow=[]
pixels=izip(*[iter(row)]*3)
for pixel in pixels:
outrow.append(0)
if is_green(*pixel):
outrow.append(255)
else:
outrow.append(0)
outrow.append(0)
out.append(outrow)
buffer=StringIO()
result = png.from_array(out,mode='RGB')
result.save(buffer)
return buffer.getvalue() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.