blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b197f59aaebf5117d1192ad617cada599b1b0402 | binarybottle/mindboggle_sidelined | /plot_fs_label.py | 1,030 | 3.84375 | 4 | #!/usr/bin/env python
"""
Visualize .label labeled surface mesh data.
Comment out the top line (below the header) of the .label file
containing the number of rows, to load an appropriately sized numpy array.
Copyright 2012, Mindboggle team (http://mindboggle.info), Apache v2.0 License
"""
import sys
import numpy as... |
11dd563df1a564416dcf677d850fb3032838948e | taohi/python | /distance.py | 899 | 3.90625 | 4 | #!/usr/bin/python
#-*-encoding:utf-8 -*-
#方法来自于Google Map
#计算地球上两点之间的距离,坐标用经纬度表示。
#1公里范围误差1米左右
import math
import sys
def distance (latA,lonA,latB,lonB):
earth_radius = 6378137.0
radlatA = math.radians(latA)
radlonA = math.radians(lonA)
radlatB = math.radians(latB)
radlonB = math.radians(lonB)
... |
bba3b2c2ad7463a92c0059f20de060931bcd0d3a | MaciejNessel/algorithms | /graphs/alg_dijkstry.py | 1,687 | 4.03125 | 4 | # Implementation of Dijkstra algorithm
from queue import PriorityQueue
from math import inf
def get_solution(p, i, res):
if p[i] == -1:
return [i] + res
return get_solution(p, p[i], [i] + res)
def dijkstry_matrix(g, s, e):
def relax_matrix(u, v):
if d[v] > d[u] + g[u][v]:
d[... |
31c290843c452b2a1d517cf148869b3c7e23006a | romerik/ZCasino | /ZCasino.py | 2,853 | 3.8125 | 4 | #coding:utf-8
from random import randrange
from math import ceil
def jeu(numero_mise=50):
continuer_partie=1
while continuer_partie==1:
somme=0
nombre_aleatoire=0
numero_mise=50
while numero_mise<0 or numero_mise>49:
try:
numero_mise=input("Entrez un numéro compris entre 0 et 49 pour miser d... |
4127e4b7d75774e8ce201c8d432b19f45c0f22b0 | pursuitdan/test_integration- | /db_utils.py | 1,962 | 3.734375 | 4 | import sqlite3
# db_name = the name of the database
def create_table_db(db_name):
# SQL statements
sql_drop_entries = '''
DELETE FROM uniqueMAC1;
'''
sql_create_table = '''
CREATE TABLE IF NOT EXISTS uniqueMAC1(
TX TEXT,
RX TEXT,
SNR REAL,
... |
a0da1222e83dd879f5867a13549b446d23f9388e | NathanLHall/Project-Euler | /Problem 014.py | 604 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
@author: NathanLHall
"""
# https://projecteuler.net/problem=14
Collatz = 0
maxCount = 0
collatz = 1
def even(n):
return n/2
def odd(n):
return 3 * n + 1
million = 1000000
while collatz < million:
count = 1
n = collatz
while n != 1:
if n ... |
d2da41803f1f63942f28d433dc56ba20e765e9a2 | mangomadhava/weather_haikus | /v2/haiku_wikipedia.py | 2,408 | 3.515625 | 4 | import random
from string import punctuation
from collections import defaultdict
import os
import wikipedia
import sys
import clipboard
def syllables(word: str) -> int:
word = word.strip().lower().strip(punctuation)
syllable_count = 0
vowels = "aeiouy"
if len(word) == 0:
return '', 0
if w... |
387f4074a878f65450705c42040eeb890da4d197 | jbschwartz/robotpy | /robot/traj/segment.py | 3,988 | 3.671875 | 4 | import abc, math
from spatial import Transform, vector3
class Segment(abc.ABC):
@abc.abstractmethod
def interpolate(self, t: float) -> 'Vector3':
pass
@abc.abstractmethod
def reverse(self) -> None:
pass
class LinearSegment(Segment):
'''A linear point-to-point segment.'''
def __init__(self, start... |
578c43feacb2aa5cf852ea66b02e749b7cf3af22 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_95/2637.py | 1,306 | 3.53125 | 4 | #!/usr/bin/env python
#encoding: latin1
ent = "A-small-attempt0.in"
sal = "output.out"
entrada = open(ent, 'r')
salida = open(sal, 'w')
def imprime(case, texto):
"""Recibe numero de case y texto que puede ser numero.
Graba en salida."""
salida.write("Case #"+str(case)+": "+str(texto)+"\n")
def crear_dic():
dic ... |
bb21abacae8a913d2435db69d6c5fdae062132fc | simran-ahuja/coffee_machine | /entity/beverage_machine.py | 2,396 | 3.53125 | 4 | from concurrent.futures import ThreadPoolExecutor
from .errors import InventoryLowException, InventoryFetchException
from .inventory import Inventory
def _prepare(beverage, inventory):
"""
Prepares the beverage if all the ingredients in the recipe are
available in inventory in sufficient amount
resu... |
ba097e5c962754396223c37d2207e48652cc4870 | leesoongin/Python_Algorithm | /프로그래머스/위장.py | 699 | 3.53125 | 4 | from collections import defaultdict
from functools import reduce
def solution(clothes):
d1 = defaultdict(list)
for name, kind in clothes:
d1[kind].append(name)
l = [len(value) for key, value in d1.items()]
l[0] += 1
answer = reduce(lambda x,y : x*(y+1),l) - 1
return answer
print(soluti... |
142c20ca684580116d4fb6174b8af7f8ff34e69c | cnukaus/3lcarsds | /backwards_collatz_conjecture.py | 1,135 | 4.09375 | 4 | def loop_backwards():
def backwards(times):
num = 1
for i in range(times):
if num%3 == 1:
num-=1
try:
num//=3
except BaseException:
print("B 1")
num/=3
... |
ec9025739abc8d4c4eb33d8367c55ac9f69c7f41 | hentvandenbroek91/programming1 | /les4/pe_2_if with 2 boolean operators.py | 197 | 3.734375 | 4 | leeftijd = int(raw_input("Geef je leeftijd: "));
paspoort = raw_input("Paspoort: ");
if leeftijd >= 18 and paspoort == "ja":
print("Gefeliciteerd, je mag stemmen!");
else:
print("Helaas"); |
d3ef6330fc367090f40ce604dd807dd0cf79182d | akimi-yano/algorithm-practice | /lc/review_310.MinimumHeightTrees.py | 2,698 | 4.125 | 4 | # 310. Minimum Height Trees
# Medium
# 4086
# 165
# Add to List
# Share
# A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
# Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges w... |
8fa1df7b39889bb49a1746a5d6deaa51d71ae34c | Codestar007/PoP1_ExamPractice | /AllRepos/worksheet-on-lists-Codestar007/ex02/Snowflake.py | 218 | 3.578125 | 4 | n = int(input())
r = [['.'] * n for i in range(n)]
for i in range(n):
r[i][n//2] = '*'
r[i][i] = '*'
r[i][n-i-1] = '*'
r[(n//2)][i] = '*'
for row in r:
print(' '.join([str(elem) for elem in row]))
|
dcfb995d0ee4d57c8ed3f93246c0a99854a771ec | chitvangarg614/Python-mini-projects | /Rock paper scissors.py | 527 | 3.984375 | 4 | import random
def play():
user=input("\'r\' for rock,\'p\' for paper, '\s\' for scissors ")
computer= random.choice(['r','s','p'])
if user== computer:
print('It\'s a tie between computer and user')
if is_win(user,computer) :
print("You won! Computer loses.")
else:
prin... |
ba818ae4d8c0dab4865b87d1c620c72b0d1b8ec6 | YixuanSeanZhou/Daily_Coding_Problem | /prob_4_first_missing_positive.py | 2,186 | 3.671875 | 4 | '''
#4
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, ... |
3e630bf0677882fdb4669d5700adb2de02183be0 | stosik/coding-challenges | /daily-challenge/1-30/day-11.py | 1,570 | 3.875 | 4 | # This problem was asked by Twitter.
# Implement an autocomplete system. That is, given a query string s and a set of all possible query strings,
# return all strings in the set that have s as a prefix.
# For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].
# Hint: Tr... |
036aaf0ef3c8cace77af39d4ff09f1952795421e | JungwanLim/sort | /selection_sort.py | 1,182 | 3.59375 | 4 | import time
from baseclass_sort import BaseSorts
from bubble_sort import BubbleSort
class SelectionSort(BaseSorts):
def s_sort(self, arr, size):
for i in range(size - 1):
pos = i
for j in range(i + 1, size):
if arr[pos] > arr[j]:
pos =... |
bc2ade3d52c24baefd3df0b243b1ce37de3be270 | zhaocong222/python-learn | /匿名函数.py | 221 | 3.625 | 4 | #匿名函数
func = lambda a,b:a+b
res = func(1,2)
#print(res)
stus = [
{"name":"zhangsan","age":18},
{"name":"lisi","age":19},
{"name":"wangwu","age":17}
]
stus.sort(key = lambda k:k['name'])
print(stus) |
ac60cd920e791f2c27c1b7aa4fd677fff6336cf3 | ddizhang/code-like-a-geek | /classDef_Graph.py | 821 | 3.671875 | 4 | class Vertex:
def __init__(self, key):
self.key = key
self.connectTo = {}
# used in bfs
self.status = 'initial'
self.pred = None
self.dist = 0
# nbr is a vertex object
def addNeighbor(self, nbr, weight):
self.connectTo[nbr] = weight
def getNeighbors(self):
return self.connectTo
class Graph:
de... |
b28c63e95f3ab813da542944af6faf5d10918c93 | Lusilucy/Sencond | /7-10Python/9_5Unittest/testcases/demo.py | 1,567 | 3.625 | 4 | import unittest
class Search:
def search(self):
print("search")
return True
class Demo2(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
print("setUpClass")
cls.search = Search()
@classmethod
def tearDownClass(cls) -> None:
print("tearDownCla... |
6b1302a3ea50c09f3a108173faa4a23eab020e17 | connorescajeda/Algorithims | /main.py | 1,233 | 3.546875 | 4 | def main():
f = open("graphs/graph-F21.txt")
edges = f.readline()
f = f.read().splitlines()
s = {}
for line in f:
if len(line.split()) != 1:
(one, two) = line.split()
if one not in s:
s[one] = []
if two not in s:
s[two] = []... |
ad2888ab93eb1ba1665cc0bdc1f71e439e3b8147 | tutunamayanlar2021/Python | /loop_alternatif.py | 819 | 4.0625 | 4 | # for x in range(10):
# print(x)
# numbers=[x for x in range(10)]
# print(numbers)
# numbers=[]
# for x in range(10):
# numbers.append(x)
# print(numbers)
# for x in range(10):
# print(x**2)
# numbers =[x**2 for x in range(10)]
# print(numbers)
# numbers=[x*x for x in range(10)if x%3 ==0]
# print(numb... |
91a1366109f52900d4463b560557377922749037 | moiseenkov/codility | /solution_02_1_odd_occurrences_in_array/main.py | 760 | 4.125 | 4 | from solution_02_1_odd_occurrences_in_array.solution import solution
def main():
while True:
try:
message = 'Enter array of positive integers, where only one of them doesn\'t have pair 1 2 1 2 3: '
numbers = list(map(int, input(message).strip().split(' ')))
negative_num... |
22071d6eff247f7026d36d6fa505ba6cae6ecd76 | Kevin-Cool/python_Mastermind | /Board.py | 3,087 | 3.875 | 4 | import random
class Board:
def __init__(self,difficulty):
self.difficulty = difficulty
self.board_state = []
self.board_evaluations = []
self.board_won = 0
def generate(self):
if self.difficulty==0:
self.__solution = [random.randint(1,6),random.randint(1,6),... |
e9bec0cf4409e27641838e668299ed76b237b402 | fabianrevilla/tilda | /p2/mult.py | 440 | 3.953125 | 4 | def mult(x,y):
n = 0
sum=0
x=int(x)
y=int(y)
if abs(x) > abs(y):
while n < abs(y):
sum=sum+abs(x)
n = n + 1
else:
while n < abs(x):
sum=sum+abs(y)
n = n + 1
if x < 0 and y > 0 or x > 0 and y < 0:
sum =-sum
re... |
e7c28775127503abf64081d11e030b5552731c4f | lasersox/twixt | /twixt_heuristic.py | 8,807 | 3.625 | 4 | from math import *
from pytwixt import node_twixt as twixt
import copy
import sys
def f_1(game, player):
""" Compute total length of bridges for player. """
conn_len = sqrt(1 + 2.**2)
total = 0
for conn in game.connections(player):
total += conn_len
return total / (game.size[... |
8c49b24de009d8ca37979a8e22b5e4959056d317 | Taofiq-Bakare/Python_Crash_Course | /name.py | 391 | 4.1875 | 4 | # another simple one.
# .title is a method
# name = 'ada lovelace'
# print(name.title())
# insert a variable into a string
# first_name = "Ada" # variable one
# last_name = "Lovelace" # variable two
# full_name = f"{first_name} {last_name}" # f-strings
# print(full_name)
# Exercise two
name = "Fatimah"
print(f"... |
c7064cd395404e6ce57b28b9fa4062be60213051 | taceroc/Data_Courses | /Data-Driven-Astronomy/test.py | 332 | 3.59375 | 4 | '''
def double(val):
return val + val
print(double(3))
print(double('3'))
'''
'''
There are two ways you can test your function before submitting it.
'''
'''
def add(a, b):
return a + b
if __name__ == '__main__':
print(add(2, 3))
print(add(1, 5))
'''
def greet(name):
return 'Hello, %s!' %name
print(gree... |
d8420fe4dd89a5f76d0a42c0b9268698ba160cdb | A-creater/turtle_exemple | /car_turtle.py | 1,968 | 3.65625 | 4 |
import turtle
from board import board_a
# class Car(turtle.Turtle):
# mileage = 0
#
# def forward(self, distance: float) -> None:
# super().forward(distance)
# self.mileage += distance
# car.mileage
#
# car = Car()
# car2 = Car()
# car3 = Car()
# car4 = Car()
# for i in range(60):
# car4.... |
414f6388572a213325b64434964f458da6030a0b | majumdarsouryadeepta/python_20-04-21 | /Day02/nested.py | 142 | 3.84375 | 4 | n = int(input("Enter a range for numbers: "))
for i in range(2,n+1):
for j in range(10,0,-1):
print(i*j,end=" ")
print("")
|
dbd1373f4847ded5efea92df5c42521c18aa9fd4 | I-in-I/Python-General-Projects | /File Handling/Text File Handling/file_reading_example.py | 361 | 4.46875 | 4 | '''
An example of how python reads an iterable file object by default.
invisble \n are shown so the user can see how python delimits new lines
'''
with open('test.txt') as test:
for line in test:
if line.endswith('\n'):
#linedup = line[:-1] + '\\n'
print(line[:-1] + '\\n')
... |
9abc4383504132a9f17509ad1adf68cf359e2585 | assafZaritskyLab/Intro_to_CS_SISE_2021-2022 | /week_11/2_linkedlist_accumulated.py | 2,741 | 4.03125 | 4 | class Node:
def __init__(self, val):
self.value = val
self.next = None
def __repr__(self):
return '[' + str(self.value) + ']'
class Linked_List:
def __init__(self):
self.head = None
self.len = 0
def __repr__(self):
out = ''
p = self.head
... |
4184f5003e70b42b1f9540435e9dfe4c467b9c86 | bengranett/synmock | /synmock/timer.py | 1,033 | 3.859375 | 4 | import logging
from timeit import default_timer as timer
class Timer(object):
units = [
("msec", 1e-3, 100),
("sec", 1, 59),
("min", 60, 59),
("hours", 60*60, 0),
]
def __init__(self, msg="Elapsed time", logger=None):
""" """
if logger is None:
l... |
0e75c3cc537ac07b2ea8f7842134fb3131939938 | AuroraStarChain/facial-recognition-temperature | /Research/Code-Snippets/camera.py | 763 | 3.609375 | 4 | # Reference https://docs.opencv.org/master/dd/d43/tutorial_py_video_display.html
import numpy as numpy
import cv2
capture = cv2.VideoCapture(0)
cv2.namedWindow("Test")
# Access camera and refresh
if not capture.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame by frame
ret, f... |
c9e61e95e677cefc49b2a711a4e06d129fbe4e96 | torietyler/conversion | /conversion.py | 461 | 4.0625 | 4 | '''
convert from f to c and from c to f
'''
degree = input("enter c for celsius, or f for fahreiheit :")
temperature = int(input("Enter the temperature value :"))
if degree == 'f':
C = (temperature - 32)*5/9
print("the temperature in celsius is :", round (C))
elif degree == 'c':
F = temperature*9... |
5e424bff970a3536b71f6af91a0c6e3bf18243a1 | meat9/Algoritms | /Спринт 13 Жадные алгоритмы/A. Расписание.py | 1,360 | 3.75 | 4 | # Дано расписание предметов. Нужно составить расписание,
# в соответствии с которым в классе можно будет провести как можно больше уроков.
# Формат ввода
# В первой строке задано число предметов. Оно не превосходит 1000.
# Далее для каждого предмета в отдельной строке записано время начала и окончания урока.
# Обра... |
53a935e20e53643a002ea8a91807e7feca01cf16 | ealbasiri/GitPractice-1 | /is_even.py | 98 | 4.09375 | 4 | val = input("Enter a num: ")
if (int(val) % 2) == 0:
print("You've entered an even number!")
|
1671159276b9ecf66a3f21c34846efac65ea1619 | grvn/aoc2018 | /08/day8-1.py | 508 | 3.53125 | 4 | #!/usr/bin/env python3
from sys import argv
def main():
with open(argv[1]) as f:
input=[int(x) for x in next(f).split()]
_,meta=find_meta(input, [])
svar=sum(meta)
print(svar)
def find_meta(input,metadata):
cnodes,meta=input[:2]
input=input[2:]
if cnodes==0:
metadata+=input[:meta]
return(inp... |
48ceeae8903157dda1e57f7dec20849d6aaf289d | G00398275/PandS | /Week 04-flow/w3Schools-ForLoops.py | 1,689 | 4.65625 | 5 | # Practicing for loops, examples in https://www.w3schools.com/python/python_for_loops.asp
# Author: Ross Downey
fruits = ["apple", "banana", "cherry"] # square brackets for list
for x in fruits: # selects all fruits in the list
print(x)
for x in "banana": # loops through all letters in banana (Note: no brackets use... |
ca391323a5bdf69f35b99e5574a8e9f187083e15 | sourav-coder/100-Days-of-Code- | /assignment week 1 & 2/Dictionary/8.py | 114 | 3.921875 | 4 | '8'
#sample data
a={'1':['a','de','bv'],'2':['d','ab']}
for key,val in a.items():
a[key]=sorted(val)
print(a)
|
7031ae17fc13e4f5250f28f30a4fc1c490d96507 | kangli-bionic/algorithm | /lintcode/657.py | 2,257 | 3.671875 | 4 | """
657. Insert Delete GetRandom O(1)
https://www.lintcode.com/problem/insert-delete-getrandom-o1/description
380. Insert Delete GetRandom O(1)
https://leetcode.com/problems/insert-delete-getrandom-o1/
"""
import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure h... |
c0ca419d3beecc8ef7c89710e4f51df62e406652 | rsconklin/PythonStudy | /Chapter_8.py | 2,325 | 4.53125 | 5 | # There are at least two distinguishable kinds of errors:
# syntax errors and exceptions.
# Exceptions can be handled.
#while True:
# try:
# x = int(input("Please enter a number: "))
# break
# except ValueError:
# print("Not a valid number. Try again.")
# Notes on the previous example: The ... |
9b8b0901cc13ab2755a31fdd1d43f72621d4f9f0 | tshuldberg/First-Python-Projects | /TicTacToe.py | 4,513 | 3.9375 | 4 |
# print('\n'*100)
def display_board(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
... |
35d68e69a4fc3b0c68830f080ddee6019f154415 | France-ioi/alkindi-tasks | /2019/2019-FR-AL-03-generators/medium_dictionary_human.py | 1,007 | 3.765625 | 4 |
from sys import argv
from random import randrange
N=int(argv[1])
fd = open("leaked_passwords.txt","r")
def is_word_from_dictionary(word1):
def lex_less_than_or_equal(word1,word2):
for i in range(min(len(word1),len(word2))):
if ord(word1[i]) > ord(word2[i]):
return False
... |
9d57bbe991fc67ee3983a3a224290fdaf664812d | ykzw/data_structures_and_algorithms | /python/strmatch/common.py | 340 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import string
import itertools
def is_valid_shift(text, pattern, s):
m = len(pattern)
for i in range(m):
if text[s + i] != pattern[i]:
return False
return True
def random_string(alphabet, n):
return ''.join(random.choi... |
29cefef1411b26dc79d0182511b73a3e29483919 | BettyAtt/myWork | /week03/Labs/lab3.2.1round.py | 304 | 4.21875 | 4 | # This program rounds a number
# Rounds will round to the nearest even number
# which can be problematic if accuracy is essential
# Author: Betty Attwood
numberToRound = float(input("Enter a float number:"))
roundedNumber = round(numberToRound)
print ( '{} rounded is {}'.format(numberToRound, roundedNumber))
|
46eeca59cb14ccfcca5d078e079bbac3ceb12b46 | tomtom0516/python-cookbook-3rd-edition | /02 String and Text/B14combineconcatenate.py | 98 | 3.640625 | 4 | parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(' '.join(parts))
print('x', 'y', 'z', sep=':')
|
d4d3b0c3f43885fc7843fd080a92e08d6b3ea199 | isaquemelo/python-backup | /Ambrósio pescador.py | 1,486 | 3.6875 | 4 | '''
Correnteza = Direita: 0
Cardume à Esquerda
Correnteza = Esquerda: 1
Cardume à Direita
'''
'''
x1 y1 = REDE
x2 y2 = REDE
S = CORRENTE
x3 y3 = PEIXES
1 2 1 5 1 5 3
1 2 1 5 0 5 3
'''
entrada = input().split()
#define variaveis principais e converte-as
rede = [int(entrada[0]),int(entrada[1])]
rede1 = [i... |
ff877b232bac604d612baf2a51773afcd858a412 | aphilliard/functions | /breakfast.py | 3,564 | 4.0625 | 4 | # make breakfast
import sys
from time import sleep
from random import choice
spices_list = ("pepper", "paprika", "nutmeg", "mace", "clove", "ginger", "cinnamon")
meats_list = ("chicken", "pork", "beef", "turkey")
cook_eggs = ("fried", "scrambled", "over-easy", "poached")
def sausage_machine(m, s):
print(f"Here is... |
497f0cacf64c7340ab47d0f0723bba97368d7f5d | dsrlabs/PCC | /CH 2/personal_message.py | 129 | 3.609375 | 4 | person_name = "Doug"
print("Hello, " + person_name + "," + " " + " How are you are enjoying learning to code using Python" + "?") |
041dffd66e98fa4e52ae6396aa4bc54129ce0249 | ConnorRules/cse491-numberz | /siev_iter/siev.py | 621 | 3.96875 | 4 | # this is an implementation of the Fibonacci series using
# Python's iterator functionality. Here, 'fib' is a class that
# obeys the iterator protocol.
def _is_prime(primes, n):
for i in primes:
if n % i == 0:
return False
return True
class siev(object):
def __init__(self):
... |
b60574ec58bf0ff9fba8ea7e6b901300a9cebadd | basiledayanal/PROGRAM-LAB | /CO1.pg6.py | 124 | 3.828125 | 4 | list = ['BASIL', 'NISHA', 'SAJIL', 'ELIAS', 'RENJU', 'REGHU']
count = list.count('a')
print('The count of a is:', count)
|
1d91f1d4fbb1b61935d3637d5dd1fdfa9ad679af | abc20899/PythonLearn | /src/flask/basic/flask_router.py | 559 | 3.59375 | 4 | from flask import Flask
# 实例化Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "<h1>Hello World!</h1>"
# 动态url 动态部分默认为string类型
# 动态类型为 <int:id>、<float:price>、<path:url> path /不作为分割部分
@app.route("/user/<name>")
def user(name):
return '<h1>Hello,%s!</h1>' % name
#http://127.0.0.1:8080/book/12... |
9aa84b73a6a725cfd92f708323138283adc721bd | toransahu/py-misc | /first_class_obj.py | 345 | 4.03125 | 4 | """
In Python, functions are first-class objects.
This means that functions can be passed around, and used as arguments,
just like any other value (e.g, string, int, float).
"""
def foo(bar):
return bar + 1
print(foo)
print(foo(2))
print(type(foo))
def call_foo_with_arg(foo, arg):
return foo(arg)
print(ca... |
3c4b74cfc71eee68b6da44e5cc2dd5f8bfc4697a | Vrokm/LeetCode-record | /99/99.py | 2,214 | 3.609375 | 4 | '''
Runtime: 116 ms, faster than 74.97% of Python3 online submissions
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solut... |
c4ec79ae1f0d559cfd0317610604442a211c03eb | ivyfangqian/python36-learning | /os_demo.py | 2,297 | 3.890625 | 4 | # 对文件系统的访问主要通过os模块来进行,os模块主要用于访问操作系统命令
# import os
import os
# 对一个文件重命名
# os.rename('D:\\test\\test.txt','D:\\test\\test01.txt')
# 删除一个文件
# os.remove('D:\\test\\hello.txt')
# 创建一个目录
# os.mkdir('D:\\test\\ivy')
# 删除一个目录
# os.rmdir('D:\\test\\ivy')
# 同时创建多个目录
# os.makedirs('D:\\test\\ivy\\test')
# os.sep 可以取代操作系统特... |
0fda719cb036653163c6a58dd65f0cfa1f50c200 | Diatemba99/Python | /tp4/exo5.py | 293 | 3.578125 | 4 | """
Donnez la sortie de ce programme
"""
nombres_entiers = (6, 2, 8, 0)
print("Plus grand nombre entier:", max(nombres_entiers))
print("Nombre d’éléments:", len(nombres_entiers))
print("Somme des nombres:", sum(nombres_entiers))
print("Liste des nombres:", list(nombres_entiers))
|
2a6f96b8ba5520247935117a181b648ed2f90d06 | holumyn/bc-python-xv | /exercises/even_numbers.py | 159 | 3.90625 | 4 | def even_numbers(low, high):
if(low > high):
even_num = [x for x in range(low,high) if x%2 == 0]
return even_num
else:
return "Low is bigger than high" |
2ee63065177960f18740c33eb5e264d46ae833ba | Cerious/Project-Euler | /multi_of_3_5.py | 246 | 3.890625 | 4 | ### Calculates and sums all the multiples of 3 and 5 below 1000.
lis = list(range(1,1000))
multi_3_5 = []
for num in lis:
if num % 3 == 0 or num % 5 == 0:
multi_3_5.append(num)
var = 0
for num in multi_3_5:
var += num
print var
|
98b6768077693080d5c104df013902480cbff7ef | sam-kumar-sah/Leetcode-100- | /202a. Happy Number.py | 691 | 3.8125 | 4 | //202. Happy Number
'''
Example:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
'''
//method-1:
def sq(n):
s = set()
while n != 1:
if n in s:
return False
s.add(n)
print("s=",s)
n = sum([int(i) ** 2 for i in str(n)])
... |
dc889a68d8ccc408b7bcb6c6b832866164debfea | denysdenys77/Beetroot_Academy | /data_structures/double_linked_list.py | 1,724 | 3.96875 | 4 | # Реализовать добавление в начало, добавление в конец и добавление после определенного элемента в двусвязном списке.
class Node:
def __init__(self, next=None, prev=None, data=None):
self.next = next
self.prev = prev
self.data = data
class DoublyLinkedList:
def __init__(self):
... |
f6c9647b0d297eca13dea3bfa4da8e49a9d09bcb | sylcrq/study | /python/reverse_integer.py | 430 | 3.828125 | 4 | class Solution:
# @return an integer
def reverse(self, x):
result = 0
negative = (x < 0)
x = abs(x)
while x > 0:
result = result*10 + x%10
x = x/10
if negative:
return -result
else:
return result
print '3/10 ='... |
f4eb513fa4b96c8b0c42d7e8819a6880f4d50c6d | KGeetings/CMSC-115 | /In Class/FileIntroTest.py | 2,030 | 3.828125 | 4 | # file_var = open("TestWriteFile.txt", "r")
# number = 5
# for line in range(number):
# print(line, file=file_var)
# print(file_var.read())
# file_var.close()
#x = set()
#for value in range(5):
#x.add(value)
#print(x)
#Lists and stuff
#listX = []
#for value in range(11):
#listX.append(value)
#listX.app... |
6bbae15a7bade2d9df869f0ed07de370e57b0d2e | bolek117/Ford-Fulkerson-PY | /fordfulkerson/breadthfirstsearch.py | 487 | 3.640625 | 4 | __author__ = 'mwitas'
def bfs_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for e in path:
if e in graph[vertex]:
graph[vertex].remove(e)
for next_point in graph[vertex]:
if next_point == goal:... |
9f6dc0f3191f80588043a8789b5d9493f1fa2dd8 | advantager/Zookeeper | /Topics/Program with numbers/The sum of digits/main.py | 154 | 3.828125 | 4 | # put your python code here
input_number = int(input())
digit_sum = 0
for i in range(3):
digit_sum += (input_number // 10 ** i) % 10
print(digit_sum)
|
775864b56710009480a375bd6b2dd6729a62ea61 | chainsofhabit/Python | /python_stage1/day11文件操作和异常捕获/03-json.py | 3,863 | 4.15625 | 4 | """
json是有特定格式的一种文本形式,它有自己的语法
json文件就是后缀是.json的文本文件
1.json格式对应的数据类型及其表现
一个json文件中只能存一个数据,这个数据的类型必须是以下类型中的一个
类型: 格式: 意义:
对象(object): {"a":10,"b":[1,2]} 相当于字典
数组(array): [100,"asd",true,[1,2]] 相当于列表,里面的元素可以是任何类型
数字(number): 100 3.14 ... |
edf8a2f67080c77e33fdc19312a042492d0b6d30 | mryingjie/basic_algorithm | /venv/Include/bubble_sort.py | 288 | 3.765625 | 4 |
arr = [32,4,21,45,6,75,4,42,523,6,42]
#冒泡排序
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(len(arr)-i-1):
#将小的数往前放
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
bubbleSort(arr)
print(arr) |
9a7c3fdaff845673cac16ebc3926419b24c027cb | vipin-t/py-samples | /listings.py | 1,058 | 4.28125 | 4 | # print ("to work on lists")
a_list = [7,1,5,8,4,2,6]
b_list = ['f', 'g', 'a', 'd', 'b', 'e', 'c']
c_list = [a_list, b_list]
b_list.
## list commands
# a_list.sort()
# a_list.reverse()
# b_list.sort()
print ( a_list )
print(b_list)
print ('\n')
print ( c_list )
#print ( b_list.pop(2) )
# prin... |
81a01d023cc7802757ba3327f25d0f85f8fcb497 | Chalmiller/competitive_programming | /python/interview_cake/arrays_strings/merge_lists.py | 1,824 | 4.28125 | 4 | import unittest
def merge_lists(my_list, alices_list):
# Combine the sorted lists into one large sorted list
"""
Task: Merge the two lists into one.
Algorithm:
1. generate a place holder list
2. keep track of three pointers, one for each list
3. compare each element and insert into... |
b066a9807d0d7acec8b1e34eb732e411e94610f2 | lucindaWMS/Interview_Preparation | /Python/Sort/BubbleSort.py | 359 | 4.125 | 4 | #Bubble Sort
def BubbleSort(num_list):
for i in range(len(num_list) - 1):
for j in range(len(num_list) - i - 1):
if num_list[j] > num_list[j+1]:
temp = num_list[j]
num_list[j] = num_list[j+1]
num_list[j+1] = temp
return num_list
if __name__ == '__main__':
num_list = [1, 1, 13, 55, 34, 8, 23, 89]
... |
309a1b9cba2d98a4e1c01ca6586528ec32b60c12 | jdfrancop/probando | /listas.py | 565 | 4.09375 | 4 | numeros = [1,2,3,4,5,6]
frutas = ["naranja", "Fresa", "manzana", "uva","pera"]
print(frutas)
print(frutas[3])
print(frutas[-2])
lista = list((1,2,3,"hola","dos",5))
print(lista)
nueva = numeros + frutas + lista
print(nueva)
nueva2 = [0]
nueva2.extend(numeros)
print(nueva2)
nueva2.insert(2,8)
print(nueva2)
saludo ... |
7212df604cb011183f198a719e2d3b22ecc75876 | mdsulemanr/pythonPractice | /default_parameter.py | 828 | 4.15625 | 4 | def greet(name, msg = "Good morning!"):
"""
This function greets to
the person with the
provided message.
If message is not provided,
it defaults to "Good
morning!"
"""
print("Hello",name + ', ' + msg)
greet("Kate")
greet("Bruce","How do you do?")
def default_arguments(table_number=2, li... |
9066a36999f1cf13b952c8ebaaa4e3979c61ab3e | cpeixin/leetcode-bbbbrent | /DataStructureDesign/MyHashMap.py | 2,975 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2021/5/13 8:28 上午
# @Author : CongPeiXin
# @Email : congpeixin@dongqiudi.com
# @File : MyHashMap.py
# @Description:不使用任何内建的哈希表库设计一个哈希映射(HashMap)。
#
# 实现 MyHashMap 类:
#
# MyHashMap() 用空映射初始化对象
# void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 k... |
ad404b4fc4fe8b6445c2379bd6da7036619e79d1 | tworthy94/Homework_03_Python | /PyBank/main.py | 1,998 | 3.578125 | 4 | # Modules
import os
import csv
# Path to collect data from the Resources folder
infile = os.path.join('Resources', 'budget_data.csv')
budgetDataCsv = csv.reader(open(infile))
header = next(budgetDataCsv)
# Define Variables
months = []
totalMonths = 0
netTotal = 0
profitLoss = []
profitLossStepped = []
# Loop throu... |
d69d231f18a5418f8fa90fa849db52975d8c42e5 | khannakanika/Misc-3 | /Problem_1.py | 1,313 | 3.984375 | 4 | """
Time Complexity : O(nlogk) where n is the length of weights array and k is the range, ie max(weights)- sum (weights)
Space Complexity : O(1)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
Here, instead of working on the array, we work on capacity. The minimum capaci... |
f2103f1b6cadd8a898e855fef23281c6956d30ba | BlancLight/Tarea-Termodin-mica | /ArregloMatriz_RandonWalk+Grafica.py | 4,250 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 18:34:08 2020
@author: Jesus Andrey Salazar Araya, Angello Marconi Crawford Clark
"""
#Librerías utilizadas
import numpy as np
import random
from matplotlib import pyplot as plt
#Creamos un arreglo 100X100 y luego a traves de un ciclo 'for' agregamos los ... |
5b1f878aa2918b79a4b9c2e73dc9e75022fe85fa | ckolds/categorical-sectional | /weather.py | 3,551 | 3.578125 | 4 | """
Handles fetching and decoding weather.
"""
import re
import urllib
INVALID = 'INVALID'
VFR = 'VFR'
MVFR = 'M' + VFR
IFR = 'IFR'
LIFR = 'L' + IFR
RED = 'RED'
GREEN = 'GREEN'
BLUE = 'BLUE'
LOW = 'LOW'
OFF = 'OFF'
def get_metar(airport_iaco_code):
"""
Returns the (RAW) METAR for the given station
... |
619f50b7d842e75246d122f957b501083a188d01 | suvansinha/maths | /calculus.py | 446 | 3.71875 | 4 | def f(x):
return x**2
def derivative(x):
h=1./1000.
rise= f(x+h) - f(x)
run = h
slope = rise/run
return slope
def integral(startingx,endingx,numberofrectangles):
width =(float(endingx)-float(startingx))/numberofrectangles
runningsum=0
for i in range(numberofrectangles)... |
063cd212a92fed7106be40d9fbc02b1615eac3c6 | hangim/ACM | /LeetCode/reverse-integer/reverse-integer.py | 179 | 3.65625 | 4 | class Solution:
# @return an intege
def reverse(self, x):
if x < 0:
return int(str(x)[:0:-1]) * -1
else:
return int(str(x)[::-1])
|
b9123c38aae456a559e71afb9d98c5db0f0150e0 | Artishevskiy/StraGame-by-Andrey-and-Artem | /main.py | 3,051 | 3.65625 | 4 | import pygame
import random
class Board:
# создание поля
def __init__(self, width, height):
self.width = width
self.height = height
self.board = [[0] * width for _ in range(height)]
self.left = 10
self.top = 10
self.cell_size = 30
for i in range(len(self... |
fbd819b8efa09bb9970cb1a97594ad273585478f | alexzinoviev/itea_c | /advance/advance_07_4.py | 515 | 3.96875 | 4 | # сопрограммы
# coroutine
def coroutine(f):
gen = f()
next(gen)
return gen
@coroutine
def f():
"""coroutine function"""
print('f start')
i = yield
print("f: ", i)
i = yield i + 1
print("f: ", i)
i = yield i + 1
# print("f: ", i)
# i = yield i + 1
def main():
pri... |
718064be173d1b2f6633ebe484dd68592340387e | shumka-kik/basic_python_course | /lesson3/lesson3_task4.py | 1,845 | 3.890625 | 4 | #4. Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y).
# При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
#Подсказка: попробу... |
e7faa8735deff10ea33d3fefad0701d30b6c9186 | tatikondarahul2001/py | /17122020/phone_no.py | 137 | 4.0625 | 4 | import re
phn="342-232-4545"
if re.search("w{3}-w{3}-w{4}",phn):
print("valid phone number !!!")
else:
print("not a valid number !!!")
|
23bf44148034836172431374222694b71d848004 | AidanDuffy/CreditCardChooser | /main.py | 22,206 | 3.96875 | 4 | """
Aidan Duffy
Class: CS 521 - Fall 2
Date: December 15, 2020
Final Project
Description: This is the main project file for the credit card choosing program
Future Goals: 1. Add a function that prints out all a user's cards
2. Incorporate naming schemes to separate user info.
3. Implement an actual user interface for e... |
df55ed41cb42bc5b0ef752872ecdac71b8120ff5 | TerryLun/Code-Playground | /Leetcode Problems/lc830e.py | 1,594 | 4.03125 | 4 | """
830. Positions of Large Groups
In a string S of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".
Call a group large if it has 3 or more characters. We would like the starting and ending pos... |
b35a06d6cefa7a9bd32e6794d30042a0c852582f | m3xw3ll/TurtleRacer | /main.py | 1,806 | 4.03125 | 4 | from turtle import *
import turtle
from random import randrange
import tkinter
import tkinter as tk
WIDTH = 600
HEIGHT = 600
TURTLE_SIZE = 10
BOTS = 6
class Racer():
def __init__(self, color, pos):
self.pos = pos
self.color = color
self.runner = turtle.Turtle()
self.runner.penup()
... |
fdebe9f3173a2cb6d8620484e55d7f0e1caaf307 | mshans66/Data-science-fundamentals-Dataquest | /calculus-for-machine-learning/Finding Extreme Points-159.py | 572 | 3.78125 | 4 | ## 3. Differentiation ##
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5,6,110)
y = -2*x + 3
fig = plt.figure()
ax = plt.axes()
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.plot(x,y)
plt.... |
3089a2ea0db746a878e77f4094dc2c9ad4759cfe | ibrahim852/programacion | /ejercicio1.py | 351 | 3.765625 | 4 | lista=[7,9,2,10,4]
iterador=0
for i in lista:
print lista [iterador]
iterador=iterador-1
diccionario={'animal1':'oso','animal2':'jirafa','animal3':'leon'}
print diccionario
print diccionario.keys()
print diccionario.values()
diccionario['animal4']='vaca'
print diccionario
diccionario['animal1']='perro'
for i in dicc... |
b66ad34a4425faf972fb77b2c83085bd24835e7e | dundunmao/lint_leet | /mycode/leetcode_old/2 string(9)/medium/151. Reverse Words in a String.py | 351 | 4.53125 | 5 | # -*- encoding: utf-8 -*-
# 2级 背下来
# 题目:给一句string, reverse the string word by word.例如Given s = "the sky is blue",return "blue is sky the".
def reverseWords(s):
# return ' '.join(s.split(' ')[::-1])
return " ".join(s.strip().split()[::-1])
if __name__ == '__main__':
s = "the sky is blue"
print revers... |
52a02e04c5902a9513da97abbe3623b80b13562a | pickdani/aoc2020-python | /4/a.py | 802 | 3.703125 | 4 | lines = [x.strip() for x in open('input').read().splitlines()]
def solve(lines):
ans = 0 # num valid passports
passport = {} # current passport
for line in lines:
if not line: # end of passpost
valid = True
# check validty of passport
fields = ['byr', 'iyr', ... |
cb4eedfb1dd0d57a55151da21b467bc8e4e95787 | ghost8399/Projet-1-POO-2-GL-2021 | /code_src/arbre.py | 1,534 | 3.875 | 4 | import turtle
from turtle import *
angle = 30
color('#3f1905')
speed(0)
t=turtle.Turtle()
# "Entrées :
# Sorties :
# Méthodes :
# Connu :
def arbre(n,longueur):
if n==0:
color('green')
forward(longueur) # avance
backward(longueur) # recule
color('#3f1905')
... |
09e76eea3e89c5e7b743ce24368c9837af3a592f | Malandru/codesignal-tasks | /Arcade/Python/Drilling the Lists/primes_sum.py | 316 | 3.71875 | 4 | import functools
def primesSum(a, b):
return functools.reduce(lambda ps, n: ps + n, filter(isprime, range(a, b + 1)), 0)
def isprime(n):
x = n if n < 100 else int(n ** 0.5)
for i in range(2, x):
if n % i == 0: return False
return n > 1
a = 1
b = 10 ** 5
print(primesSum(a, b)) |
0040f7bd4d9c3eef4003c3daca92fc0893ccaf20 | ravalrupalj/BrainTeasers | /Edabit/Generating_Words.py | 946 | 4.125 | 4 | #Reorder Digits
#Create a function that reorders the digits of each numerical element in a list based on ascending (asc) or descending (desc) order.
def reorder_digits(lst, direction):
final_l=[]
for i in lst:
t=''.join(sorted(str(i)))
if direction=='asc':
final_l.append(int(t))
... |
a4aff5720d640a5b1c28daec43db3e3dc219b8fe | linrakesh/python | /Tkinter/messagebox.py | 499 | 3.828125 | 4 | from tkinter import *
import tkinter.messagebox
import tkinter.simpledialog
root = Tk()
"""
yesno = tkinter.messagebox.askyesno('Question',"Are you sure to delete this record ?")
tkinter.messagebox.askokcancel()
tkinter.messagebox.askquestion()
tkinter.messagebox.askretrycancel()
tkinter.messagebox.askyesnocancel()... |
3318821f924beffba38ccfbb6a6e8c2501e3443b | tnbie/hsmu-python-scripts | /primeiro_programa.py | 5,111 | 4.28125 | 4 | #-------------------------------------------------------#
## primeiro_programa.py
## primeiro contato com python no curso da hsm university
#-------------------------------------------------------#
# usando o print
print("Hello World!")
# criando uma variavel numerica e vendo o seu tipo
numero = 10
print(type(numero)... |
b5bdcba4912a40f397091092e1b3a41357c206a1 | ScottMorse/DC-Sep-26 | /for_eslam.py | 4,111 | 4 | 4 | class PoolTable:
#When you make a new PoolTable instance, it ALWAYS needs table_number to create it
def __init__(self,table_number):
#All of these are what every NEW PoolTable instance gets:
self.table_number = table_number # You need to give each table a table number
self.occupied = Fa... |
58e2029cc20575a0699ac989d2bd2bceb0f0ad0d | CStratton00/CST-215-Programming-Assignments | /LabQuestion4.py | 3,303 | 3.6875 | 4 | A = True
B = True
def APT(): return "T" if(A == True) else "F"
def BPT(): return "T" if(B == True) else "F"
def abAND(): return "T" if(A and B) else "F"
def abOR(): return "T" if(A or B) else "F"
def abNAND(): return "T" if(not(A and B)) else "F"
def abNOR(): return "T" if(not(A or B)) else "F"
def abXOR(): return "T"... |
d96ccc59df05f56ad7aef23b61032363f57bd4b0 | pythonCore24062021/pythoncore | /HW/homework06/rrasi/task11.py | 818 | 3.90625 | 4 | #Матриця 5x4 заповнюється введенням з клавіатури (крім останніх елементів рядків). Програма повинна обчислювати суму введених
#елементів кожного рядка і записувати її в останній рядок. Наприкінці слід вивести отриману матрицю.
m = 5
n = 4
matrix = []
for i in range(m):
a = []
for j in range(n):
a.appen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.