blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b25a60e2013b9451ba7eb8db5ead8f56e5a59fcd
Pdshende/-Python-for-Everybody-Specialization-master
/-Python-for-Everybody-Specialization-master/Coursera---Using-Python-to-Access-Web-Data-master/Week-6/Extracting Data from JSON.py
1,695
4.1875
4
''' In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the...
43d98b424833385bd912121edab91fef1bc20395
Leonardo-KF/Python3
/ex087.py
707
3.78125
4
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] sp = s3 = m2 = 0 for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite um numero para a posição [{l}, {c}]: ')) if matriz[l][c] % 2 == 0: sp += matriz[l][c] if matriz[l][2]: s3 += matriz[l][2] ...
6d106239f14939f1aa44767fc84426d80bec0fc1
lvah/201903python
/day16/BinaryTree.py
3,335
4.15625
4
class Node(object): """ 二叉树节点对象封装的类 """ def __init__(self, element): self.element = element self.lchild = None self.rchild = None def __str__(self): return self.element def __repr__(self): return self.element class Tree(object): """二叉树的封装""" ...
6508d4b6361cec6419dcdc7fbf8e0ffb8056b0f5
LukasHe/exercises
/2_Exercise/threads_in_python_lock.py
531
3.8125
4
# Python 3.3.3 and 2.7.6 # python threads_in_python.py import threading from threading import Thread i = 0 lock = threading.Lock() def thread_1(): lock.acquire() global i for j in range(10000): i = i + 1 lock.release() def thread_2(): lock.acquire() global i for j in range(10000): i = i - 1 lock.rel...
e2f0136c4450908b1b5bd17a5af305b07f323dca
Iswaryadevi98/guvi
/codeketa/powerof2.py
75
3.5
4
ws=int(input()) a=(ws&(ws-1)) if(a==0): print("yes") else: print("no")
f5ceea860cb50723f69e28e64fe4933131ec3b0e
jabadia/advent-of-code-2017
/d17/d17p1.py
919
3.625
4
from collections import namedtuple TestCase = namedtuple('TestCase', 'case expected') def check_case(test_case, actual): if test_case.expected == actual: print("OK %s" % (test_case.case,)) else: print("FAIL %s, expected %s, got %s" % (test_case.case, test_case.expected, actual)) TEST_CASES ...
10683d46786229f143d935ce759361175ecb84f5
ArsalanMacknojia/Computational-Data-Science
/Exercises/Ex04/average_ratings.py
1,475
3.65625
4
# CMPT 353 - Exercise 4 # Arsalan Macknojia import sys import difflib import pandas as pd def avg_movie_ratings(movie_title, user_ratings): """ Function compares titles present in user_ratings DF with movie_title and calculate the average rating. Rating is only accepted if the title in user_ratings matc...
cab2719eeabe6db8ab43c67db3c47d5c2e71e8e0
vaishalicooner/Practice-Linked-list
/practice_linkedlist/search.py
455
3.875
4
# searching a given a node in linked list class Node(object): def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __int__(self): self.head = None self.tail = None def find(self,data): current = self.head while current...
2c196f3bda70c70fe0ce1d47954263a729dd03a7
amberbhanarkar/CompetitiveProgramming
/chfideal.py
202
3.96875
4
import random X = random.randint(1,3) print(X) Y = random.randint(1,3) while X==Y: Y = random.randint(1,3) print(Y) Z = random.randint(1,3) while Y==Z or X==Z: Z = random.randint(1,3) print(Z)
7c762f9af8f9c6bdc6e19b52bc4fcafcaab2d7c5
fensoms7343/cti110
/P2HW2_fensom.py
755
4.21875
4
#CTI110 #P2HW2 #Scott Fensom #11/1/18 #Get the total number of students student_total= int(input('Enter the total number of students in the class: ')) #Get the total number of female students student_female= int(input('How many students are female?: ')) #Get the total number of male students student_male...
383ebe52fdf7ba2d60facf0e6e60b90d9c62fb3a
Ghost-Zephyr/PROGMODX
/innleveringer/uke 9/derived.py
477
3.6875
4
# -*- coding: utf-8 -*- from matplotlib import pyplot as plt import numpy as np derived = lambda f, x, h: (f(x+h) - f(x)) / h # Newtons kvotinent symderived = lambda f, x, h: (f(x+h) - f(x-h)) / (2*h) # Newtons symmetriske kvotinent if __name__ == '__main__': f = lambda x: np.sin(x) #f = lambda x: x**3 - 2*x*...
15650f943423cf9092f06a96a783848c53ca274a
ucandoitrohit/Python3
/Python_Basic_script/41.function-with-argument-retrun-value.py
585
3.921875
4
def add(a,b): result=a+b # print(f"Addition {a}+{b}={result}") return result def sub(a,b): result=a-b print(f"Subtraction {a}-{b}={result}") return None def main(): a=eval(input("Enter the first value-")) b=eval(input("Enter the second value-")) result=add(a,b) print(f"Addition...
de3989e3fa158ca2e8a51a9b641a02231eaa18c2
pwang867/LeetCode-Solutions-Python
/0045. Jump Game II.py
2,757
3.625
4
# method 3: time O(n), space O(1) greedy, similar to BFS searching minimum depth # try to get the furthest front for each jump class Solution(object): def jump(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n < 2: return 0 ...
22ed333f22618692e11768ea2590888df3e90464
SRoseDev/adventofcoding2018
/Day12/day12-efficient.py
2,928
3.546875
4
import operator state = dict() next_state = dict() keys = dict() key = '.....' # initial key state def get_state_for_index(index: int): global state return state.get(index, '.') def build_key_for_index(index: int): key = '' for i in range(index-2, index+3): key = key + get_state_for_index...
5df93b343a5f8c3f55cb0425ac74015407023129
brucetony/cslsi-homework
/cslsi-09-Schultz-Kaur-Kandarpa.py
9,842
3.921875
4
""" Created on Sun Dec 10 14:01:40 2017 @author: Bruce """ from graphviz import Digraph class BinaryTree: def __init__(self, root = None): '''Can create an empty tree''' self.root = root #Each child will be root of new tree self.leftChild = None self.rightChild = None def ...
df051cc2ac87b09858439553c80784fd3c8a3f7a
RainMoun/nowcoder_program
/剑指offer/数组中出现次数超过一半的数字.py
444
3.890625
4
def more_than_half(num_lst): if not num_lst: return -1 # 数组为空 count = 1 now_num = num_lst[0] for num in num_lst[1: ]: if num == now_num: count += 1 else: if count > 0: count -= 1 else: count = 1 ...
43ffd255efec7c846837f3712a109dccebe20653
vshrivastava1970/Python
/Py/bin/for_ex.py
901
3.671875
4
''' S = 'Python' for a in S: print('a =', a) b=100 L=[10,20,30] for b in L: print('b=', b) print('type=', type(b)) print('Now b =', b) ''' D = {'A': 10, 'B':20} ''' for c in D: print('C=', c) print('Value=', D[c]) for d in D.keys(): print('d=', d) for e in D.values(): print('e=', e) ...
2fc8bfd4530c5c3c842792dec7109ff53a56740c
JuliyShulaeva/TPG
/2sem/laba1/laba4/laba4.py
2,038
3.59375
4
import sqlite3 import csv class Student(object): def __init__(self, data, curs): for key, value in data.items(): object.__setattr__(self, key, value) object.__setattr__(self, 'cursor', curs) def __setattr__(self, key, value): object.__setattr__(self, key, value)...
3303f5c322e70921c4cba8fb0e74da2202389bb2
Mahmood08/Class_Repo
/Session03/strformat_lab.py
1,024
4.1875
4
#Write a format string that will take four element tuple: tuple=( 2, 123.4567, 10000, 12345.67) print("'First item: {:03d}, second item: {:.2f}\n,third item :{:.2e} and fourth item: {:.2e}'".format(*tuple)) #Task-3 def formatter(in_tuple): width= 4 tuple_m =(4,)*in_tuple # format_string="'{:d},{:...
e9662e7c3b5ec760acd11b4fd93987207cbae0b1
lradebe/simple_programming_problems
/quick_sort.py
219
3.5625
4
def quick_sort(list): list = sorted(list) half = int(len(list)/2) list1 = list[:half] list2 = list[half:] #print(f'{list}\n\n{list1}\n\n{list2}') list = [79, 23, 1, 78, 55, 108] quick_sort(list)
60d708d8b28dbd54732eb2f4c8c24618fc3f91b5
Taoge123/LeetCode
/Binary Tree/SumAllLeftLeaves3.py
1,032
3.890625
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def sumOfLeftLeaves(root): if (root is None): return stack = [] stack.append(root) sum = 0 while stack: currentNode = stack.pop() if currentNode.left is ...
2b96b7dd86cc485189f87f81fae1f875f3c76d19
swaraj1999/python
/chap 3 if_and_loop/for_loop_string.py
293
3.640625
4
# for i in range(len(name)): # print(name(i)) #old process name="swaraj" for i in name: print(i) #python #1256= 1+2+5+6 num=input("enter name ::") total=0 for i in num: total+=int(i) print(total) #python spl
2c9924e097c743d5745631d4192561f58d56f90c
meighanv/05-Python-Programming
/LABS/Group-Project/parseTextfile.py
1,077
3.640625
4
# This function is meant to read in the help text file to parse it into # helpObjects that are returned as a list def parseHelp(filename): # Opening and reading the lines of the file f = open(filename, 'r') # This reads in each line as it's own list item contents = f.read() f.close() import r...
c56fbda0caea88ed3420eb411842d73d3bb9bf3f
Mon-Lay/PythonTestRepo1
/pant.py
1,299
4.125
4
### TODO: # - code a Pants class with the following attributes # - color (string) eg 'red', 'yellow', 'orange' # - waist_size (integer) eg 8, 9, 10, 32, 33, 34 # - length (integer) eg 27, 28, 29, 30, 31 # - price (float) eg 9.28 ### TODO: Declare the Pants Class ### TODO: write an __init__ function to init...
b59e942d2ae9b23e6f6a493d278a2edecc7168df
eternalseptember/CtCI
/01_arrays_and_strings/7_rotate_matrix/rotate_matrix.py
1,026
3.75
4
""" Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? """ """ def rotate(N, image): new_image = [] for col in range(N): col_entry = [] for row in range(N): col_entry.append(image[row][col]) new_i...
858b80b5df792c5e53dc4424af7fd6238eb82b6e
fenglihanxiao/Python
/Module01/DataStructure/SliceDataStructure.py
1,292
4.1875
4
""" 1. Slice only operate on list and tuple, not including set and dict """ list1 = [1, 2, 3, 4, 5, 6] list2 = [1, 2, 3] tuple1 = (101, 32, 121) set1 = {84, 32, 84, 32, 12} dict1 = {"name": "Feng", "age": 18} """ 1. @parm1: start index 2. @param2: end index (exclusive) 3. @param3: step ""...
e7a11b02aeaac8066c962f5d1f3c4bcfcae75102
giom-mallet/python-first-program
/database/my_sqlite.py
1,471
3.71875
4
import sqlite3 def create_table() : conn=sqlite3.connect("giom_data.db") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)") conn.commit() conn.close() def insert_data(item, quantity, price) : conn=sqlite3.connect("giom_data.db") cur...
fa02a50ae6ec90e6c4f0e5c4aee2209322117cb3
nitinverma99/Codeforces---800
/Petya_and_Strings.py
133
3.84375
4
str1 = input().lower() str2 = input().lower() if str1 == str2: print("0") elif str1 > str2 : print("1") else: print("-1")
10c0a0a42bdf8dce0d9c695174b565e0b1d7f616
Vipinraj9526/Python
/pgm6.py
142
3.578125
4
import csv with open("city.csv","r") as file: r=csv.DictReader(file) for row in r: print(row["slno"],row["name"],row["city"])
697603fdc02282abc3885b525abe496529e59368
phiysng/leetcode
/leetcode/python/25.reverse-nodes-in-k-group.py
2,805
3.75
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None ''' 递归的解法 只需对链表进行一次遍历 递归层次O(n/k) ''' class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head: return head # prev k 个一组的最后一个...
c230905359bf94de232d4753270e00bf77c9c6e6
idxcky/code
/python/爬虫/天气预报数据可视化/spyder.py
2,210
3.625
4
""" 2019年3月2日07:08:57 安徽省主要城市天气抓取 做一个可视化 """ import requests from lxml import etree from time import sleep import random import pandas as pd BASEURL = 'http://www.tianqihoubao.com/weather/' WEATHER = [] def get_html(url): sleep(random.randint(1,3) + random.random()) headers = {'User-Agent': 'Mozilla/5.0 ...
61b0fc06f2569d2d00c75d0e3cd5443d78e64fd3
Xiangyaojun/Algorithms
/二叉树/完全二叉树的最后一个节点.py
2,736
3.96875
4
# coding:utf-8 ''' 阿里面试题:求一个完全二叉树的最后一个节点指针,也就是最后一层的最右节点 解析: 1.暴力求解:层次遍历即可求出最后一个节点,时间复杂度O(n) 2.二分查找法:时间复杂度O(logn) 空间复杂度O(1) 通过判断右子树是否可以到达树的最深处,如果能到达,则先去右子树,若不能到达,则去左子树 就这样,递归的划分寻找区间 3.如果二叉树的节点个数是已知的为N,不断除以2,记录奇偶性 例如知道完全二叉树有9个节点:9 9/2=4 4/2=2 [奇,偶,偶],则反过来从根节点就是左->左->右(偶->偶->奇) 算法时间复杂度O(logn) 空间复杂度 O(logn) ...
d6a228e1884eb5c5a659a68dde3cfb637edc64b4
rayhan-rimon/Python-beginne-to-advance-code-project
/beginner part/day 5/High Score.py
498
4.0625
4
# How to define a high score without using max() function # input some list of score. as like 55 60 100 95 ... student_scores = input('Input a list of students score: \n').split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print("List of student scores: ", student_scores) h...
1118621417946658983a21c7ea05a3dc65046980
d27khan/R3-SoftwareTraining-2-DanielKhan
/othermain.py
4,530
3.546875
4
import pygame import random import math WIDTH = 800 HEIGHT = 800 FPS = 30 MARGIN = 50 gridsize = input("Enter size, n (note it will be size n x n): ") grid = [] visited = [] gridSize = int(gridsize) cellSize = WIDTH/gridSize ## size of each box cellSize = math.floor(cellSize) class cell(): def __init__(self,r,...
a9653b2bd4bcd2f6cb24b8d6e5c5046370a77a80
kaletap/neural-network
/nnet/losses/quadratic_loss.py
677
3.71875
4
import numpy as np from .base_loss import Loss class QuadraticLoss(Loss): """ Loss for simple regression: squared error. For `n` observations it will produce n error values. """ def forward(self, y_predicted: np.ndarray, y_true: np.ndarray) -> np.ndarray: assert y_true.shape[0] == y_pred...
3bb0875f2973efe1b24410db17547dfb57d99962
neelamy/Leetcode
/Graph/286_WallsandGates.py
1,278
3.515625
4
# Source : https://leetcode.com/problems/walls-and-gates/description/ # Algo/DS : Graph, BFS # Complexity : O(nm) class Solution(object): def wallsAndGates(self, rooms): """ :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. ...
22a660150654ee0e5afa74b43934b6a124e75098
JakubKazimierski/PythonPortfolio
/Coderbyte_algorithms/Easy/GroupTotals/GroupTotals.py
1,090
3.953125
4
''' Group Totals from Coderbyte December 2020 Jakub Kazimierski ''' def GroupTotals(strArr): ''' Have the function GroupTotals(strArr) read in the strArr parameter containing key:value pairs where the key is a string and the value is an integer. Your program should return a strin...
aa4ea1ce89e640575211119d7b2312551ba29427
bucknermr/algorithms
/interview_cake/highest_product_of_3/highest_product_3_alternate.py
1,060
4.0625
4
def highest_product_of_3(int_list): if len(int_list) < 3: raise "Need at least 3 integers" highest = max(int_list[:2]) lowest = min(int_list[:2]) highest_product_of_2 = highest * lowest lowest_product_of_2 = highest_product_of_2 current_answer = float('-inf') for int in int_list[2:...
fcc3983c35d811e6d7aafc21a963f0089b0077c8
Lemmah/james-lemayian-bootcamp-17
/Day 2/Andelabs/DataTypesLab/data_types.py
777
4.21875
4
#!/usr/bin/env python # encoding: utf-8 """ TODO: string returns length of string None returns 'no value' Booleans return the boolean itself integers return a string of how it compares to 100 lists return the third item or None if it doesnt exist """ def data_type(data): if isinstance(data, str): return ...
836ca64a25ebd343609d6a0bdf2d721ac8920bac
nag-sa/testpython
/filehandling/test1.py
333
4.1875
4
#Create a text file “intro.txt” in python and ask the user to write a single line of text by user input. file = open("D:\\python\\filehandlingtestprog\\intro.txt" , "w") userinput = input("Enter user input: ") file.write(userinput) file.close() file = open("D:\\python\\filehandlingtestprog\\intro.txt" ,"r") print(fil...
8f6126b5c02ab5461ec74150908be70ce5c71ae5
mglu123/MealPrep_ML
/mealprep/mealprep.py
12,766
3.75
4
import numpy as np import pandas as pd from sklearn.compose import ColumnTransformer from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder, StandardScaler def find_fruits_veg(df, type_of_out="categ", n_rows=100): """ This function will drop row with NAs and find ...
f05a326a8949260828e8b6967f1d08cdc1e55524
Shulun/Python-Coursera
/Word_Wrangler_Iterative.py
4,397
3.796875
4
import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elemen...
81527a6932a41892dab3312a4f730f264472d19a
ycisacat/catteryofyc
/seek_and_sort.py
3,964
3.65625
4
#coding=utf-8 from __future__ import division #问题:1怎么N行同时加#和去除#号? 2类名和函数名是不是一定要大写的?貌似不大写没问题? __metaclass__ =type class SortAndSeek: def bisearch(sequence,number,lower=0,upper=None): #二分法查找 list.sort() if upper is None: upper = len(list)-1 if lower == upper: assert number == list[...
5deda6151acd3f629fea0d8d30ee39c573a21a16
ftorresi/PythonLearning
/Unit2/ej2.7.py
169
3.515625
4
a=18 b=188 n=10 coord=[] h=(b-a)/float(n) #part A for i in range(1+n): x=a+i*h coord.append(x) print coord #part B coordB=[a+i*h for i in range(1+n)] print coordB
34513702c915959e944043f688b7d3176528bb0d
honeytoast/PythonProgramming
/VigenereCipher/vigeneredecipher.py
1,041
3.84375
4
#### Name: Grace Hadiyanto #### E-mail: ifoundparis@gmail.com #### CPSC 223P #### Assignment 2 import sys import cipher def main(): keyword = input('What is the keyword?: ') # Stores the name of the input file and reads its contents infile_name = str(sys.argv[1]) infile = open(sys.argv[1], 'r') c...
aa1060734c6d3228e78bc2a2df7ded5fa740590e
zenhack/python-ast-format
/pyast/indent_io.py
981
3.5625
4
class IndentIO(object): def __init__(self, output, indent=' ', newline='\n'): self.output = output self.indent_str = indent self.newline = newline self.level = 0 self.on_new_line = True def write(self, text): lines = text.split(self.newline) lines = [[...
caf62da3715921f34c0d07c571775be7b2f562a7
vv31415926/python_lessons_01_4
/main.ru.py
134
3.671875
4
s = input('Введите ФИО через пробел:') lst = s.split() print( 'Привет, ' ) for si in lst: print( si)
b5801876c75381b918e1b5c14d18e04f83bb933d
NeopoloJIND/Programacion
/ejercicio88.py
1,461
4.34375
4
# EJERCICIO 88 # ¿Es un triángulo válido?. # Si tiene 3 pajitas, posiblemente de diferentes longitudes, puede o no ser posible # acostarlos para que formen un triángulo cuando sus extremos se toquen. por # ejemplo, si todas las pajitas tienen una longitud de 6 pulgadas. entonces uno puede construir fácilmente # ...
ca1f6f286023fd80eac668c7c301c2393e7a5d83
stefan42/adventofcode
/day12_python/puzzle.py3
1,516
3.71875
4
#!/usr/bin/python3 import json def iterate_json(input_json): if isinstance(input_json, dict): accu = 0 for k, v in input_json.items(): accu += iterate_json(v) return accu if isinstance(input_json, list): accu = 0 for o in input_json: accu += iter...
599ec42e5219847d1535253cb065c71b6fa9e091
tomholmes19/LoR-Fiora-Simulation
/cards/generics.py
1,391
3.84375
4
""" Generic classes which can be extended to create specific cards """ class Card: def __init__(self, name, cost) -> None: self.name = name self.cost = cost def __str__(self) -> str: return ( "Name:\t {}\n".format(self.name) + "Cost:\t {}".format(self.cost) ...
45c558fd715746d495f6b000109964ae81810f9f
rafaelperazzo/programacao-web
/moodledata/vpl_data/25/usersdata/110/11858/submittedfiles/av1_3.py
284
3.828125
4
# -*- coding: utf-8 -*- from __future__ import division import math n1=input('Digite n1: ') n2=input('Digite n2: ') a1=n1 a2=n2 cont=1 if a1%a2!=0: while a1%a2!=0: r=a1%a2 cont=cont+1 a1=a2 a2=r print(r) print(cont) else: print(a2) print(cont)
efa3ff3e31f583c051fa9de0801c02565ccc5bfe
heyf/cloaked-octo-adventure
/leetcode/0258_add-digits.py
449
3.5
4
# # @lc app=leetcode id=258 lang=python3 # # [258] Add Digits # # @lc code=start class Solution: def addDigits(self, num: int) -> int: while num // 10 > 0: prev_num = num new_num = 0 while prev_num > 0: new_num += prev_num % 10 prev_num //...
848f4fea463f7f7fc1d3f42c5f493705e3d3b102
Yizong98/Questionnaire-to-DF
/main.py
1,877
3.6875
4
import pandas as pd import numpy as np def questions_input(): questions = ["What major are you?", "How often do you read?", "What kind of books do you read?", "Through what medium do you prefer to read?", "Do you want to read more?", "Why do you like to read?", "What stops you from reading i...
d8824e995fc90bdccb4f93a1b19a35334e2c1456
sry19/python5001
/hw12/disk.py
814
3.671875
4
BLACK = 1 WHITE = 255 class Disk: '''A disk''' def __init__(self, color, row, column, gamecontroller): if color == 'white': self.color = WHITE elif color == 'black': self.color = BLACK self.row = row self.column = column self.gc = gamecontroller ...
a327708eb91560c39f02f74a6b17eecb5a7e51ce
NeuromatchAcademy/course-content
/tutorials/W1D4_DimensionalityReduction/solutions/W1D4_Tutorial4_Solution_2e8ff78c.py
776
3.796875
4
def explore_perplexity(values, X, labels): """ Plots a 2D representation of the data for visualization with categories labeled as different colors using different perplexities. Args: values (list of floats) : list with perplexities to be visualized X (np.ndarray of floats) : matrix with the dataset ...
c64e967bd447ee0923c0e96becb48236782c8e64
Crc-64/geekbrains-python
/Lesson1-HW/t2/t2.py
289
3.9375
4
isNumberCheckFailed = True while(isNumberCheckFailed): in_num = input("Enter time in seconds: ") isNumberCheckFailed = not in_num.isdecimal() in_num = int(in_num) hours = in_num//3600 minutes = in_num//60 - hours*60 seconds = in_num%60 print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
ca69ad1b27ed8b3bbcbe6ed4174cbb5c1d5e1859
maurimaldonado89/Taller_python
/Python/tema5 pandas.py
515
3.671875
4
# -*- coding: utf-8 -*- """ Created on Tue May 25 18:14:14 2021 @author: L01268185 """ import pandas as pd alumnos={'Matricula':['a011','a012','a013','a014','a015'], 'Nombre':['Santiago', 'Lizzie','David','Elizabeth','José'], 'Notas':['95','98','90','88','92'], 'Deportes':['Futbo...
ad2acd6e0c4aa6956659ddf4427493e38338256c
Aasthaengg/IBMdataset
/Python_codes/p02747/s516411849.py
190
3.53125
4
S = input() flag = 0 for i in range(len(S)): if i%2 == 0 and S[i] != 'h': flag = 1 if i%2 == 1 and S[i] != 'i': flag = 1 if flag == 1 or len(S)%2 == 1: print('No') else: print('Yes')
baa6a6c59b521a00328cd61e3a6f39f7e1abebd3
shujunwei/test
/语法/基础语法/条件控制.py
2,048
3.875
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :test @File :条件控制.py @Author :Administrator @Date :2020/10/29 16:13 ''' ''' 条件控制 Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。 4个空格或者tab缩进 ''' ''' if 语句 Python中if语句的一般形式如下所示: ''' # a = 1 # if a < 2: # print("a < 2") # elif a > 2: # p...
d35672c42a8d0ef774bb739d353778ab957869be
ddcv/pythonscripts
/Dijkstra/dijkstra.py
1,118
3.515625
4
import itertools from itertools import groupby # To run, provide: Array C # initial value of 0 for pivloc #Divide Algorithm def dijkstra(G,s,n): #Initialize X = [s] A = [] for x in range(0,n): A.append(x*0) #Computed Shortest Path Distance #Main Loop while len(X) is not n: min_dist = 0 minimizer = [] ...
7972ab899aaf99fa81bcb0ce6365ffb6f885a33f
z-o-e/algoFun
/findPath.py
840
3.71875
4
''' unique path from board(0,0) to board(X,Y) with off-limit spots ''' def isFree(x,y): if board[x,y]!=-1: return True return False def getPath( x, y, path, cache): # use array list to record path # array dict cache to store current spots avoiding duplicates if [x,y] in cache...
d6585aa2edeec7565ad31a462ffad59f79b06ab6
allansundays/primeirorepositorio
/exercicios/ex004.py
134
3.734375
4
# Raiz Quadrada n1 = int(input('Digite um número para tirar a raiz 25')) raiz = n1**(1/2) print(f'A raiz de {n1} é igual a {raiz}')
a15f35a8243876a96f6d71d459ca10a1f7b8b1ab
Guruscode/getting-started-with-python
/data-types/complex.py
498
4.0625
4
# define a complex number a = 1 + 2j print(a) # coplex number without a real part a = 2.5j print('imaginary only complex a', a) # convert complex number from a string a = complex('1+2j') # do not add spaces print(a) # get real part print(a.real) # returns float # get imaginory part print(a.imag) # return float # ...
1591c1018538dceecdb642ff2610ca858f01dcd5
anirudhRowjee/12th-school
/files_replacechar.py
389
4.09375
4
# character replacer def replace_char_by_char(source, char_tbr, repl_char): f = open(source, 'r+') chars = f.read() replace(chars, char_tbr, repl_char) f.write(chars) f.close() source = input("enter file path>>") c_tbr = input("enter character to be replaced") c_repl = input("enter character to re...
a5a771509b2ba4af43dbc2a39455c5a36f90708f
maoqiansheng/python_interview
/interview_test/lambda函数.py
229
3.546875
4
g = lambda x:x[1] def func(x): return x[0] print(g([1,2,3])) print(func([1, 2, 3])) d = {'a': 30, 'g': 17, 'b': 25, 'c': 18, 'd': 50, 'e': 36, 'f': 57, 'h': 25} dd = dict(sorted(d.items(), key=lambda x: x[1])) print(dd)
a69623dff7665d15c6304efcb1a8473f8bd614e7
Jane11111/Leetcode2021
/081_3.py
1,060
3.671875
4
# -*- coding: utf-8 -*- # @Time : 2021-05-30 21:30 # @Author : zxl # @FileName: 081_3.py class Solution: def search(self, nums , target: int) -> bool: lo = 0 hi = len(nums)-1 while lo<=hi: m = (lo+hi)//2 if nums[m] == target: return True ...
5982c6cc1907bf496503f8f2215e430aa5c53ae0
kangli-bionic/HackBG
/Week8/LastHR/last_hr.py
4,393
3.5
4
import requests import json import sys import sqlite3 class Request: def __init__(self): self.information = "" def get_information(self): r = requests.get("https://hackbulgaria.com/api/students/") return r.text class DataBase: def __init__(self): self.conn = sqlite3.c...
96fdb3f37819683bdc6483b8d2d4d790ca65ef40
zuxinlin/leetcode
/leetcode/editor/cn/[面试题 02.01]移除重复节点-remove-duplicate-node-lcci.py
1,403
3.8125
4
#! /usr/bin/env python # coding: utf-8 # 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。 # # 示例1: # # # 输入:[1, 2, 3, 3, 2, 1] # 输出:[1, 2, 3] # # # 示例2: # # # 输入:[1, 1, 1, 1, 2] # 输出:[1, 2] # # # 提示: # # # 链表长度在[0, 20000]范围内。 # 链表元素在[0, 20000]范围内。 # # # 进阶: # # 如果不得使用临时缓冲区,该怎么解决? # Related Topics...
9ae8a7758d25310e054597162ef9ed3e7d1cc0a7
wangfaping0707/PythonProject
/rfresh_Python/chapter3_demo/StudyDay7_demo.py
815
4.03125
4
# 关键字可变参数 def squsum(*param): sum = 0 for i in param: sum += i * i print(sum) squsum(1, 2, 3, 4, 5, 6) # 函数的可变关键字参数 def city_temp(**param): for k, v in param.items(): print(k, ":", v) print(param) print(type(param)) city_temp(bj="34c", cd="27c", sh="35c", hz="28c") dict = ...
7db3b24f868215b692902fa5a1b1c678ce9cdd4d
gilbert99009/Number-Guessing-Game
/Number-Guessing-Game.py
2,047
4.25
4
import random def start_game(): # 1. Display an intro/welcome message to the player. print(""" ------------------------------------ Welcome to the Number Guessing Game! ------------------------------------""") highscore = [10] def inner_play(highscore): # 2. Store a random integer as the ans...
87984c09d4ef1808b506ee87e0683c35a8d372ff
yunieyuna/Solutions-for-Leetcode-Problems
/python_solutions/166-fraction-to-recurring-decimal.py
1,330
3.5
4
# https://leetcode.com/problems/fraction-to-recurring-decimal/ class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return "0" res =[] # 首先判断正负,异或作用就是两个数不同为True,即 1 ^ 0 = 1 或者 0 ^ 1 = 1 if (numerator > 0) ^ (de...
7c4510f76793b0bd7c8e59ad5d48582940202a27
miscer/adventofcode-2019
/3/two.py
1,175
3.5
4
import sys from collections import defaultdict from itertools import repeat def parse_wire(line: str): parts = line.strip().split(',') return [ (part[0:1], int(part[1:])) for part in parts ] directions = { 'R': (1, 0), 'L': (-1, 0), 'U': (0, 1), 'D': (0, -1) } def get_po...
7e0f4369174d9fde7f2e40bcbf503df7489dee8b
dinidininta/arkademy-bootcamp-2
/Nomor2.py
522
3.53125
4
import re def verify_username(username): special = re.compile('[@_!#$%^&*()<>?/|}{~:]') letter = re.compile('[A-Za-z]') if len(username) < 8: return "username harus berjumlah lebih dari 8 karakter" else: if special.search(username) is None or letter.search(username) is None: ...
2c7fbec33cbd73cc72834152955161039da0d7b9
Smurphy822/Python-Examples
/python mad lib.py
344
3.75
4
adjective1= "mo" noun1= "penguin" noun2= "zebra" adjective2= "says" noun3= "snake" print ("Eeny meeny, miny " + adjective1) print ("Catch the " + noun2 + " by the toe") print ("Even if the " + noun1 +" "+ adjective2 + " let him go") print ("My " + noun3 + " told me") print ("to pick the very best one") print ("and you...
5fe70e50126f50b5b708a29b4e7d0c21836a9367
shabeerv/PythonBasics
/5.py
533
4.03125
4
# Write a program to show the grade obtained by a student after he/she enters their total mark percentage. totalMark = float(input("Enter the mark:\n")) if totalMark >= 90: grade = 'Grade A' print(grade) elif totalMark >= 80: grade = 'Grade B' print(grade) elif totalMark >= 70: grade = 'Grade C'...
4c022f9c3572e6a709bf972921199e1b13de1b2d
Ashi-s/coding_problems
/DevPost/str_odd_even_alternate.py
1,040
3.875
4
''' Given an array of positive and negative integers {-1,6,9,-4,-10,-9,8,8,4} (repetition allowed) sort the array in a way such that the starting from a positive number, the elements should be arranged as one positive and one negative element maintaining insertion order. First element should be starting from positiv...
3ebdc4b231b1011b42836f0beea909667177aa26
bgun26/common
/python/decorators/callable.py
967
3.5625
4
class entry_exit(object): __calls = {} MAX_ALLOWED = 1 def __init__(self, f): self.f = f num_calls = self.__calls.setdefault(f.__name__, 0) if num_calls: raise ValueError def __call__(self, *args, **kwargs): self.__calls[self.f.__name__] += 1 num_cal...
baee3f09c3bcb67a2de0db262e1d8ec768902504
Julius-V/Project-Euler
/Problem087.py
1,232
3.734375
4
from math import floor, sqrt # Using the sieve of Sundaram to generate primes up to upper_limit def sieve_sundaram(upper_limit): sieve_limit = floor((upper_limit - 2) / 2) nums = [True] * (sieve_limit + 1) nums[0] = False for i in range(1, floor(sieve_limit / 2)): for j in range(1, floor(sieve...
2ef2bcacf34e6a506626acb9615a7b1c02034ee8
cleverer123/Algorithm
/动态规划/leetcode_62_Unique_paths.py
897
3.640625
4
class Solution(object): # 递归 def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m == 1: return 1 if n == 1: return 1 return self.uniquePaths(m-1, n) + self.uniquePaths(m, n-1) # 动态规划...
2e86b9337474048cb616657ced64dd9bf7a243c2
moontree/leetcode
/version1/1186_Maximum_Subarray_Sum_with_One_Deletion.py
2,368
3.6875
4
""" ========================= Project -> File: leetcode -> 1186_Maximum_Subarray_Sum_with_One_Deletion.py Author: zhangchao Email: zhangchao@kuaishou.com Date: 2019/12/7 6:33 PM ========================= """ """ Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at m...
7f9738cd3734f308408a19f854f770876de7609a
sssssssshao/PythonStudyProj
/study/basePython/tuple.py
674
4.21875
4
# tuple 元组:一旦初始化就不能修改 classmates = ('shao', 'feng', 'yi') print(classmates) # 这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义, # 因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1。 t = (1) print(t) t = (1,) print(t) # 元组中存在列表时,列表是可变的 t = (1,2,3,[22,3,4,5]) print(t) t[-1][1] = 's' t[-1][2] = 'f' print(t) L = [ ['Apple', 'Google', '...
6f0c3793039c44ca8a21e87dff99a8bd74a66651
0daybug/TnT
/尾递归.py
1,011
3.96875
4
#-*- coding:utf-8 -*- #合并两个有序列表 #采用尾递归 #solution One def _recursion_merge_sort2(l1, l2, tmp): if len(l1) == 0 or len(l2) == 0: tmp.extend(l1) tmp.extend(l2) return tmp else: if l1[0] < l2[0]: tmp.append(l1[0]) del l1[0] else: tmp.append...
75fb5c9080431d344843319b471d9db231d3e039
prathimaautomation/python_live_currency_exchange_rates
/program.py
446
3.8125
4
from app.live_currencyEX import Live_Currency_EX #prompting the user for currency code currency_input = input("Please enter a currency code for the live exchange rate: ").upper() #get the live exchange rate from the api by calling Live_Currency_EX class method live_rate = Live_Currency_EX.read_live_rate_from_api(curre...
93c00a74f6a3a7689c140b56bc9994caae7b742e
radhikasrinivasan8/Leetcode
/[35]searchInsert.py
561
3.8125
4
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ k = len(nums) if target > nums[k-1]: ret = k elif target <= nums[0]: ret = 0 else: ...
fb7f39b141c92005e3c6877532cf007dc7ea94a8
kn33hit/Coursework
/GL_backup/201/PJT/PJT2/stack.py
1,142
4.25
4
# Filename: stack.py # Contains the code to implement a Stack # stack() # creates a new stack # Inputs: None # Output: an empty stack def stack(): return [] # top() # returns the item on top of the stack without popping # Inputs: items, a stack # Output: an item from the stack, if not empty def top(items): if...
374a6ce2dc0a2af8d4e12bc0e5bf22d402cfd207
srinivasdasu24/Programming
/Python_certified/generator_examples.py
857
4.15625
4
# Power calculation def powersOf2(n): pow = 1 for i in range(n): yield pow pow *= 2 for v in powersOf2(8): print(v) #using list compherension def powersOf2(n): pow = 1 for i in range(n): yield pow pow *= 2 t = [x for x in powersOf2(5)] print(t) # converting to l...
4ae48545534c2fbacdce0ca8ee5ac3eaf12f064c
letilab/Coursera-Python-Programming-A-Concise-Introduction
/Week-1/Problem 1_2.py
396
3.890625
4
# -Problem 1_2.py *- coding: utf-8 -*- """ Problem 1_2: Write a function problem1_2(x,y) that prints the sum and product of the numbers x and y on separate lines, the sum printing first. """ #%% def problem1_2(x,y): sum = x + y product = x * y print(sum) print(product) #%% """ Test run. Note th...
17a99c5009edbaebb9e35fa7645f286a4d7673c5
rogeriosilva-ifpi/teaching-tds-course
/programacao_estruturada/20192_186/resolucao_recuperacao_bimestral/youtube.py
658
3.890625
4
def programa(): # Entrada inscritos_antes = int(input('Quantos inscritos antes: ')) visualizacoes_antes = int(input('Quantas visualizações antes: ')) inscritos_depois = int(input('Quantos inscritos depois: ')) visualizacoes_depois = int(input('Quantas visualizações depois: ')) # Processamento ...
b21508fdbec9795884be2b668a436c51b68d8183
danicon/MD2-Curso_Python
/Aula14ex/ex08.py
447
3.9375
4
c = 'S' soma = 0 cont = 0 maior = 0 menor = 0 while c == 'S': num = int(input('Digite um número: ')) soma += num if cont == 0: maior = num menor = num else: if num > maior: maior = num if num < menor: menor = num c = str(input('Deseja continua...
19115761ce5eaf458dc2829785a17edd367aecf7
saumya1510/root-test
/rootCodingTest.py
3,805
3.75
4
import sys from timestringFunctions import findTimeDifference from objectHelperFunctions import addValuesFromTuples, sortDictionaryByValues """ Reads an input file provided as a command line argument, containing details of drivers and their trips. Writes to another file called "output" the average speed and distance ...
22fff837cf19f2649aa35ceb883859a39a5360cf
Bovey0809/Algorithm
/leetcode/recursion_homework.py
503
4.03125
4
def recursive_sum(n): if n == 1: return 1 else: return n + recursive_sum(n-1) assert 5050 == recursive_sum(100) def recursive_nums(n): """Recursively print the digits in the num. Args: n: the digits you want to use. Returns: return the str of the digits. ...
4a3132c4c94bcf4a4b192e475dd6174cdef188b8
parhamzm/Algorithm-Design-Project
/greedy.py
440
3.5625
4
# -*- coding: utf-8 -*- def main(board): while(not board.check_board_solve()): best = board.select_base_condidate() board.move(best) board.show_board() print("-----------------------------") def main2(board): while(not board.check_board_solve()): best = board.select_bast_...
6a62ce1e57c60c6e5003c182771fa6e8b227f903
liu666197/data1
/8.12/8.12/05 函数的参数.py
1,478
4.03125
4
# 定义一个约一约的函数 (设置该功能) def yueyiyue(name): print('打开手机') print('打开%s'%(name)) print('在该软件里面,找一个比较好的xxx') return '小哥哥' # 函数终止了,不会往下运行 return '小姐姐' #也是不执行的 print('+++++') print('------') # 某陌里面约一约 a = yueyiyue('某陌') print(a) print('工作后....') # # 某信里面约一约 b = yueyiyue('某信') print(b) # print('发工资...
91a1426d62463d43dbb38ae57c5a29a09c266153
shantanu609/Competitive_Coding_2
/Problem1.py
760
3.546875
4
# Time Complexity : O(n) # Space Complexity :O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach class Solution: def twoSum(self,nums,target): result = [] if not nums: return ...
9b9703bef7fb36d1a1b0403f09383b430ec9e085
akkiteja/GAMES-I-KNOW
/Pictonary-Livestream-master/Pictonary/server/board.py
1,157
4.0625
4
""" Stores the state of the drawing board. """ class Board(object): ROWS = COLS = 720 def __init__(self): """ init the board by creating empty board (all white pixels) """ self.data = self._create_empty_board() def update(self, x, y, color): """ updates a ...
37d7335bc85ad61cf6c2af7df5c05fea2178b0f2
HarshitMangukiya/Python-Practice-Programs
/dic.py
341
3.75
4
a=dict.fromkeys(['name','age','address'],',harshut') a=dict.fromkeys({'a','d'},'man') a=dict.fromkeys(('a','d'),'man') a=dict.fromkeys("sdsddfkjdf",'man') a=dict.fromkeys(range(1,15),'df') print(a) b={'name':'man','age':'ram'} print(b['age']) print(b.get('name')) if b.get('name'): print(b.get('name')) else: ...
b2791faf889a7cac1abc03e3f59e0a605229948a
shlvd/Leetcode_Hackerrank
/Medium/simplify_path.py
370
3.53125
4
def simplifyPath(self, path: str) -> str: path_lst = [s for s in path.split('/') if s.strip()] stack = [] for s in path_lst: if s == '.': continue if s == '..': if stack: stack.pop() else: sta...
d4016d0d416b0e5b5a7993f11c8f692023380615
pragyan154/hackerrank-Questions
/chocolate_feast.py
218
3.703125
4
def chocolateFeast(n, c, m): x = n // c ans = x while x >= m: remainder = x % m #print(remainder,"remainder") d = x // m ans += d x = remainder + d return ans
9b18e444bdbffdb0370215d912c824651cccb6d6
VidhiPS/Vidhi
/10.05.20.py
220
3.953125
4
number=int(input("Tell me your number : ")) calculation=int(number)% 10 if calculation == 0: print("Your number can be dived by 10") else: print("Your number cant be didvied by 10")
c6349c6209dab4bc87b2c39c0efdb19bbd834a23
Snakeheart404/labs
/lab5_python.py
261
3.71875
4
print('Palindromes: ') for i in range (1, 10): x = i * 1000 + i #власне паліндром print(x) for j in range (1, 10): x = i * 1000 + j * 100 + j * 10 + i #власне паліндром print(x)