blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0c96c5942b7825247bcf23e95e227c5d657db094
Ting-art/ML
/deep_learn_1.3.4_01.py
1,854
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 3 18:48:31 2019 @author: 清矿轩 """ #列表 a=[1,2,3,4,5]#创建列表 print(a)#输出列表的内容 print(len(a))#获取列表的长度 print(a[0])#访问列表的第一个值 a[4]=99#赋值 print(a) print(type(a)) print(a[0:2]) print(a[:3]) print(a[:-1]) #字典 me={'height':180}#生成字典 print(me['height'])#访问元素 me['weight']=70#添加新元素 prin...
7b81d427d8475a3860261a61478ef86711cd39cb
Zirmaxer/Python_learning
/Bitroot/Test9.1.3.py
1,347
4.1875
4
''' Напишіть клас TypeDecorators, який має різні методи конвертації результатів функцій у зазначений тип, якщо це неможливо – викликати відповідний виняток. Методи: to_int to_str to_bool to_float Не забувайте використовувати @wraps ''' from functools import wraps class TypeDecorators: pass def to_int(self):...
2c5de26a38a64d1c060531e4899f885b67946f5a
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/5c67ec82f571478f815c36ae838582cd.py
508
3.765625
4
__author__ = 'jetties' def _sanitize_input(phrase): """ Remove superfluous whitespace and newlines from the given input for easier processing. """ return str(phrase).strip() def word_count(phrase): """ Given a phrase, count the occurrences of each word in that phrase. :return: Map of word...
8362f2fb227de5688f6224775f7d119d4e4742fb
cvankerkhove/NBA-Model
/Webscraper-Python/user_functions.py
8,559
3.8125
4
""" File name: user_functions.py Description: This file contains the functions that provide user functionality with their input parameters. """ from NBA_Games import get_games from averages import Averages def get_averages(Team, Season, start = None, end = None): """ Creates and updates an abject of clas...
00b88a706b584ad17aba303524794c7f2d8d0319
ohcasta/AlgorithmsUN2021I
/Lab5/Flask_app/cifrador.py
3,428
3.546875
4
import random def gcd(x, y): while x!=y: if x>y: x = x - y else: y = y - x return x class CifradorRSA: def __init__(self): self.__list_primes = [2, 3, 5, 7, 11, 13] self.p = None self.q = None self.n = N...
64beeca1040a6f9666f6cbb8b3cdf0868fcc7ba8
StephenCatsamas/OATS
/builtIn.py
258
3.5
4
class INT(): def __init__(self): self.i = 0 def add(self, a,b): self.i = a+b return self.i def sub(self, a, b): self.i = a-b return self.i def set(self, a): self.i = a return self.i
e59e24fbb69fa51b5b28539555068164c24516e6
afranciax2/hackspace
/semana02/generador2.py
369
3.71875
4
# Función Generador que devuleve ciudades def devolver_ciudades(*ciudades): # * --> número indeterminado de argumentos for elemento in ciudades: #for subelemento in elemento: yield from elemento ciudades_devueltas = devolver_ciudades("Madrid", "Barcelona", "Lima", "Trujillo") print(next(ciuda...
befc91290065204e4ce5e63985bf8f30617e8873
Pelhans/leetcode
/jianzhi/40.py
754
3.625
4
#!/usr/bin/env python # coding=utf-8 # -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here if len(tinput) <= 0: return 0 if len(tinput) < k: return tinput min_k = ["inf" for i in range(k)] for i in tin...
780db6d7fc2b7828460bbcc5c1fc016e555bbd1c
fredy-prudente/python-brasil-exercicios
/Estrutura de Repetição/ex41.py
1,102
4
4
""" Faça um programa que receba o valor de uma dívida e mostre uma tabela com os seguintes dados: valor da dívida, valor dos juros, quantidade de parcelas e valor da parcela. """ juros = 0 valorparcela = 0 v = False divida = float(input('Digite o valor da dívida: R$')) parcelas = int(input('Quantidade de parcelas: ')) ...
75826135db929920bd27765c5a1fd41a1d4e6175
NHopewell/coding-practice-problems
/OOP/corey-ms/tutorial-3.py
1,198
3.78125
4
class Employee: num_of_employees = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.email = f"{first}.{last}@company.com" self.pay = pay Employee.num_of_employees += 1 def display_fullname(self): retu...
0336008740a520d3255a2a82ef9d0ca3da82d86c
kimhyeyun/2020-DataMining
/실습과제2/In[5].py
149
3.59375
4
import numpy as np x = np.array([2,4,6,8,10]) y = np.array([1,2,3,4,5]) print(x+y) print(x-y) print(x * y) print(x / y) print(x // y) print(x ** y)
be000cc939af25ac26f9cbd0076d9a4b4ac94678
RickXie747/UNSW-18S1-COMP9021-
/Lab1/5_ Drawing_pictures_with_turtle.py
1,070
4.09375
4
from turtle import * edge_length = 60 angle = 60 def draw_dodecagram(colour1,colour2): left(180 - angle) color('white') forward(edge_length) right(angle) for _ in range(3): color(colour1) forward(edge_length) right(180 - angle) forward(edge_length) color(...
10a06fdb2348bfdd38a6f6c6e648c939dbb777ec
davidtsu/SSW567A_HW04A
/gh.py
945
3.78125
4
""" HW04A @Author: David Tsu for fetching github data """ import requests def get_user(): ''' fetches username ''' g = input("Enter GitHub ID:").lower() return g def get_data(g): ''' fetches user repos ''' try: repo_url = f"https://api.github.com/users/{g}/repos" github_data = req...
acda54e639de203f40e183401c5119476f1c9025
prajapatisweta/python-program
/list_common_member.py
294
3.953125
4
# date 17/09/21 # Write a program that takes two lists and returns True if they have at least one # common member. list_1 = [4, 14, 24, 34, 44, 54, 64, 74] list_2 = [8, 18, 28, 38, 44, 58, 64, 74] for i in list_1: if i in list_2: print("True") break else: print("Flase")
4af42aff4a53a88072c320f20e4f8d88582cf88e
Castrol68/opencv-practice
/computer_version/facial_landmarks/sample/face_utils.py
423
3.5625
4
#!/usr/bin/env python3 # -*- coding=utf-8 -*- import numpy as np # 矩形到边框 def rect_to_bb(rect): x = rect.left() y = rect.top() w = rect.right() - x h = rect.bottom() - y return x, y, w, h def shape_to_np(shape, dtype="int"): coords = np.zeros((68, 2), dtype=dtype) for i ...
bc141e13cd98f3f9f30589085553d65513387aa6
Rosie96/Homework-Wd1
/HW_9.3. Make strings lower case.py
115
4.03125
4
#make a string lower case answer = str(input("Howdy, what would you like to tell me?")) print(answer.lower())
98ef4e1ba52d25cfecc8ab52efb194be4a9e5cbd
ekselan/Intro-Python-I
/class_II/rps2.py
2,077
4.46875
4
# Things that could be improved: # Make way the computer pick a choice smarter so that it # wins more consistently # Allow more choices other than rock, paper or scissors # Save the outcomes # Sanitize the user input: make it so that program can handle # shorthand, like "r" for rock # Be smarter about comparing us...
43b546201420072fd95bc2e331abaa13f6a5baaf
LiKevin/python
/Aglorithm/python_heapq_usage.py
1,017
3.875
4
#-*- coding: utf-8 -*- __author__ = 'k22li' # #需1求:给出N长的序列,求出TopK大的元素,使用小顶堆,heapq模块实现。 # import heapq import random class TopkHeap(object): def __init__(self, k): self.k = k self.data = [] def Push(self, elem): if len(self.data) < self.k: heapq.heappush(self.data, elem)...
842788cf899c3e819746c0b8f587bd69b24e16fa
viperk17/Practice_with_python3
/Calculate no of days, weeks or months.py
1,965
3.96875
4
# #script for monthly # #script for day # #script for week to pay the credit card bill # import datetime # import calendar # # balance = 5000 # interest_rate = 13* 0.1 # monthly_payment = 500 # # #write script to payoff the credit card bill # '''specify the dates''' # today = datetime.date.today() #today # # #how man...
a2a4bdb88f7cb2bbad68aa9f08f1f59b63983acd
ddzz/algorithms
/heaps.py
778
3.59375
4
# This algorithm calculates the sum of the rolling median of a # stream of integers. A min heap and max heap are used to reduce # the running time of the algorithm. from heapq import heappush, heappop arrayleft = [] arrayright = [] total = 0 array = [] for line in open('Median.txt', 'r').readlines(): array.ap...
89647cf3d4cec2a47dc7f1677ee95e1a2cca8dae
lllchen/python100daysscript
/09/lxfmetaclass.py
656
3.71875
4
#!/usr/bin/env python3 #-*- coding = utf-8 -*- ''' 廖雪峰元类练习 下面的-->代表“实例”关系,不是继承关系。 type-->int -->1 type-->Metaclass-->Commonclass type-->EnumMeta-->Enum or Customclass --> Customclass.__members__ 写代码的时候Customclass继承自Enum,type函数的结果显示Enum和Customclass都由EnumMeta“实例”而来, ''' __auther__ = 'BrilliantDawn' def fn(self,name...
150e7cb2cd0362ec818c440ea2ad86c7cb4959cb
Tvashta/cp
/Interview Practice/Medium/decodeStr.py
634
3.828125
4
# Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. # For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. # You can assume that the messages are decodable. For example, '001' is not allowed. def decode(s): if...
1ed53925b1288af5cc241cbcc0c4fcd19b2a1c7a
sindhuja2001/Best-Enlist-30-days-30-hours-Challenge
/Day 10/Ex 1 Day 10.py
1,075
4.5625
5
#1) To check a string that contains only a certain set of characters import re def check(string): A= re.compile(r'[^a-zA-Z0-9.]') string= A.search(string) return not bool(string) print(check("Apple1234")) #2) Check it matches a word 'ab' import re def A(text): pattern= '\w*ab\w*' if re.search(pa...
4c14656ab5eb34f458719775790e861e2dfdb9c4
MMVonnSeek/HacktoberFest2021-3
/Algorithms/Binary_Search python 3.py
1,658
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: def binary_search(arr,n): #Declaring Function named binary search start=0 #Creating a start end=len(arr) #Creating an end which will be the length of the list arr.sort() ...
5da600a0b914274192d8d17e193fd4fd4a0ffea2
simospirit/openstreetmap
/Unique_Users.py
721
4.03125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #identifying unique users contribute the to the map area: Melbouren, FL. """ Your task is to explore the data a bit more. The first task is a fun one - find out how many unique users have contributed to the map in this particular area! The function process_map should ...
33caef9deb50e665b310653dc0b72a245abbc33b
Oleh-Synytskyi/Course_WD
/Client.py
1,853
3.546875
4
import socket import threading import smtplib from tkinter import * import sys import os #Wait for incoming data from server #.decode is used to turn the message in bytes to a string def receive(socket, signal): while signal: try: data = socket.recv(2048) print(str(data.decode("ut...
5c2342e8dd13f69769c6ccbc7b0a8f79b4bd5f94
jnobre/lxmls-toolkit-2017
/solve.py
3,034
3.640625
4
''' This script solves the exercises of days that have been completed. Jut in case the students did not made it by their own. ''' import sys import urllib2 def download_and_replace(url, target_file): ''' Downloads file through http with progress report. Version by PabloG obtained in stack overflow ...
5ff1d82d889816863c7a2fe6efd7529a27dd6739
Aasthaengg/IBMdataset
/Python_codes/p03828/s531420550.py
1,004
3.609375
4
import math from collections import defaultdict N = int(input()) mod = 10 ** 9 + 7 ans = 1 # それぞれの因数となる素数の数をセットする dp = [0] * (N + 1) # 素因数分解する関数 def prime_factorize(n): divisors = [] # 27(2 * 2 * 7)の7を出すためにtemp使う temp = n for i in range(2, int(math.sqrt(n)) + 1): if temp % i == 0: c...
89680e9975fb34fad81e66a3a84b5dec2f72ae05
JohnReeves/quizzes-etc
/stars.py
643
3.96875
4
from turtle import * # turtle methods https://docs.python.org/3/library/turtle.html color('red', 'brown') shape("turtle") # a function to do the annoying penup/pendown etc # to move somewhere without drawing a line def moveto(xpos, ypos): penup() setpos(xpos,ypos) pendown() # a function for drawing stars, if y...
188e67d59baa23022614a84af6dc52262e7b5447
kunxin-chor/tgc-10-gitpod-demo
/revision.py
667
4.4375
4
print("Happy 2021!!!") # variables # integers, floats, booleans and strings secret_of_life = 42 gst_percentage = 0.07 sentence = "The quick brown fox jumps over the lazy dog" is_raining = True # BMI calculator # print is used for output print("2021 New Year Resolution BMI Calculator") weight = float(input("Please ent...
ce78fd440969b6d160e3cb56c209f2c8f61f5f93
tyiannak/inf_teiste_info_theory_lab
/example11.py
2,187
3.71875
4
import ITlib import string import sys import numpy def huffmanCodeFromFile(filePath): f = open(filePath) text = f.read().lower() f.close() text = ITlib.removeUnknownCharacters(text) # remove "unknown characters" counts = ITlib.getTextCounts(text) # generate histogram of charac...
10438e873b63709c65ce91ecf2e4d15d9459cb61
hajarlch/mundiapolis-math
/math/0x01-plotting/6-bars.py
806
3.640625
4
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt np.random.seed(5) fruit = np.random.randint(0, 20, (4,3)) index = ('Farrah', 'Fred', 'Felicia') width = 0.5 apples = fruit[0] bananas = fruit[1] oranges = fruit[2] peaches = fruit[3] plt.bar(index, apples, width, color='red', label='apples') p...
bc25cecef6d4ca479f4d094b482f714b83b9b2f5
Nithanaroy/PythonSnippets
/Intuit1.py
383
3.5
4
# Problem: 5 (in base 10) = 101 (in base 2). Invert 101 to 010 (in base 2) = 2 (in base 10) # Input: 5 # Output: 2 def getIntegerComplement(n): a = '' while (n > 0): a = str(abs(1 - (n % 2))) + a n /= 2 i = 1 num = 0 for j in xrange(len(a) - 1, -1, -1): num += i * int(a[j]) ...
4aaa180f0340444da9fdb0e1888ee2f3b074807b
10arturoV/curso-programacionATS
/calculadora aritmetica.py
833
4.03125
4
operacion = input("que operacion desea realizar? ") if operacion == "S" or operacion == "s": a = float(input("ingrese primer digito ")) b = float(input("ingrese primer digito ")) c = a + b print("la suma es "+str(c)) elif operacion == "R" or operacion == "r": a = float(input("ingrese primer digito ...
a0b6e82f4df6d4bc5c02a6e7a2a9cbaa59081ffb
alepeglow/Web-Scraping-in-Python
/weather_data.py
2,812
3.8125
4
import requests from bs4 import BeautifulSoup as bs import pandas as pd ''' * Download the web page containing the forecast. * Create a BeautifulSoup class to parse the page. * Find the div with id seven-day-forecast, and assign to seven_day * Inside seven_day, find each individual forecast item. * Extra...
0eae99ac7afe1aed3350b836ad4ff5e68983712b
nfredrik/kistapython
/LinkedList/linked_list.py
1,760
3.796875
4
from invariants import EnforceCheckRep class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) def print_backward(self): if self.next != None: tail = self.next tail.print_...
c7ee4e59c0098560e75d7d5adcb2866622b8ac3e
progresivoJS/LeetCode
/167. Two Sum II - Input array is sorted/binary-search.py
764
3.5625
4
class Solution: def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ solution = [] for i in range(len(numbers)): real_target = target - numbers[i] index = binary_search(numbers, i + 1, ...
ebefb750088c41cd5ee6faefbb4dd7f0820bffff
matheusmcz/Pythonaqui
/Aula07/ex015.py
278
3.875
4
# Aluguel de carro print('-' *5, 'ALUGUEL AUTOMOVEL', '-' *5) dias = int(input('QUantidade de dias alugados: ')) km = float(input('Quantidade de Km rodados:')) valordia = dias * 60 valorkm = km * 0.15 print('O valor a pagar será de R${:.2f}'.format(valordia + valorkm)) print('----' *8)
147e13fb9419fcdf2e142b583c0ec6233905cb15
SamuelSYLee/Elevator
/elevator.py
1,161
4.15625
4
from time import sleep current_floor = 5 # Current floor Lower = 1 # Upper floor Upper = 7 # Lower floor ask_flag = False # Floor-asking flag target_floor = 5 # Target floor while True: while (target_floor < Lower) or (target_floor > Upper) or (target_floor...
e3e0e254754210dbc429af96373d23038c41b8cf
benmega/tic-tac-toe
/main.py
2,307
3.515625
4
import tkinter as tk from tkinter import messagebox top = tk.Tk() turn = 'X' def button_press(j): global turn if turn == 'X': turn = 'O' else: turn = 'X' if str(buttonText[j].get()) == '': buttonText[j].set(turn) else: if turn == 'X': turn = 'O' ...
1517770b098427950c4825cb77ee9cd49d96201e
okaysidd/Interview_material
/June_challenge/Cheapest Flights Within K Stops.py
1,760
3.84375
4
""" Cheapest Flights Within K Stops There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w. Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If the...
309750872614dca86f01d98b8d20b5a73bbff53d
adv-py-geos/Easterwood_rain
/Easterwood_rain/plot_util.py
3,160
4
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from .regress import linreg def lin_plot(df, x, y): ''' Uses the linreg function from regress.py to produce the model_dict that contains the model, values, and variable names. Values fr...
e2e60367caae8c5310b1d0c6e6f4ae0f8dfa5542
jakoud/python_starters
/randomlists.py
785
3.734375
4
from random import randint N=int(input('podaj rozmiar tablicy: ')) tab=[] for value in range(N): tab.append(randint(1, 10)) print(tab) counter=0 for value in range(N-2): if (tab[value]<tab[value+1] and tab[value+1]>=tab[value+2]): counter+=1 print(counter) triplets=[0,0,0] for value in range(N-2...
a0a4a12beb533e5dffdde752da44e871c3649cd1
octomberr/RestockBot
/product_dict.py
2,337
3.8125
4
class Product: # Constructor def __init__(self): self.products = dict() # Initializing a new product def new_product(self, product_name): self.product_name = product_name self.products[product_name] = { 'Product URL': None, 'Product ID': None, ...
508df16fb9593b9f73c92d3729305173f416d86b
uabua/rosalind
/bioinformatics-stronghold/complementing-a-strand-of-dna/revc.py
728
4.0625
4
""" ID: REVC Title: Complementing a Strand of DNA URL: http://rosalind.info/problems/revc/ """ def reverse_complement_strand(dna): """ Finds the reverse complement of a dna. Args: dna (str): DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T'). Returns: str: the re...
757d2d66317841e1385759889c0e27faf8ac9a40
rgforge/sandbox
/calctest.py
3,755
4
4
#! /usr/bin/env python # Calculator def adding(): a = map(int,(input('Enter the numbers you would like to add seperated by spaces. ')).split()) a = (sum(a)) print('The answer is %d' % a) def subtracting(): x = int(input('Enter the first number to be subtracted from. ')) y = int(input('Enter the second num...
3cb8240dfc7bf7a9cb1318a711c4352461ff95cd
priyanshudasgupta8/Entire-Project-including-Results
/interpretingResults.py
1,610
3.71875
4
# IMPORT MODULES import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import plotly.express as px # READ THE CSV df = pd.read_csv("upgrade.csv") # MAKE LISTS OF GRAPH DATA FROM CSV star_names = df["star_names"].tolist() star_names.pop(0) star_mass = df["mass"].tolist() star_mass.po...
ab903c5c5744f3b1c5cd26c691feed15e0107dec
DianaLuca/Algorithms
/LeetcodePython/FactoriseANumber.py
816
4.28125
4
""" To factorise a number, divide it by the first possible prime number. Take the resulting quotient below the number. If it is possible, continue dividing this quotient successively by the same prime number. When you cannot do the division by this prime number, divide it by the next possible prime number. And so forth...
e27e2b6ee10ccb48fa7939c445b958f8e2ac96b9
compelecbox/RaspberryPI
/fanControl.py
3,105
3.90625
4
#!/usr/bin/env python # coding: latin-1 # By Ralph Beardmore Jan 2017 for PI 3 # this is a temperature control. It runs in Python 2.x so code accordingly # this is designed for NPN transistor and is normally OFF # Import the libary functions we need import RPi.GPIO as GPIO import time import subprocess # Set which GP...
c9e02bb593344923bd437a90d9b54bb53a79d9bd
DanielCalimayor/DS-Unit-3-Sprint-2-SQL-and-Databases
/Unit 3 Sprint Challenge 2 demo_data.py
935
3.84375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import sqlite3 # In[2]: conn = sqlite3.connect('demo_data.sqlite3') # In[3]: cursor = conn.cursor() # In[4]: cursor.execute('''CREATE TABLE demo_data (S TEXT PRIMARY KEY NOT NULL, X INT NOT NULL, Y INT NOT NULL);''') # In[5...
dd8210aa087701eed5b02811ab0df097878b210b
amukherjee1991/InterviewPrepAlgo
/LinkedList.py
570
3.921875
4
class Node: #constructor def __init__(self,data,next=None): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def insert(self,data): newNode=Node(data) if self.head: current=self.head while current.next: current=current.next current.next=newNode else: s...
a228754fe548dae9a8be26e7ddb80473c77bc36e
rajatbhat07/python
/asgn1.py
298
4.1875
4
no1 = int(input("Enter Ist number:")) no2 = int(input("Enter 2nd number:")) no3 = int(input("Enter 3rd number:")) if no1>=no2 and no1>=no2: biggest = no1 elif no2>=no1 and no2>=no3: biggest = no2 else: biggest = no3 print("biggest number between",no1,",",no2,"and",no3,"is",biggest)
0b54af8f60ebb0c96b8670ebeb657fd72c3a7f08
AidenSmith09/Python
/Day10_While/Days_10_while.py
1,096
3.921875
4
# /bin/etc/env Python # -*- coding: utf-8 -*- # while 循环 current_number = 1 while current_number <= 5: # 循环变量从1开始,小于等于5 print(current_number) # 输出当前变量 current_number += 1 # 输出后变量+1 """ while 条件: pass continue # 跳过本次循环,且继续循环完成。 break # 中断循环 """ #用户选择何时退出 prompt = "\nTell me something, and I will repe...
6db8295d5a2198bc6692d65c65a88839a5fbccac
Brekkjern/SudokuSolver
/SudokuSolver/board.py
3,109
4.03125
4
import math from SudokuSolver.cell import Cell class Board(object): """The board object. It does Sudoku things""" def __init__(self, boardstring, super_cell_size=3): self.cells = list() self.SUPERCELL_SIZE = super_cell_size self.load_board(boardstring) for cell in self.cells: ...
f2e7672f067fb98423741e175da5915e489c9bb0
davll/practical-algorithms
/LeetCode/111-minimum_depth_of_binary_tree.py
761
3.96875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def min_depth(root): def _traverse(node, h): if node.left: if node.right: return min(_traverse(node.left, h+1), _trav...
c30cbd90c3a58dbcc32be37d303d1e164166f290
estraviz/codewars
/7_kyu/Odd or Even?/test_odd_or_even.py
175
3.5625
4
from odd_or_even import odd_or_even def test_odd_or_even(): odd_or_even([0, 1, 2]) == 'odd' odd_or_even([0, 1, 3]) == 'even' odd_or_even([1023, 1, 2]) == 'even'
68fa03b9a57a57562134c8de2d18e6873bbfc947
LukeRoantree4815162342/InformationTheoryProject
/Project2Tools.py
6,743
3.734375
4
import pandas as pd # panadas provides an R-like DataFrame object, ideal for working with tabular data import numpy as np # numpy provides access to many mathematical operations, # and can perform vectorised operations on pandas dataseries objects (columns) import string # string provides us with a list of ascii lower...
1a0f6f4e9a7ac92b9f8c1d16fd9517692e0c4113
lin13k/practice
/algo_problems/extra/prefix_permutation.py
1,272
3.609375
4
class Solution: def check_prefix_permutation(self, numbers): for n in range(len(numbers)): if numbers[n] == n + 1: continue # print('main', n, numbers[n] - 1) if not self.swap(numbers, n, numbers[n] - 1): return False return True ...
0581738b0b25a3878bd4b14df25eac25f715acc0
UnexceptedSpectic/Binary-ASCII-Image-Generation
/ascii_customizer.py
1,269
3.5
4
# This script replaces the background of an ASCII image (consisting of "1"s as its # background and "0"s as its foreground) with whitespace, uses 1s as foreground # edges, and randomizing the inner foreground with "0"s and "1"s. import random as rand with open("imagetoascii.txt", "r") as f: txt = f.read() output...
e45beb70176df996dc7d3c43807ae7e5be607591
sweetpand/Tensorflow_Best_practices
/Tensorflow_tutorial_practice/204_activation.py
1,033
4
4
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # fake data x = np.linspace(-5, 5, 200) # x data, shape=(100, 1) # following are popular activation functions y_relu = tf.nn.relu(x) y_sigmoid = tf.nn.sigmoid(x) y_tanh = tf.nn.tanh(x) y_softplus = tf.nn.softplus(x) # y_softmax = tf.nn.sof...
a279d5f609ccf73b3011d861bbc43b913c95ba0f
qiujiamin/pypro
/python/hmtest/hm_10元祖.py
1,359
4.25
4
# tuple # 元祖与列表类似,不同之处在于元祖的元素不可修改 """ 元组表示多个元素组成的序列 元组在ptrhon开发中,有特定的应用场景 用于存储一串信息,数据之间使用 ,分隔 元组用()定义 元组的索引从0开始 """ info_tuple =("zhangshan",18,1.75) print("%s 年龄是 %d 身高是 %.2f" %info_tuple) # 使用格式化字符串,可以使用 一个元组,来拼接字符串 info_str ="%s 年龄是 %d 身高是 %.2f" %info_tuple print(info_str) print(type(info_tuple)) print(info_tuple[1...
8793a44109d931e024bd5d0791566a31c0ca9271
rpolley/rpgtools
/util.py
839
3.515625
4
from collections import defaultdict # takes the cartesian product of two probability distributions # i.e. given A, B are pdfs and a <= A, b <= B, what is the probability of `a and b` def cartesian_product(lhs, rhs): result = {} for k1, p1 in lhs.items(): for k2, p2 in rhs.items(): result[(*k1, *k2)] = p1*p2 ret...
bb263c4b50a6294fe8f58f408f945c0f8d5a6526
shubhavee/python_specialization_coursera
/Python/week 6/random1.py
228
3.796875
4
def greet(lang): if lang=='es': return ('Hola') elif lang =='fr': return ('Bonjour') else: return ('Hello') print(greet('en'),'Glenn') print(greet('es'),'Sally') print(greet('fr'),'Michael')
e49e7cd0c125d79b8ecef8b99168746c9c04b9fe
stcybrdgs/myPython-refresher
/learningPython/formatting.py
1,479
4.28125
4
# # Example file for formatting time and date output # from datetime import datetime def main(): # Times and dates can be formatted using a set of predefined string # control codes now = datetime.now() print( now ) #### Date Formatting #### # %y/%Y - Year print( now.strftime( "The current year is: %Y"...
8f793b6a407ff909a25e11852926076db4003f1d
razzaksr/SasiPython
/functions/DefPosFuns.py
473
3.578125
4
# default and Positional arguments teck=[12,23,56,99,12,90,11,56,78,67,56,23] def findOut(element=0): print(element,"is existing in following positions") for pos in range(len(teck)): if element == teck[pos]: print(pos) def findSum(beg=0,end=len(teck)): sum=0 for pos in range(beg,en...
a0582033026f61cef43b6f04f4d903b11832a06d
dpaneda/code
/jams/euler/41.py
766
3.953125
4
#!/usr/bin/env python3 import math import itertools def is_prime(n): if n == 1: return False if n < 0: n = -n for m in range(2, 1 + int(math.sqrt(n))): if n % m == 0: return False return True def is_pandigital(n, r): digits = [] for digit in str(n): digits.append(int(digit)) ...
ba0bdd435524e11f918cff116b83894564f340a7
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_06_dictionaries/uppercase.py
878
4.40625
4
""" Write a function capitalize(lower_case_word) that takes the lower case word and returns the word with the first letter capitalized. Eg., print(capitalize('word')) should print the word Word. Then, given a line of lowercase ASCII words (text separated by a single space), print it with the first letter of each word ...
a2a5f433e39e8597e56d0386df040527c11e005c
jiayiwangjw/pythonstudy
/5.1.4.Coding Exercise 3.py
2,140
4.21875
4
#Previously, you wrote a class called ExerciseSession that #had three attributes: an exercise name, an intensity, and a #duration. # #Add a new method to that class called calories_burned. #calories_burned should have no parameters (besides self, as #every method in a class has). It should return an integer #representi...
d9e1a48e3d20d0a140fc25d3b36a8b2636877f8c
ravi4all/PythonEveRegJan_2020
/FileHandling/03-WithKeyword.py
510
3.5
4
# with open('data_2.txt') as file: # data = file.read() # print(data) # csv - comma seperated values import csv data = [ {"name":"Sachin", "score":54}, {"name":"Dhoni", "score":48}, {"name":"Virat", "score":88} ] # with open('data.csv','w', newline='') as file: # writer = csv.wr...
21b57fcbe06d35a2f155c3be76d83f05801987d0
bupthl/Python
/Python从菜鸟到高手/chapter25/demo25.02.py
1,145
3.734375
4
''' --------《Python从菜鸟到高手》源代码------------ 欧瑞科技版权所有 作者:李宁 如有任何技术问题,请加QQ技术讨论群:264268059 或关注“极客起源”订阅号或“欧瑞科技”服务号或扫码关注订阅号和服务号,二维码在源代码根目录 如果QQ群已满,请访问https://geekori.com,在右侧查看最新的QQ群,同时可以扫码关注公众号 “欧瑞学院”是欧瑞科技旗下在线IT教育学院,包含大量IT前沿视频课程, 请访问http://geekori.com/edu或关注前面提到的订阅号和服务号,进入移动版的欧瑞学院 “极客题库”是欧瑞科技旗下在线题库,请扫描源代码根目录中的小程序码安装“极客...
0db751fe72b8e21b54ca20c0aa090ec18f79b56f
la1313/ai-python
/ai python/projects/tictactoe/a3_player.py
502
3.890625
4
# Who's the next player X = "X" O = "O" EMPTY = None def player(board): """ Returns player who has the next turn on a board. """ raise NotImplementedError if __name__ == '__main__': board = [[EMPTY, X, O], [EMPTY, X, EMPTY], [EMPTY, O, EMPTY]] #It sho...
ad69d6fb5fc0af9251c7eb34f050dcb37f400545
satrijotomo/Python_codes
/draw_square.py
728
4.03125
4
#! /usr/bin/env python3 import turtle bgcol = "yellow" reccol = "blue" circol = "red" tricol = "white" def draw_shape(): window = turtle.Screen() window.bgcolor(bgcol) drawme = turtle.Turtle() drawme.shape("turtle") drawme.speed(1) drawme.color(reccol) i = 0 while i <= 3: dr...
037f23cced84d6d4381a3fbd433baad8f85f5aa0
Usefmuq/AI-project
/BFS.py
3,285
3.625
4
class BFS: def __init__(self, n): self.N = n self.G = [[False for x in range(self.N)] for y in range(self.N)] self.Acc = [False] * self.N self.Q = [] self.setupGraph() def setupGraph(self): self.G[1][0] = self.G[0][1] = True self.G[0][5] = self.G[5][0] = ...
d8c0376ebc7af0cb760ad856d84d4862e30b4032
prophecyofagod/Python_Projects
/lab6partB.py
511
3.796875
4
#Author: Mario Saiz #Class: COSC 1336 #Program: Lab 6b #Prints out every line from the file and tells you how many inputs there are. def main (): counter=0 infile = open ('powerball.txt', 'r') number = infile.readline() number = number.rstrip('\n') while number != '': print (number) ...
932122401325daadd1808c8cff8a053b4538978d
aammokt/newProject
/objects102/hero_rpg_v7bc2.py
2,372
4.1875
4
#!/usr/bin/env python # In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee class Character: def __init__(self, health, power): self.health = health self.power = power def char...
50b737b27d354b1f162c1fdc5627748441abfc62
accasey/python-unit-test-1
/phonenumbers/phonebook.py
731
3.859375
4
from typing import List class PhoneBook: def __init__(self): self.numbers = dict() def add(self, name: str, number: str): self.numbers[name] = number def lookup(self, name: str) -> str: return self.numbers[name] def is_consistent(self) -> bool: for name1, number1 in ...
7a5981bb7681ddfdfab186ad29b01cf8f461ed26
lobanow/LR13
/barrel.py
591
3.625
4
import random n=int(input('Введите N: ')) a=[] for i in range(n):#создание пустого массива a.append(0) for j in range(n):#заполнение массива t=1 while(t!=0):#генерация случайного числа с проверкой на повторение t=0 p=random.randint(1,n) for i in range(n): ...
54fc55b7f35a5e369cd2296ce0f0ba6d4cba220f
gg50202gg/pythoncalss108
/hw4/hw4.py
488
4
4
import datetime as dt def main(): year = input("Which year are you born? ") month = input("Which month? 1-12 ") born = dt.datetime.strptime(year+"-"+month, "%Y-%m") print("you are born on %s, %s" % (born.strftime("%Y"), born.strftime("%b"))) print("you are %s years old." % ( rou...
9b8e9cf1bf6240d78eba324de85396d70fcefea9
bbster/PythonBigdata
/workspace_b/3-numpy/exam13.py
937
3.5
4
import numpy as np data1 = 10,20,30,40,50,60 arr1 = np.array(data1) print(arr1) print('-'*40) # 1차원 인덱싱 arr1 = np.array(data1) print(arr1[2]) print(arr1[[1,3,5]]) print(arr1[arr1 > 40]) #print(data1[data1 > 40]) # list는 인덱싱에 조건 달수없음 print('-'*40+'1차원 끝') # 2차원 인덱싱 arr2 = np.arange(10, 100, 10).reshape(3, 3) print(...
b8597e3985358bdbf41ff9ba58b8d6c59c8fc72d
nija/shopping-site
/customers.py
949
3.75
4
"""Customers at Hackbright.""" class Customer(object): """Ubermelon customer.""" def __init__(self, first_name, last_name, email, password): self.first_name = first_name self.last_name = last_name self.email = email ...
4943cac108475b506e1cb3f12a50687b5fea5df7
IoC-Sunderland/Relational-Databases-SQL-and-ORMs
/insert_record.py
378
3.890625
4
import sqlite3 # Connect to the database connection = sqlite3.connect("college_database.db") # Create a cursor cursor = connection.cursor() # Write your SQL query sql_command = """INSERT INTO students (student_number,student_name) VALUES (33289,"Susan Smith"), (67830,"Bob Martin");""" # Execute your ...
ba5df400972dbacd4d1f45afbb8b672e98ad4c52
Teyeph/Silent-Auction-Revision
/silentauctiontest.py
1,172
4.0625
4
""" Title: silentauctiontest Version: 1 Author: Jamie U Created: 4/2/18 Description: This program allows someone to run a silent auction. """ def get_float(message): choice = -1 while choice == -1: try: choice = float(input(message)) except: print("Please enter numbers o...
2c7c7e11b5f4834e52f7662de2819c9a389c8dcd
wkqls0829/gamemaking
/CaesarCipher.py
1,106
4.125
4
class CaesarCipher: def __init__(self): self.message_to_return = "" self._begin() def _begin(self): self.mode = input("Do you wish to encrypt or decrypt a message?") while self.mode != "encrypt" and self.mode != "decrypt": self.mode = input("Please choose between...
d6455328e8bf4ef2b576713fb95fe3d57cf99575
hisonic001/project
/coding_test/addition_of_lists.py
303
3.640625
4
a = [[1], [2]] b = [[3], [4]] c = [[0] * len(a[0]) for _ in range(len(a))] for i in range(len(a)): for j in range(len(a[0])): c[i][j] = a[i][j] + b[i][j] print(c) ## zip의 활용 num = [1, 2, 3, 4] name = ["kim", "jun", "cho", "lee"] li = [[i, j] for i, j in zip(num, name)] print(li)
a4cdbe182e095cb6ed7c38285cef9e222ad2f30c
aditya95sriram/python-vc
/reduction.py
13,589
3.578125
4
#!/usr/bin/python # -*- coding: utf-8 -*- import networkx as nx import utils def print(*args): # mute printing in this module pass def degreedel(graph: nx.Graph, k: int): """ Degree 0 and degree greater than k vertices (RR1) :param graph: graph to reduce :param k: parameter k :return: 4-t...
b70149d75a09072048d9c5b5f5e56c0e7a61094c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2173/60760/297915.py
221
3.796875
4
def func(n:int): res=0 for i in range(1,n+1): res+=i**2 return res tests = int(input()) # 找规律 lists = [] for i in range(tests): lists.append( int(input())) for i in lists: print(func(i))
7fdb9dfb9c35531865bcd815108db16c851417a6
j-mak/python3-exercism.io
/hamming/hamming.py
316
3.8125
4
def distance(dna_strand1, dna_strand2): """Calculate hamming distance between two DNA strands.""" if len(dna_strand1) != len(dna_strand2): raise ValueError counter = 0 for i in range(len(dna_strand1)): if dna_strand1[i] != dna_strand2[i]: counter += 1 return counter
bd3f389f2df0e4932ddc30ec7f45de2dfa5399f8
jxie0755/Learning_Python
/ProgrammingCourses/MIT6001X/week3/list_mutate_alias_clone.py
961
4.15625
4
# mutation, alias, cloning warm = ["red", "yellow", "orange"] hot = warm print(warm) print(hot) hot.append("pink") print(hot) # change items in hot leads to change items in warm as well print(warm) cool = ["blue", "green", "grey"] chill = ["blue", "green", "grey"] # These two list looked like the same, but not the...
160339c2df66c7b748b600b56e93292f5a70a161
ittapa/AIFFEL_LSG
/lms/02-FUNDAMENTAL/F06-data_array_table_withPy/99-test.py
763
3.71875
4
treasure_box = {'rope': {'coin': 1, 'pcs': 2}, 'apple': {'coin': 2, 'pcs': 10}, 'torch': {'coin': 2, 'pcs': 6}, 'gold coin': {'coin': 5, 'pcs': 50}, 'knife': {'coin': 1, 'pcs': 30}} print(type(treasure_box)) def display_stuff(ptreasure_box): ## type ...
fe3ba4fe7f807e19356cd1f7a6d43d8a4117dc80
MaximBlinov22/cs102
/homework01/vigenere.py
3,447
4.1875
4
def encrypt_vigenere(plaintext: str, keyword: str) -> str: """ Encrypts plaintext using a Vigenere cipher. >>> encrypt_vigenere("PYTHON", "A") 'PYTHON' >>> encrypt_vigenere("python", "a") 'python' >>> encrypt_vigenere("ATTACKATDAWN", "LEMON") 'LXFOPVEFRNHR' """ ciphertext = "" ...
8daf9be696d91a21b8c515d63217bc7df358c0c7
gabrielkenji12/faculdade
/Estrutura de Dados/Recursividade/Recursividade.py
2,140
3.65625
4
def inter_listas(L1,L2): lista1 = L1 lista2= L2 for i in range (len(lista1)): n1 = lista1[i] for j in range (len(lista2)): n2 = lista2[j] if n1 == n2 : return True return False def lista_sub(L): lista = L lista2 = [] for i in range (len(lista)...
cdb3fc4cdb5a2d8ad3d8c4964263f71961918eee
vikramzsingh/Python
/maxinlist.py
487
4.03125
4
#Find max in the list lst=[] n=int(input("Enter the number of elements: ")) for i in range(0,n,1): ele=int(input("Enter the element of the list: ")) lst.append(ele) print("Element inputted in the list",lst) print("Manual list: ") for i in range(0,n,1): if(i==n-1): print(lst[i],...
2ac986b6ae697c5766565fc1522156db4cafbe2e
SnRahman/MY-Codes
/stackoverflow.py
763
3.5625
4
def question_posted(down_votes,up_votes): down_points = down_votes * (-2) up_points = up_votes * 10 return down_points + up_points def answers(accept,down_votes,up_votes): if accept == 'accepted': accepted_points = 15 else: accepted_points = 0 down_points = down_votes * (-2) up_points = up_votes...
6d1240b5f036343fc0aaa4b58431ff711a1f3a2c
artheadsweden/python_oct_18
/day2/lambda1.py
208
3.828125
4
def ff(x, y): return x + y def main(): f = lambda x, y: x + y print(f(3, 4)) print(ff(3, 4)) result = (lambda x, y: x + y)(4, 5) print(result) if __name__ == '__main__': main()
731b1372c087218dd6f8efa69210988600945f26
Aravinthr20/Beg-Set5
/range.py
93
3.890625
4
x=int(input()) if(x>10) or (x==0) or (x<0): print("NO") elif(x<=10): print("yes")
0b6816321e56be5da1a2f5ad4e00ea095f42cad9
seanremenyi/nato_alphabet
/main.py
254
4.125
4
import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") nato_dict = {row.letter: row.code for (index, row) in data.iterrows()} word = input("Enter a word ").upper() nato_letters = [nato_dict[letter] for letter in word] print(nato_letters)
0b0b2b9b4460663ca2950e4b7295d462dc061ef2
Nivethika7623/sample2
/H133.py
104
3.671875
4
sentence =input() words = sentence.split() sentence_rev = " ".join(reversed(words)) print(sentence_rev)
4efcf309b42bd392fdb7eee55d1a5cd3f18df7f3
hamdea98/-
/flow.py
142
3.578125
4
import turtle ob=turtle.Turtle() ob.speed(20) d=200 angle=140 for i in range(1,100): ob.forward(d) ob.left(angle) d=d-1
b4b469aeb580da7bf9a83b6b1b3c64a967cd3dc8
Turhsus/coding_dojo
/python/bike.py
736
4.21875
4
class Bike(object): def __init__(self, price, max_speed, miles = 0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print "Price:", self.price, "Dollars; Max Speed:", self.max_speed, "MPH; Miles:", self.miles return self def ride(self): print "Riding" self.miles...
de3c2985596b0c278089bc3f723851e5052d1265
pluzun/supinfo_1ads_labs_2018
/2.4.1.py
292
4.09375
4
n = int(input("Donner un nbr : ")) def fibonacci(n=10): if n < 2: return n else: a = 0 b = 1 number = 0 for i in range(2, n + 1): number = a + b a = b b = number return number print(fibonacci(n))