blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
51407405fde33bf260053b5950891ac72af7ab2f
sean578/advent_of_code
/2015/17/17.py
1,313
3.640625
4
# import numpy as np # container_sizes = [1,2,3,4,5,6,7,8,9] # eggnog_total = 10 container_sizes = [ 33, 14, 18, 20, 45, 35, 16, 35, 1, 13, 18, 13, 50, 44, 48, 6, 24, 41, 30, 42 ] eggnog_total = 150 # print(container_sizes[0]) # print(n...
9be85856d86283513d6a6e5c4c24caddea318313
pedrolgcs/curso_python
/world_03/exerc/007.py
476
3.9375
4
numbers = [] for i in range(0, 5): numbers.append(int(input(f'Digite um valor para posição {i}: '))) print('=-=' * 11) print(f'O maior valor digitado foi: {max(numbers)} nas posições: ', end =' ') for i, v in enumerate(numbers): if v == max(numbers): print(f'{i}', end = ' ') print(f'\nO menor valor digitado...
0f2cc76b8e6fd6218bb60be0c8d744f90c5a1075
devionncode/projetos_poo
/Produto/produto_regra.py
398
3.640625
4
from produto import Produto class ProdutoRegra: def cadastrar(self): print('\n=========CADASTRO PRODUTO===========') nome = input('Informe o nome: ') marca = input('Informa a marca: ') quantidade = float(input('Informe a quantidade: ')) valor = float(input('Informe...
bb83ef35310b96c8f8c682f16253f42aa5ec832e
cwjshen/dailycodingproblems
/python/12-staircase-climb.py
2,108
4.28125
4
# This problem was asked by Amazon. # There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. # Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. # For example, if N is 4, then there are 5 unique ways: # 1,...
cbfccff814c8d4226fe30b28feda59450d2dcca8
bibongbong/pythonCookBook
/src/8.13.ImplimentDataModelTypeConstraint.py
1,906
3.890625
4
''' 想定义某些在属性赋值上面有限制的数据结构。 所以需要自定义属性赋值函数,可以使用描述器 ''' class Descriptor: def __init__(self, name=None, **opts): print(name) print(opts) self.name = name for key , value in opts.items(): setattr(self, key, value) def __set__(self, instance, value): instance.__dict__[self.name] = value # Descriptor for en...
a13e974be88e7e397bfc6385b697d639ccf020f1
gayathrimahalingam/interview_code
/check_if_btree_is_bst.py
747
3.9375
4
# Implement a function to check if a binary tree is a valid binary search tree # BST - left <= root < right # An in-order traversal array should be sorted # recursively check if BST property is maintained # more optimal: have a min and max variable and check while you traverse to get a O(N) solution import os def ...
05ef03b1a91a1f88e959b4d320850da02d8c5224
vprusso/toqito
/toqito/state_props/sk_vec_norm.py
2,328
3.53125
4
"""Compute the S(k)-norm of a vector.""" from __future__ import annotations import numpy as np from toqito.state_ops import schmidt_decomposition def sk_vector_norm(rho: np.ndarray, k: int = 1, dim: int | list[int] = None) -> float: r""" Compute the S(k)-norm of a vector [NJDK09]_. The :math:`S(k)`-norm...
21cf5e52be746b766794ce5288fb94a153ca0d32
mgoldey/hackerrank
/ai/botclean.py
1,056
3.625
4
#!/usr/bin/python # Head ends here def next_move(posr, posc, board): def count_dirty(board): c=0 for i in board: for j in i: if j=="d": c+=1 return c def get_next(r,c,b): scope=[i for i in range(5)] for n in range(1,5): for i in range(r-n,r+n+1): for j in r...
b20b247d5da4954765473dc86624d2fce7516b33
NiceToMeeetU/ToGetReady
/Demo/DataStructre/sort_methods.py
11,544
3.5
4
# coding : utf-8 # @Time : 21/02/16 19:23 # @Author : Wang Yu # @Project : ToGetReady # @File : sort_methods.py # @Software: PyCharm import random from _TOOL import cal_time import copy class SortMethods: """ 手写排序算法 为利于不同方法对比,每种方法先设置对待排序数组的深拷贝 """ def __init__(self,...
e17a80959d131234eb2e393b659365a94158e3fc
IanPaulDaniels/Python_CrashCourseBook
/c10 - Files and Exceptions/1004_guest_book.py
235
3.625
4
filename = 'Chapter10/guest_book.txt' while (True): user_name = input('Please enter your name: ') if user_name == 'exit': break with open(filename, 'a') as file_object: file_object.write(user_name + '\n')
b29643f293397c06496d7c672dc33430887f43c7
A-Alexander-code/150-Python-Challenges--Solutions
/Ejercicio_N049.py
422
3.859375
4
compnum = 50 cont = 1 guess = int(input("Adivina el número. Prueba ingresando uno\n")) while guess != compnum: if guess < compnum: print("El número es muy bajo. Intenta de nuevo") else: print("El número es muy alto. Intenta de nuevo") cont = cont + 1 guess = int(input("Adivina el número....
6311380eaee8aa96a95b4d00e10f2eb974bdcc03
Jamye/algos_py
/misc_algo/anagram.py
837
3.796875
4
def show(str1, str2): list1 = list(str1) list2 = list(str2) list1.sort() list2.sort() pos = 0 matches = True while pos <len(str1) and matches: if list1[pos] == list2[pos]: pos = pos + 1 else: matches = False return matches def anagram_solutio...
7fc87241f663577c635ecd3cc7d1e471b2c389c3
Indra24710/Implementation-of-Algorithms
/Linkedlist.py
2,513
4
4
# coding: utf-8 # In[3]: class Node(): def __init__(self,value=0,next=None): self.value=value self.next=next class linked_list(): def __init__(self,head=Node(),tail=None): self.head=head self.tail=tail def addnode(self,value): node=Node() ...
316f54bd985b3439085b85eb8017506412176f1e
BuragaIonut/SoftUni
/SoftUni Exercices/arrayrotation.py
161
3.53125
4
arr = list(map(int, input().split())) n = int(input()) for i in range(n, len(arr)): print(arr[i], end = ' ') for i in range(n): print(arr[i], end = ' ')
71c4ae5acbf348e5392556d796078ad73cbb71b6
acadien/projecteuler
/p35.py
1,358
3.75
4
#!/usr/bin/python from math import * def check_prime(x,primes): sqt=int(sqrt(x)) for i in primes: if x%i==0: return False if i>sqt: break return True def circ(x): return x[1:]+x[0] primes=list() primes.append(2) for i in range(3,1000000,2): if check_prime(i...
79602bd8821f8481f94372c5e33158612ce3566b
Armanious/codiff-demo
/fizzbuzz.py
345
4.0625
4
''' For all numbers in [1, n], if the number is divisible by 3, print "<number> fizz", if the number is divisible by 5, print "<number> buzz", if the number is divisible by both 3 and 5, print "<number> fizzbuzz", otherwise print "<number>" ''' def fizzbuzz(n): pass def main(): fizzbuzz(100) if __name__ =...
ff074451e92f4af60852bd6fde0677113512d9d3
Aniruddha019/Python_Training
/Batches/2021-Aug-22/AnanyaSaikia/Exercise_001_Python_basics.py
266
4.46875
4
""" Practice using the Python interpreter as a calculator: 1. The volume of a sphere with radius r is 4/3 * π(r^3) . What is the volume of a sphere with radius 5? """ # Write your program below radius=5 PI = 3.14 volume=4/3 * PI*(radius**3) print("output",volume)
ba16dfbf9dcce52cbb638e70c6cc0b6fb1014c1a
santhosh790/competitions
/hackerrank/decodeString.py
767
4.15625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'decodeString' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. INTEGER numberOfRows # 2. STRING encodedString # def decodeString(numberOfRows, encodedString):...
84e84c4df3a9e4afa5eba4ed8de2b66d6971da6d
buridiaditya/Machine-Learning
/assignment1/assignment1_3.py
5,824
3.53125
4
import numpy as np import matplotlib.pyplot as pl import csv import math import pandas as pd # Linear Regression Model class LinearRegression: def __init__(self): self.W = None def predict(self,X): y_predict = X.dot(self.W) return y_predict def L2Cost(self, X, y_target,reg): ...
81749fdc9e50110f8c38100775cd348e72fdae44
southpawgeek/perlweeklychallenge-club
/challenge-156/eric-cheung/python/ch-2.py
2,501
4.125
4
## Remarks ## https://www.geeksforgeeks.org/weird-number/ ## Python 3 Program to Check if the Number is Weird or not from math import sqrt ## Code to Find all the Factors of the Number Excluding the Number itself def factors(n): ## Vector to Store the Factors v = [] v.append(1) ## Note ...
d2863b70f2656b166522b682921b8a886c5b3b1f
daniel-reich/turbo-robot
/cvA35yPFAggr7rtve_3.py
2,459
4.25
4
""" This is a sequel to [part #1](https://edabit.com/challenge/9yk63KrKDHzNFWKBJ), with the same setup, but a different goal. A folder system on a computer might look something like the picture below: ![](https://edabit-challenges.s3.amazonaws.com/folders_smaller.png) In this challenge, folder systems will be rep...
779ea6c55e24de7efe2ae621f4cd4ab7e9f758d2
daniel-reich/ubiquitous-fiesta
/PYEuCAdGJsRS9AABA_6.py
1,121
3.703125
4
class CoffeeShop: orders=[] def __init__(self, name, menu, orders): self.name=name self.menu=menu self.orders=orders def add_order(self, item): M=[x['item'] for x in self.menu] if item in M: self.orders.append(item) return "Order added!" else: return "This item is curren...
94636b52579ddef3e7e2fb499f019ea6445131cb
destefano1986/ClassLearning
/ClassLearning.py
1,838
3.71875
4
# 1. Class/Instance/Attribute/self/property # 2. Hook/Magic method => Operator Override/__init__/__str__/__call__ # 3. Inherit/多根/单根 class A(object): aField = ['TestAField'] def aMethod(self): print(self.aField) print('TestAMethod') birthday = 1983 @property def age(self): ...
2c1b3fd327c5b326fd66ba5eb8dc5657f3865913
ChocolatePadmanaban/Learning_python
/Day7/part_11.py
401
3.890625
4
# milti dimenstional element finding(find the location of first occurance) A= [[1,2],[2,[5,6]],3] def Extract(a, e): for i in a: b = [a.index(i)] if i == e: print(i) break elif type(i) == list and Extract(i,e) != None: c = Extract(i,e) b = b ...
8fe1fa799fd5cfba0909da8dd7bc787c1ccd8938
Houchaoqun/Daily-Coding
/python_numpy/timer.py
1,018
4.0625
4
# -*- encoding: utf-8 -*- ''' author: hcq date: 20170713 what is it for: 1. To calculate time that the program cost. 2. To know how the class works. 1) timer = ElapsedTimer() // class ElapsedTimer(object): 2) def __init__(self): // __init__ function run once you new an object of class ElapsedTimer() 3) o...
687e2a96ae9118d248e2d084d18af0cfb1b3771b
mattjp/leetcode
/practice/easy/0069-Sqrt.py
598
3.65625
4
class Solution: """ SLOW BUT PASSES: def mySqrt(self, x: int) -> int: y = 1 while y * y <= x: y += 1 return y-1 """ def mySqrt(self, x: int) -> int: def binarySearch(l, r, x): if l > r: return r ...
fbb10a91a8efddf7a6ca32532ab4e88cacd1c5f5
ivanromanv/manuales
/Python/DataCamp/Intro to Python for Data Science/Excercises/E23_Familiar functions.py
793
4.4375
4
# Out of the box, Python offers a bunch of built-in functions to make your life as a data scientist easier. You already know two such functions: print() and type(). You've also used the functions str(), int(), bool() and float() to switch between data types. These are built-in functions as well. # Calling a function is...
f6f6cfcd9256c0ff0b8a348433a8b3f808187733
m-sterling/Advent-of-Code-2020
/code/day12.py
2,505
3.71875
4
def main(): with open('../inputs/day12', 'r') as f: src = [line.strip() for line in f.read().split('\n') if line] print(part1(src)) print(part2(src)) def part1(src): # ship x, ship y: east/south = positive, west/north = negative # ship direction: N = 0, E = 1, S = 2, W = 3 x, y, d = 0,...
a6500c12434556b37545f32fb06322fab575a845
shomayon/Twitter
/Sentiment Analysis2/sentiment_ANA.py
3,000
3.5
4
from textblob import TextBlob import re from credentials import * import tweepy import pandas as pd import numpy as np # For plotting and visualization: from IPython.display import display import matplotlib.pyplot as plt #import seaborn as sns #%matplotlib inline def twitter_setup(): # Authentication and acc...
3fdaed348fb61dd811312395ae63d685b5b920a9
AdamZhouSE/pythonHomework
/Code/CodeRecords/2419/60628/267143.py
218
3.5
4
def differenceOfProductAndSum(n): s = 0 prod = 1 while (n > 0): r = n % 10 n //= 10 prod *= r s += r return prod - s n = int(input()) print(differenceOfProductAndSum(n))
7e3cbb65613d5a9d7446da7e8fe8e59ef9268900
bendog/shecodes_RonakReyhani_shecodes-week-6-task-1
/survey.py
2,166
3.6875
4
from question import Question from section import Section from keep_answers import answer_dictionary class Survey: # define survey parameters : title, description, sections def __init__(self, title, description, qualify_questions, survey_sections): self.title = title self.description = descrip...
f50f1b6b127eb4b225b698d76e96ff59b418d964
jkbstepien/ASD-2021
/graphs/bfs_adj_list.py
799
3.96875
4
from queue import Queue def bfs(graph, s): """ Breadth First Seach algorithm. Prints vertexes in visited order. :param graph: representation of a graph as adjacency list. :param s: starting vertex. """ visited = [] queue = Queue() visited.append(s) queue.put(s) i = 0 while...
bfc1ca63e41c9261dd6917265ba200eae503e55d
amalietm/exam_coding_1
/Amalie_M_week_7_2.py
362
3.921875
4
# Implement a Random Walker using Turtle Graphics from turtle import Turtle from random import choice t = Turtle() t.hideturtle() t.pensize(6) t.speed(7) directions = [0, 90, 180, 270] #angles turtle can rotate i = 0 while i < 200: t.setheading(choice(directions)) #direction of turtle - default right, if 90 ...
dea29a16200741d8fb6275cfc9428a8452cdee54
tinselcity/experiments
/lc/find_duplicate_number.py
542
3.71875
4
#!/usr/bin/env python3 class Solution: @staticmethod def findDuplicate(nums: list[int]) -> int: slow = 0 fast = 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow2 = 0 while True: slow = nums[slow] slow2 = nums[slow2] if slow == slow2: break retu...
8d64e2d957ede9616426698fa47cf59e5a52b195
filius-fall/py_prac
/python/test1.py
124
3.59375
4
# def f(*args): # k = list(args) # print(k) # f(1,2,3,4,5) d = {2:["a","b","c"],"3":["d","e","f"]} print(d[2][0])
e58f586e9a2d761b16919288982efa919136ab5d
andytwigg/algorithms
/mergesort.py
428
3.84375
4
import utils # mergesort def mergesort(A): n=len(A) if (n<=1): return A L=mergesort(A[0:n/2]) R=mergesort(A[n/2:n]) return merge(L,R) def merge(L,R): A = [] i=0 j=0 while (i<len(L) and j<len(R)): if (L[i] <= R[j]): A.append(L[i]) i=i+1 else: A.append(R[j]) j=j+1 # check for any leftovers ...
90469d839453703257937a60a98e96d415f0e465
ammedmar/simplicial_operators
/simplicial_operators/_utils.py
1,485
3.625
4
from itertools import combinations, product, chain, permutations from math import floor def partitions(n, k, smallest_value=1, largest_value=None, ordered=False): '''n is the integer to partition and k is the length of partitions. It returns all k tuples of integers greater or equal to smallest_value and ...
64f64f36d0f5bef400e59ae80900dc29d56b7521
DudkoMatt/PhysicsProjectSpring2021
/mixing.py
3,374
3.546875
4
import math import scipy.optimize import numpy as np def mix_it_2(first_color: list[float], second_color: list[float], first_color_part, second_color_part) -> list[float]: """ :param first_color: first color to be mixed :param second_color: second color to be mixed color list represents normalised fro...
74985a14ebffad1cad5be8d1e781ee67b36564b4
jdrnd/CTCI
/ch1/1-7.py
495
3.765625
4
def rotate_90_right(matrix): size = len(matrix) print(size) new_matrix = [[0 for x in range(size)] for y in range(size)] for i in range(0, size): row = matrix[i] for j in range(0, size): new_matrix[j][size - 1 - i] = matrix[i][j] return new_matrix def rotate_90_right_i...
289e0394891ad5c7c706664abf31daa621278276
vishrutjai/Codechef
/TSORT.py
92
3.5
4
a = input() l = [] for x in range(a): l.append(input()) l.sort() for y in l: print y
c4a9c608bca90daa3c56336b5d50cc0a20fa2f2e
developyoun/AlgorithmSolve
/solved/16727.py
253
3.6875
4
p1, s1 = map(int, input().split()) s2, p2 = map(int, input().split()) if [p1, p2] == [s2, s1]: print("Penalty") elif p1+p2 == s1+s2: print('Persepolis' if s1 < p2 else 'Esteghlal') else: print('Esteghlal' if p1+p2 < s1+s2 else 'Persepolis')
4970ca102bc967e7f3d6e3ea98ec71daa8bba5e5
GabrielSalazar29/Exercicios_em_python_udemy
/Exercicios Seção 07 parte 1/ex016.py
943
4
4
""" Faça um programa que leia um vetor de 5 posições para números reais e, depois, um código inteiro. Se o código for zero, finalize o programa; se for 1, mostre o vetor na ordem direta; se for 2, mostre o vetor na ordem inversa. Caso, o código for diferente de 1 e 2 escreva uma mensagem informando que o código é invál...
7c7b67dbf65d83a989c1850aa232f3a97d152964
jbaker8935/analyzing-the-new-york-subway-dataset
/ProjectFiles/project_4/exercise_2/data_visualization.py
2,730
4.4375
4
import pandas as pd from ggplot import * import pandasql import datetime def plot_weather_data(turnstile_weather): ''' Use ggplot to make another data visualization focused on the MTA and weather data we used in assignment #3. You should make a type of visualization different than you did in exercise ...
6d89785ee00387c05b6a1f1e0e1c10cd1e2f7e17
JieFrye/leetcode
/StackandQueue/OnlineStockSpan.py
1,268
3.96875
4
# Write a class StockSpanner which collects daily price quotes for some stock, # and returns the span of that stock's price for the current day. # The span of the stock's price today is defined as the maximum number of # consecutive days (starting from today and going backwards) # for which the price of the stock was ...
c76fb2cfb6d627ef8234a1380536a4632d2de528
aditya-doshatti/Leetcode
/check_if_it_is_a_straight_line_1232.py
1,271
4.0625
4
''' 1232. Check If It Is a Straight Line Easy You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true https://leet...
86cec6c5c0db98fb78728e358cd1facbc348bd24
alpsilva/PG-2020.2
/projeto0/structures/vetor.py
943
3.859375
4
class Vetor: def __init__(self, x1, x2, x3): self.x1 = x1 self.x2 = x2 self.x3 = x3 # Igualdade entre vetores. def __eq__(self, outro): return self.x1 == outro.x1 and self.x2 == outro.x2 and self.x3 == outro.x3 # Multiplicacao por numero real. def __mul__(self, num)...
550dc1b59c2315f1171050827b93f5664852253d
Dom88Finch/RecipeScraper
/util.py
341
3.765625
4
import statistics def remove_outliers(arr): if (len(arr) < 3): return arr avg = statistics.mean(arr) std_dev = statistics.stdev(arr) for a in arr: if (a > avg + std_dev or a < avg - std_dev): arr.remove(a) avg = statistics.mean(arr) std_dev = statistics.stdev...
dfdd71a95486533cd79323aee8ebcc93e200d759
SiddhiPevekar/Python-Programming-MHM
/prog29.py
320
4.0625
4
#to remove duplicate from a list lst=[] n=int(input("enter the number of elements:\n")) for i in range(n): x=input("enter elements:\n") lst.append(x) lst=(dict.fromkeys(lst)) print(lst) lst=list(dict.fromkeys(lst))#this prints in list form print(lst) #print(set(lst)) this prints in the form of set
81e982958b29e6bbf6137de796cacb99f11bd793
jod35/coding-challenges
/011.py
167
3.859375
4
x=int(input("Enter a number greater than 100 ")) y=int(input("Enter a number less than 10: ")) number_of_times=x/y print(f"{x} enters {y} {number_of_times} times")
c18a6bbd673bac4d82d3e695ee141c83caee5993
o-hill/utilities
/pdf_scraper.py
4,019
3.65625
4
import requests import re import sys import os ''' This is a python file that will download all PDFs that are linked to by a provided URL. It can be run like this: python pdf_scraper.py <URL> <OPTIONAL DIRECTORY NAME> If a directory name is specified, it will create a directory with that name...
36203225d36c72a9a65e85bc519d08d210114678
BlueBlueSkyZZ/LeetCode
/Python/145Binary_Tree_Postorder_Traversal.py
771
3.921875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from typing import List class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: result = [] d...
f646550090ea0a37ab64cc1c42f8f439ba43cd53
rithinark/arkfile
/stone,paper,scissor_game.py
2,094
3.859375
4
import random lists = ["stone", "paper", "scissor"] ai_points, user_points = 0, 0 def chance(ai_choice, user_choice): global ai_points, user_points if ai_choice == user_choice: print("\t\t\t\tboth are same") elif ai_choice == "paper" and user_choice == "stone": ai_points = ai_points + 1 ...
bc9fe8f8deb2b3f0fde2fc2829481f710efe54f6
Gabriela-Santos/study_python
/1-basics/05-functions.py
273
4.125
4
# print the type of an object - escrevendo o tipo de um objeto print(type(1)) print(type(1.0)) print(type('a')) print(type(True)) # use brackets to declare a list - use colchetes para declarar uma lista print(type([1, 2, 3])) print(len('Gabriela')) print(len([10, 11, 12]))
970e0538ac63f783738dd974f0e0ed5f8a1a4b10
qzylinux/Python
/filter.py
633
3.84375
4
#filter(函数,序列),使用惰性计算,只有取filter得结果时才会返回值 #生成器生成序列,然后用生成器(generator)和过滤器(filter)返回新的序列 #其中新序列的生成原则是:序列每一个元素除以序列的第一个元素,整除的过滤掉 def odd_iter(): n=1 while True: n=n+2 yield n def prime_filter(n): return lambda x : x%n>0 def primenumber(): yield 2 t=odd_iter() while True: n=next(t) yield n t=filter(p...
623c064dd80b90d337b7a618cb0f1a9706e33919
john-ko/project-euler
/3.py
866
3.84375
4
""" Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ from math import sqrt def is_prime(number): for i in range(int(sqrt(number))): if i + 1 < 2: continue if number % (i + 1) == 0: retur...
4582a1c69b0949376d4885a2dbce19c1a11d71ac
JakeEdm/CP1404Practicals
/prac_02/files.py
547
3.8125
4
# # 1. # # out_file = open('name.txt', "w") # # name = input("What is your name: ") # # print(name, file=out_file) # # out_file.close() # # # 2. # # in_file = open('name.txt', 'r') # # name = in_file.read() # # print(f'Your name is {name}') # # in_file.close() # 3. # in_file = open('numbers.txt', 'r') # # line1 = int...
80c99537af382296bed6fb832a6197c2bbd89da8
imsamuel/pcc
/exercises/chapter-5/5.7.py
806
4.375
4
""" 5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of independent if statements that check for certain fruits in your list. • Make a list of your three favorite fruits and call it favorite_fruits. • Write five if statements. Each should check whether a certain kind of fruit is i...
8975d1a0db28d952721747d232c7aa043106649e
orlewilson/lab-programacao-tin02s1
/aulas/exemplo5.py
1,518
4.25
4
""" Disciplina: Laboratório de Programação Professor: Orlewilson B. Maia Autor: Orlewilson B. Maia Data: 31/08/2016 Descrição: Exemplos com condições (if). """ """ Sintaxe if (condição): bloco verdadeiro else: bloco falso if (condição): bloco verdadeiro else: if (condição): bloco verdadeiro if (condição):...
7a1c1f40ad98a930b4419e2263ecc1d8418405c3
cylinder-lee-cn/LeetCode
/LeetCode/371.py
902
3.609375
4
""" 371. 两整数之和 不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。 示例 1: 输入: a = 1, b = 2 输出: 3 示例 2: 输入: a = -2, b = 3 输出: 1 """ class Solution: def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ maxmask = 0x7fffffff ...
8eefc12f190a8ba388c8c5d5e69fedd596f4dbfb
hopekbj33/python20200322
/st01.Python기초/py07선택문/py07_01ex1_if홀짝.py
787
3.84375
4
# 정수를 입력을 받습니다. # 입력 받은 문자열을 정수로 바꿉니다. # 숫자로 변환하기 ####################################### # 홀수, 짝수 판별법 # 방법1. 나머지를 사용하는 방법 # 방법2. 문자열을 사용하는 방법 ####################################### a=int(input("정수를 입력하세요")) if a%2==0: print("짝수") else: print("홀수") ####################################### # 방법1. 나머지를 사용하여 ...
7236ed2fa8502de5461aec7ce249eebbc36cbbd8
adusachev/Algorithms-and-Data-structures
/Algorithms/Graphs/BFS.py
1,885
3.765625
4
def bfs(G, start_vertex, n): """ Обход графа в ширину. :param G: невзвешенный неориентированный граф(вершины - числа от 1 до n) :param start_vertex: начальная вершина :param n: кол-во вершин в графе :return: список distances: distances[i] = кратчайшее расстояние от start_vertex...
6e131621d1e442626c075f63a755e8f119e4ef07
imqishi/HardToSay
/147. Insertion Sort List.py
912
3.84375
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ newHead = ListNode(0) cur = ...
ae4f55af470af7f88647af099be8d85757b5e343
sunilpedada/htmlANDjavascripts
/timeMatplot.py
423
3.609375
4
import time import matplotlib.pyplot as pt validating=0 seconds=[] while(len(seconds)<5): print(len(seconds)) start=time.time() a=input("type") end=time.time() time_lape=end-start seconds.append(round(time_lape)) if a!="words": validating+=1 print("no of mistake",validating) print(le...
1a86519f7e2a914318ac4d66d21ec1e8f4d673c6
jpch89/picpython
/pp_047_多线程同步之Event.py
1,492
3.625
4
from threading import Thread, Event, current_thread import time event = Event() # 用于判断 event 对象管理的内部标志是否被设置为 True print(event.is_set()) # 刚开始是 False def do_sth(): print('%s开始等待' % current_thread().getName()) # 当 event 对象管理的内部标志为 False 时调用 wait() 方法 # 会将调用方法的线程阻塞 event.wait() print('%s结束等待' % cur...
839fc0d06eae5d57c2cf1da1c51fa54bda2cbd5a
ntmoore/phys150_fall20
/01e_snore_carl.py
1,221
3.890625
4
# Carl Ferkinhoff # starting from from adafruit example # https://learn.adafruit.com/welcome-to-circuitpython/creating-and-editing-code # import board import digitalio import time # set up the (red) LED led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT while True: num_repeats=2 #s...
6dbb3718b4f863c51c19a18bcdf122f67da6b941
bd52622020/appSpaceUmer
/task5 python/pointsCalculate.py
803
4.03125
4
''' Created on 9 Jun 2020 @author: umer ''' def point(team ='unknown',games =0, wins =0, loss =0, draw = 0): Points = 0 if wins ==0: wins = games -loss - draw Points = Points + (wins * 3) elif loss ==0: loss = games -wins - draw Points = Points + 0 elif draw ==0: ...
03d7a424c1345826d848b2c829aae11707fafc03
jkane002/TCS-python
/U2/lesson17/stack.py
764
4.03125
4
class Stack(): #Constructor def __init__(self,list): # __ means private (our __stack attribute is private) self.__stack = [] for value in list: self.__stack.append(value) def push(self,value): print(" < PUSH < " + str(value)) self.__stack.append(value) ...
1f1741f0ac28c326795a1f0599f771f4086a4d35
djarufes/Python_Crash_Course
/Excercises/HW07/car.py
731
3.75
4
######################################################## # Author: David Jarufe # Date: April. 19 / 2019 # This program is a Class that can be imported # for later use ######################################################## #The Car class (car.py) class Car: def __init__(self, yearMod, carMake): self.__year_...
8b9199f3521a6c8277054c82d6a9b405cbfafd53
jackyng88/Queens-College-Projects
/Logistic Regression/Classification.py
7,673
3.609375
4
import numpy as np from sklearn import datasets import scipy.optimize as opt import math as math import random from random import randrange from numpy import linalg as la import copy import matplotlib.pyplot as plt import time def sigmoid (x): return 1 / (1 + np.exp(-x)) def cost_function(w, x, ...
3bcea6be445a02097536ac80000d029020a3c058
devAbdifetah/python_dev
/deletegaree1.py
1,195
4.0625
4
##for i in range(1,11): ## print("the value is {:03}".format(i)) ## ##pi = 3.14159265 ##sentence = 'Pi is equal to {:.2f}'.format(pi) ##print(sentence) ## ## class BankAcc: def __init__(self): self.balance=0 print("Hello,!!! Welcome to the deposit and withdrawn machine") def depos...
f3694cc1ed5e677b77e302d781bfeb8ca0b2178f
collenjones/genetic_algorithm
/genetic.py
3,737
4.125
4
from operator import add from random import random, randint def individual(length, min, max): """Create a member of the population. :length int: the number of values for an individual to contain :min int: the minimum possible value :max int: the maximum possible value """ return [randint(min,...
d7f79a8235a355a9b26066779ed1ac653d31e3ce
aaronbushell1984/Python
/Day 3/working.py
247
3.96875
4
def calculateFactorial(N): factorialN = 0 if N == 0: factorialN = 1 return factorialN else: for number in range(1, N+1): factorialN += number return factorialN print(calculateFactorial(0))
ce2a7084134cbbfc11019ca5f42afd04fdbf6edc
SvetlanaD/Python_practice
/Day2.py
1,471
3.65625
4
import json class Day2: def text_func(text: str, max_len: int): symbols_with_spaces = len(text) symbols_no_spaces = len(text.replace(' ', '')) symbols_even = symbols_with_spaces % 2 == 0 print(f'Kоличество символов в тексте {symbols_with_spaces}') print(f'Kоличество симв...
9dd161ce41b136e05e37be5d12accdee63cb647f
joaogehlen91/calculo_numerico
/Trabalho2/questao1/questao_1_a.py
258
3.625
4
# -*- coding:utf-8 -*- import numpy as np from math import * h = 0.125 a = -3.0 b = 3.0 n = int(((b-a)/h)+1) x = np.linspace(-3.0, 3.0, n) y = 2.71828182846**-(x**2) for i in range(1, n-1): y[i] = 2*y[i] AT = (h/2)*sum(y) AT = AT*(2/sqrt(pi)) print AT
77b0e749b02694d95b434906f1f9b27b4badc24e
JobsDong/leetcode
/problems/349-1.py
428
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = ['"wuyadong" <wuyadong311521@gmail.com>'] class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ s1 = set(nums1) s2 = ...
68cd81952afbe80a51c33f54c409d77a3711ac15
MOHAMMADSHAIBAZQAISAR/Hactoberfest-2021
/Programming_Languages/PYTHON BASIC PROGRAMS/tuple.py
231
3.828125
4
numbers = (1,2,3,4) #numbers[0] = 10 print(numbers[0]) #unpacking coordinates = (1,2,3) coordinates[0] * coordinates[1] #x = coordinates[0] #y = coordinates[1] ##z = coordinates[2] #x * y x,y,z = coordinates print(x)
93618796b9a7e185cd111468884dc2fd3739c452
hfujima/rssreader
/bin/hfujima/lib/functions.py
1,193
3.953125
4
# -*- coding: utf-8 -*- def truncate(text, max_length, suffix=u'…', return_none=False): """ 一定文字数を超えた文字列を「…」などで置換する。 suffixがmax_lengthより長い場合、suffixをmax_lengthまで切り詰めた文字を返却する。 :param text: 整形対象のテキスト :param max_length: 表示する文字数(suffix込) :param suffix: max_lengthを超えた文字列を置換する文字列 :param return_no...
1cd539e0aa7d1a46bf272816f694a75dad375dd0
richardsun-voyager/SentimentAnalysis
/tools/text_hier_split.py
5,382
3.765625
4
######Split texts into sentences############## import re import nltk import nltk.data import string from time import time from nltk.tokenize import WordPunctTokenizer from nltk.stem import WordNetLemmatizer import spacy class text2words: ''' Using spacy tool to tokenize texts into sentences or words ''' ...
3ef8b812e3ab07a71e41e4c73479e66d080b8c27
Ys-Zhou/leetcode-medi-p3
/201-300/229. Majority Element II.py
1,147
3.53125
4
# Runtime: 44 ms, faster than 100.00% of Python3 online submissions class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] num_1, num_2 = nums[0], nums[0] votes_1, votes_2 = 0, 0 ...
c455766e61398aada0323dc5095ec41bf3d4d37a
joybangla71/atomisticdomains
/atomistic_domains/lattice.py
1,576
3.734375
4
import numpy as np from typing import List from atomistic_domains import Atom class Lattice: """ The class "lattice" defines methods which manipulate lattice structures. Lattice structures have the following attributes: :param type: Lattice type: e.g. fcc, hcp, bcc, etc. :param box: Unit cell box ...
333ce1437d366239f44a096e0c1b156eab0cd9e7
shuklaham/python_progs_think
/e5.4.py
347
4.21875
4
import math def is_triangle(a,b,c): if (a > (b+c)) or (b > (a+c)) or (c > (b+a)): print "No" else: print "Yes" print "Type your 1st side - a \n" first_num = int(raw_input()) print "Type your 2nd side - b \n" sec_num = int(raw_input()) print "Type your 3rd side - c \n" third_num = int(raw_input()) is_triangle(f...
2e8fd0ec0d49fb0dbc796b7c91af41f2451b1320
alisher0v/MeFirstPrograms
/sum.py
283
3.921875
4
number = int(input()) def sum(number): answer = 0 if number == 0: return 1 if number < 0: for i in range(number, 1): answer += i else: for i in range(1, number+1): answer += i return answer print(sum(number))
9d6c4a43459a2ac3cdc8bd28b0b4a8cdf2bcc5d6
abhayshekhar/PythonPrograms
/isPhoneNumber.py
817
4.15625
4
def isPhoneNumber(text): if len(text)!=12: return False for i in range(0,3): if not text[i].isdecimal(): return False if text[3]!='-': return False for i in range(4,7): if not text[i].isdecimal(): return False if text[7]!='-': return Fa...
7572d0270b7ad6f91473b2680e5c96a87c2ecfbc
souravs17031999/100dayscodingchallenge
/strings/check_binary_codes_substring.py
2,943
3.984375
4
# Program to check if given "k", and string "s", if s contains all possible binary codes of length k as substring in s. # Example 1: # # Input: s = "00110110", k = 2 # Output: true # Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, 1, 3 and 2 re...
a6eae747fe32b3e9c3b662c39dbfa5bd214030eb
Cekurok/codes-competition
/hackerrank/python/Date and Time/python-time-delta-English.py
444
3.84375
4
import time import datetime monthDict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12} testcase = int(input()) for i in range(testcase): date1 = datetime.datetime.strptime(str(input()), "%a %d %b %Y %H:%M:%S %z") date2 = datetime.dateti...
7899f9a83b1e3df468278a3bec043a07762c136e
Sibyl233/LeetCode
/src/LC/81.py
1,948
3.6875
4
from typing import List """解法1:两次二分查找。先找分界(LC154),再找target。 """ class Solution: def search(self, nums: List[int], target: int) -> int: lo, hi = 0, len(nums)-1 while lo < hi: mid = (lo + hi) // 2 if nums[mid] > nums[hi]: lo = mid + 1 elif nums[mid]...
adb077a552563ff04bd40e3645ec43c7231b2623
nomura-takahiro/study
/loop/for_while.py
1,669
4.0625
4
################ ### ループ ### ################ #for text = "Nomura" #デフォルトで in XXXに指定したものから1要素ずつを取り出すっぽい for char in text: print(char) tmp = ["Nomura","Baz","Jista"] #リストの1要素ずつを出力 for li in tmp: print(li) #ミュータブルなものなら更新ができる i = 0 for li in tmp: new = tmp[i] new = new.upper() tmp[i] = new i += 1 print(tmp) #...
dfa0faec7b6d7df384e9cb2d6aac2a855f55dfa7
jhanvi-shingala/linear_regression
/linear_regression.py
867
3.78125
4
#Linear regression import numpy as np import csv2array import matplotlib.pyplot as plt infile = input("Enter a csv filename: ") ar = csv2array.csvar(infile) # Training X = ar[:,0] Y = ar[:,1] m = X.shape[0] #number of training examples epoch = 150000 #number of iterations t0 = 0.9999 t1 = 0.9999 alpha = 0.00009 i =...
ede2f4b7b5fe4b1214ececb6f047e4833fe570b4
Travis-ugo/pythonTutorial
/while loop,for loop.py
663
3.875
4
call = 0 while call < 3: name = input('User name :') call += 1 if name == 'Travis': print('Hey ' + name) break else: print('try again') for cap in range(3): other = input('Other name :') if other == 'Okonicha': print('Hello ' + name + ' ' + other) ...
6d2c3167c570e4b8dbee58462ab874f758fa3579
reshma-jahir/GUVI
/set18.py
67
3.5
4
val=int(input()) sat=0 for i in range(val): sat=sat+i print(sat)
c1590abf4f311e7b0e1bc7edea0f35b9b4704d6b
mikaevnikita/algorithms-and-data-structures
/algorithms/quick_sort.py
550
3.921875
4
def quickSort(array, beg, end): pivot = array[(beg+end)//2] left = beg right = end while(left <= right): while(array[left] < pivot): left+=1 while(array[right] > pivot): right-=1 if(left <= right): array[left],array[right] = array[right],array[...
777356dd2d0ff5ceb6eee0f9e3ca49d5e3dee7e2
themillipede/data-structures-and-algorithms
/algorithmic_toolbox/PA3_greedy_algorithms/3_car_fueling.py
2,092
4.0625
4
# python3 """ 3. Car fueling Introduction: You are going to travel to another city that is located d miles away from your home city. You can travel at most m miles on a full tank and you start with a full tank. Along your way, there are gas stations at distances stop_1, stop_2, ..., stop_n from your home city...
d45bfb2f42a0ed486a8cfad278fa2f079a05f8f7
AllysonKapers/2143-Object-Oriented-Programming
/Resources/10-PyGame/02_pygame_example.py
1,243
4.3125
4
#!/usr/bin/env python3 # Import and initialize the pygame library import pygame import random """ This version simply changes the color of the ball using the random library in python. """ pygame.init() # Set up the drawing window screen = pygame.display.set_mode([500, 500]) # Run until the user asks to quit runni...
b98d9ded2b1f33b1249b61fc35e6e9c3cd12bda6
lazydroid/pgn-tactics-generator
/modules/investigate/investigate.py
1,676
3.59375
4
# # Check if the position is worth trying for a puzzle: # 1. there's a sufficient drop in evaluation # 2. there's enough material # 3. the possibility of mate # import chess def sign(a): if a > 0: return 1 elif a < 0: return -1 else: return 0 def material_value(board): return sum(v * (len(board.pieces(pt, T...
e27f2583e6c3015153cefa43efad46d6f24f0598
DanilaDz/2020-CS50-Work
/MyCS50 code/DanilaDz-cs50-problems-2020-x-sentimental-cash/cash.py
656
3.890625
4
# I used some examples from cash in C from cs50 import get_float import math def main(): # keeps prompting user for input while True: change = get_float('Change owed: ') cents = round(change * 100) if change > 0: break # does all the math to get the remainder...
925788aa60eca2365f44f3722225cf60126df30a
cuviengchai/Programming
/0001.py
452
3.84375
4
score1 = int(input().strip()) score2 = int(input().strip()) score3 = int(input().strip()) sum = score1 + score2 + score3 if sum >= 80 and sum <= 100: print("A") elif sum >= 75 and sum < 80: print("B+") elif sum >= 70 and sum < 75: print("B") elif sum >= 65 and sum < 70: print("C+") elif sum >= 60 and su...
e2d955891b70084c3e3ce185681593915abee8e0
AUTHENTICGIT/PC
/function_varargs.py
558
3.8125
4
def func(a, b, *c, **d): print(a) print(b) for x in c: print(x) for k,v in d.items(): print(k, v) func('a', 10, 'single_item 1', 'single_item 2', 'single_item 3', Inge=1560, John=2231, Jack=1123) #案例 def total(a=5, *numbers, **phonebook): print('a', a) #遍历元祖中的所有项目 for single...
3d73f7ca9fa3735490926beb496c38d7e9d9105c
princeofpython/UCSD-DSA-specialization
/1. Algorithmic ToolBox/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py
1,049
3.828125
4
# Uses python3 import sys def fibonacci_partial_sum_naive(from_, to): sum = 0 current = 0 next = 1 for i in range(to + 1): if i >= from_: sum += current current, next = next, current + next return sum % 10 def pisano_period(m): previous=0 current=1 for i...
193fbb483798d00bc8a965e116cdfc7e5f3f6a01
pschafran/Notes
/scripts/trimFastaBases.py
1,227
3.515625
4
#!/usr/bin/python # 2020 April 30 (C) Peter W Schafran ps997@cornell.edu # # Trims a range of bases out of a single sequence in FASTA format. Base range is inclusive (start and end positions are removed). # Usage: trimFastaBases.py singleSequence.fasta startBasePosition endBasePosition import sys openSeqFile = open(s...
2a98c8dfead68665cd5f9f3f0e8d3685b3b3a719
wendrewdevelop/Estudos
/Python/python_logging/aula/format.py
752
3.578125
4
''' Formatando a mensagem do log. ''' import logging # DateTime:Level:Arquivo:Mensagem log_format = '%(asctime)s:%(levelname)s:%(filename)s:%(message)s' logging.basicConfig(filename='exemplo.log', filemode='w', level=logging.DEBUG, format=log_format) #...