blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2c9ee26b6423019db6701ce06d63e6b2f8fd1a9e
najarvis/DatabaseResearchCode
/test_mongo.py
2,768
3.953125
4
"""Basic contact book program""" from pymongo import MongoClient def get_phone(user): """Extracts a phone number from a user dictionary and returns it as a string""" phone_dict = user.get('phone_num') if phone_dict is not None: return "{}-{}".format(phone_dict.get('area'), phone_dict.get('num')) ...
76d8c678a8d779b495d2eae58d00dd425ad5874e
andre23arruda/pythonCeV
/Aula12.py
3,691
4
4
import datetime import random # ==================== DESAFIO 36 ======================== # print('VAI COMPRAR UM CASA?') casa = int(input('Digite o valor da casa: ')) salario = int(input('Digite seu salario: ')) anos = int(input('Digite em quantos anos pretende pagar: ')) prestacao = casa/(12*anos) if prestacao>0.3*sal...
637bf5bd13b4b2a8aea861b48507f5038d1aa335
caleb-1212/ministry
/file_functions.py
476
3.71875
4
import os # Ensures that a directory exists, it creates it if necessary def ensure_dir(dir): if not os.path.exists(dir): os.makedirs(dir) # Creates a file and writes the string into it def writeStringToFile(fileName, contentStr): file = open(fileName,"w") file.write(contentStr) # File closing is handled a...
01e555636656384332367f963f239957d0918fbc
impradeeparya/python-getting-started
/array/PascalTriangle.py
880
3.765625
4
class PascalTriangle(object): def binomial_coefficient(self, line, index): # C(n r) = n!/((n-r)! * r!) n_factorial = 1 for number in range(1, line + 1): n_factorial = n_factorial * number n_r_factorial = 1 for number in range(1, (line - index) + 1): n...
0cad813e776d034d231a8fd207c34bce5bc6aa28
cmbrooks/APCS
/python/matrixmath.py
3,024
3.828125
4
#Scalar Addition ~~ WORKS def add (A, p): result = [[0 for x in range(len(A))] for x in range(len(A[0]))] if checkMat(A) == True: print "Number of Rows: " + str(len(A)) print "Number of Columns: " + str(len(A[0])) for i in range(0, len(A)): for j in range(0, len(A[i])): ...
85c30ce8ef7215062cc5d117a53768ba868c3e81
Ariussssss/leetcode
/for-fun/gift-count.py
1,455
3.59375
4
""" 评分分数不同 每个分数有他的礼物 打得比小的多 最少有多少个礼物 """ def smallHeap(arr, root=None): left = 2 * root + 1 right = left + 1 length = len(arr) small = root if left < length and arr[small] > arr[left]: small = left if right < length and arr[small] > arr[right]: small = right if small != root...
89e5bdb099b970ffc93e3c03db11bd8c01368a23
FatChicken277/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
559
3.890625
4
#!/usr/bin/python3 """This module contains a class MyInt that inherits from int """ class MyInt(int): """class MyInt that inherits from int Arguments: int -- int """ def __eq__(self, other): """[summary] Arguments: other -- other Returns: not...
7a1794023d7eeb023c4f9d85fa1d35dd63f88617
UtkarshBhardwaj123/Commit-Ur-Code
/Day - 4/Rohan-Saini.py
298
3.734375
4
def check(s_1, s_2): s_1 += s_1 if (s_1.count(s_2) != 0): print("YES") # Now Rajat Become Happy. else: print("NO") for i in range(int(input())): s_1 = input() s_2 = input() if len(s_1) == len(s_2): check(s_1, s_2) else: print("NO")
e18f804bf10298f005c634ba34781ffe67576ac5
Rafiul-Islam/Data-Structure-And-Algorithms
/Data Structures/Tree/BST.py
3,026
3.859375
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BST: def __init__(self): self.root = None def insert_data(self, data, current_node): if self.root is None: new_node = Node(data) self.root = new_...
03d707fa03cf1bd56bbe3cf0530be1bdb8547390
pfreisleben/Blue
/Modulo1/Aula 08 - Listas /listas.py
135
3.6875
4
lista = [1, 2, 3, 4, 5, 6] lista2 = [1, 2, 3, [4, 5]] print(lista[0]) print(lista[2:4]) print(lista[1] + lista[4]) print(lista2[3][0])
223678ab3366c5eaa46a0fee06c84a08e177a8d6
CodecoolBP20172/pbwp-1st-si-game-inventory-RichardSzombat
/gameInventory.py
3,604
3.828125
4
# This is the file where you must work. Write code in the functions, create new functions, # so they work according to the specification import operator from pathlib import Path import os.path import os import csv from collections import Counter mylist = list() inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': ...
fa036d1fca1693f827f8c129ac3b2a8ec396ae76
cryoMike90s/Daily_warm_up
/Basic_Part_I/ex_118_bytearray.py
214
3.796875
4
"""Write a Python program to create a bytearray from a list.""" def bytearray_from_list(lista:list): return print(bytearray(" ".join(lista), 'utf-16')) lista = ["a","dupa","hehe"] bytearray_from_list(lista)
d5e86c8cacdb71567a506fafbd0672d29814dcc9
alexwaweru/Algorithm-Design-and-Analysis
/selection_sort.py
306
3.59375
4
def selection_sort(list1): n = len(list1) for i in range(n-2): min_idx = i for j in range(n-1): if list1[j] < list1[i]: min_idx = j temp = list1[min_idx] list1[min_idx] = list1[i] list1[i] = temp return list1
268bbd92ab5c59b2a42d1f608d0881e7205e1ff1
Nkaka23dev/data-structure-python
/general/prime_numbers.py
149
3.640625
4
def prime(num1,num2): for i in range(num1,num2+1): if num1>1 and num2>1: if i%2!=0: print(i) prime(900,1000)
9e0b210e4c2a78f5a3a9ae25820c28d3553abee4
a-tal/nagaram
/nagaram/scrabble.py
4,618
4.15625
4
"""Scrabble related functions, score counters, etc.""" import os def letter_score(letter): """Returns the Scrabble score of a letter. Args: letter: a single character string Raises: TypeError if a non-Scrabble character is supplied """ score_map = { 1: ["a", "e", "i", ...
3bdc1d05fa08767e70ed1678fde95475c1e36aa5
jjti/euler
/Done/52.py
1,079
3.75
4
import utils """ Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def split_map(n): """Create a dictionary...
a521b1d9a959401706622576f4a495e1037d72bb
NPencheva/Python_Advanced_Preparation
/03_multidimensional_lists/2021.02_multidimensional_lists_exercises/03_Maximum Sum.py
1,583
3.84375
4
from sys import maxsize number_of_rows, number_of_columns = [int(x) for x in input().split()] matrix = [] for row_index in range(number_of_rows): row = [int(y) for y in input().split()] matrix.append(row) max_3x3_square_sum = -maxsize starting_row = 0 starting_column = 0 for row_index in range(number_of_ro...
3361f966a3ea45d6134aa5e35e2d9a7984f8e6c8
bruhmentomori/python
/lek1.py
200
3.71875
4
print("hej på er i ee17") firstName = "William" lastName = "Lannerblad" #dateOfBirth = 20000518 age = 19 teacher = True print(firstName , lastName + str(age) + str(teacher)) print(dateOfBirth + " ")
7e169df5ec7f0f24a7fa2c42cc350a14d1727be0
jahosh/coursera
/algorithms1/assignment1/practice_ds/quickunion/quickunion.py
1,078
3.578125
4
from typing import Tuple class QuickUnion: def __init__(self, size: int) -> None: self.size = size self.storage = [i for i in range(size)] def _check_indicies(self, a: int, b: int) -> None: if a > self.size or b > self.size: raise Exception(""" Index ouit o...
0b4d40692b1d4d74c5f9ca1bda24afe6975ecf63
MamaD33R/Python-Projects
/Web Page Generator/WebPageGen.py
1,152
3.59375
4
import webbrowser import tkinter as Tk from tkinter import * window = Tk() # GUI resizable window window.title("Web Page Generator") window.geometry('600x350') # label details of program lbl = Label(window, text="Greetings! Go ahead and get started!", font=("Arial Bold", 15)) lbl.grid(row=1, column=4, pady=20, padx=2...
03becef898404e7f974ca88d5e5404033196b047
wangjiaxin1100/PythonAutoTest
/Course/Chapter9/die.py
289
3.578125
4
from random import randint class Die(): """定义一个色子""" def __init__(self): self.sides = 6 def roll_die(self): number = randint(1,self.sides) print(number) die = Die() die.roll_die() die.sides = 10 die.roll_die() die.sides = 20 die.roll_die()
2ac1bfdf70fef9cd8e2889a77956d90c3bab67d5
joaohfgarcia/python
/uniesp_p2/lista1_6.py
810
3.953125
4
def calculaNotas(valor): notas100 = int(valor/100) valor = valor - 100*notas100 notas50 = int(valor/50) valor = valor - 50*notas50 notas20 = int(valor/20) valor = valor - 20*notas20 notas10 = int(valor/10) valor = valor - 10*notas10 notas5 = int(valor/5) print ("Notas de R$ 100...
acd0a496bcbb0e404bd46af96080c466df5a342e
jdferreira/hackerrank
/Practice/Algorithms/02 Implementation/queens-attack-2.py
1,206
4.09375
4
#!/usr/bin/env python3 DIRECTIONS = [ ( 1, 0), ( 1, 1), ( 0, 1), (-1, 1), (-1, 0), (-1, -1), ( 0, -1), ( 1, -1), ] def get_tuple(convert=int): return tuple(convert(i) for i in input().split()) def move(here, direction): return tuple(h + d for h, d in zip(here, direction))...
912472c51112c443bd3a846e6e921edb851fdbed
nmm6025/Homework4
/main.py
3,971
4.25
4
# Author: Nick McCuch nmm6025@psu.edu grade1 = input("Enter your course 1 letter grade: ") course1 = input("Enter your course 1 credit: ") if grade1 == "A" or grade1 == "a": gradepoint1 = float(4.0) print(f"Grade point for course 1 is: {gradepoint1}") elif grade1 == "A-" or grade1 == "a-": gradepoint1 = float(3.6...
4d9b74ab539885e6d1d667b7fc4b9cc8c839c793
hasanunl/Hierarchical-Clustering-in-Python-Training
/hc_training.py
1,246
3.515625
4
#Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing the mall dataset with pandas dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:,[3,4]].values # Using the dendrogram to find the optimal number of clusters import scipy.cluster.hierarchy as sch dend...
fae4c1488518b5b0af4424e52b792f856eb1dc9c
yeboahd24/Python201
/competitive programming/problem5.py
840
4.34375
4
#!usr/bin/env/python3 # Python program to find the smallest and second smallest elements import sys def print2Smallest(arr): # There should be atleast two elements arr_size = len(arr) if arr_size < 2: print('Invalid Input') return first = second = sys.maxsize for i in range(0, arr_size): ...
a2b3384b5e04e99f794c2a4dfd836cdca902fb05
rathoddilip/InheritanceUsingPython
/single_inheritance.py
268
3.640625
4
class Father: fatherName = "" def father(self): return self.fatherName class Son(Father): def parents(self): print("Father name :", self.fatherName) if __name__ == '__main__': s1 = Son() s1.fatherName = "RAM" s1.parents()
6350846861ea3cef8cf10674c79c8522a0e7f036
rohit2219/python
/bloomberg3.py
2,691
3.90625
4
import copy class Node(): def __init__(self, inpToNode): self.data = inpToNode self.next = None self.random = None class linList(): def __init__(self): self.head = None def insertNode(self, inpData): if self.head == None: tempNode = Node(inpData) ...
5a0df33c1898a7c95d25754ed5dc3387854c7eac
murtekbey/python-temel
/4-donguler/for-demo.py
2,801
3.9375
4
sayilar = [1,3,5,7,9,12,19,21] ################################################################################################################################### # 1. Sayılar listesindeki hangi sayılar 3'ün katıdır ? for sayi in sayilar: # liste içerisindeki elemanları tek tek dolaşır. if sayi%3==0: print(...
76b6e7d11907193dff7133c19174c00d633feef0
gayathri-kannanv/Python-logics
/sum_prime.py
242
3.984375
4
max=int(input("ENTER THE MAXIMUM VALUE OF THE RANGE:")) sum=0 for i in range (1,max): if i>1: for j in range (2,i): if i%j==0: break; else: sum=sum+i print("THE SUM OF PRIME NUMBERS IN THE GIVEN RANGE IS: ",sum)
f060a3f48fa098831a9082dad0ba39a855e5b7a8
Mohican-Bob/CIT-228
/Chapter10/guest_book.py
1,067
3.90625
4
""" userName = input("What is you user name? (q to quit)") with open("Chapter10/userName.txt", "a") as userFile: while userName != "q": userName += "\n" userFile.write(userName) input("What is you user name? (q to quit)")""" import os import random filename = "Chapter10/guests.txt" #delet...
4299c9080958a439ffb5efe719295d8a8e477b8c
gear106/leetcode
/7. Reverse Integer.py
575
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 15 20:27:31 2018 @author: GEAR """ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ x_reverse = 0 if x < 0: x = int(str(abs(x))[::-1]) x_reverse = -x else: ...
27bb7b5f8cfad804de0266ac6845501250c41b32
swapnilnandedkar/Python-Assignment
/Assignment1/Assignment1_8.py
410
4.28125
4
# 8. Write a program which accept number from user and print that number of “*” on screen. # Input : 5 Output : * * * * * def DisplayStarPattern(Number): for counter in range(Number): print("*", end=" ") def main(): print("Enter Number to print * pattern") Number = int(input()) ...
e70cad28df82f15c6815287ce245c18449a0cbdf
kavinyao/Pure
/lcs.py
1,197
3.765625
4
# Code from: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_subsequence#Python def LCS(X, Y): m = len(X) n = len(Y) # An (m+1) times (n+1) matrix C = [[0] * (n+1) for i in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if X[i-1] == Y[j-1...
0295ee51ca523c683e7e563109def2e3517e176a
darvat/ProgramozasAlapjai
/elagazasok-if-szerkezet/source.py
434
3.5
4
szepVagyok = True if szepVagyok: print("Tudom, hogy szep vagy") print("de lehetsz meg szebb") else: print("csunya vagy") print("de lehetsz meg szep") felesegekSzama = 1 if felesegekSzama < 1: print("meg nem ert el a vegzet") elif felesegekSzama == 1: print("ismered a dorgest") elif felesegekSzama == 2:...
b148ce412d17e42ce3efbb822dc3b48bd99bfd22
RodiMd/Python
/Insure.py
322
4.0625
4
#How Much Insurance #should ensure your property for atleast 80 percent of the cost #to replace it costToReplace = input('Enter the amount it would cost to replace it ') def minInsurance(): amountToInsure = 0.8 * float(costToReplace) print ('amount to insure is %.2f' %amountToInsure) minInsurance()...
f63bb312de7cd3e8e9d1eee48023cee01a143acf
dchartor/hackerrank
/counting_valleys.py
239
3.5
4
def countingValleys(n, s): level = 0 valleys = 0 for i in s: if i == 'D': level -= 1 if level == -1: valleys += 1 if i == 'U': level += 1 return valleys
944033cf667d3455ce265e1b494bc7d562b09d24
parkchu/python-study
/clock/Untitled.py
148
3.6875
4
import turtle as t def draw(a): t.fd(100) t.lt(a) b = 120 for x in range(7): draw(b) if x == 2: b = 90 t.circle(50)
eec8e994de795229924ee993216993b051d6d350
SobuleacCatalina/Rezolvarea-problemelor-IF-WHILE-FOR
/problema_6_IF_WHILE_FOR.py
617
3.9375
4
""" Se dă numărul natural n. Să se compare sumele S1 și S2,unde: a)S1=1**3+2**3+...+n**3 și S2=(1+2+...+n)**2; b)S1=3(1**2+2**2+...+n**2) și S2=n**3+n**2+(1+2+...+n) """ n=int(input("Introdu numărul: ")) s1a=0 s1b=0 s2a=0 s2b=0 s2=0 s1=0 s2i=0 for i in range(1,n+1): s1a+=i**3 for i in range(1,n+1): s2+=i s2a=s2...
e122441d78fd99ad6652ca25f1a2db5091edce19
soumitra9/Binary-Search-4
/intersection2arrays.py
2,140
3.609375
4
# Time Complexity : Add - O(mlogm + n logn) # Space Complexity :O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No ''' 1. Sorting both arrays and then using 2 pointers 2. If value is same add it to reult and move both pointer 3. If value not same move away from low va...
2ef3a03d62f17fc3ab893256ef23151502b12894
lkkliukeke/PythonExcel
/pymysqlcreat.py
1,097
3.515625
4
import MySQLdb import mysql.connector #打开数据库 db = MySQLdb.connect('localhost','root','admin123',"test") crr = db.cursor() sql = """insert into tests(name, age, sex) values ('张三3',17,'女')""" # print(sql) try: crr.execute(sql) db.commit() except: db.rollback() db.close() #创建一个游标对象 # cur = db.cursor() #使用ex...
d40673fbbfd7a6140df34d4a7300f25c27bf9efc
shortpoet/cs_washu_bootcamp
/week14homework/static/js/data.py
333
3.59375
4
import json from pprint import pprint with open('data.json') as f: data = json.load(f) cityList = [] for x in data: for k, v in x.items(): if k == 'city': #print(v) cityList.append(v) citySet = set(cityList) uniqueCities = list(citySet) citySort = uniqueCities.sort() print(un...
a9774f401cea5f731d4f7939b389d7e2c243fb3b
deepcpatel/data_structures_and_algorithms
/Graph/find_city_with_smalles_number_of_neighbours.py
1,963
3.59375
4
# Link: https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/ # Approach: Apply Floyd-Warshall algorithm to find distance between each node in the graph. Now calculate number of nodes within given threshold distance for each node and return the one with smallest # n...
f0c7ea46d2777ae75badfde5c49b316a448a8468
ThanushaK/session15_statistics1
/Statistics1.py
650
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 2 11:56:08 2019 @author: thanusha """ import numpy as np #importing numpy library #import scipy.stats #import matplotlib.pyplot as plt # 1 x= [1550,1700,900,850,1000,950] #given list of numbers std=np.std(x) #standar...
24429329b4ade990e34388039bdcbb3bb520cfa8
cz495969281/2019_-
/Project/day5/01-bs4创建和调试.py
973
3.78125
4
from bs4 import BeautifulSoup html = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="s...
8375286eb88e35db374511ece3bd8894f082ee49
Vibhuti12354/first-project
/first code.py
248
3.59375
4
#%% file="demo.txt" word="hello" c=0 with open(file,'r')as f: for line in f: words=line.split() for i in words: if(i==word): c=c+1 print("occurence of word",word) print(c) # %%
43590da819ba83cccc4ec9d64bb06cf59fb34abb
navnoorsingh13/GW2019PA2
/venv/Session3.py
636
4.21875
4
# Controller : Logic by which you will solve problem """ 1. Operators 2. Conditional Constructs | if/else 3. Loops / Iterations """ # Arithmetic Operators : +, -, *, /, %, //, ** dish1 = 100 dish2 = 200 bill = dish1 + dish2 print("Bill is:",bill) # Assume taxes to be 5% taxes = .05 * bill print("Taxes :"...
66ee22f38fb881626d849cf5bbf740f1619c13b7
angrajlatake/100-days-to-code
/day10-function.py
1,216
4.28125
4
#change name from any case to title case(first letter in capital) def format_name(fname,lname): fname = fname.title() lname = lname.title() return f"{fname} {lname}" fname = input("What is your first name?") lname = input("What is your last name?") print(format_name(fname,lname)) # USE THE LEAP YEAR ...
c1e04a7f9f402368a71e5550e505bdbdefbec9d9
sassafras13/coding-interview
/problems/chapter_03/p01_three_in_one_soln.py
2,967
4.3125
4
# source: https://github.com/careercup/CtCI-6th-Edition-Python/blob/master/chapter_03/p01_three_in_one.py # Their solution appears to be similar to mine # use a list to store three stacks # use a second list to keep track of the sizes of each stack # the push and pop methods are standard, there are no surprises in how...
f1c796d107b4d933b3b9272d4ad950feb37d269d
VerityG/tmskurs
/homework2/zad2math.py
668
3.75
4
import math def teorCos(): cosa = math.cos(((a ** 2) + (c ** 2) - (b ** 2)) / (2 * a * c)) cosb = math.cos(((a ** 2) + (b ** 2) - (c ** 2)) / (2 * a * b)) cosc = math.cos(((b ** 2) + (c ** 2) - (a ** 2)) / (2 * c * b)) print(cosa, cosb, cosc) print(math.degrees(cosa), math.degrees(cosb), math.deg...
740717db1a8828569cd3127754440936d2ba9804
antony10291029/lxfpyanswer
/32debug.py
820
3.890625
4
# -*- coding: utf-8 -*- def foo(s): n = int(s) print('>>> n = %d' % n) return 10 / n def main(): foo('0') #main() #可以用print来打印调试信息,确认程序的错误信息 def foo(s): n = int(s) assert n != 0,'n is zero!' return 10 / n def main(): foo('0') #main() #assert是断言的意思是断言后面跟的内容如果满足,则什么都不做,否则抛出错误,显示后半段内容 #此处n=...
1a34911569dd448030c0e75a5dae46a1a477ce63
dm36/interview-practice
/hacker_rank/insert_node.py
280
3.734375
4
def insertNodeAtPosition(head, data, position): count = 0 node = head while count < position - 1: node = node.next count += 1 temp = node.next current_node = SinglyLinkedListNode(data) node.next = current_node current_node.next = temp
2a3532f7a65a750971b6cb5ff0047e65e56ba8d8
momchilantonov/SoftUni-Programming-Basics-With-Python-April-2020
/While-Loop/While-Loop-Lab/06_max_number.py
218
3.734375
4
import sys numbers = int(input()) count = 0 max_num = -sys.maxsize while count != numbers: new_number = int(input()) count += 1 if new_number > max_num: max_num = new_number print(f'{max_num}')
c76d1e0a558d0e2acf9558fd686b362caa941454
Botxan/Ada-labs
/lab1/python/ordenar_dos_numeros_2/ordenar_dos_numeros_2.py
265
4.0625
4
num1 = int(input("Introduzca el primer número: ")) num2 = int(input("Introduzca el segundo número: ")) assert num1 > 0 assert num2 > 0 if (num1 > num2): num1 = num1 + num2 num2 = num1 - num2 num1 = num1 - num2 print(f'{num1} <= {num2}')
4dc0419892df9fca078ca1f03a4a349473e8a86c
Silvia-man/test-
/python习题/仅菜鸟上的/62.py
380
3.796875
4
# 62.题目:查找字符串。   sStr1 = 'abcdefg' sStr2 = 'cde' print (sStr1.find(sStr2)) ''' find()方法语法: str.find(str, beg=0, end=len(string)) 参数 str -- 指定检索的字符串 beg -- 开始索引,默认为0。 end -- 结束索引,默认为字符串的长度。 返回值 如果包含子字符串返回开始的索引值,否则返回-1。 '''
b0f21da13fed786cb7bfe3c6547131fb3eb0cfa9
bunshue/vcs
/_4.python/__code/Python邁向領航者之路_超零基礎/ch9/ch9_20.py
415
3.6875
4
# ch9_20.py # 建立內含字串的字典 sports = {'Curry':['籃球', '美式足球'], 'Durant':['棒球'], 'James':['美式足球', '棒球', '籃球']} # 列印key名字 + 字串'喜歡的運動' for name, favorite_sport in sports.items( ): print("%s 喜歡的運動是: " % name) # 列印value,這是串列 for sport in favorite_sport: print(" ", sport)
f9f726b94bb1ffc2aafd125dafb9837dc84708f0
jury16/Python_Course
/Homework #7.py
2,862
3.609375
4
#convert inch to cm def inch_cm(a): return f'{2.54 * a} cm' #convert cm to inch def cm_inch(a): return f' {(0.39 * a):.2f} inch' #convert miles to km def miles_km(a): return f' {(1.60934 * a):.2f}' #convert km to miles def km_miles(a): return f' {(0.621371 * a):.2f}' #convert pound to kg de...
e3192d33bc7dc09ece087ae98a0eab40e5788178
chenzhiyuan0713/Leetcode
/Easy/Q23.py
914
3.625
4
""" 1732. 找到最高海拔 有一个自行车手打算进行一场公路骑行,这条路线总共由 n + 1 个不同海拔的点组成。自行车手从海拔为 0 的点 0 开始骑行。 给你一个长度为 n 的整数数组 gain ,其中 gain[i] 是点 i 和点 i + 1 的 净海拔高度差(0 <= i < n)。请你返回 最高点的海拔 。 示例 1: 输入:gain = [-5,1,5,0,-7] 输出:1 解释:海拔高度依次为 [0,-5,-4,1,1,-6] 。最高海拔为 1 。 示例 2: 输入:gain = [-4,-3,-2,-1,4,3,2] 输出:0 解释:海拔高度依次为 [0,-4,-7,-9,-10,-6,-3,-1]...
8bb1574974ba158bfd32d35748c08a3ae00c0e6c
mohitsaroha03/The-Py-Algorithms
/src/3.1Array/rearrange array alternately.py
997
4.5
4
# Link: https://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form/ # Python program to rearrange an array in minimum # maximum form # Prints max at first position, min at second position # second max at third position, second min at fourth # position and so on. def rearrange(arr, n): # Auxiliary array ...
a388a345a51db839c86cc3c36c6a54e10a4e7fd3
crispto/algorithm
/test2.py
812
3.609375
4
class Node: def __init__(self, x): self.val = x self.left = None self.right = None def width(root): """ 1 1 1 2 / 2 1 3 / 2 # \ 3 \ 4 """ if not root: return 0 lr = [0,0] width_help(root, 0, lr) ...
a3238401ea1118cb3022578c502d6bafba1277d4
sobriquette/interview-practice-problems
/Pramp/countPaths.py
1,013
3.578125
4
class SolutionDP: def num_paths_to_sq(self, i, j, memo): if i < 0 or j < 0: return 0 elif i < j: return 0 elif i == 0 and j == 0: return 1 elif memo[i][j] != -1: return memo[i][j] else: memo[i][j] = self.num_paths_to_sq(i, j - 1, memo) + self.num_paths_to_sq(i - 1, j, memo) print("i: {}, j:...
752aba60a28b09b5f28de295a39b54442d0d76e9
FranklinA/CoursesAndSelfStudy
/PythonScript/PythonBasico/operadores.py
187
3.71875
4
def sumar(numero1,numero2): return numero1+numero2 valor=sumar(5,5) print "El resultado de la FUNCION sumar es ",sumar(5,5) print "El resultado de la VARIABLE valor es igual ",valor
df5eb1d452b7bfd4e748e7e1616c2aa9ee088bb4
yuktha-05/Python-Coding
/Python_programs/leapyear.py
149
4.1875
4
year = int(input("Enter any year : ")) if((year%4==0 and year%100 != 0) or(year%400 == 0)): print("Leap Year") else: print("Not a Leap Year")
330ece901042386a3f185b511d29c85024d86841
yiyuhao/DataStructureAndAlgorithm
/algorithm/sort/heap_sort.py
768
3.71875
4
def sort(lst): """采用大顶堆排序""" def siftdown(elems, e, begin, end): p, c = begin, begin * 2 + 1 while c < end: if c + 1 < end and elems[c + 1] > elems[c]: c += 1 if e > elems[c]: break else: elems[p] = elems[c] ...
e2bcea129e1520daf1ec6ace72ca268eb9067ced
baichen7788/test
/CurveFitting.py
586
3.671875
4
#Curve fitting( m is number of data points, n is degree of curve fitting) import numpy as np def CurveFit(x,y,n): m=len(x) x,y=np.array(x),np.array(y) A=np.zeros((n+1,n+1)) B=np.zeros(n+1) for row in range(n+1): for col in range(n+1): if row==col==0: A[r...
e012b519aa48e6351c1bb038cf290fb9500a96fb
DrRhythm/PythonNetworking
/week_2/exercise2.py
660
4.125
4
#!/usr/bin/python # Create a list of 5 IPs ip_list = ["10.1.2.4", "172.16.15.9", "154.69.45.26", "10.5.7.1", "10.7.96.5"] print(ip_list) # use append to add an ip to the end of the list ip_list.append("192.65.8.2") print(ip_list) # user extend to add two more ips to the end new_ips = ["192.168.1.1", "192.168.1.2"] ip_...
52f8de17f41a628aba737c48658088e51d938092
Shantti-Y/Algorithm_Python
/chap03/prac02.py
991
3.765625
4
# Linear Search (Standardized way) def search(a, n, key): st_num = [] st_ele = [] for i in range(n): st_num.append(str("{0}".format(i))) st_ele.append(str("{0:02d}".format(a[i]))) st_num = " ".join(st_num) st_ele = " ".join(st_ele) print(" | {0}".format(st_num)) pri...
6b1444c8ead0884dcc20da8d4f303b6f15ed6f3e
siddharthrajaraja/WordCloud
/file1.py
929
3.5625
4
import numpy as np import re import json count_Words={} def createDictionary(l): for i in range(0,len(l)): if l[i].lower() not in count_Words: count_Words[l[i].lower()]=1 else: count_Words[l[i].lower()]+=1 all_strings=[] if __name__=="__main__...
dd45ea99e1e5520f5328e73f3a6d86c1de6b4dd8
dalerxli/PSO_Simulation
/pso.py
3,839
3.640625
4
''' Paper referred: Particle Swarm Optimization: A Tutorial PSO : Particle Swarm Optimizer For the objective function: |(0.07*i - 10)**3 - 8*i + 500|, which has a local minima and a global minima. Requires optimization along a single dimension. ''' ''' v(t+1) = w*v(t) + c1*r1*[p_best(t) - x(t)] + c2*r2*[g_best(t) - ...
0afa56935e964d423088829055647ed2c371bd1a
thaolinhnp/Python_Fundamentals
/PYBai_07_project/ex03_List_for.py
136
3.5625
4
lst_SoNguyen=[3,5,7,9] tong = 0 for item in lst_SoNguyen: # print(item) tong += item tongDaySo = sum(lst_SoNguyen) print('end')
b9f3192e0217490551ed6ac1c97d6a9bdf19593b
yz5308/Python_Leetcode
/Algorithm-Easy/190_Reverse_Bits.py
1,259
3.78125
4
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): b = bin(n)[:1:-1] return int(b + '0'*(32-len(b)), 2) def reverseBits1(self, n): result = 0 for i in range(32): result <<= 1 result |= n & 1 n >>= 1 ...
aa9280b1fa00ac3d109ed13e78f5fb5339887f79
mehzabeen000/loop_python
/sum(12-421).py
145
3.921875
4
counter=12 sum=0 while counter<=421: sum=sum+counter counter+=1 print(sum) #we have to print the sum of numbers from 12 to 421.
01d27f13efdc04b50efd5e17d3e1e5c05def92b3
Thetvdh/FastTyping
/main.py
2,919
3.53125
4
import sys import time import string import random import pandas as pd import matplotlib.pyplot as plt def trainer(sentences_dict): data = {} for key, value in sentences_dict.items(): start_time = time.time() input1 = input(value['sentence'] + " ") runtime = round((time.time() - start_...
20d6c0ec72415f62df2bfcce0ef4d8a02aa8beaa
NewMike89/Python_Stuff
/Ch.1 & 2/bday_err.py
148
4.15625
4
# Michael Schorr # 2/19/19 # general program to convert an INTEGER to work with STRINGS. age = 28 msg1 = "Happy " + str(age) + "th Birthday!" print(msg1)
e64c9ecd3937f4e211717fb33d581d723fa668dc
vasilypht/mathematical-pendulum
/pendulum.py
1,608
3.546875
4
import pygame as pg import const import math class Pendulum(pg.Surface): def __init__(self, size=(200, 200), length=200) -> None: """ Initialization :param size: The size of the area on which the sphere will be drawn. :param length: Length of "thread". """ pg.Surfa...
142e82bbe801570c5f1ce5e0ea0fd794aa04c59f
meisnehb/99-CapstoneProject-201920
/src/shared_gui.py
31,815
3.640625
4
""" Capstone Project. Code to run on a LAPTOP (NOT the robot). Constructs and returns Frame objects for the basics: -- teleoperation -- arm movement -- stopping the robot program This code is SHARED by all team members. It contains both: -- High-level, general-purpose methods for a Snatch3r EV3 robot...
ccc340a673369c61e7dfb2e399244fc966cca561
YangXinNewlife/LeetCode
/easy/shuffle_string_1528.py
442
3.546875
4
# -*- coding:utf-8 -*- __author__ = 'yangxin_ryan' """ Solutions: 题意是给字符串重新排序, 排序的顺序就是给定的indices, 直接数组转字符串即可 """ class ShuffleString(object): def restoreString(self, s: str, indices: List[int]) -> str: length = len(indices) result = [-1] * length for i in range(length): result...
45c4c2e27fb5a8c43a792d8eb31d2ce9724f1b1d
gabrielwai/Exercicios-em-Python
/ordenando jogos de loteria pelos valores sorteados.py
1,156
3.5625
4
import random import operator jogos = dict() lista = list() lista1 = list() for c in range(0, 4): jogos['nome'] = 'jogador' + str((c + 1)) for j in range(0, 6): while True: n = random.randint(1, 60) print(f'{lista1} ; {n}') if n not in lista1: lista1....
b772799f884f494f263325c8f6572987761bce90
jennyfer250113/practica-2
/ejercicio3.py
136
3.640625
4
a = int(input(u"ingrese nùmero de filas")) b = int(input(u"ingrese nùmero de columnas")) if matriz: matriz = a * b print(matriz)
75235576c941a4d0e4d3aed5657b2cf40fbef5d8
SR0-ALPHA1/hackerrank-tasks
/path_bw_2_nodes_bin_tree.py
1,009
4
4
#!/usr/bin/python # given 2 nodes of a binary tree, find number of nodes # on the path between the two nodes ### ### DID NOT FINISH ### NEED MORE TIME TO COMPLETE ### class Node: def __init__(self, data): self.data = data def search(self, data, cnt=0): if(self.data != data): cnt...
fd818bb127ac71d926addb524e1115a4048caa6a
jakehoare/leetcode
/python_1001_to_2000/1026_Maximum_Difference_Between_Node_and_Ancestor.py
1,222
3.859375
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ # Given the root of a binary tree, find the maximum value V for which there exists different # nodes A and B where V = |A.val - B.val| and A is an ancestor of B. # A node A is an ancestor of B if eith...
db74516576a42cb00f2f6f10acee4472b69f1f85
ka10ryu1/activation_func
/func.py
848
3.59375
4
#!/usr/bin/env python3 # -*-coding: utf-8 -*- # help = '便利機能' # import os def argsPrint(p, bar=30): """ argparseの parse_args() で生成されたオブジェクトを入力すると、 integersとaccumulateを自動で取得して表示する [in] p: parse_args()で生成されたオブジェクト [in] bar: 区切りのハイフンの数 """ print('-' * bar) args = [(i, getattr(p, i)) for...
82f9f4797d32390bade47e3784ae680f5819bc2a
mattfemia/datacamp
/intermediatepython_ds/dictionaries.py
553
3.828125
4
# List strategy to connect two data sets (Order matters) pop = [30.55, 2.77, 39.21] countries = ["afghanistan", "albania", "algeria"] ind_alb = countries.index("albania") print(ind_alb) print(pop[ind_alb]) # Dictionary strategy (Order doesn't matter) world = {"afghanistan": 30.55, "albania": 2.77, "algeria":39.2...
1f8b9086ca824debb48d7d0811f1db3185ea1e27
yeraygit/repositorio
/1_tutorias/4_listas.py
1,418
4.5625
5
''' * Es una estructura de datos que nos permite almacenar gran catidad de valores. * Es Equivalente a los arrays en otros lenguajes. * Se pueden expandir dinamicamente añadiendo nuevos elementos (poderoso) ''' # indices 0 1 2 3 4 elementos = [1, 2.5, 'Aprendiendo python', [5,6] ,True]...
a29ec2f3fadd4b47dd83c7b14a79c54f1ad46310
lucasp0927/python_numerical_project
/src/homeworks/30/ps12.py
2,141
3.546875
4
#-*-coding:utf-8-*- #Problem 11 #Name:Yu-Yi Kuo, Cheung Hei Ya #Collaborators: #Time:3:00 import numpy as np def gaussElimin(a,b): """Solves [a]{x} = {b} by Gauss elimination. USAGE: x = gaussElimin(a,b) INPUT: a -numpy array (n*n) b -numpy array (n*1) OUTPUT: ...
53d7ec40465ac4970b97b0c8a7635c639d04f365
cryjun215/c9-python-getting-started
/python-for-beginners/04 - String variables/format_strings.py
366
4.375
4
# 사용자에게 이름과 성을 입력 받습니다. first_name = input('What is your first name? ') last_name = input('What is your last name? ') # capitalize 함수는 다음과 같은 문자열을 리턴합니다. # 첫 글자는 대문자이고 나머지 단어는 소문자 print ('Hello ' + first_name.capitalize() + ' ' \ + last_name.capitalize())
64c37106f6846fc1ac1cf6f919b8bf2a5d0426bb
mpant84/pynet_ons
/madhur_exercise4.py
188
3.5625
4
#!/usr/bin/env python ip_addr = raw_input("Please enter an IP addr? ") octets = ip_addr.split(".") print ("{:<12} {:<12} {:<12} {:<12}".format(octets[0],octets[1],octets[2],octets[3]))
1d6a63e6c5f3fc1089ccaededec8dcc9bf742195
kumalee/python-101
/part-2/shapes/parallelogram_5.py
1,491
3.734375
4
#! /usr/bin/python # encoding: utf-8 import math class Shape(object): def __init__(self, width, height): self.length = width, height def setLength(self, width, height): self.length = width, height def getLength(self): return self.length def getName(self): pass def getDe...
c3d7bd5263646afda5efadf099dd7108f2e7705c
nazhimkalam/Data-Science-Course
/Seaborn/lecture_02.py
1,834
3.59375
4
# CATEGORICAL PLOT import seaborn as sns import matplotlib.pyplot as plt import numpy as np tips = sns.load_dataset('tips') print(tips.head()) # sns.barplot(x='sex', y='total_bill', data=tips) # by default the estimate is set to the aggregate function of calculating the mean # sns.barplot(x='sex', y='tip...
0b09963ffdc533117857cc8b0ba8c74d12ab45bf
bala4rtraining/python_programming
/python-programming-workshop/set/2.pythonsetadd.py
224
3.859375
4
# An empty set. items = set() # Add three strings. items.add("cat") items.add("dog") items.add("tiger") items.add("tiger") items.add("cow") #animal = input("give an domestic animal name") #items.add(animal) print(items)
a49c5a30c9964f9628ce430272c8c47dd667868a
shtakai/cd-python
/pylot/semirestful/app/controllers/Products.py
2,106
3.84375
4
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * from time import strftime import datetime impo...
54cc16249d3ef4ff1058ebb4bdd6f6c095ab5e69
pycoder682/easyhash
/sha224encrypt.py
256
3.515625
4
import hashlib import time word = input('Enter what you want hashed in sha224 here: ') enc = word.encode('utf-8') hash1 = hashlib.sha3_224(enc.strip()).hexdigest() print('The sha224 hashed result is: ' + str(hash1)) time.sleep(10) quit()
2fc7ed6895ac53ddce3e8cb7d364b87b3b9bb9b5
JonathanGamaS/hackerrank-questions
/python/capitalize.py
828
4.1875
4
""" You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck. Ex: alison heck -> Alison Heck Given a full name, your task is to capitalize the name appropriately. """ import os def solve(s): ...
c27b4c97fc4865745cd358dbec8a8b7129850314
sweetherb100/python
/interviewBit/Strings/04_pretty_json.py
3,811
3.5625
4
# print("AAAA\t sgjdkgdlj \nd asdjgkgl") ''' Pretty print a json object using proper indentation. Every inner brace should increase one indentation to the following lines. Every close brace should decrease one indentation to the same line and the following lines. The indents can be increased with an additional ‘\t’ Ex...
4adbbc26f25be224bab4658952321dff0e1e0f07
qihong007/leetcode
/2020_03_05.py
1,848
4
4
''' Given an image represented by an N x N 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? Example 1: Given matrix = [ [1,2,3], [4,5,6], [7,8,9] ], Rotate the matrix in place. It becomes: [ [7,4,1], [8,5,2], [9,6,3] ] Exam...
68900eeabc166831d274e8a399d8b336413b9140
PoorPorter1/JSteg
/unhide.py
4,412
4.15625
4
# Hi, # This photo has a message embedded in it. # As a hint, I have given the code of how I have encoded it. # I have also defined all the functions that you will need to decode the image # You just need to come up with the logic of decoding it. # It is your job to complete the unhide() function. # Sorry if this is to...
a58dfb27e779435d35cef18bf0195ca7fc3663eb
CityQueen/bbs1
/Abgaben - HBF IT 19A/20191128/count Joshua Pfeifer.py
183
3.578125
4
t1 = str(input("Bitte gebe einen Text ein: ")) z1 = str(input("Bitte gebe ein Welches Zeichen du zählen willst: ")) z2 = t1.count(z1) print("Das Zeichen", z1, "gibt es", z2, "mal")
9b4348ee3f6e765b4a6e6699ea06772b3d74b5b1
KristofferFJ/PE
/problems/unsolved_problems/test_283_integer_sided_triangles_for_which_the__areaslashperimeter_ratio_is_integral.py
646
4.09375
4
import unittest """ Integer sided triangles for which the area/perimeter ratio is integral Consider the triangle with sides 6, 8 and 10. It can be seen that the perimeter and the area are both equal to 24. So the area/perimeter ratio is equal to 1. Consider also the triangle with sides 13, 14 and 15. The perimeter...
3ae19bf77907c357d66b8809888a06bb3f1e444e
marydawod/Replit
/main.py
4,396
4.28125
4
from GPA import foo #imports the def foo(letter_grade) from GPA.py to main.py #In this marking period, there will be three homework grades, two quiz grades, and one test grade. print("WELCOME TO THE PYTHON CALCULATOR!!\n\n\tThe Python Calculator calculates your grade point average as well as category averages for sec...
7d6403c1ad8388f32de82dffbc0b0218548a4dae
justellie/py4e
/ultimo_reto_curso1.py
612
3.90625
4
#TIENES QUE ESTAR PENDIENTE DE LOS ESPACIOS PORQUE ESA VAINA SI IMPORTA COÑO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! acum=0 mayor=None menor=None while True: print("ingrese numero o done para salir:") inp=input() if inp=='done': break try: inp=int(inp) except : print('Invali...