blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
71b41acf70da44badd09c67abf2bd7cb8fa58a97
theme716/small-routine
/insect/9.nine_day/2.yield_方法实现基本的协程.py
688
3.859375
4
import time def A(): while True: print('----------------a-------------') yield time.sleep(1) def B(a): while True: print('-----------------b--------------') next(a) time.sleep(1) if __name__ == '__main__': a = A() B(a) ''' 过程思考: 调用B函数, print('-...
aa153fcb09fbabfda7b6d4686a25087a07fdabea
theme716/small-routine
/ClassicalProject/4.文件复制程序.py
687
3.703125
4
#提示并获取要复制的文件名 name = input('要复制的文件名') #打开要复制的文件 f = open(name,'r') #创建一个新文件,用来存储源文件的数据内容 findPosition = name.find('.') newName = name[:findPosition] + '[附件]' + name[findPosition :] p = open(newName,'w') #复制 #第一种(很危险,容易挤爆内存) #content = f.read() #p.write(content) #第二种(可以一行一行复制过去,减少内存压力) #for lineContent in f.readl...
085eba8d9c41e59cf9b808acf5e2251073fd8458
theme716/small-routine
/insect/6.six_day/1.bs4_demo.py
3,744
3.65625
4
from bs4 import BeautifulSoup import re html = ''' <html><head><title>The Dormouse's story</title></head> <body> <p class="title" id="p1"><b>The Dormouse's story</b><b>----2b</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="siste...
cbbd325bd3d1b090e9497e7dcf8e484cd0ce89bf
theme716/small-routine
/ClassicalProject/在线选菜谱.py
1,412
3.9375
4
# 菜谱在线选择系统 def caipu(): x = int(input("请输入您要选择的套餐,回复相应的数字进行查看\n" "0----》退出\n" "1----》套餐一\n" "2----》套餐二\n" "3----》套餐三\n")) if x == 1: print("红烧茄子+米饭\n") elif x == 2: print("鱼香肉丝+馒头\n") elif x == 3: print("包子豆浆...
b42198b9ebc16ba93a91a03d80fa6c5756298e62
CeciliaHelen/desafio-summer-job-Navi-Capital
/Questao_02.py
853
3.984375
4
#Questão 02 import math #função de preenchimento do vetor x def fillVector(vector): #criação for i in range (0,10): if(i % 2 == 0): pair = (3**i) + (7*math.factorial(i)) vector.append(pair) else: odd = (2**i) + (4*math.log(i)) vector.append(odd) #função de cálculo da ...
0fefb18aafc44a4664d431341ad5be7bc2a060fc
Krish4U2/ROS-course
/week2/src/scripts/server.py
1,872
3.5625
4
#!/usr/bin/env python3 import matplotlib.pyplot as plt from pickle import TRUE import rospy import numpy as np from week2.srv import values, valuesResponse class Unicycle: def __init__(self, x: float, y: float, theta: float): self.x = x self.y = y self.theta = theta ...
52ac59f0022893a3af984af178e5507abb287671
trevinwisaksana/Data-Structures
/source/search.py
4,878
4.3125
4
#!python from __future__ import print_function def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests ...
6f9f456f5dfdd490e99337c63b6344fa43d13a1e
D-kavinya/python-programs
/even_odd_list.py
307
4.03125
4
list1=[] list2=[] def sequence(n): while n != 1: if n%2 == 0:# n is even list1.append(n) n-=1 else: # n is odd list2.append(n) n-=1 return(list1,list2) print("even and odd numbers from {} to n are".format(2),sequence(100))
9244f7ebc826c208aaed4cf698b442202515e203
dianaarnos/studies
/python/thinking-python/src/04/mypolygon.py
770
3.84375
4
import turtle import math def draw_lines(turtle, steps, step_angle, step_length): for i in range (int(steps)): turtle.lt(step_angle) turtle.fd(step_length) def polygon(turtle, length, sides): draw_lines(turtle, sides, (360 / sides), length) def square(turtle, side_length): polygon(turtle,...
ecedc264b64153bec0276ec7bd8146a1ce20094d
bigbob004/yandex-algos-training
/2nd_homework/G. Наибольшее произведение двух чисел/main.py
544
3.65625
4
def search_first_and_second_positive_max(lst): max1 = max2 = lst[1] for i in range(1, len(lst)): if lst[i] > max1: max2 = max1 max1 = lst[i] if lst[i] > max2: max2 = lst[i] return (max2, max1) def search_first_and_second_negative_max(lst): max1 = max2...
58d28df374fbcd34b2370a170288ececfb88d96e
Actimia/phoebix-hn
/src/testing.py
1,440
3.515625
4
import random import math tree = [ [ [], [ [ [[[[], [], []]]] ], [] ], [] ], [ [], [] ], [], [], [] ] def randomTree(level=0): maximum = 8 - (2 * level) if max...
836920d244e22cad6671f12c36c6f4cb16562ef6
antonio-abrantes/Neps_Academy-Python
/bondinho.py
126
3.671875
4
a = int(input()) m = int(input()) if(a < 1) or (m < 1): print("N") elif(a + m) > 50: print("N") else: print("S")
778472f655990800a7aade5673e35f5100e0dcee
antonio-abrantes/Neps_Academy-Python
/raizes.py
125
3.6875
4
import math qtd = int(input()) lista = input().split() for num in lista: print("{:.4f}".format(math.sqrt(float(num))))
6a209b29e280a40288b3f3a40f081ea971a24a07
davcheng/tree
/pytree.py
4,710
3.59375
4
#!/usr/bin/env python3 import subprocess import sys # YOUR CODE GOES here from sys import argv import os from os import path import re count_dict = {'dir_count': 0, 'file_count': 0} folder_dict = {} indent_count = 0 indent_of_indent_count = 0 def main(): # check if there are no arguments if len(sys.argv) ==...
f2f6dcf98da276c5b8042a56f4f6f215f9f8bb4e
klittlepage/aoc2020
/aoc/common/helpers.py
318
3.578125
4
from typing import Iterator, List, IO def read_chunked(input_file: IO) -> Iterator[List[str]]: chunk: List[str] = list() for line in input_file: if line == '\n': yield chunk chunk = list() else: chunk.append(line.strip()) if chunk: yield chunk
83e41f90abe6db66461dbf1e968f98b7076c812a
walxc1218/git
/ab.py
531
3.640625
4
a = 1 while a <=100: print(a) a += 1 while语句嵌套 while语句本身是语句 和其他语句一样,可以嵌套到任何的复合语句当中 while 真值表达式1: while 练习: 输入一个数,打印指定的宽度的正方形 输入正方形宽度:5 12345 12345 12345 12345 12345 宽度为 3 123 123 123 #输入一个数,来指定正方形宽度w w = int(input("请输入正方形的宽度:")) # 打印一行从1到w的数 i =1 while i <= w: print(i,end = "") i += 1
23e7503f403de0674ecd0de60f71232fc24ab076
toqueteos/aoc
/2017/day07.py
3,719
3.90625
4
import collections example_input = ( "pbga (66)", "xhth (57)", "ebii (61)", "havc (66)", "ktlj (57)", "fwft (72) -> ktlj, cntj, xhth", "qoyq (66)", "padx (45) -> pbga, havc, qoyq", "tknk (41) -> ugml, padx, fwft", "jptl (61)", "ugml (68) -> gyxo, ebii, jptl", "gyxo (61)"...
79926c372352f01844c5e50aa0cf513810135c62
toqueteos/aoc
/2017/day06.py
1,756
3.625
4
class Day06(object): def __init__(self, puzzle_input): self.steps = 0 self.seen = set() self.when = dict() self._run(puzzle_input) def _run(self, puzzle_input): self._save(puzzle_input) while True: idx = self._find_largest_bank(puzzle_input) ...
1f99bc10dd9a3e982dcab85b4d40d0f708e6d9d6
jm824/RiverLevelsANN
/scripts/KML/gauge_stations_to_kml.py
1,766
3.609375
4
import csv import os from xml.etree import ElementTree """ One time script to take the locations of each river gauge stations and plot them in KML. This script only needs to be run once. This reads data from a static file and creates a static kml file in return. This file can be read straight into Google Earth """ d...
36e7fb7b862e12aa87e215453b3d86c0f6125236
MrRusss/UData
/test1/matrix.py
209
3.546875
4
import random n = int(input('number')) m = [] for i in range(n): m.append([]) for j in range(n): m[i].append(random.randint(1,10)) for r in m: print(m) def gauss(n): for i in range(n):
bd66cc04dc1a6388395f4bab9c81b5bc36253703
ShlomiRosh/DatabaseProject
/Ui/OverViewButtons.py
1,797
4.1875
4
from tkinter import * import tkinter as tk FONT_NOTE = ("Ariel", 10, "bold", "underline") # This class is basically a tool that creates a cool display window for the user, when the # user moves the mouse to a specified place he will be able to read the particular message according # to the needs of the app. class Too...
df5be23195306dcff39d09aaf7a352bdd98b8838
matildasmeds/python_practice
/day_one.py
1,038
3.515625
4
import requests API_URL = "https://api.github.com/search/repositories" def create_query(languages): query = "stars:>50000 " for language in languages: query += f"language:{language} " return query def repos_with_most_stars(languages): params = { "q": create_query(languages), ...
026d6f0ad3da4ce63e66780611e920195651c5d5
distrib-dyn-modeling/sabaody
/sabaody/scripts/benchmarks/biopredyn/b1/get_param_name.py
342
3.546875
4
# Sabaody # Copyright 2018 Shaik Asifullah and J Kyle Medley import argparse parser = argparse.ArgumentParser(description='Get the name of a parameter.') parser.add_argument('index', type=int, help='The parameter index.') args = parser.parse_args() from params import param_index_to_name_map print...
80cad7e2e992c4ce854ce98b1ca1368e9d2b939a
Moarram/snek
/snek.py
8,086
4.0625
4
import pygame import random as r UNIT = 70 # size of individual square in pixels COUNT_W = 10 # width in units COUNT_H = 10 # height in units FONT_SIZE = 20 FRAMERATE = 60 # frames per second SPEED = 20 # number of frames between movement (greater than 0) TAIL_GROWTH = 5 # increase in tail length for each food eaten ...
0924efb91a858289e80d87b13a27db7fc7c07116
zhou1224271/python-homework
/python/sublist/sublist.py
1,242
3.65625
4
SUBLIST = 1 SUPERLIST =2 EQUAL = 3 UNEQUAL = 4 def check_lists(first_list, second_list): len_first_str = len(first_list) len_second_str = len(second_list) if len_first_str == 0 and len_second_str != 0: return SUBLIST elif len_first_str != 0 and len_second_str == 0: return SUPERLIST ...
eb4edc7af778b67c049f08e7e77d5e230f6d8ad8
CarlMears/covid-plotting
/covid_counties.py
10,100
3.90625
4
import matplotlib.pyplot as plt import datetime import numpy as np import csv import urllib.request import io def smooth(x,window_len=11,window='hanning'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is ...
403446432ceef125d82020eef1e0b71543cf6ce6
five510/atcoder
/20190810/main_c.py
557
3.5
4
import math N = int(input()) sorted_map = {} def combinations_count(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r)) for i in range(N): inserted_flag = True input_sorted = ''.join(sorted(input())) if input_sorted in sorted_map.keys(): sorted_map[input_sorted] += 1...
7a4f912eb842ede693c25cc0f12caf39fa5b1d5c
five510/atcoder
/20200502/main_a.py
357
3.578125
4
def read_int(): return int(input()) def read_int_map(): return map(int,input().split(' ')) def read_int_list(): return list(map(int,input().split(' '))) def read_s_list_loop(n): return [input() for _ in range(n)] K = read_int() A,B = read_int_map() for i in range(A,B+1): if i%K == 0: pr...
b030cb642a13fac86919d0f2042b0adfad794e8b
five510/atcoder
/20200502/main_d.py
467
3.734375
4
def read_int(): return int(input()) def read_int_map(): return map(int,input().split(' ')) def read_int_list(): return list(map(int,input().split(' '))) def read_s_list_loop(n): return [input() for _ in range(n)] import math A,B,N = read_int_map() if N < B: print(math.floor(A*N/B)-A*math.floor(N...
cdf73768ce953e7d14a46295d067bc9150dbcb2c
five510/atcoder
/20200426/main_c.py
297
3.625
4
def read_int(): return int(input()) def read_int_map(): return map(int,input().split(' ')) def read_int_list(): return list(map(int,input().split(' '))) def read_s_list_loop(n): return [input() for _ in range(n)] N = read_int() Sn = {input() for _ in range(N)} print(len(Sn))
f4a0479b2889c6f0c32dcbdb324d63b615b2e1aa
five510/atcoder
/20200216/main_b.py
182
3.671875
4
N = int(input()) An = list(map(int, input().split(' '))) for a in An: if ( a%2 == 0 ) and not( a%3 == 0 or a%5 == 0 ): print('DENIED') exit(0) print('APPROVED')
d58f739b8de2203b2d3b3f3d368ea09fb3fd392b
alaw1290/advent2018
/day13/day13.py
2,262
3.65625
4
# day 13 challenge # assumptions: # all tracks are in loops (each "/" will have a corresponding "\") # intersections are all "+" (no three ways) # loops can be represented in 1D (0th index is the top left corner of a loop) # intersections can be represented as a point along the 1D loop (linking to one other loop) ...
fa3df86d646d5e60643d748c2f5f8aaca4374ff5
Alohasprit/TIL
/2_Machine_Learning/9_SKT Machine Learning III/Code/script16_nonlinreg.py
4,015
3.515625
4
# libraries import numpy as np import scipy as sp import scipy.stats import pandas as pd import matplotlib.pyplot as plt # read data df = pd.read_csv('data06_wage.csv') X = df[['age']] y = df['wage'] xtrain = X[df['year']<=2005] ytrain = y[df['year']<=2005] xtest = X[df['year']>2005] ytest = y[df['year']>2005] # scat...
4f3b690fd4e22cdc73fa8a9b329c9e0a399801e7
pulkitt15/find-ddos-attack-source
/interface.py
550
3.5
4
from network import * v = input("Enter number of nodes: ") k = input("Enter agent density (in percentage): ") d = input("Enter number of attacker nodes: ") n = input("Enter number of attacks: ") t = input("Enter threshold: ") v=int(v) k = float(k) k = (100+k-1)//k d=int(d) n=int(n) t=float(t) g = grid(v,d,k,n,t) g.i...
c7c42881ce8ced9108b424a84f9a522e91f23f6d
JinshanJia/leetcode-python
/+Surrounded Regions.py
2,082
3.921875
4
__author__ = 'Jia' ''' Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X ''' impo...
78361575c974dcbc31cae00646be60ecc79a02ed
JinshanJia/leetcode-python
/Sudoku Solver.py
2,518
3.734375
4
__author__ = 'Jia' ''' Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. ''' class Solution: # @param board, a 9x9 2D array # Solve the Sudoku by modifying the input board in-place. ...
918d5f0b1d5c4de871bcb4cc23fbd5b731c5e1e5
JinshanJia/leetcode-python
/Search in Rotated Sorted Array II.py
1,584
4.09375
4
__author__ = 'Jia' ''' Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. ''' class Solution: # @param A a list of integers # @param target an integer # @re...
25b229601c4cd4aee77770014654f3ff62e1f051
JinshanJia/leetcode-python
/+Trapping Rain Water.py
1,453
3.578125
4
__author__ = 'Jia' ''' Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. ''' class Solution: # @param A, a list of integers # @return an integer def t...
76e9a289d2602c22dc659d50130d11611377bc35
JinshanJia/leetcode-python
/Merge k Sorted Lists.py
1,870
3.96875
4
__author__ = 'Jia' ''' Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. ''' import collections # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param a list of ListNod...
1bcca143a7d73608a5551b4dae4cd4659ce22ebb
JinshanJia/leetcode-python
/Container With Most Water.py
1,129
3.75
4
__author__ = 'Jia' ''' Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most wa...
f37ab9d76de588fc4d9427fc604fa62211eaf7bf
JinshanJia/leetcode-python
/Permutations II.py
1,141
3.765625
4
__author__ = 'Jia' ''' Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. ''' class Solution: # @param num, a list of integer # @return a list of lists of integers ...
8992a9b2ce5c95b204432df9b31c7bf9649dce88
JinshanJia/leetcode-python
/Construct Binary Tree from Preorder and Inorder Traversal.py
1,832
3.9375
4
__author__ = 'Jia' ''' Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. ''' # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ...
e363c14bd86fb7fa3ad1297989babbbcdc29dbc5
JinshanJia/leetcode-python
/Best Time to Buy and Sell Stock.py
699
3.59375
4
__author__ = 'Jia' ''' Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. ''' class Solution: # @param prices, a list o...
629d1df261758c1fe456c2b5784e3011dbf8345b
JinshanJia/leetcode-python
/Maximum Subarray.py
1,740
3.984375
4
__author__ = 'Jia' ''' Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. More practice: If you have figured out the O(n) solution, try coding another...
c3aa5f62fe2afb1a8375b9f2aa2d166b0335c6bf
JinshanJia/leetcode-python
/+Best Time to Buy and Sell Stock III.py
1,079
3.59375
4
__author__ = 'Jia' ''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again...
3421497ba049ccf3571fde5969b55c1f7d3892d1
JinshanJia/leetcode-python
/Sort Colors.py
1,325
4.15625
4
__author__ = 'Jia' ''' Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to...
a1a37273c26954f5b95d203930c65d1e889d29f8
JinshanJia/leetcode-python
/Generate Parentheses.py
1,127
3.75
4
__author__ = 'Jia' ''' Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" ''' class Solution: # @param an integer # @return a list of string def generateParen...
6f83590ba68c63fc115bcae399a0f52703fd10c5
JinshanJia/leetcode-python
/+First Missing Positive.py
853
3.78125
4
__author__ = 'Jia' ''' Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. ''' class Solution: # @param A, a list of integers # @return an integer def firstMi...
0d279e522eacd832d3332dd7290fbb80ba22ae0d
I-Atlas/COP-Population-Dynamics
/src/utils_ising_model.py
850
3.546875
4
import numpy as np from numba import njit, bool_ @njit def choice(p: float) -> bool: """Because np.random.choice is horribly slow we write our own. Fastest implementation I could think of to do a fast weighted bool choice""" if np.random.random() > p: return False else: return True # We...
b159c3ea653505ef71fcee1094bf691efe7a0339
davld-R/FrameWorks_8A
/scrips_python/Race.py
709
3.71875
4
''' Se requiere un Script en python que permita simular el juego de carrera numérica con dos players. La carrera inicia en la posición CERO y finaliza en la posición 100. El juego se realiza por default con 2 jugadores. EL juego que llegue primero a la meta (Posición 100 será el ganador) Si un jugador genera 3 pares co...
4d1ff595fe2ac51be8b21688c279b23de2f003bc
SarbjitGahra/movie_recommendations
/movie_recommend_improved.py
864
3.546875
4
#importing dependcies from bs4 import BeautifulSoup as soup from urllib2 import urlopen import csv mydatasaved='' # the url to be crawled my_url='https://www.rottentomatoes.com/' #using urlopen to open and read the url client=urlopen(my_url) page = client.read() client.close() #The file to be outputted to filename="...
bcbfe1491416edefef8eaf45914471b8dc5e681a
tchartchke/Exercism
/python/perfect-numbers/perfect_numbers.py
446
3.78125
4
def classify(number): if number <= 0: raise ValueError("Invalid number") if number == 1: return "deficient" num = number s = 1 div = 2 while num > div: if number % div == 0: num = number//div s += (div + num) div += 1 if s == number: return "perfect" if s >...
4c3349afca705b2996c47d0fb5831cf3ba94faad
yothinix/Budget
/Budget.py
2,674
3.609375
4
import calendar import datetime import unittest def get_total_day_from(start, end): days_in_period = end - start first_day_of_period = datetime.timedelta(days=1) return (days_in_period + first_day_of_period).days def get_days_of_month(date): _, days_in_month = calendar.monthrange(date.year, date.mon...
9abb0304283d772fec4dc149bf238964089f95a3
AlbertMukhammadiev/NumericalAnalysis_Labworks
/Cauchy_problem/methods.py
5,004
3.953125
4
"""Tool for solving the first-order ODE(y' = f(x, y)) by various algorithms. Functions: finite_differences(ys, m) -> ndarray supremum_abs(func, min_x, max_x, min_y, max_y) -> float Runge_Kutta(func, x0, y0, h, nsteps) -> tuple(ndarray, ndarray) Euler(func, x0, y0, h, nsteps) -> tuple(ndarray, ndarray, ...
b900b5b0677ab9610a1dc7dd9a9d72f9469ad3f3
eigenmatrix/kilogram_redefined
/ripple_adder.py
786
3.578125
4
def adder(data): a, b, c = data[0], data[1], data[2] sum = a + b + carry if sum > 10: out = sum - 10 carry_out = 1 elif sum == 10: out = 0 carry_out = 1 else: out = sum carry_out = 0 return [out, carry_out] a = [1,2,4,5,4,3,2,1,5,5,4,3,2] b = [6...
f7bfe031622273f72201c7f81d76c1909191b066
Daria-Lytvynenko/homework23
/homework23.py
1,396
3.859375
4
from typing import Union # task 1 def to_power(x: Union[int, float], exp: int) -> Union[int, float]: if exp == 0: powered = 1.0 elif exp == 1: powered = x else: powered = x * (to_power(x, exp - 1)) return powered # task 2 def is_palindrome(looking_str: str, ind...
6cb187a80c1067ee28b5abd65cccf19322936698
Mrsth/vehicle-counting-system
/confidence_plot.py
3,237
3.59375
4
import pandas as pd import matplotlib.pyplot as plt import statistics as st df = pd.read_csv('confidence_plot.csv') bike = df.loc[df["Type"]=="motorbike"] car = df.loc[df["Type"]=="car"] bus = df.loc[df["Type"]=="bus"] truck = df.loc[df["Type"]=="truck"] cycle = df.loc[df["Type"]=="bicycle"] #print(bike[...
81c4fe89122bdde2827ce1954559784a34cb3986
jerin17/AdvancedPython
/Functional Programming/reduce.py
180
3.84375
4
from functools import reduce list1 = [1, 2, 3] def accumulator(acc, item): print(acc, item) return acc + item new_list = reduce(accumulator, list1, 0) print(new_list)
27b5046f83fc4c7e3db5c1c3480b212da41e80f0
jerin17/AdvancedPython
/Functional Programming/lambda.py
349
4
4
list1 = [1, 2, 3] new_list = list(map(lambda x: x*2, list1)) print(new_list) print(list1) print() list2 = [5, 4, 3] new_list = list(map(lambda x: x**2, list2)) print(new_list) print(list2) print() list3 = [(0, 2), (4, 3), (9, 9), (10, -1)] list3.sort(key=lambda x: x[1]) # new_list = list(map(lambda x: x**2, list2)) #...
187ab73ae2885085a2623a5c18f26da3cc32a058
Nenu1985/PythonHomework
/3.py
2,510
4.0625
4
""" Docstrings may compare list's instead of sets because of sets are unsortable and can't be equal to the docstring literals """ from functools import reduce import itertools import string from collections import Counter test_strings = ["hello", "world", "python", ] def test_1_1(*strings): """ characters t...
296f1b95a9b234ee44a6b24557a515464777823a
Nenu1985/PythonHomework
/leetcode/two_sums.py
391
3.5625
4
from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hash_keys = {} for idx, num in enumerate(nums): if target - num in hash_keys: print(hash_keys[target - num], idx) else: hash_keys[num] = id...
b7fc3e475a61815a21a16c76f3769edc042b59d5
Aayush360/Shamshad_Ansari_CV_ANN
/list_2_3.py
486
3.59375
4
# Drawing a line in an image from __future__ import print_function import cv2 # image path image_path = '../images/test.jpg' # read or load image from its path image = cv2.imread(image_path) # set start and end coordinates start = (0,0) end = (image.shape[1], image.shape[0]) # set the color in BGR color = (255,0,...
479b13aa0cb9ff90e8000450fa9aa43ca97f03cf
Aayush360/Shamshad_Ansari_CV_ANN
/list_2_2.py
464
3.515625
4
# Description: # access and manipulate image pixels from __future__ import print_function import cv2 # image path image_path = '../images/test.jpg' # read or load image from its path image = cv2.imread(image_path) # access pixel at (0,0) location (b,g,r) = image[0][0] print('Blue, Green and Red value at 0,0 is',...
e38a9948d33b3006adc2a7a9a933a5445fcf2b5d
Aayush360/Shamshad_Ansari_CV_ANN
/list_4_3.py
967
3.6875
4
# histogram equalization: to adjust contrast of the image import cv2 import numpy as np import matplotlib.pyplot as plt # read the image and convert to grayscale image = cv2.imread('../images/Lenna.png') image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("original grayscale image", image) # calculate the...
81613579eef0fcc5c4b2c0f262a4fcff831c68af
Aayush360/Shamshad_Ansari_CV_ANN
/list_3_10.py
574
3.59375
4
# splitting and merging channels # these techniques are useful to perform feature engineering import cv2 import numpy as np # load the image nature = cv2.imread('../images/nature.jpg') # split the images into component color (b,g,r) = cv2.split(nature) # show the blur image cv2.imshow("blue image", b) cv2.waitK...
a6435b7d69387540ddf70702519e981dfd3b71b2
andersonf007/Recursividade-Python
/6 - inverte - RECURSIVA.py
169
3.984375
4
#Inversão de uma string de caracteres def inverte(s): if len(s) == 1: return 0 else: return inverte(s[1:len(s)]) + s[0] print(inverte('casa'))
0d0cb3e65376a73cdf24ea9d41a0596504993d85
YorickDong/python_crash_course
/unit_6.py
1,254
3.578125
4
alien_0 = {'color':'green', 'points':5} print(alien_0['color']) print(alien_0['points']) alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) alien_1 = {} alien_1['color'] = 'red' alien_1['points'] = 10 print(alien_1) alien_1['color'] = 'yellow' #在已有键值对的情况 再次赋值,就是修改。 print(alien_1) print(...
833526ce339e8684756d69079b9936c1819539cc
Marlysson/HackerRank
/Algorithms/Warmup/staircase.py
311
3.90625
4
# -*- coding : utf8 -*- # Challenge : https://www.hackerrank.com/challenges/staircase """ # ## ### #### ##### ###### """ altura = int(input("Altura da figura: ")) nao_preenchidos = altura - 1 preenchidos = 1 for i in range(altura): print( (nao_preenchidos - i)*" " + (preenchidos + i)*"#")
a962970f706e96f55f1a0cb16bd4e69dc2160190
Andrew-Onishchenko/python_language
/students/km63/Onishhenko_Andrij/hw_2.py
10,757
3.625
4
#task1------------------------------------------------------------ """ Дано два цілих числа. Вивести найменше з них. """ a=int(input()) b=int(input()) if a>b: print(b) else: print(a) #--------------...
cf49518243e84ab71b94f910f45fe50db988cf92
elecheung/algorithm_python
/1003번(practice).py
208
3.703125
4
def fibonachi(n): a={ 0 : 0, 1 : 1, 2 : 1 } if n<=1: return n if n not in a: b= a[n-1] +a[n-2] a[n]=b return fibonachi(n-1)+fibonachi(n-2) a=fibonachi(int(input())) print(a)
0532db7ada1c70649ac314994f9b311fd341fff8
liuqi0725/Python3-OOP-Notes
/chapters/chapter3/example/MultipleExtend.py
4,272
3.515625
4
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # @File : Property.py # @Created : 2020/8/17 4:31 下午 # @Software : PyCharm # # @Author : Liu.Qi # @Contact : liuqi_0725@aliyun.com # # @Desc : 多继承 # ---------------------------------------------------...
cf8adaff1db328a02296aea8f1123f341badd6b7
Shrekinator19/unit3_lesson17_lesson18
/bootlegpokemon2.py
4,038
3.734375
4
import time import random print() print('A wild Jigglypuff appears!') time.sleep(0.2) print('You only have one pokemon, Snorlax.') time.sleep(0.2) print('I choose you, Snorlax!!!!!') print() time.sleep(0.2) # Starting HPs snorlax_hp = 200 jiggly_hp = 125 #Print out the starting HP: print('Original HP:') time.sleep(...
cc6277f2188d3353cde69489df12d5e4e9993bc4
Lemonchasers/msds510
/src/msds510/util.py
1,340
3.703125
4
# 4a import datetime numbers = "0123456789" def get_month(input1): """The get_month function takes an argument and returns the numerical month.""" if input1[0] in numbers: month_number = datetime.datetime.strptime(input1, '%d-%b').month print(month_number) else: month_number = dat...
44ec670fc708a165f482cdd8c8845fee784c9b1a
Deepthi-Rao/CSC495
/Project2/utils/queue.py
580
4.09375
4
from collections import deque import threading #This is the Queue class class Queue: #this initializes the queue object def __init__(self): self.queue = deque([]) #this enqueues an element to the end of the list def enqueue(self, element): self.queue.append(element) #this dequeu...
3838e50c27764f3e2f7046397fe5fa5d84c0de07
khalidammarmo/python-cs
/pal/pal-2.py
281
3.734375
4
def pal_recur(test): if len(test) == 1: return True elif len(test) == 2: return test[0] == test[-1] else: if test[0] == test[-1]: return pal_recur(test[1:-1]) else: return False print(pal_recur("somanydynamos"))
d4ff5fba8aa0e81e856834905354db70cd00d2de
khalidammarmo/python-cs
/crypt/crypt-1.py
1,574
4.25
4
#A simple substitution encryption using alphabet strings import string import sys #Hey, a new module! args = sys.argv try: shift_count = int(sys.argv[1]) except: shift_count = 0 try: phrase_to_encrypt = sys.argv[2] except IndexError: print("No phrase given!") exit() lowers = string.ascii_lowercase ...
72bb535bc28f59759b72071512f3a137901c3224
khalidammarmo/python-cs
/mult/mult-1.py
292
4.5625
5
""" Here we'll create a simple program that multiplies two numbers together. """ #Assign the values to the numbers x = 5 y = 3 #We need a place to store our product product = 0 #Now we take those two numbers and feed them through a loop for i in range(x): product += y print(product)
1864b4e80507a98a83b954ffb91dca0f9673d34f
nGreg72/learning
/checkio/even the last.py
1,786
4.1875
4
"""Дан массив целых чисел. Нужно найти сумму элементов с четными индексами (0-й, 2-й, 4-й итд), затем перемножить эту сумму и последний элемент исходного массива. Не забудьте, что первый элемент массива имеет индекс 0. Для пустого массива результат всегда 0 (ноль). Входные данные: Список (list) целых чисел (int). Выход...
0d0ec3107c9be91c44ce9b8d44c79ed61da104c8
TestowanieAutomatyczneUG/laboratorium-7-maciej-witkowski
/src/sample/zad1.py
306
3.71875
4
class Hamming: def distance(self, a, b): if len(a) == len(b): count = 0 for i in range(len(a)): if a[i] != b[i]: count += 1 return count else: raise ValueError("Invalid length of a string or b string")
c1ed7d2c608bf65786a0fa6058eb8a0de9d75eeb
jeeHwon/Algorithm
/basic/datatype.py
2,889
3.875
4
# ==========================실수형========================== # 실수형 오차 발생 문제 a = 0.3 + 0.6 print(a) if a == 0.9: print(True) else: print(False) print('*'*30) # round 함수 활용 a = 0.3 + 0.6 print(round(a,4)) if round(a,4) == 0.9: print(True) else: print(False) print('*'*30) # 나누기 연산자 / : 실수형 # 나머지 연산자 % # 몫...
556179ac9e18b9fc2c8f5f5f36197febb5cbffc5
jeeHwon/Algorithm
/practice/baek10/2447.py
619
3.640625
4
def out_star(n): global graph if n == 3: graph[0][:3] = [1]*3 graph[1][:3] = [1,0,1] graph[2][:3] = [1]*3 return tmp = n//3 out_star(n//3) for i in range(3): for j in range(3): if i == 1 and j == 1: continue for ...
4151e07d060794a8ca748a39c95785a81491e94c
Lanceconan/data-science-python
/codigo-utilitario/script.py
629
3.65625
4
# -*- coding: utf-8 -*- """ Formato de Script de python Para ejecutar python script.py argumento1, argumento2, argumento3, ..., argumenton @autor Daniel Gutiérrez """ import sys # Importar los argumentos brindados al script def parseArguments(): arguments = sys.argv[1:] return arguments # Método princip...
dcc6beab0a83069d8abe73ef079b0ce099d9df9b
Lanceconan/data-science-python
/CursoDeepLearning/declareIf.py
201
3.609375
4
import numpy as np from numpy.random import randn answer = None x = randn() if x < 1: answer = "Mayor que 1" print(answer) else: answer = "Menor o igual que 1" print(answer)
c8065fd0718da966490e124d8fde57985b6bbc8d
ciszakdamian/cdv_interface_api
/09-11-2019/1/4.py
361
3.84375
4
import math def pole_kola(r): pole = round(math.pi * math.pow(r, 2), 3) return pole def obwod_kola(r): obwod = round(2 * math.pi * r, 3) return obwod r = input('Podaj promien kola: ') print('Pole kola o promieniu ' +str(r)+ 'wynosi: ' + str(pole_kola(int(r)))) print('Obwod kola o promieniu ' +str(r...
b9c0f59699d4deb9089f2f30ba27223b5333cfa6
VivekRedD1999/Python_Datastructures
/StackImplementation.py
631
4.125
4
class stack(object): def __init__(self): self.items=[] def isempty(self): return self.items==[] def push(self,item): self.items.append(item) return item def peek(self): return self.items[len(self.items)-1] def pop(self): return self.items.pop() def...
2ed0c75e621cbc5c9b6bcd4139eddeafd4c1721f
foolkevin/CodeInterviews
/Offer12.py
1,731
3.765625
4
class Solution: def __init__(self): self.row, self.columns = 0, 0 self.wordlen = 0 self.record = None self.index = 0 def exist(self, board, word) -> bool: if len(board) == 0 or len(word) == 0: return False self.index = 0 self.rows, self.column...
f59c0fd7ab0f0820aba3c90ace6548e05078bdcc
foolkevin/CodeInterviews
/Offer21.py
1,236
3.78125
4
class Solution: def exchange(self, nums): pointer1, pointer2, n = 0, 0, len(nums) while pointer1 < n and pointer2 < n: while (nums[pointer2] & 1 == 0 or pointer2 <= pointer1): pointer2 += 1 if (pointer2 >= n): return nums wh...
6e8a896e626340bfa384ee0efbad4b199130c2ed
foolkevin/CodeInterviews
/02_01.py
517
3.5
4
class ListNode: def __init__(self, val): self.val = val self.next = None class Solution: def removeDuplicateNodes(self, head: ListNode) -> ListNode: if head is None: return head valset = set([head.val]) pos = head while pos.next is not None: ...
0e2f10cca59de77bd3b3b06bd6069f155f27f8d9
foolkevin/CodeInterviews
/02_03.py
327
3.640625
4
class ListNode: def __init__(self, val): self.val = val self.next = None class Solution: def deleteNode(self, node): curr = node while curr.next.next is not None: curr.val = curr.next.val curr = curr.next curr.val = curr.next.val curr.next...
0ffb165928a37a7877c575ea173a1b86f8430a13
vladyslavnUA/CS-1.3
/trees/article.py
907
4.0625
4
def insert(self, item): if self.is_empty(): self.root = BinaryTreeNode(item) self.size += 1 return parent = self._find_parent_node_recursive(item, self.root) if parent == None: self.root.left = BinaryTreeNode(item) elif parent.d...
b83654b54b032f9110b3ece52fbe6135d737325e
aga-moj-nick/Python-List
/Exercise 014.py
329
4.125
4
# 14. Write a Python program to print the numbers of a specified list after removing even numbers from it. def bez_parzystych (lista): lista2 = [] for liczba in lista: if liczba % 2 != 0: lista2.append (liczba) return lista2 lista = [1, 2, 3, 4, 5, 6, 7, 8, 9] print (bez_parzystych ...
794e226b0dd5ecb9fb566979e2e1f77619fe5448
aga-moj-nick/Python-List
/Exercise 009.py
417
4.125
4
# 9. Write a Python program to clone or copy a list. # Sposób1: def kopiowanie (lista1): lista2 = [] for cyfra in lista1: if cyfra not in lista2: lista2.append (cyfra) return (lista2) lista1 = [1, 2, 3, 4, 5] print (kopiowanie (lista1)) # Sposób2: import copy lista1 = [1, 2, 3, 4, ...
18bd179d3f61443b836b26cb9045df6fed250cb8
JrenW/cs110
/book_mill_ranum/python/1.12_self_check.py
1,324
4.28125
4
### ### self check: random shakespear ### goal randomly generate 28 characters such that ### eventually return the goal string: ### "methinks it is like a weasel" from string import ascii_lowercase import random ## function 1: randomly generate a string of 28 characters from 26 letters plus the space # create a pool...
abf2c9903a5d8daff495ade54d258965a6e26908
nucfive/Python
/ex16_listExpression.py
340
4.0625
4
#列表白表达式 #取出一个列表中某些数据 一般做法 newList = ['魏如峰', '微软', '张鑫', '李霖', '李龙'] # emptyList = [] # for name in newList: # if name.startswith('李'): # emptyList.append(name) # print(emptyList) #第二种表达形式 print([name for name in newList if name.startswith('魏')])
aa8ff63923d26a6353dac66814fd9b94f2f5b991
nucfive/Python
/ex4_tuple.py
363
3.921875
4
#tuple(元组) 数据类型,不想让用户更改数据,tuple运算比较快 my_list = [1, 2, 3, 4, 5] my_tuple = (1, 2, 3, 4, 5, "wrf") print(type(my_list)) print(type(my_tuple)) print(len(my_list)) print(len(my_tuple)) print(my_list[0]) print(my_tuple[0]) # 取元组中的值 # print(dir(my_list)) # print("^^^^^^^^^^^^^^^^") # print(dir(my_tuple))
509f1e8fd6a0402990409f108e6ae9aaaf7cdeb0
deuzm/python_lab2
/serializer/test/utils.py
1,293
3.71875
4
import collections from math import pi def compare(x, y): return collections.Counter(x) == collections.Counter(y) def clear_func(x, y): return x + y z = 5 class Empty_cls: pass class ClsWithInheritance(Empty_cls): def __init__(self, x, y): self.x = x self....
a9c4bfb6d89aba04e80e146d16b48b486a777c71
PXPX11/algorithm009-class02
/Week_03/236.py
846
3.84375
4
#根据以上定义,若 rootroot 是 p, qp,q 的 最近公共祖先 ,则只可能为以下情况之一:p 和 q 在 rootroot 的子树中,且分列 root的 异侧(即分别在左、右子树中); p = root ,且 q 在root 的左或右子树中;q = root ,且 p 在root 的左或右子树中; # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ...
9634138db4d12b99d1e5d4f58940e322a29fe203
sayazamurai/todo-cli
/tasks/task2/todo.py
94
3.65625
4
print("Welcome to your todo list!") todo = input("Add a todo:\n") print(f"You added: {todo}")
ce088bd60777a26919cb7f8a1cfd9b5a2abb8c79
sayazamurai/todo-cli
/tasks/task6/todo.py
626
3.90625
4
print("Welcome to your todo list!") todo_list = [] todos_txt = open("todos.txt") while True: todos_readline = todos_txt.readline() if todos_readline: todos_readline_strip = todos_readline.strip() todo_list.append(todos_readline_strip) else: break todos_txt.close() def todo(): ...
0fae1f2bb3eb5783fd67255e9381febb506b9759
timnurm/Tesak
/tesak.py
674
4.03125
4
name = input('Как тебя зовут?: ') print(name + ", ты похож на пидораса") print(name + ', откуда ты?') city = input("Укажите ваше местоположение: ") print(city + '? ты третий пидорас из '+ city + ' которого я ловлю') print(name + ', хуй сосешь?') statuspidor = input('Да/нет: ') print(statuspidor + "?\nмы похожи на де...