blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
d067279b31675070c7982ef4cf781e0e3487700d | nsforero10/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 199 | 4.0625 | 4 | #!/usr/bin/python3
def uppercase(str):
for letter in str:
num = ord(letter)
if num > 96 and num < 123:
num -= 32
print('{:c}'.format(num), end='')
print()
|
d056f0d301b293c4bff720f164bfa304667bdd25 | aiifabbf/aiifabbf.github.com | /posts/mathworks-interview/317.py | 3,026 | 3.625 | 4 | from typing import *
class Solution:
def shortestDistance(self, grid: List[List[int]]) -> int:
rowCount = len(grid)
columnCount = len(grid[0])
buildings = set()
obstacles = set()
for rowIndex, row in enumerate(grid):
for columnIndex, box in enumerate(row):
... |
894dc9200ff82a915a321648c06486ea5eb929a6 | aiifabbf/aiifabbf.github.com | /posts/amazon-interview/20.py | 623 | 3.78125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
stack = []
for v in s:
if v in "([{":
stack.append(v)
else:
if stack == []:
return False
else:
if stack[-1] == "(" and v == ")":
... |
781c6655b85014348b7bd446ebb1ab857aaa6b61 | aiifabbf/aiifabbf.github.com | /posts/mathworks-interview/49.py | 334 | 3.53125 | 4 | from typing import *
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = dict()
for v in strs:
root = "".join(sorted(v))
if root in res:
res[root].append(v)
else:
res[root] = [v]
return list... |
fd05964ade729da5f73de7f0cd9d94a971db9486 | aiifabbf/aiifabbf.github.com | /posts/paypal-interview/25.py | 1,008 | 3.625 | 4 | from typing import *
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
sentinel = ListNode(None)
sentinel.next = head
length = 0
... |
01e8af8235fbb218eefb99d4d5fff96e17734edd | nevladimir92/LearnPython | /lesson2/homework/while2.py | 686 | 3.5625 | 4 | def ask_user_dict():
q_dict = {
'что делаешь': 'Программирую.',
'как дела': 'Отлично!'
# ...
}
answer = input("Привет! Как дела? \n").lower()
while True:
if answer == "пока":
print("Ну пока!")
break
answer = input("Давай спрашивай что хоте... |
92077bb80eda2fe5208c7b2eeeac3d53c4251ebc | PriyankaBangale/30Day-s_Code | /day_8_DictionaryMapping.py | 1,381 | 4.34375 | 4 | """Objective
Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will th... |
37bec14ce3668fff5b0dac193744f6d77d6d7741 | assuom7827/Hacktoberfest_DSA_2021 | /Code/data_structures/stack/Python/check_for_balanced_parathesis/check_for_balanced_parantheses.py | 750 | 3.96875 | 4 | # code to Check for balanced parentheses in an expression
# Function to check parentheses
def par_check(myStr):
open = ["[","{","("]
close = ["]","}",")"]
stack = []
for i in myStr:
if i in open:
stack.append(i)
elif i in close:
cls = close.index(i)
i... |
015cac95f4680a6fa0f62999caff7e8d500634b9 | assuom7827/Hacktoberfest_DSA_2021 | /Code/game_projects/word guessing game/word_guessing_game.py | 1,088 | 4.28125 | 4 | from random import choice
# list of words(fruits and vegetables)
words=["apple","banana","orange","kiwi","pine","melon","potato","carrot","tomato","chilly","pumpkin","brinjol","cucumber","olive","pea","corn","beet","cabbage","spinach"]
c_word = choice(words)
lives=3
unknown = ["_"]*len(c_word)
while lives>0:
gue... |
6a2fe93f3e881140a2b84be74530b853d587167d | assuom7827/Hacktoberfest_DSA_2021 | /Code/data_structures/array/print_array_in_reverse/print_array_in_reverse.py | 64 | 3.53125 | 4 | arr = [1,2,3,435,23,12,3,2]
print(arr)
arr.reverse()
print(arr)
|
6cd2051eaaea40046410b7e1dce24734248c8ee1 | assuom7827/Hacktoberfest_DSA_2021 | /Code/data_structures/queue/queue.py | 505 | 3.703125 | 4 | def __init__(self):
"""
Initializing Queue.
"""
self.queue = []
def isEmpty(self) -> bool:
return True if len(self.queue) == 0 else False
def front(self) -> int:
return self.queue[-1]
def rear(self) -> int:
return self.queue[0]
def enqueue(self... |
61f1e9cf5cfa09641194d75fa1ca1c36e5ae9ef8 | assuom7827/Hacktoberfest_DSA_2021 | /Code/matrix/saddle point/saddle_point.py | 397 | 3.640625 | 4 | mat = [[1,2,3],[4,5,6],[7,8,9]]
saddle_pt = None
for row in mat:
for elem in row:
if elem == min(row):
column_n = row.index(elem)
column = []
for i in range(len(mat)):
column.append(mat[i][column_n])
if elem == max(column):
saddle_pt = elem
if saddle_pt == None:
print("The matrix has no... |
9c32992faf3335c9e0746ce48c6c25b1348e4dc3 | assuom7827/Hacktoberfest_DSA_2021 | /Code/matrix/matrix_multiplication/python.py | 1,241 | 4.25 | 4 | r1=int(input("Enter number of Rows of Matrix A: "))
c1=int(input("Enter number of Columns of Matrix A: "))
A=[[0 for i in range(c1)] for j in range(r1)] #initialize matrix A
print("Enter Matrix Elements of A:")
#input matrix A
for i in range(r1):
for j in range(c1):
x=int(input())
A[i][j]=x
r2=int(i... |
d56252288e0a576e767411ab0a2b1015c4624933 | assuom7827/Hacktoberfest_DSA_2021 | /Code/matrix/Rotate_Matrix_90/rotate_by_90.py | 1,335 | 3.75 | 4 | def rotateclock(m):
n=len(m)
for i in range(n):
for j in range(i):
temp=m[i][j]
m[i][j]=m[j][i]
m[j][i]=temp
#CLOCKWISE
#swap columns
for i in range(n):
for j in range(n//2):
temp=m[i][j]
m[i][j]=... |
fb278d9975471e74e188f621cc722444410ada76 | Sarthak1503/Python-Assignments | /Assignment4.py | 1,100 | 4.28125 | 4 | #1.Find the length of tuple
t=(2,4,6,9,1)
print(len(t))
#2.Find the largest and smallest element of a tuple.
t=(2,4,6,8,1)
print(max(t))
print(min(t))
#3.Write a program to find the product os all elements of a tuple.
def pro(t):
r=1
for i in t:
r=r*i
return r
t=(1,2,3,4)
p=pro(t)
print(p)
#4.Cal... |
9b7380e82a01b8a68bec953a32119f10b2f34ad1 | Sarthak1503/Python-Assignments | /Assignment11.py | 1,317 | 4.34375 | 4 | import threading
from threading import Thread
import time
#1. Create a threading process such that it sleeps for 5 seconds and
# then prints out a message.
def show():
time.sleep(5)
print(threading.current_thread().getName(),"Electronics & Communication Engineering")
t= Thread(target=show)
t.setName("B.tech... |
ee05da1077d87581c628fbb2c1f0baa2ce4348e3 | dionisos2/my_codefights_answers | /utils.py | 846 | 3.765625 | 4 | import time
def benchmark(func):
"""
st decorator to calculate the total time of a func
"""
def decoredFunc(*args, **keyArgs):
t1 = time.time()
r = func(*args, **keyArgs)
t2 = time.time()
print(f'Function={func.__name__}, Time={t2 - t1}')
return r
retur... |
a1e326537c4cadefbae38f73356c33a3cb920f1c | ArnabC27/Hactoberfest2021 | /rock-paper-scissor.py | 1,678 | 4.125 | 4 | '''
Rock Paper Scissor Game in Python using Tkinter
Code By : Arnab Chakraborty
Github : https://github.com/ArnabC27
'''
import random
import tkinter as tk
stats = []
def getWinner(call):
if random.random() <= (1/3):
throw = 'Rock'
elif (1/3) < random.random() <= (2/3):
throw = 'Scissors'
... |
863b9c95f106d33079dd73eef5112210165a257d | Genesis-99003583/TestingTeam | /Project-with_Classes/lib/common.py | 1,182 | 3.546875 | 4 | import requests
def getID():
id = int(input("Enter ID of a person: "))
return id
def getData():
id = int(input("Enter ID: "))
first_name = input("Enter FIrst_Name: ")
middle_name = input("Enter Middle_Name: ")
last_name = input("Enter Last_Name: ")
date_of_birth = input("Enter DOB(dd/mm/yyyy): ")
... |
c371e0b80c256f7c4990184c7492e3c2be35cabf | juicekey/cs50-pset6 | /dna.py | 1,407 | 3.859375 | 4 | from sys import argv, exit
import csv
def main():
if len(argv) != 3:
print('database, sequence')
exit(1)
#check number arguments
database = open(argv[1])
i = next(database)
database.close()
strList = i.strip('\n').split(',')
strList.pop(0)
#get list of STRs
with o... |
da55b5218fd70fc9b5e096f91fc909ceb213e6ab | MeinSpaghett/C4T16-1 | /Session8/for.py | 336 | 3.90625 | 4 | this_list=["captain america", "iron man", "thor", "hulk", "hawkeye", "black widow"]
print(*this_list)
# for i in range(len(this_list)):
# print(this_list[i])
# for item in this_list:
# print(item)
for i, item in enumerate(this_list):
print(i+1, ".",item.upper())
for x in this_list:
if "e" in x:
... |
9bda3c01999ebea6de762a15b6781077d961f6c6 | MeinSpaghett/C4T16-1 | /Session8/BT3.py | 388 | 3.984375 | 4 | import random
from random import shuffle
this_list=["captain america", "iron man", "thor", "hulk", "hawkeye", "black widow"]
print(*this_list)
i=random.randint(0,len(this_list)-1)
this_list[i]=this_list[i].upper()
list1 = list(this_list[i])
shuffle(list1)
print(*list1)
x=str(input("Enter the character name: "))
if x ==... |
44e86a5cc1f28b532572af09670b73c38d0113c2 | MeinSpaghett/C4T16-1 | /Session7/minihack11.py | 185 | 3.9375 | 4 | while True:
n=input("Enter your first name: ")
m=input("Enter your last name: ")
if m.isalpha() and n.isalpha():
print(n,m)
break
else:
continue |
cab78ac067653b0d49310665f7bd599143063144 | MeinSpaghett/C4T16-1 | /Test/test8.py | 153 | 3.890625 | 4 | list1=[1,2,3,4,5]
bien1=input("H or T: ").upper()
if bien1=="H":
list1.pop(0)
print(*list1)
if bien1=="T":
list1.pop()
print(*list1)
|
a9ec42edd411b083dee96bed9f0603b2a0b9257c | MeinSpaghett/C4T16-1 | /SessionAd/stack.py | 489 | 3.8125 | 4 | class Stack:
def __init__(self):
self.items = []
def __str__(self):
x=""
for i in range(0,len(self.items)):
if i==0:
x=x+str(self.items[i])
else:
x=x+" "+str(self.items[i])
return x
def is_empty(self):
return sel... |
f2bc62890e8f510a3d51428eafed2be9122f869b | MeinSpaghett/C4T16-1 | /Session7/minihack31.py | 82 | 3.78125 | 4 | n=int(input("Enter a number: "))
if n>13:
print("Co")
else:
print("Khong") |
576a87938b4b7ba45b9890268e9b10f805649cad | MeinSpaghett/C4T16-1 | /Test/test7.py | 153 | 3.890625 | 4 | list1=[1,2,3,4,5]
for x in list1:
print(x,end=" ")
print(" ")
new_number=int(input())
list1.insert(0,new_number)
for x in list1:
print(x,end=" ") |
7bd543fa0f5ec8383f5e77c08196d325026db79b | MacHu-GWU/pyclopedia-project | /pyclopedia/p02_ref/p03_objective_oriented/p07_multiple_inherit.py | 1,685 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
当一个类继承自多个父类时, 如果多个父类(可能以及父类的父类)都定义了同一个方法,
那么调用这个类的这个方法时, 到底是在调用哪一个?
ref:
- 你真的理解Python中MRO算法吗?: http://python.jobbole.com/85685/
- https://docs.python.org/2/tutorial/classes.html#multiple-inheritance
- https://docs.python.org/3/tutorial/classes.html#multiple-inherita... |
11c26a253c853126444434da4f83e42971b23450 | MacHu-GWU/pyclopedia-project | /pyclopedia/p03_stdlib/_internet_data_handling/p02_binascii.py | 1,196 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
binascii这个库主要提供了binary数据和ascii数据之间的各种转化。
Reference:
- binascii: https://docs.python.org/3.3/library/binascii.html
- int.from_bytes: https://docs.python.org/3/library/stdtypes.html#int.from_bytes
"""
import binascii
def test_bytes_to_int():
"""本例提供了将任意的字符串, byt... |
afec24bef224233ed008984d728b759e62e3c3d0 | MacHu-GWU/pyclopedia-project | /pyclopedia/p02_ref/p03_objective_oriented/p04_magic_method/p08__missing__.py | 1,244 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
``__missing__`` is been called by ``dict.__getitem__()`` to implement ``self[key]``
for dict subclasses when key is not in the dictionary.
**中文文档**
只有类是从dict继承而来的子类时, 在 ``__getitem__()`` 找不到key时, ``__missing__`` 才
会生效。综合看来, 这一特性用处不大。
"""
class SelfUpdateDict(dic... |
c66911b7118dfe6ca6dde2d28c00b8eeaf0ace72 | MacHu-GWU/pyclopedia-project | /pyclopedia/p01_beginner/p03_data_structure/p03_set/p01_constructor.py | 1,219 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Set Constructor
==============================================================================
"""
import random
import string
def construct_a_set():
"""Syntax: ``set(iterable)``
"""
assert set([1, 2, 3]) == {1, 2, 3}
assert set(range(3)) == {0, 1, 2... |
6c983ff6d1b91561c632b8f954aff02a09370b8b | MacHu-GWU/pyclopedia-project | /pyclopedia/p02_ref/p03_objective_oriented/p04_magic_method/p07__hash__.py | 599 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
``__hash__(self)`` 定义了 hash(obj)的行为。
"""
class MyClass(object):
def __init__(self, a):
self.a = a
def __hash__(self):
return hash(self.a)
def __eq__(self, other):
return self.a == other.a
if __name__ == "__main__":
m1 = MyC... |
533ffaa60ef2f8281ed8383f38b9b9336082bbcb | MacHu-GWU/pyclopedia-project | /pyclopedia/p03_stdlib/_datapersistance/sqlite3/database_rollback.py | 798 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
rollback机制是数据库中最重要的机制之一。有了它数据库的完整性才能得到保证。
rollback的功能是恢复到最近一次commit()的状态
"""
import sqlite3
connect = sqlite3.connect(":memory:")
cursor = connect.cursor()
def test_rollback():
cursor.execute("CREATE TABLE test (id INTEGER, name TEXT)")
connect.commit() # ... |
97e41cbf643c0fcfb4ea6809a0c1cc25117bd26e | MacHu-GWU/pyclopedia-project | /pyclopedia/p03_stdlib/_built_in_function/_type.py | 923 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ref:
- PY2: https://docs.python.org/2/library/functions.html#type
- PY3: https://docs.python.org/3/library/functions.html#type
"""
def as_get_class_type_function():
"""``type(a_instance)`` can get the type of a instance.
"""
assert type(1) is int
as... |
8c861a6e8470b89c7180659761f7d469cdd172ae | MacHu-GWU/pyclopedia-project | /pyclopedia/p02_ref/p01_exception/p02_customize_exception.py | 666 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Exception is a class too.
"""
import random
class BaoZi(Exception):
pass
class Big(Exception):
pass
class Small(Exception):
pass
def toss_dice():
numbers = [1, 2, 3, 4, 5, 6]
return [random.choice(numbers) for _ in range(3)]
def play():
... |
b375f1960cee578170e9192c2efcc486565b776f | MacHu-GWU/pyclopedia-project | /pyclopedia/p03_stdlib/_functional_programming/p03_functools/_lru_cache.py | 2,552 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
LRU (least recently used) cache这种缓存能将函数最近N次被调用的输入参数和返回值
缓存起来, 每次有新的访问时, 会首先到缓存保存过的输入参数中查找, 如果找不到,
才真正执行函数。
LRU缓存的典型应用场景是 **动态编程**, 或是 **IO为主要耗时的操作**。
例如著名的求 fibonacci 数列的动态编程解法就可以用到。
又例如新闻客户端, 服务器缓存保存用户最近点击的1000篇新闻。由于最热的新闻一定
一直在缓存中保存着, 所以大量用户的请求将会落在这1000篇缓存文章中, 则可... |
5f5b0d32ef546a3c641f41288cbecfcbee50cb42 | MacHu-GWU/pyclopedia-project | /pyclopedia/p03_stdlib/_datapersistance/sqlite3/trick_low_memory_use_select.py | 627 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
如何在当选择的数据量极大时, 避免将所有结果的数据放入内粗, 减少内存开销。
结论: 直接对cursor进行for循环即可。
"""
import sqlite3
connect = sqlite3.connect(":memory:")
cursor = connect.cursor()
# Create Table
cursor.execute("CREATE TABLE test (id INTEGER)")
# Insert Test Data
records = [(i, ) for i in range(100... |
ea067a756ae8aa716dd00cea9dcebaa30d6a1328 | MacHu-GWU/pyclopedia-project | /pyclopedia/p03_stdlib/_internet_data_handling/p03_binascii_vs_base64.py | 1,814 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python标准库中为 ``base64 encoding`` 提供了两个库:
`binascii <https://docs.python.org/3/library/binascii.html>`_ 和
`base64 <https://docs.python.org/3/library/base64.html>`_.
都可以用来做base64编码, 推荐使用base64
本文档测试了:
1. 这两个库得到的结果是不是完全一样? (是)
2. 这两个库的速度到底哪个更快? (差不多)
"""
import time
... |
35a80660e586c33d01119dc7b8bac1a82e60ac26 | stiehlrobot/data_structures_big_o | /ArrayOptimization.py | 3,557 | 3.859375 | 4 | import timeit
import inspect
import time
import types
from typing import cast
#The task is to find if the two separate arrays have common items and return true if this is the case. Else return false.
def slowFunction(array1, array2):
for item in array1:
for val in array2:
if item == val:
prin... |
ed515f1bc3ffb737ce288323171e06aeb22c1d35 | ntpl/ntpl | /ntpy/lattice.py | 19,279 | 3.5625 | 4 | ## ## ## lattice.py v.0.1
## ## ## This program performs lattice and reciprical space manipulation
## ## ## Created: 06/21/2012 - KDP
## ## ## Last Edited: 1/18/2013 - KDP
import numpy as np
def buildNumpy(blocks):
"""
This creates numpy array based on the blocks provided
lattice.Numpy.buildNumpy(blocks)
Paramet... |
6d0a66054d14084131eebb1256cee81e1f576cec | ntpl/ntpl | /ntpy/nmdpy/pp-1.6.2/examples/callback.py | 2,506 | 3.625 | 4 | #!/usr/bin/env python
# File: callback.py
# Author: Vitalii Vanovschi
# Desc: This program demonstrates parallel computations with pp module
# using callbacks (available since pp 1.3).
# Program calculates the partial sum 1-1/2+1/3-1/4+1/5-1/6+...
# (in the limit it is ln(2))
# Parallel Python Software: http://www.para... |
09ecc0066b81b738d8f6383653a55544a4af72b3 | Erick-INCS/FSDI-110 | /main.py | 6,146 | 3.53125 | 4 | """ Main module """
import pickle
from menu import cls, header, menu, product_info
from product import Product
# gloval vars
CATALOG = []
NEXT_ID = 1
def serialize_data():
""" Save the catalog in a file called warehouse.data """
try:
writer = open('warehouse.data', 'wb') # wb = write binary
... |
1447c1c63b299d57234ccfb4f5c6e3ce8ed102ad | ISSAE/NFP103 | /A04/asyncio_version.py | 481 | 3.53125 | 4 | # un exemple de coroutine
import asyncio
import sys
async def hello_world():
await asyncio.sleep(0.2)
print("Hello World")
def run_hello_word():
if sys.version[2:3] > '6':
print(sys.version[2:3], sys.version, "asyncio.run")
asyncio.run(hello_world())
else:
print(sys.version[2:... |
7e37a1798223d3e1a75f8a329ca64b22ad088e6e | ichHowell/WHL_Python | /ex8.py | 546 | 4.15625 | 4 | formatter = "{} {} {} {}" #做好框,等待填进去,取代{}
print(formatter.format(1,2,3,4)) #数值不用双引号
print(formatter.format("one","two","three","four")) #字符串需要双引号才能填进去
print(formatter.format(True,False,True,True)) #布尔字符页不需要双引号
print(formatter.format(formatter,formatter,formatter,formatter)) #我填我自己,12个{}
print(formatter.format(
"Try yo... |
d83114c969ac1b41d8a3d994f2539cebb42ff476 | GCGWCP/typo | /lib/vice_iterator.py | 1,502 | 3.59375 | 4 | #!/usr/bin/env python
from itertools import product as prod
def reverse_charset(charset):
rev_charset = list(charset)
rev_charset.reverse()
rev_charset = ''.join(rev_charset)
return rev_charset
def intersections(charset, n_chars, n_threads):
# n_threads <= len(charset)
total_iterations = l... |
91f10ddbe5292c99b03a60b7a84e44c6e6ef42bc | vinleclair/advent-of-code-2018 | /Day_4/day_4.py | 1,724 | 3.625 | 4 | from collections import defaultdict
def main():
records = open_input_file()
most_asleep_minute, guard_sleep_minutes = get_time_dicts(records)
print("---Puzzle Answers---")
print("Part 1:", arg_max(guard_sleep_minutes) * arg_max_minute(most_asleep_minute, arg_max(guard_sleep_minutes)))
print("Part ... |
96290a7e696a0c6c70bcf234648877536d5c53e2 | DiQuUCLA/python_59_skill | /3_python_bytes_str_unicode.py | 1,180 | 4.1875 | 4 | """
Two types that represent sequence of char: str and bytes(Python3), unicode and str(Python2)
Python3:
str: Unicode character
bytes: 8 bits raw data
Python2:
unicode: Unicode character
str: 8 bits raw data
"""
import sys
version = sys.version_info[0]
if version is 3:
#encoding will take unicode ... |
861b4de44c46641548aa14a0fe42c996bb89f353 | DiQuUCLA/python_59_skill | /8_avoid_using_more_than_2_exp_in_list_comprehension.py | 414 | 3.5625 | 4 | matrix = [[1,2,3], [4,5,6], [7,8,9]]
#The below one seems cool, but not hard to read
filtered = [[x for x in row if x % 3 == 0]
for row in matrix if sum(row) > 10]
print(filtered)
filtered = []
for row in matrix:
if sum(row) > 10:
new_l = []
for n in row:
if n % 3 == 0:
... |
b29dafa9bd437e616487a424f38171d04dc29df3 | NabihaAslam/scheduling-algos | /sjf.py | 1,303 | 3.828125 | 4 | #Shortest Job first implementation in python
#taking processes as input from user
print("Enter the number of process: ")
num=int(input())
pro=[]
for j in range(0,num):
pro.insert(j,j+1)
#burst time array
b_t=[]
print("Enter the burst time of the processes: \n")
#burst timre list
b_t=list(map(int, raw_input().split(... |
924a6e07030f670c253f61c981af3f6fde95d0bb | Madanfeng/JianZhiOffer | /python_offer/65_不用加减乘除做加法.py | 4,221 | 3.96875 | 4 | """
写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
示例:
输入: a = 1, b = 1
输出: 2
提示:
a, b 均可能是负数或 0
结果不会溢出 32 位整数
"""
def add(a, b):
"""
一. 十进制计算
大家都举5+7的例子。那我另想一个例子,计算十进制13+9:
1.计算不进位的和。十位1不变,个位3加9等于2,结果为12;
2.计算进位。十位没进位,个位进位为1,结果为10。
再计算十进制12+10:
1.计算不进位的和。十位1加1等于2,个位... |
7cccb81b583d640dd7f8bf59ff3e7a996a6d6c4b | Madanfeng/JianZhiOffer | /python_offer/07_重建二叉树.py | 1,386 | 3.71875 | 4 | """
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.lef... |
da58f2de164ca666eae2901215ff8b474066fb9e | Madanfeng/JianZhiOffer | /python_offer/17_打印从1到最大的n位数.py | 679 | 4 | 4 | """
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
示例 1:
输入: n = 1
输出: [1,2,3,4,5,6,7,8,9]
说明:
用返回一个整数列表来代替打印
n 为正整数
"""
def printNumbers(n):
"""
:param n: int
:return: List[int]
"""
maxvalue = 9
for i in range(n-1):
maxvalue = maxvalue * 10 + 9
r... |
1310c05b4c6a95a972b22446762b03f8e56df008 | Madanfeng/JianZhiOffer | /python_offer/13_机器人的运动范围.py | 2,580 | 3.578125 | 4 | """
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。
一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。
但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
示例 2:
输入:m = 3, n = 1, k = 0
输出:1
提示:
1 <= n,m <= 100
... |
d41f370a9c2b877728f0b32c5b3c84b7cd089ec4 | Madanfeng/JianZhiOffer | /python_offer/59_2队列的最大值.py | 1,342 | 4.0625 | 4 | """
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:
输入:
["MaxQueue","pop_front","max... |
e85ca4f066fbec45110455b2e0684a5838d9c234 | Madanfeng/JianZhiOffer | /python_offer/47_礼物的最大价值.py | 1,275 | 3.703125 | 4 | """
在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。
你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。
给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
示例 1:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 12
解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
提示:
0 < grid.length <= 200
0 < grid[0].length <= 200
"""
def max... |
e27d87b87d61339804625c8a8213f4d51ce5e442 | Madanfeng/JianZhiOffer | /python_offer/55_2平衡二叉树.py | 1,154 | 3.53125 | 4 | """
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。
如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
... |
d58920a1718a9425dddbac9dfc5d98b3ee49b447 | Madanfeng/JianZhiOffer | /python_offer/39_数组中出现次数超过一半的数字.py | 602 | 3.65625 | 4 | """
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
"""
def majorityElement(nums):
"""
:param nums: List[int]
:return: int
"""
if nums == []:
return None
vote = 0
for num in nums:
... |
79f5ad33c3b213df679c819b41c060746b18252e | Madanfeng/JianZhiOffer | /python_offer/37_序列化二叉树.py | 1,977 | 3.921875 | 4 | """
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
"""
import collections
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def ser... |
184b7da2b7085944213de2c86efe221bd29c8454 | nekoTheShadow/my_answers_of_rosetta_code | /babbage_problem/main.py | 862 | 4.125 | 4 | """
Babbage problem: http://rosettacode.org/wiki/Babbage_problem
269,696で終わる自然数のうち、最小の平方数は何か?
チャールズ・バベッジはこの問題の答えを9,947,269,696(=99,736^2)と予想した。
さてこの予想は正しいだろうか? 君の眼で確かめてみよう --というのが本問の趣旨。
===
端的に述べると、彼の予想は間違っている。答えは638269696=25264^2。
平方数判定はもう少しエレガントに書きたかった(´・ω・`)
"""
import math
def is_square(x):
sqrt = int(math.sq... |
d5cb8d7f17a92d9ed1fb8d25ffda8d75e58859b4 | nekoTheShadow/my_answers_of_rosetta_code | /read_a_configuration_file/main.py | 1,706 | 3.640625 | 4 | """
Read a configuration file: http://rosettacode.org/wiki/Read_a_configuration_file
とあるフォーマットのファイルを読み込む問題。仕様がゆるふわの極みであるが、以下の通りに忖度した。
- 空行は無視する。
- #からはじまる行はコメント行とする。
- 基本的なフォーマット ---> UPPER value1,value2,...
- valueが省略された場合はBooleanでTrueと解釈する。
- ただしUPPERの前に;が付与された場合はFalse
- valueはカンマ区切りで、複数値を扱うことができる(=配列... |
e621baa21f874842bcdb1d987ef18f6e9b649c99 | joshpas64/Python-Socket-CS-132 | /ReversiTemplate/ReversiConsole.py | 2,843 | 3.75 | 4 | import ReversiLogic
### Name: Joshua Pascascio
#### ID: 52192782
def check_range(dimension:int)->bool:
''' Checks that the range of inputs meets the dimension requirements'''
if ((dimension>=4) and (dimension<=16) and (dimension%2 == 0)):
return True
return False
def start_game():
... |
538c4fb78529bbf1371a389abf349f8f14fd7997 | Jaltpi/Food_app_mini_project | /mini_project.py | 4,514 | 3.578125 | 4 | # mini_project
from module import main_menu, products_menu, couriers_menu, orders_menu, show_current_list
from module import create_new_product, create_new_courier, create_new_order, update_order_status, update_existing_item
from module import delete_existing_item
LOADING = "Loading Main Menu..."
INVALID = "Invalid s... |
da27aefca8d57bdda3f870387e8ac7d43523f221 | openacid/openacid.github.io | /post-res/dict-cmp/table-eq-circle.py | 466 | 3.75 | 4 | def eq(a, b, walked=None):
walked = walked or {}
if (id(a), id(b)) in walked:
return True
walked[(id(a), id(b))] = True
for k in set(a) | set(b):
if k not in a or k not in b:
return False
if not eq(a[k], b[k], walked):
return False
return True
... |
6b38e79b9864cec936b503d30a301ca1be365f71 | AaronScruggs/blackjack | /HardBlackjack.py | 8,144 | 3.75 | 4 | import random
class Hand:
def __init__(self):
self.cards = []
self.hand_value = 0
def calculate_hand(self):
amount = [card.value for card in self.cards]
while sum(amount) > 21 and 11 in amount:
first_ace = amount.index(11)
amount[first_ace] = 1
... |
11954ef3d5a736927d33faa12c9ad7c89dfea710 | nazaninsh/Bioinformatics | /GC_Content/GC_content.py | 1,029 | 3.625 | 4 | #find GC content of brca1 gene
#brca1 gene is the one for breast cancer
#download the FASTA format of the gene from NCBI
with open('brca1.txt','r') as GC:
#set the values to zero
a=t=c=g=0
#skip the header which is first line
GC.readline()
for line in GC:
#make all the char lower case
... |
382d76a57eaa3ac1977efcc150dd609c41e831c4 | rtain/RM_ICS_Debugging_Challenge | /ICS-Debugging_Challenge_Ristic.py | 4,201 | 3.640625 | 4 | #code creator: ella
#number of errors: ~3
from tkinter import *
from tkinter import ttk
import random
print('meeemaw')
root = Tk()
root.title("Rock Paper Scissors")
mf=ttk.Frame(root)
mf.grid(row=0, column=0, sticky=(N, W, E, S))
#resetting the game
def reset():
wins.set(0)
ties.set(0)
l... |
8aa752a015ebd23995854243c91ff30dab5d9dcd | rtain/RM_ICS_Debugging_Challenge | /Schweighauser_ICS_Debugging_Challenge_01.py | 665 | 3.890625 | 4 | def whereismymoney(hours, rate):
if hours <= 40:
pay=(hours*rate)
# Ben Schweighauser
# Syntax error #1: extra parentheses in else statement
else:
pay=(((40*rate)+(hours-40)*(rate*1.5)))
return pay
try:
a=float(input("How many hours did you work?\n"))
b=float(input("What is y... |
7401314a48f6f39891ac2b54de2f873775058a0b | Lorifraun/python-challenge | /PyPoll/mainpoll.py | 2,028 | 3.78125 | 4 | import os
import csv
#set varibles
candidate_list = []
total_votes = 0
total_of_candidatevotes = []
percent_of_candidatevotes = []
candidate_one_votes = 0
candidate_two_votes = 0
candidate_three_votes = 0
candidate_four_votes = 0
#set path
csvpath = os.path.join('C:\\Users\\lorif\\Demo\\python-challenge\\PyPoll\\Res... |
6b0dab7e02ad00a6576cce2a633787abc8e45e24 | devjuliet/busquedas-clasicas | /busqueda.py | 7,965 | 3.671875 | 4 | from abc import ABC,abstractmethod
## Esta es una clase para el ambiente de un problema
class ambiente:
def __init__(self,grafo,hs=None):
self.grafo=grafo
self.hs=hs
def getGrafo(self):
return self.grafo
def getHs(self):
return self.hs
def setHs(self,hs):
self.hs... |
3eec7c5d6847099cadf29cc6ad67c357714f1f4c | iswarup/HackerEarth | /Arrays/decoratorsProblemFromHackerrank.py | 562 | 3.8125 | 4 |
'''
The link to the problem
https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem?isFullScreen=true&utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign
'''
def wrapper(f):
def fun(l):
# complete the function
newl = ["+91" + " " + st... |
d4b446792894ff013f7dd3d2b7d60a156a9a1d71 | jsMRSoL/CEM_vocab_lister | /input_list_sanitiser.py | 1,424 | 3.59375 | 4 | #!/usr/bin/env python3
import nltk
def remove_unwanted_word_fragments():
'''Remove unwanted words and fragments from a text file.
Requires nltk.'''
# Create a set of words for reference
words = set(nltk.corpus.words.words())
# Remove common words from the tests and common fragments from OCR
... |
511c03ff0dc1cfe51c95bfb066a14dd27e8240ac | lcampagnaro/Exerc-cios-Python | /ex058 - Adivinhação melhorado.py | 868 | 3.859375 | 4 | from random import randint
from time import sleep
computador = randint(0, 9) # Faz o computador "sortear" o número
print('\33[33m-=-\33[m' * 25)
print('Olá sou o COMPUTADOR...')
print('Vou pensar em um número entre 0 e 9. Tente adivinhar qual...')
print('\33[33m-=-\33[m' * 25)
acertou = False
palpites = 0
whil... |
c03744735ae94c6f424630d2f51b7ff736350906 | brandypoiry/PY4E_Class | /4.6.py | 352 | 4.03125 | 4 | def computepay(workedHours, standardRate):
if hours > 40:
standardPay = 40*rate
overTimePay = (hours-40)*(1.5*rate)
pay = standardPay+overTimePay
else:
pay = hours*rate
return pay
hours = float(input("Enter Hours: "))
rate = float(input("Enter Rate: "))
totalPay = computepa... |
05f8da9518d53bc8669a784d85f8241815b183be | MTDahmer/pychallenge | /pybank/main (2).py | 1,499 | 3.84375 | 4 | import csv
import os
def main():
with open("Resources/budget_data.csv", newline ='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
count = 0
total = 0
numberList = []
maxNumber = 0
maxDate = ""
minNumber = 0
minDate = ""
... |
9c30b847859dc19b8cdaa8c16f56f4e6d8651e89 | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Análise de dados em uma tupla - 75.py | 946 | 4.21875 | 4 | #Exercício Python 075: Desenvolva um programa que leia quatro valores pelo teclado
# guarde-os em uma tupla. No final, mostre:
#A) Quantas vezes apareceu o valor 9.
#B) Em que posição foi digitado o primeiro valor 3.
#C) Quais foram os números pares.
valores = (int(input("Primeiro valor: ")),
int(input("Segu... |
b45e42273efc868dea8f4690154fa383bea5c1ab | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Melhorando a matriz - 87.py | 1,399 | 4.15625 | 4 | #Exercício Python 087: Aprimore o desafio anterior, mostrando no final:
# A) A soma de todos os valores pares digitados.
# B) A soma dos valores da terceira coluna. ... |
512e793f16e31059c50e32b3e8aeffd6a3afdc1d | MatheusKlebson/Python-Course | /SECUNDO MUNDO - SECOND WORLD/Validação de dados - 57.py | 580 | 4.09375 | 4 | #Exercício Python 057: Faça um programa que leia o sexo de uma pessoa,
# mas só aceite os valores 'M' ou 'F'. Caso esteja errado, peça a digitação novamente até ter um valor correto.
sexo = str(input("Informe o sexo[M/F]: ")).strip().upper()[0] #Variavel que guardará o valor do sexo
#Condição caso o usuario digite erra... |
76d8f4bb927db5d23dec1970d05e0b86b51a130e | MatheusKlebson/Python-Course | /SECUNDO MUNDO - SECOND WORLD/Factorial - 60.py | 462 | 4.21875 | 4 | #Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial.
# Exemplo: 5! = 5 x 4 x 3 x 2 x 1 = 120
from time import sleep
from math import factorial
num = int(input("Número: "))
cont = num
f = factorial(num)
print("Calculando factorial...")
sleep(2)
while cont > 0:
print(" {} ".for... |
dade3a6ec2e80193463315972b1dc8b7f33ec9a5 | MatheusKlebson/Python-Course | /SECUNDO MUNDO - SECOND WORLD/Super progressão aritmetica - 62.py | 666 | 4.0625 | 4 | #Exercício Python 62: Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos.
# O programa encerrará quando ele disser que quer mostrar 0 termos.
# no final mostre quantos termos foram mostrados
print("="*25)
print("PROGRESSÃO ARITMETICA")
print("="*25)
primeiro = int(input("Primeiro te... |
aec7beaeb6bc66cd0d01fed39c37626a6e4c43a8 | MatheusKlebson/Python-Course | /SECUNDO MUNDO - SECOND WORLD/Progressão aritmetica com for - 51.py | 428 | 4.03125 | 4 | #Exercício Python 051: Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final,
# mostre os 10 primeiros termos dessa progressão.
print("="*25)
print("PROGRESSÃO ARITMETICA")
print("="*25)
primeiro = int(input("Primeiro termo: "))
razão = int(input("Razão: "))
decimo = primeiro + (10 - 1) * razão... |
290e8ba810b59b20c4cd3a3ed33339649d3f011b | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Função de contador - 98.py | 1,553 | 4.1875 | 4 | ''' Exercício Python 098: Faça um programa que tenha uma função chamada contador(),
que receba três parâmetros: início, fim e passo.
Seu programa tem que realizar três contagens através da função criada:
a) de 1 até 10, de 1 em 1 ... |
ae17752fa96c1a869fe80c2346f85508dbd48c01 | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Organizando uma lista sem o sort() - 80.py | 721 | 4.21875 | 4 | #Exercício Python 080: Crie um programa onde o usuário possa digitar cinco valores numéricos
#cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela.
numbers = []
for accountant in range(0,5):
num = int(input(f"Write a number: "))
if accountant == ... |
80a81cca5bdb82f5ba18c68f3351256ac14e64bb | MatheusKlebson/Python-Course | /PRIMEIRO MUNDO - FIRST WORLD/Encontrando string - 26.py | 539 | 3.96875 | 4 | #Exercício Python 026: Faça um programa que leia uma frase pelo teclado
#mostre quantas vezes aparece a letra "A"
#em que posição ela aparece a primeira vez
#em que posição ela aparece a última vez.
from time import sleep
frase = str(input("Frase: ")).strip().upper()
print("Analisando...")
sleep(2)
print("A frase possu... |
072db63bb43c2d09bddf30bba01b8bb925a20ecc | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Analisando e gerando Dicionários - 105.py | 1,950 | 4.21875 | 4 | # Exercício Python 105: Faça um programa que tenha uma função notas()
# que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações:
'''– Quantidade de notas ... |
eadd2c2fdddc167a52590ea2c21ab3067f7cd3b9 | MatheusKlebson/Python-Course | /SECUNDO MUNDO - SECOND WORLD/Gerenciador de pagamento - 44.py | 1,515 | 4.03125 | 4 | #Exercício Python 044: Elabore um programa que calcule o valor a ser pago por um produto,
# considerando o seu preço normal e condição de pagamento:
# à vista dinheiro/cheque: 10% de desconto
# a vista no cartão: 5% de desconto
# Em até 2x no cartão: preço normal
# 3x ou mais no cartão: 20% de juros
from time import sl... |
05f0de12aa2a42cf35c87f7fff3b5f9306ad0ec6 | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Lista de preços com tupla - 76.py | 645 | 4.15625 | 4 | #Exercício Python 076: Crie um programa que tenha uma tupla única com nomes de produtos
# seus respectivos preços, na sequência.
# No final, mostre uma listagem de preços, organizando os dados em forma tabular.
produtos = ("COMPUTADOR",1220,
"TABLET",355,
"CELULAR",420,
"GELADEIRA",3... |
8480108953305c02872b0655c56ff18c44afca8d | MatheusKlebson/Python-Course | /PRIMEIRO MUNDO - FIRST WORLD/Analisador de textos - 22.py | 603 | 4.25 | 4 | #Exercício Python 022: Crie um programa que leia o nome completo de uma pessoa e mostre:
#- O nome com todas as letras maiúsculas e minúsculas.
#- Quantas letras ao total (sem considerar espaços).
#- Quantas letras tem o primeiro nome
from time import sleep
nome = str(input("Nome completo: ")).strip()
n = nome.split()
... |
838bb1864c991317edec4a7c72f92c9e770e7f30 | dunn0052/UofM | /4041/disjoint_set.py | 693 | 3.515625 | 4 | class make_set:
rank = 0
def __init__(self, x):
self.x = x
self.p = self
self.c = [self]
def union(x,y):
link(find_set(x), find_set(y))
def link(x, y):
if(x.rank > y.rank):
y.p = x
x.c.extend(y.c)
else:
x.p = y
y.c.extend(x.c)
... |
31d47bb7127a34e3d831a127db63c18b61f8ec6b | AlphaJia/LLCode | /leetcode/editor/cn/[7]整数反转.py | 1,658 | 3.875 | 4 | # 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
#
# 示例 1:
#
# 输入: 123
# 输出: 321
#
#
# 示例 2:
#
# 输入: -123
# 输出: -321
#
#
# 示例 3:
#
# 输入: 120
# 输出: 21
#
#
# 注意:
#
# 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
# Related Topics 数学
'''
函数str():将参数转换成字符串类型,即人适合阅读的形式
函数list(... |
3012ce5f66bf575392b8d7b5f1dfa8610ae1eb6f | AlphaJia/LLCode | /leetcode/editor/cn/[345]反转字符串中的元音字母.py | 1,261 | 3.640625 | 4 | # 编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
#
#
#
# 示例 1:
#
# 输入:"hello"
# 输出:"holle"
#
#
# 示例 2:
#
# 输入:"leetcode"
# 输出:"leotcede"
#
#
#
# 提示:
#
#
# 元音字母不包含字母 "y" 。
#
# Related Topics 双指针 字符串
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def reverse... |
237eafe92d75cc8aec78b8e961f99c89db58f031 | pavan-kancharla/Code | /Keybinds/Keybinds.py | 1,790 | 3.640625 | 4 | import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
root.title("Basic Interface")
interface=tk.Frame(root)
interface.configure(bg='white')
interface.grid(row=0, column=0,sticky='news')
interface.tkraise()
#Tkinter Variables
inputedData= tk.StringVar()
outputData= tk.StringVar()
#Define Functi... |
415351a17f0bcb3f892b88c65aa0f8f53d9fe140 | khushalp-jpg/weather-app | /weather-app.py | 2,047 | 3.578125 | 4 | from tkinter import *
from configparser import ConfigParser
from tkinter import messagebox
import requests
url_api = "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}"
api_file = 'weather.key'
file_a = ConfigParser()
file_a.read(api_file)
api_key = file_a['api_key']['key']
def weather_find(ci... |
1637404e5dd9008aae6f24b9bd680dafd5601348 | reuseman/ase-fall-20 | /Lab_1/Calculator/calculator.py | 409 | 3.546875 | 4 | def sum(m, n):
sign = 1 if n > 0 else -1
n = abs(n)
while n != 0:
m += sign
n -= 1
return m
def divide(m, n):
if n == 0:
raise ZeroDivisionError
i = 0
isNegative = m > 0 and n < 0 or m < 0 and n > 0
m = abs(m)
n = abs(n)
while m - n... |
b97436b4f89db6a1dbee2e440e76ef173eb15374 | AnnikaGeng/Mypython | /second.py | 1,933 | 3.875 | 4 |
def convert_seconds(s):
hour = int(s)//3600
minute = int(s) % 3600 // 60
second = s - hour * 3600 - minute * 60
if hour == 1:
if minute == 1:
if second == 1:
return str(hour) + ' hour' + ',' + str(minute) + ' minute' + ',' + str(second) + ' second'
else:
... |
8844f86c7d088c154994c218c700128d909653c7 | AnnikaGeng/Mypython | /generator.py | 283 | 3.78125 | 4 | def triangle(n):
L = [1]
while True:
yield L
L = [L[x]+L[x+1]for x in range(len(L)-1)]
L.insert(0,1)
L.append(1)
if len(L)>n:
break
t=int(input("please enter the number of lines:"))
lines = triangle(t)
for m in lines:
print(m) |
ad6da1fc01d3f9c310bb79d6b9febbd3d9b2e941 | kanoga/Day0_kanoga | /prime_numbers.py | 378 | 4.09375 | 4 | #Query the user for n(The maximum number in the range)
n = input('Insert the maximum value in the range:')
#According to value n inserted by the user, find the prime numbers in that range and print them out
def prime(number):
for x in range(2,n+1):
count = 0
for y in range(2,x):
if x%y != 0:
... |
7dfa4068f30a0d8c06a45231b02415874594e15b | kurumiwj/PAT-Advanced-Python | /1152.py | 404 | 3.75 | 4 | import math
def isPrime(s):
s=int(s)
if s==2 or s==3:
return True
for i in range(2,int(math.sqrt(s))+1):
if s%i==0:
return False
return True
l,k=map(int,input().split())
num=input()
flag=False
for i in range(len(num)-k+1):
if isPrime(num[i:i+k]):
... |
5cf86089f329c098cb19a23bc823e71ef9f500d5 | kurumiwj/PAT-Advanced-Python | /1011.py | 320 | 3.65625 | 4 | from functools import reduce
games=3
odd=[]
bet=["W","T","L"]
bet2=[]
def mul(x,y):
return x*y
for i in range(games):
l=list(map(float,input().split("\n")[0].split(" ")))
odd.append(max(l))
bet2.append(bet[l.index(max(l))])
total=(reduce(mul,odd)*0.65-1)*2
print(*bet2,"%.2f" % total)
|
16d1ba10a4046abb9c9837caefad22cf2e77060d | kurumiwj/PAT-Advanced-Python | /1100.py | 863 | 3.546875 | 4 | low=["tret","jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"] #低位
high=["tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"] #高位
def earth_to_mars(n):
ret=""
h=int(n/13)-1
l=n%13
if h>=0:
ret+=high[h]
if l!=0:
... |
e5d3d5fcc86b340efb23b0cf99b4652daa6e3e4d | juanjosua/codewars | /find_the_odd_int.py | 599 | 4.1875 | 4 | """
Find the Odd Int
LINK: https://www.codewars.com/kata/54da5a58ea159efa38000836/train/python
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
"""
def find_it(seq):
numbers = set(seq)
return[n for n in numbers ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.