blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
32f6871e21771794ed2a94f00a5b48c6f8ac07f6
Fakhri-Amin/Python-Projects
/tempCodeRunnerFile.py
174
3.78125
4
for i in range(3): # random_num = random.randint(0, 1) # if random_num == 0: # turtle.right(90) # else: # turtle.left(90) # turtle.forward(50)
2cd35eb73afae788f58019a06985196ad5985d4e
Reido50/CSE-331
/Project1/DLL.py
13,410
3.59375
4
""" Project 1 CSE 331 S21 (Onsay) Reid Harry DLL.py """ from typing import TypeVar, List, Tuple import datetime # for more information on typehinting, check out https://docs.python.org/3/library/typing.html T = TypeVar("T") # represents generic type Node = TypeVar("Node") # represents a Node object (f...
89527e8e6c28805002a454b0bc4d7777d7df562c
Sheep-coder/practice2
/Python00/chap03list0333.py
306
3.984375
4
# 二つの整数値を昇順にソート(その3) a = int(input('整数a:')) b = int(input('整数b:')) a,b = sorted([a,b]) # 昇順にソート print('a≦bとなるようにソートしました。') print('変数aの値は',a,'です。') print('変数bの値は',b,'です。')
a434e9ac79ba764ff6c2ab45d7f33ba31bbfc020
liang1024/PythonDemo
/Learning/Test38_UnpackListorTuples.py
492
4.03125
4
''' Unpack List or Tuples:打开列表或元组 ''' # 变量tuples item=['December 23,2015 ','Bread Gloves',8.51] print(item) print("-----------------") # 接收tuples date,name,price=['December 23,2015 ','Bread Gloves',8.51] print(name) print("-----------------") # 截取中间并求平均值 def drop_first_last(grades): first,*middle,last=grades ...
81ee23a737cd0b6b2bd3e5ffa303581c2c72c884
joelivey/PFAB
/Homework.python
766
3.921875
4
#!/usr/bin/env python import math first = "Joel" last = "Ivey" age = 70 print first + " " + last + " " + str(age) print sideA = 12.55 sideB = 17.85 sideC = math.sqrt((sideA*sideA)+(sideB*sideB)) print "length of side C = " + str(sideC) print operand1 = 95 operand2 = 64.5 string1 = str(operand1) string2 = str(operand2) ...
7c35a2f455de02f2d79d6caa23d49be501b41ba2
yzheng21/Leetcode
/leetcode/data structure/priority queue vs heap/heapify.py
1,957
3.953125
4
''' Given an integer array, heapify it into a min-heap array. For a heap array A, A[0] is the root of heap, and for each A[i], A[i * 2 + 1] is the left child of A[i] and A[i * 2 + 2] is the right child of A[i]. Clarification What is heap? Heap is a data structure, which usually have three methods: push, pop and top. wh...
60d4f926973df76d5f7fbb95b2991102ca2d5729
VeltanV/py
/longtestrun.py
676
4.21875
4
def longest_run(L): """ Assumes L is a list of integers containing at least 2 elements. Finds the longest run of numbers in L, where the longest run can either be monotonically increasing or monotonically decreasing. In case of a tie for the longest run, choose the longest run that occurs first....
317d7a7f45238ea86af61e200ff45bed54bea168
davide-belli/deep-learning-labs
/assignment_1/code/modules.py
6,613
3.78125
4
""" This module implements various modules of the network. You should fill in code into indicated sections. """ import numpy as np class LinearModule(object): """ Linear module. Applies a linear transformation to the input data. """ def __init__(self, in_features, out_features): """ Initializes the pa...
ae83b2ec0a461cafd419d428a51fc57a5a61c6aa
kip-codes/python-sandbox
/PythonCrashCourse-EricMatthes/6. Dictionaries/favorite_languages.py
2,215
4
4
# File: favorite_languages # Project: python-sandbox # Local author: kevin # Created on 09/30/2017 at 4:59 PM # # For inquiries about the file please contact the author. # Assignment prompt print('* ' * 20) tiy6_6 = "6-6. Polling:\nUse the code in 'favorite_languages.py' (p. 104)." tasklist = ["Make a list of people w...
08237904cb94075b6f52c92e0ebda3ce8ad5ea78
AleexOwwl/Lettuce_FigurasGeometricas
/Figuras.py
1,731
3.734375
4
class Figuras(object): def __init__(self): self.resultado = 0 def circulo(self, radio): try: if radio <= 0: self.resultado = 'No se aceptan 0s' else: pi = 3.1416 radio = int(radio) area = pi...
9eee53eac8cff77e6415d6c4f264e04c1bb0492a
Nekroze/partpy
/partpy/fpattern.py
930
4.09375
4
"""Predefined function patterns for use in Matcher.match_function methods. Defines the following: - alphal = lower case alphabet - alphau = upper case alphabet - alpha = lower and upper case alphabet - number = digits - alnum = digits or lower and upper case alphabet - identifier = first(alpha)...
88495c359eb5155804b25a15a815c73e1b7c43f6
dwolfhub/dots-in-a-line
/dots/__init__.py
1,108
3.609375
4
class Dot: def __init__(self, x, y): self.x = x self.y = y class DotCollection: def __init__(self, dots): self.dots = dots def is_on_same_line(self): dot_len = len(self.dots) # 1 or 0 dots is not a line if dot_len < 2: return False # 2...
2c32785b9c8e08353f18ed6abd59ade659c99578
colorstheforce/sypy.github.com
/js/nextdates.py
894
3.515625
4
from datetime import date, time, datetime, timedelta def date_of(weekday, incidence, month_within): current_month = month_within.replace(day=1) shift = (weekday - current_month.weekday()) % 7 return current_month + timedelta(days=shift, weeks=incidence) def next_date(weekday, incidence, after = None): ...
58530b844228cfcf5d1f3e5550b44e6678233717
YangJiao85/MicrosoftDS
/C9_MachineLearning_FinalExam/2DataPreparation.py
2,111
3.578125
4
## Data preparation using scikit-learn ## Labels ## Category: BikeBuyer ## Numeric: AveMonthSpend --> log_AveMonthSpend import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import numpy.random as nr import math # Import data for customer information aw = pd.read_csv('AW_join.cs...
0e65668c41f2a8db12090010ba87a4c506e0a11b
cburdine/database-project-spring2019
/src/model/classes.py
7,445
3.953125
4
""" This file contains classes for our database entities. Notes: - classes are made based off of actual entities - classes are meant to help store class information retrieved from database """ """ The idea behind this class is to store and retrieve information from the curriculum table In this iteration, I too...
1da4a2ac43b3cb18b75a72b424fdb2ef45d95288
ChernovSS/SendComLetter
/main.py
2,050
3.546875
4
import json from Modules.Gmail import Gmail def read_data(): with open('test.json') as file_json: data = json.load(file_json) return data def main(): input_data = read_data() recipients = input_data['recipients'] product_lists = input_data['productLists'] sender = input_data['sender...
4b81983e5a3ba1006ccf6981c5638df2d7d1035b
gervanna/100daysofcode
/w3resources/Basic_pt.1/29.py
431
4.125
4
#Write a Python program to print out a set containing all the colors #from color_list_1 which are not present in color_list_2. #Test Data : #color_list_1 = set(["White", "Black", "Red"]) #color_list_2 = set(["Red", "Green"]) #Expected Output: {'Black', 'White'} #02_13_21 color_list_1 = set(["White", "Black", "Red"])...
70b7a2d5e0f68478bc1f39dbc355776d67bc3bfb
kurianmelvin/python
/algo.py
3,324
3.546875
4
compMs = 0 compQs = 0 def InsertionSort(file): compIs = 0 fileName = open('10_Random.txt', 'r') ## fileName = open('10_Reverse.txt', 'r') ## fileName = open('10_Sorted.txt', 'r') ## fileName = open('100_Random.txt', 'r') ## fileName = open('100_Reverse.txt', 'r') ## fileName = op...
a77dbd94bca7614782317e79c4ce847c383201a8
PAVAN467/PYTHON-059
/parenthesisvalidate.py
569
3.828125
4
import sys class validity : def __init__(self,stack,o,c,s) : self.stack=stack self.o=o self.c=c self.s=s def check(self) : for i in self.s: if i in self.o : self.stack.append(i) elif i in self.c : ch=self.stack[len(self.stack)-1] ch1=self.c[self.o.index(ch)] ...
6027695b90ac5b220df2072e32b4d3252620f504
SVerma19/python101
/labs/lab4.py
980
4.09375
4
candyCount = 5 candyList = [] while (int(candyCount) > 0): candy = input("Enter a candy: ") candyCount -= 1 candyList.append(candy) listCount = candyList.count print(" ") print("number of elements in the list: ", len(candyList)) print(" ") print("the list consists of: ") print(*candyList, sep = ", ")...
c98b3cf348cd021bbe727814d9a334f297092bae
wawatsai/Data-Structure
/My_sort_1.py
503
3.578125
4
import time import random random_list = [random.randrange(10000) for _ in range(10000)] answer_list = random_list[:] data = [] time_start = time.time() def min_my(data): correct = float('inf') for data_correct in data: if data_correct < correct: correct = data_correct return correct whil...
fce057af9beafb4557eda7fb9d9d36914245ff0f
lylam09/pyautogui_lm
/madlibs_lm.py
2,009
3.515625
4
### MAD LIBS ### ### https://i.pinimg.com/736x/4f/d2/fd/4fd2fdcd1a24611d0bbd238876096bbe--outer-space-camp-mad-libs-for-adults.jpg ### print("Give me an adjective.") adj1 = input() print("A noun?") noun1 = input() print("Adjective?") adj2 = input() print("Give me a plural noun.") pluralnoun1 = input() print("...
ba9398a2fe5a1bff1df09efc400a187a4e7e548c
dennyto/Python_SoftUni
/Python Fundamentals/1. Declaring and Invoking Functions/07. Greater of Two Values.py
445
4
4
type_of = input() a = input() b = input() def int_type(c, d): if int(c) > int(d): return c else: return d def char_type(c, d): if ord(c) > ord(d): return c else: return d def string_type(c, d): if c > d: return c else: return d if type_of =...
a6aeacf183778eeb0d192dfbfb7d3c3e1acfef71
Markitox/PythonLabs
/FunctionsComprehensions.py
1,192
3.65625
4
#!/usr/bin/env python # encoding: utf-8 """ FunctionsComprehensions.py Created by Marko on 2010-03-13. Copyright (c) 2010 Bstards. All rights reserved. """ # Las listas comprensibles, hacen uso de las sentencias FOR, IF por lo menos, para generar # una lista con ciertas caracteristicas u orden # Son mas flexibles, y...
8ccbf4ea3b10c39e99ddabd7c97230bebd794897
AlexanderBauer/HackerRank
/Python/Basic Data Types/Nested Lists.py
587
3.96875
4
if __name__ == '__main__': students = [] for _ in range(int(input())): name = input() score = float(input()) students.append([name, score]) # sort list by grade, get second lowest grade, students.sort(key = lambda x: x[1]) lowest_grade = students[0][1] for x, y in ...
b164c0e804196688e7bce7fda3a021a3dd2ee767
M-Minkov/Project-Euler
/Problem 46/Naive Solution.py
4,689
4.25
4
prime_table = [] odd_composite = [] # Simple Big-O(n log(log(n))) Sieve of Eratosthenes used to compute the prime numbers, and all odd composite numbers def sieve(n): A = [] for i in range(n+1): A.append(True) for i in range(2, (int(n**0.5))+1): if A[i]: j = i**2 ...
7fccfb6cae960f00dcd29dd06f73aede8c373c37
lybtt/python_notes
/itertools_note/permutations_notes.py
239
3.53125
4
# coding:utf-8 # author: 'lyb' # Date:2018/8/24 20:38 from itertools import permutations # 获得列表所有的排列方式 colors = ['red', 'blue', 'black'] for random_colors in permutations(colors): print(random_colors)
d3f0e28dcacb71e05760220310d3c5cd2fd65253
hrhartmann/WaterRocketjpnt
/rocket.py
3,126
3.578125
4
from math import pi import matplotlib.pyplot as plt from vars import * class Rocket: def __init__(self, bottle_radius, bottle_height, water_lvl, air_pressure, r_coefficient, bottle_neck_radius, bot...
efc5dbd479914a0ba9c9867de6bec80d9ed40031
iabreuda/CompI_2018-1
/aula4.py
2,793
3.71875
4
import math import datetime def concat(a, b): return str(a) + str(b) + str(b) + str(a) def suaSorte(nome, idade): sorte = (((((idade*4) + 8)*60)/240) + 22) - idade return "Parabens " + nome + "! seu numero da sorte eh " + str(sorte) + "!" def stringConc(palavra1, palavra2): if (len(palavra1) < 15): ...
171386fba0b68236e09355db98bfa62fb39859be
diovanedm/exercicios-python
/Exercicios/ex021.py
430
3.921875
4
""" Escreva um programa em C que solicite ao usuário a digitação do nome de um arquivo texto já existente, e que então gere um outro arquivo, que será uma cópia do primeiro """ def clonar_arquivo(file): file1 = open(f'{file}.txt', "r") file_content = file1.read() file2 = open(f"{file}-copia.txt", "w") ...
2b5633fdc718fb83239bfec14101f3d59e00cb7d
bayram98/APME_class
/module03_stacks_and_queues/part01/transfer_reverse.py
2,276
4.28125
4
""" Your task is to implement the two functions below. Note below the import statement to reuse the code that you have already seen in this week's "preclass" """ from module03_stacks_and_queues.part00_preclass.stack import ArrayStack def transfer(S,T): """ this function tranfers all the elements from stack S...
90f3277c0fecd6a70f7b4f259e97ca624423a84c
YutingYao/crater_lakes
/bin/plot_scatter_v0.py
688
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ plot_scatter.py Created on Mon Feb 13 19:01:40 2017 @author: sam """ import pandas as pd import matplotlib.pylab as plt x = 'T' y = 'T' # opens excel file df = pd.read_excel('/home/sam/Dropbox/HIGP/Crater_Lakes/Dmitri_Sam/data/Yugama/Yugama.xlsx') # scatter plot...
2c02250062a6f37b6cb31905f9ce49f3d07f606f
portisk8/ucp-analisis-numerico
/Guia4-RaicesDeEcuaciones/Ejercicio4.py
1,215
3.734375
4
from MetodoCerrado import MetodoCerrado from matplotlib import pyplot var = input("Ingrese funcion polinómica: Ej: 0.7 - ln(x**2) \n>>> ") xl = float(input("Ingrese xl: EJ: 0.5\n>>> ")) xu = float(input("Ingrese xu:EJ: 2\n>>> ")) iteraciones = int(input("Ingrese cantidad de iteraciones:\n>>> ")) if(iteraciones == 0):...
4cae7f0acaafdbf3745e344ebd7723c855697a5a
Chalol/Pygame-calculator
/PG Calculator ver.1.py
8,431
3.9375
4
# This code is about calculator by PyGame for calculate # This is first version # for subject Software development and practice I # Code by 6001012630021 Chanakan Thimkham # Ref. of my code : # Module : https://www.pygame.org/docs/ # Change button color : https://bit.ly/2p3bSUI # Github : https://github.c...
a5f47c4f7c15b8faaa68d000b57162b1330fc1e2
starrye/LeetCode
/all_topic/difficult/239 滑动窗口的最大值.py
1,351
3.609375
4
# encoding: utf-8 """ @author: liuwz @time: 2021/3/29 2:33 下午 @file: 剑指 Offer 59 - I. 滑动窗口的最大值.py @desc: """ from collections import deque """ 给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。 示例: 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 输出: [3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [...
a661e29858e01e47af0b6e1849d9b5b21ccae102
chrisxue815/leetcode_python
/problems/test_0260_hash.py
626
3.8125
4
import unittest class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ pending = set() for num in nums: if num in pending: pending.remove(num) else: pending.add(num) ...
62d8262c2517b3cae262af3139f8700f11525068
shanJoy/python_work
/08-函数/8_test1.py
823
3.890625
4
__Author__ = "noduez" #8-3 T恤 def make_shirt(size, message): """Summarize the shirt that's going to be made.""" print("\nI'm going to make a " + size + " t-shirt.") print('It will say, "' + message + '"') make_shirt('large', 'I love Python!') make_shirt(message="Readability counts.", size='medium') #8-4...
93cfc1f7028a1a1eb7b72de94162a870a1d87347
DayGitH/Python-Challenges
/DailyProgrammer/DP20151016C.py
2,854
3.90625
4
""" [2015-10-16] Challenge #236 [Hard] Balancing chemical equations https://www.reddit.com/r/dailyprogrammer/comments/3oz82g/20151016_challenge_236_hard_balancing_chemical/ # Description Rob was just learning to balance chemical equations from his teacher, but Rob was also a programmer, so he wanted to automate the p...
545166758d9c26f8bb376098947633f818bb6d56
dellax/ads2014
/6 cvicenie/cviko6.py
1,193
3.71875
4
# Uloha 1 # v prednáške sme ukázali heapsort zapísaný pomocou prioritného frontu s haldou # triedenie haldou: # def heap_sort(pole): # p = HeapPriorityQueue() # for i in pole: # p.add(i, i) # for i in range(len(pole)): # pole[i] = p.remove_min()[1] # prepíšte túto funkciu tak, aby nepoužíval...
9757254c6ddd1c42a200d572df186c8f6b545300
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/ff008460301a4fdda728987f61b1b67d.py
270
3.765625
4
def word_count(phrase): word_list = phrase.split() word_dict = {} for i in range(len(word_list)): if word_list[i] not in word_dict: word_dict[word_list[i]] = 1 else: word_dict[word_list[i]] += 1 return word_dict
22e3068f9274392980686569ab53287022990587
kevincleppe/Python-Crash-Course
/Chapter_10/wordcount.py
426
3.9375
4
def word_count(filename): try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print("Sorry we cant't find the file") pass else: words= contents.split() num_words=len(words) print(num_words) filename=['mil...
d9acb8e19ceeb91980cb048736e11780eb4986ab
ieferreira/algorithms
/Sorting/quickSort.py
378
3.78125
4
def quickSort(ls): if len(ls) <= 1: return ls pivot = ls.pop() less = [] greater = [] for i in ls: if i > pivot: greater.append(i) elif i < pivot: less.append(i) return quickSort(less) + [pivot] + quickSort(greater) import random ls = rando...
0dcb160c49f5ed2c6381fce8afb36b48c054f3aa
jm9176/RRT_RRTstar_Bi-RRT
/RRTstar.py
4,659
3.578125
4
''' Finding the path from start to goal position using Rapidly exploring Random Tree (RRT) ''' import numpy as np import math from Node import Node from retrace_path import retrace_path import matplotlib.pyplot as plt from shapely.geometry import Point from shapely.geometry.polygon import Polygon # Calculating heuri...
ac78dc886daa4918be42e8cc0345a3e1c27710d6
dsitum/code-eval-challenges
/easy/QueryBoard.py
722
3.578125
4
#!/usr/bin/env python3 import sys with open(sys.argv[1], "r") as f: board = [[0 for i in range(256)] for j in range(256)] for line in f: line = line.strip().split() if len(line) == 3: command, rowcol, value = line rowcol = int(rowcol) value = int(value) else: command, rowcol = line rowcol = i...
6e572da9785e4bc61f6e2e7fcd7c7b08c73080c6
rdsilvalopes/python-exercise
/estruturarepeticao09.py
419
3.734375
4
#! usr/bin/env python3 ############################################################################# #Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50. ############################################################################# def imprimir_impares(): #lista com numeros impares entr...
5c83bc944a847021eb9eedcffeddb6f1eaf36147
stankiewiczm/contests
/ProjectEuler/UC solutions/Successful 150--/Q207.py
286
3.578125
4
from Numeric import * def Pow2(m): t = m; while (t%2 == 0): t = t/2; if (t == 1): return 1; else: return 0; PRF = 0; TOT = 0; m = 1; while (PRF*12345 >= TOT): m += 1; k = m*(m-1); TOT += 1; PRF += Pow2(m); print k, PRF, TOT;
d84a972d5c397881eb168597ab1b417086acca67
BJODAWAT98/python_data
/day3.py
4,325
3.984375
4
input_list=input("enter the commaseperated numbers") main_list=list(input_list.split(",")) main_list=[int(x) for x in main_list] main_tuple=tuple(main_list) ########################################### all_days=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') my_days=('Wednesday', 'Thursda...
0409fa0a0468cca1399f29a3ddfb17f136394b78
samarth30/machine-learning
/python-solutions-nptel/week 2/2.py
107
3.609375
4
a = [int(x) for x in input().split()] if(a[0]>a[1]): print(a[1],end=""); else: print(a[0],end="");
1069e9a80ba73ba1b6c0431e2d36f15d8672b918
alexander-koronovskiy/practice
/class_buildin_methods_overload/del.2.0_xy_references.py
559
4.03125
4
class my_class(): def __del__(self): print('destroy start and at the end of the programm we delete it') print('self = ' + str(self)) #self = None print( 'self = '+str(self)+" but delete it after method __del__(), 'cause we rewrited __del__() without 'self = None' part") if __n...
dc4669fb7047c8e2d8963323eb4fa49582e23e92
marcoaurelio97/LFA
/projeto1/program.py
4,123
3.890625
4
from classes.node import Node from classes.graph import Graph while (True) : variaveis = input('Digite as variáveis: ') if (variaveis == '') : print('Digite no mínimo uma variável!') continue variaveis = variaveis.split(' ') if (len(variaveis) >= 1) : break while (True) : ...
9ec459b52b2500f2c8afb6605c4bbf16eb265d5b
leerobertsprojects/Python-Mastery
/Advanced Python Concepts/Error Handling/Error Handling.py
329
3.765625
4
try: print(1+'String') except TypeError: print('You had an error') finally: print('Try Again') def number(num): try: result = 5 / num return result except ZeroDivisionError: print('You cannot divide by zero') finally: print('You have fucked up') print(numbe...
d7aacab785adf3a172cba69264721bd9121804d3
viniciosarodrigues/python-estudos
/ex007.py
266
3.984375
4
print('======== Exercício 08 (Calcula valores em centímetros e milímetros ========') metros = float(input('Informe a quantidade em metros: ')) print('O valor de {}m em centímeros é de {} e em milímetros é de {}'.format(metros, (metros*100), (metros*1000)))
2414e57e69f3d26baf3e18844d3011a1c6d8ecac
clausserg/war
/war/player_class.py
1,725
4.25
4
""" Module: player_class.py This is the Player class implementation. A Player object: 1. Has a name and holds a given number of cards. 2. __str__() dunder: returns player name and number of cards he owns. 3. __len__() dunder: easy return of how many cards the palyer owns. 4. get_cards(...) method: allows the player to...
acde58a98858e84d447b97cef6aad1267e5d5394
amitanand/python_w3_tutorials
/old/sumofnintegers.py
140
4
4
import time n=int(input("Enter the number to which you want to find the sum : ")) sum=0 i=0 for i in range(n+1): sum=sum+i print(sum)
68b09bd078cea1d5c122fb8beaa55798a740c052
taiyeeka/AIND-Sudoku
/solution.py
9,869
4.28125
4
assignments = [] def assign_value(values, box, value): """ Please use this function to update your values dictionary! Assigns a value to a given box. If it updates the board record it. """ # Don't waste memory appending actions that don't actually change any values if values[box] == v...
1360628854738c64136911b883259b16c3bdd172
LuisDiego10/Circuit-Designer
/src/code/mergesort.py
646
4.3125
4
#Function performs the comparisons and joins the elements to show the result def merge(left,right): result=[] i,j=0,0 while i<len(left) and j<len(right): if left[i]<=right[j]: result.append(left[i]) i+=1 else: result.append(right[j]) j+=1 r...
cc20690c33a57132c7aaeee9ad80aae692bdcf77
ilisha13/computationalAstrophysicsPython-
/1_unstableCalculation.py
2,350
3.96875
4
""" Implement the recurrence relation for various functions. Calculate the relative and absolute errors for each calculation. Based on these errors, determine whether the calculation is stable or not. """ import numpy as np from math import * """ Part 1 Consider the recurren...
6091ae440ad5f033b6373a8e6989b8c6e6b21275
LWS-CSDN/python
/2021/工作需要/已完成-多线程,线程锁,互斥,同步/main1.py
612
3.578125
4
import time import threading ''' 同步 ''' NUM=0 #创建一把锁,锁是开的 mutex=threading.Lock() class MyThread(threading.Thread): def run(self): global NUM mutexFlage=mutex.acquire() print('线程(%s)的锁状态为%d'%(self.name,mutexFlage)) #判断上锁是否成功 if mutexFlage: NUM=NUM+1 tim...
ae1d76a80ed9d87002eaf01eb88601462b4002c1
coingraham/codefights
/python/arrayChange/arrayChange.py
343
3.671875
4
def arrayChange(inputArray): count = 0 for x in range(1, len(inputArray)): if inputArray[x - 1] >= inputArray[x]: count += inputArray[x-1] - inputArray[x] + 1 inputArray[x] = inputArray[x-1] + 1 return count if __name__ == '__main__': print arrayChange([2, 3, 3, 5, 5, ...
b889f638d2bda2397f70119ce78dca235aa91a4f
self-study-squad/Python-examples
/String/untitled-20.py
422
4.1875
4
#Write a Python function to reverses a string if it's length is a multiple of 4. def callen(strip): if len(strip) % 4 == 0: return True else: return False def reverse(strip): result = strip[::-1] return result stringip = input('Input a string: ') if callen(stringip): result = rev...
c7b6e8ab84b73c74c7b4abe9dd648f9c5ebb0223
sharmakajal0/practise-programs
/mathematics/sqrt.py
353
4.40625
4
#!/usr/bin/env python '''Module for square root''' from math import sqrt def square_root(int_num): '''Function definition to print root of the given number''' print(sqrt(int_num)) print(int(sqrt(int_num))) TEST_CASES = int(input()) while TEST_CASES > 0: TEST_CASES -= 1 TEST_INTEGER = int(input(...
c238f2ef8a7c63590fb16f2684864f4d8ff4d2c4
art-bug/Python-scripts
/double_linked_list.py
5,756
4.25
4
''' This module provides double linked list class with insert and remove methods and iterating ability. ''' class DoubleNode: ''' The class represents double linked list node. ''' __slots__ = ("data", "next", "prev") def __init__(self, data=None): self.data = data self.next = None ...
43e983b5ba44fa13e1f0f376b8df8550d1713c20
sakshi303/CS50_web_programming
/lecture_python/loops.py
145
3.796875
4
animals = ["tiger","elephant","lion","panther"] for animal in animals: print(animal) colour = "blue" for letter in colour: print(letter)
58eacd0119550a5e2c78866c55f67954353e0cdc
KIRANROUTH/Python-Basic-Programming
/45_setmethodsAndOperations.py
851
3.71875
4
s1=set([1,2,3,4,5]) s1.add(6) s2={10,11,12,21} s1.update([7,8,9,4,3,2,5,7,8,5,3],s2) s1.remove(9) s1.discard(10) print("list to set:"+str(s1))#set cannot have same element twice or more s1={1,2,3} s2={2,3,4} s3={3,4,5} s4=s1.intersection(s2) print(f"{s1}.intesection({s2}): {s4}") s4=s1.difference(s2) print(f"{s1}.di...
29b90ce449609ce29c466e4199ece138a6a05a2a
ShiJingChao/Python-
/PythonStart/dist/7.19基本数据类型.py
8,136
3.953125
4
# stu = True # if not stu: # print('你不是学生') # else: # print('你是学生') # or前面的判断不成立,则值取决于后面 # a = 5 # b = a > 7 or 4 # print(b) # 运行结果为4 # # a = 5 # b = a > 3 or 4 # print(b) # 运行结果为True # # b = 10 # a = 7 if b > 10 else 8 # print(a) # 运行结果为 8 # i = 1 # while i < 5: # print(i, '<5') # if i == 3: # ...
b7becfe81c9232c1574f29c5f89a1fc02fe0628d
bentannoy/stores_rest_api
/models/item.py
1,790
3.703125
4
import sqlite3 from db import db class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) store_id = db.Column(db.Integer, db.ForeignKey('stores.id')) stores = db.relationship('Stor...
cc32f2c0575a67bfebb3bb1c48cd09da98752fca
SaadAbdullah11/Internship-coding
/game_gg.py
3,371
4.1875
4
import random n=random.randint(0,10) print("This is a guessing game where the user needs to guess a number from 0 to 10 inorder to win.") print("") print("The quicker the user guesses the number, the higher the number of points.") print("") print ("Following are the rules:") print("> Maximum number of guesses would b...
a2ec22c036f5b9917509ebadd2a9e2f8ec4c8366
dth0/Exercism
/python/yacht/yacht.py
1,852
4.09375
4
""" This exercise stub and the test suite contain several enumerated constants. Since Python 2 does not have the enum module, the idiomatic way to write enumerated constants has traditionally been a NAME assigned to an arbitrary, but unique value. An integer is traditionally used because it’s memory efficient. It is a...
30c3dd4bc0419d4bae1dd3b24e75379d970f8799
josepablocam/aquery2q
/src/benchmark/pandas/src/experiments/make_data.py
9,669
3.5
4
import pandas as pd import numpy as np import string import sys from numpy.random import rand as randn # We scale our experiments to N , so all data frames are created # relative to this size, when appropriate. # Meaning, if the original created a data frame of size # 10,000, and used 100 different random numbers to ...
3b75687f94c8bc1836fe82ac2c0d607f1449b9bf
limeng0415/muddyhippo
/toolCodeStat/pathwalk.py
1,477
3.8125
4
#coding:utf-8 import os def dirs(path): """show input path and show its sub-paths recursively""" #return false if input is not a path if False == os.path.isdir(path): print path+" is not a path" return False #return list of paths l = [] for i in os.walk(path): l.append(i[0]) return l def dirs_under(path)...
2b8b968d0c7e36c3f048423c4ff294c4bade93f0
julienc91/utools
/utools/dates.py
2,039
4.59375
5
# -*- coding: utf-8 -*- """ Useful functions to work with dates and durations """ from datetime import datetime class timer: """ Get the execution time of a block of code. Example: The easiest way to use the timer is inside a 'with' statement:: >>> import time >>> t = timer...
735e580e34e5b6e98ff8bd25826daa5be78d7c03
li-xiuliang/algorithm009-class01
/Week_03/Construct Binary Tree from Preorder and Inorder Traversal.py
895
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if len(preorder) == 0: return None...
362db271ec00091725894191094ca59261bcc49f
Rahma3100/Task3
/main.py
294
3.703125
4
list = [] def num(): for i in range( 4 ): x = int( input( "Enter Number" ) ) list.append( x ) len( list ) return list n = num() print( n ) y = int( input( "Enter divisible Number" ) ) for z in list: if z % y ==0: print(z) else: pass
c5706e09be0b328b62b4c4d945e93f62d02ba4ed
Richard5127/Python
/ifelse/if1.py
129
3.578125
4
#!/usr/bin/env python # coding: utf-8 var = raw_input("請輸入一字串") if var: print ("輸入的字串是:" + str(var))
86385aabcfe058bdf97cda65136e41177e869c1f
zhuyf0522/WAF_API
/testcase/tmp/thread_test.py
437
3.6875
4
#!/usr/bin/python # -*- coding=utf-8 -*- import threading import time def newPrint(n): print('1: HaHa HaHa:%s' % n) time.sleep(2) print('2: HeHe') time.sleep(1) print('Wait:') for i in range(3): print(i) t = threading.Thread(target=newPrint,args=('t-%s' % i,)) print('a') t.setDa...
3a2468b30e4220db510713082621fd06136877ae
manniqueen/python-basics
/For_cinema_tickets.py
1,206
3.8125
4
total_tickets = 0 student = 0 standard = 0 kid = 0 percentage_students = 0 percentage_standard = 0 percentage_kid = 0 movie_tickets = input() while movie_tickets == 'Finish': free_seats = int(input()) for ticket in range(0, free_seats + 1): ticket_type = input() if ticket_type ...
52df1da69acbd9e94827f9f07ba8e8ecb8b415c3
Eddonofuture/DSDesafLatam
/Introduccion a Programacion/Presencial 9/agrupados.py
443
3.53125
4
from itertools import groupby ventas = { "Enero": 15000, "Febrero": 22000, "Marzo": 12000, "Abril": 17000, "Mayo": 81000, "Junio": 13000, "Julio": 21000, "Agosto": 41200, "Septiembre": 25000, "Octubre": 21500, "Noviembre": 91000, "Diciembre": 21000, } def agrupar(diccionario): lista = list(dicci...
36643ae286ac916dede21d105a4d3fcbe76b7a65
Andrewlearning/Leetcoding
/leetcode/DP/背包问题/494. 目标和(01背包,求方案数和).py
2,606
4.09375
4
""" You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to b...
df81ef90dedb568a6829149a0d89d6bf94c9c06f
shashitn/P1_facial_keypoints
/models.py
2,951
3.65625
4
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I '''LeNet in PyTorch.''' class LeNet(nn.Module): def __init__(self): ...
b33b660fa4bf18d93b3ab06ff4e56a8cba288323
Vasilic-Maxim/LeetCode-Problems
/problems/414. Third Maximum Number/2 - NHighest.py
208
3.578125
4
import heapq from typing import List class Solution: """ Time: O(n * log(n)) Space: O(n) """ def thirdMax(self, nums: List[int]) -> int: return heapq.nlargest(3, set(nums))[-1]
11af04f70a655747c2d40fe275c59f1456f902c6
asing012/GS-Shapley
/gs
3,878
3.59375
4
#!/usr/bin/env python3 # GS-Shapley Algorithm # Created by: Akshay Singh and # Date: 09/20/2017 # Purpose: It creates pairs of men and women # using gale-shapley alroithm. # INPUT(S): None # OUTPUT(S): Participants # Preferences # Pairing # CPU Time and CLock Time # EXAMPLES: # Sahr :Erik...
dea4c9bfc1b8e83c14927ce4a790ccb24709944c
SR0-ALPHA1/hackerrank-tasks
/twitch1.py
1,708
3.6875
4
#!/usr/bin/python import csv, sys, numpy class Table: def __init__(self, tbl): self.tbl = tbl def compute(self): names = self.tbl.pop(0) values = map(list, zip(*self.tbl)) i = 0 for nm in names: values[i] = map(float, values[i]) print nm + \ ...
df4327ce37d12e5babb276fe7c11e608cb9e4ca8
KFranciszek/Python-Dla-Kazdego
/rozdzial5.py
138
3.703125
4
lista = ["1","2",'1212'] lista.sort(reverse=True) print(lista) slownik = {"graf" : "4","grafik" : "1"} print (slownik["graf"])
c0b5a793eb610a1decc43161765f08a0278c37bf
kdragonkorea/TIL
/Bigdata_analysis_course_20201228/2_Python/Python_exam/day2(20210105)/forTest8.py
527
3.578125
4
endFlag = False for dan in range(2, 10): for num in range(2, 10): result = dan * num if result > 30 : endFlag = True break print(dan, "*", num, "=", result, end="\t") if endFlag : break print() # 2중 for문에 if까지 결합되서 어떻게 구현되는지 이해하기가 어렵다. # 구구단의 ...
8b35a7ae0f2904c47c2277bd6bbfb112511d40cc
songshengwen/py_learn
/01_python3/day15/code/enumerate.py
301
3.546875
4
numbers = [10086, 10000, 10010, 95588] names = ['中国移动', '中国电信', '中国联通'] # L = [(0, '中国移动'), (1, '中国电信'), (2, '中国联通')] for x in enumerate(names): print(x) # 扩展 for no, n in enumerate(names): # (等同于序列赋值) print(no, " ----->", n)
1f5e4de6fadcdc27d2511de4946a8d21044494ed
dellaub/Files
/Python_Projects/check_circle_area_by_radius.py
441
4.46875
4
#Area of the circle = pi*radius**2 Pr^2 print("\n[Check for the Area of a circle by its radius]\n") #Import pi from math module from math import pi #ask for and set radius radius = float(input("Circle Radius (cm) ? : ")) #area calculation circle_area = pi * radius ** 2 #print string r = radius print("Radius = " + ...
99f5e4e8cfdb5d8cbc9e0470e34c2fb9cd148cc4
horsewave/python
/change-batch-file-names/change_batch_file_names.py
1,813
3.90625
4
""" change a batch of file names in one directory @file change_batch_file_names.py @author Bo Ma @version 1.0 @date 2019.09.28 """ import os def rename_file(): """ function to rename a batch of files @param @return """ i = 0 path_dir = "/home/mabo/2019-now-work-bo/work/working-note...
ca8f222a0aa1749bc0f94f3406f9e2f61581dd75
alemiaschi/PythonForBeginners
/Exercises/lezione_2/if_else/es_1_comandi_condizionali.py
208
3.875
4
a = input("Inserisci il primo numero: ") b = input("Inserisci il secondo numero: ") a = float(a) b = float(b) if a > b: print("Il numero maggiore è: ", a) else: print("Il numero maggiore è: ", b)
0d1ef79eabfee3ee2c69bdcf3b21c77354017d83
zideajang/python_tuts
/intro_decorators/intro_decorators/demo_05.py
1,238
4.125
4
def before_and_after(func): def wrapper(text): print("BEFORE") func(text) print("AFTER") return wrapper @before_and_after def greet(text): print(f"hi {text}") greet("decorators") # def before_and_after(func): # def wrapper() # def params(*args,**kwargs): # print(f"{arg...
6fd4a2bcf3fd62d6254bc6c2d2aad2f2225e9e42
vellaichamy/machine-learning
/learning/classes/model_selection/detecting_overfitting_underfitting.py
1,420
3.828125
4
# Import, read, and split data import pandas as pd data = pd.read_csv('data.csv') import numpy as np X = np.array(data[['x1', 'x2']]) y = np.array(data['y']) # Fix random seed np.random.seed(55) ### Imports from sklearn.linear_model import LogisticRegression from sklearn.ensemble import GradientBoostingClassifier fro...
b3b5e35898b2aa5187fe33ae570d85e95b851d93
snufkinpl/public_glowing_star
/School/AJP introduction in programming/zadania1/1_3.py
946
3.734375
4
user_number1 = int(input("Podaj liczbę 1: ")) user_number2 = int(input("Podaj liczbę 2: ")) if user_number1 > user_number2: print(f"Wynik dodawania dwóch liczb: '{user_number1}' oraz '{user_number2}' = {user_number1 + user_number2}") print(f"Wynik mnożenia dwóch liczb: '{user_number1}' oraz '{user_number2...
b745ee40435d04802d8928f98876ba6aff73dbd7
arittrosaha/CS_and_Algorithms
/epi_study/14_binary_search_trees/2.py
1,308
4.03125
4
# Find the first key greater than a given value in a BST # Prompt: # A program that takes a BST head and a value, and returns the first key that greater than input value (or the first key that would appear next in an inorder traversal) # Time: O(h), h is height of the tree # Space: O(1) # PDF - 201; Book - 215 def ...
6a418fa8b303d64dfb60e430ab7f0244b43d0349
Bizcho/Curso-Python
/insert.py
117
3.546875
4
items = [4,6] print items items.insert(0, -1) #insertar en la posicion 0 print items items2 = [ ] print items2
37a00fdfbdb33cec82872b281dd0fa592526ca3e
Amarildop1/Python
/CalculaAreaDeTriangulo.py
163
3.859375
4
base = float(input('Informe o valor da base: ')) altura = float(input('Informe o valor da altura: ')) area = (base*altura)/2 print('A area do triangulo eh:', area)
dd7aa50d126ddab75b24da79f3b0ac1b0d61bcf3
gy09/python-learning-repo
/PythonLearning/FunctionLearning/forLoop.py
290
4.15625
4
def upperConversion(): sentence = input("Enter the sentence to loop on:") for word in sentence: print(word.upper()) def listLoop(): friends = ["test1","test2","test3","test4"] for friend in friends: print(friend.upper()) upperConversion() listLoop()
ac28693a23b52d55b8dba9b654728992f2beb81b
EricGao2015/leetcode-using-python
/easy/BinaryTreeLevelOrderTraversal.py
919
3.984375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrder(self, root): if root: bsf_list = [(root,root.val)] result = [] while bsf_list: result.append([i[1] for i in bsf_list]) fo...
e9a8ea478ef3d23017afdcc08e62ee20b7558d2b
jrvanderveen/Algorithms-and-datastructs
/MedianOfTwoSortedArrays.py
1,597
3.78125
4
##### # Input : two sorted arrays on ints # Output : the median value of the two arrays # Constraint : overall run time O(log (m+n)) where m = array1.len and n = array2.len # Edge cases : ##### ''' The median value is the middle value in a list. For this solution we simply need to iterate through both lists ...
a52b9234bc3ba13e6413d167d29d6ce3260b58dc
surya20516/python
/py4e/assign3.py
691
3.53125
4
# To run this, download the BeautifulSoup zip file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file from urllib.request import urlopen from bs4 import BeautifulSoup import ssl import re count=0 sum=0 # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx...
4ae65b0a73280a64a6e6db85143abab2f0de3761
LeandroBP/Python
/HandsOn/Aula06/funcoes.py
1,744
3.625
4
#!/usr/bin/python import sys import json import banco usuarios = [] def exibeMenu(): print "\n1 - Para cadastrar usuarios" print "2 - Para listar todos os usuarios" print "3 - Para deletar um usuario" print "4 - Para autenticar um usuario" print "5 - Sair" def cadastraUsuario(): login = raw_in...
ba22dade76a26a7bfe952bc0b021177b7d9f5034
byui-cs/CS312-Course-2020
/week02/teach1.py
2,238
4
4
""" Course: CS312 File: teach1.py Description: Simple Numpy problems You are NOT submitting this program. """ """ Instructions: - You will creating numpy arrays in the following functions """ import numpy as np def task1(): """ create an array of size 10 of zeros """ # Replace 'None' with the array ...