blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
2d19065a8f6356231b8ad0ba2c16fb788dac5602
Pabaz22/slcities
/slcities/utils.py
3,410
3.609375
4
import os import pandas as pd import geopandas as gpd def list_files_in_dir(dir_path): """ list files in a directory Parameters : ------------ dir_path (str) -- The directory where the files are located Returns : --------- (list of str) -- The list of the files names. """ ret...
4978ba4a620b9252bd5fbf54cc7598a4ba086dc8
wpram45/CodeFights
/areEquallyStrong.py
1,221
3.703125
4
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): #strongest arm is left if max(yourLeft,yourRight) ==yourLeft: #friend weak arm is left if min(friendsLeft,friendsRight)==friendsLeft: #compare weaks if yourRight==friendsL...
25281f8c94140e89a54e4267c6cabe62c9709d7d
gustavlagneborgold/stefanos_angels
/pre_processing/impute.py
1,852
3.8125
4
import pandas as pd def impute(dataset: pd.DataFrame, strategy, drop_threshold=300) -> pd.DataFrame: """ Deals with missing or invalid values in a specific dataset :param drop_threshold: Threshold for when an entire column should be dropped from the dataset :param dataset: The pandas dataset to be imp...
d9a8c55b85bd0f4d5c6c3adb1cc11b478c5ca883
SandervWickeren/Heuristics_Amstelhaege
/Functions/alg_simannealing.py
4,542
3.9375
4
""" Uitleg: Dit algoritme werkt als een variant op onze hill climb. Er wordt in eerst instantie een random huis gepakt. Vervolgens wordt er een willekeurige kant gepakt en het huis een aantal stappen die kant op geplaatst. De score wordt berekend en bij een verbetering of gelijke score wordt de kaart gehouden. Wanneer...
c9a5b87753f39fcba2507dccad905d0e9dc8b279
avi527/Encapsulation
/encap_intro2.py
166
3.6875
4
class Person: def __init__(self,name,salary): self.__name=name self.__salary=salary p=Person('avinash',5000) p.salary=6000 print(p.salary)
4844eb4416c99f709e8d8d7d4219bee020c7adb6
nbpillai/npillai
/Odd or Even.py
205
4.3125
4
print("We will tell you if this number is odd or even.") number = eval(input("Enter a number! ")) if number%2==0: print("This is an even number!") else: print ("This number is an odd number!")
125d271558ace2519036c0b4ab441afc1d7abe86
icarogoggin/Exercitando_python
/Exercicios09_Tabuada.py
348
3.890625
4
n1 = int(input('Digite o número que você quer para tabuada: ')) print(f'{n1} x 1 = {n1*1}') print(f'{n1} x 2 = {n1*2}') print(f'{n1} x 3 = {n1*3}') print(f'{n1} x 4 = {n1*4}') print(f'{n1} x 5 = {n1*5}') print(f'{n1} x 6 = {n1*6}') print(f'{n1} x 7 = {n1*7}') print(f'{n1} x 8 = {n1*8}') print(f'{n1} x 9 = {n1*9}') prin...
0a0f7987b99a69ee8ad795e828ab1f81cafe73c9
icarogoggin/Exercitando_python
/Exercicios15_AlugueldeCarros.py
498
3.640625
4
dias = float(input('Por quantos dias você alugou o veículo? ')) km = float(input('Quantos km você rodou com o veículo? ')) paluguel = float(input('Quanto está o aluguel deste veículo? ')) pkm = float(input('Quanto está o preço da gasolina na sua cidade ? ')) autonomia = float(input('Qual autonomia do seu carro? ')) pri...
ac99b156021ef703047f59bc632be6c1a6818138
icarogoggin/Exercitando_python
/Exercicios25_ProcurandoUmaStringDentroDeOutra.py
98
3.65625
4
nome = input('Digite seu nome completo: ').strip() print(f'Seu nome tem Silva: {"Silva" in nome}')
f0ce13a96a9c5cfb8f3cda4e1faa0eeda1d59c7b
Hashininirasha/Snow_Falling
/xmz.py
122
3.703125
4
n = 0 while n < 3: print("\tHo !!") n += 1 print("We Wish you a Merry magical \n\t\tXms")
1a59a944f171a4b30c4b45b00d74552ba7b0adb0
DarioDiGulio/python_b
/daro/Clase 2/mini-desafios/listas_pares.py
200
3.6875
4
# Crear una lista con los números pares menores a 50. def es_par(number): return number % 2 == 0 numbers = [] for i in range(0, 50): if es_par(i): numbers.append(i) print(numbers)
5b68b1ab33e683d12ea1246f5e836a533c644e1c
DarioDiGulio/python_b
/daro/Clase 1/ejercitación ingegradora/entrevista_ingematica.py
444
3.734375
4
def esMultiploDeCinco(num): return num % 5 == 0 def esMultiploDeTres(num): return num % 3 == 0 def esMultiploDeAmbos(num): return esMultiploDeCinco(num) and esMultiploDeTres(num) for i in range(1, 100): number = str(i) if esMultiploDeAmbos(i): number = number + ' N3N5' elif esMultipl...
3143b60b634f030a78cd5f0e856f82a689fd65e2
chingchunliao/try-password
/pass.py
259
3.71875
4
password = 'a123456' i = 3 while True : pwd = input('請輸入密碼: ') if pwd == password : print('輸入正確') break else : i = i - 1 print('你還有' , i , '次機會') if i == 0: break
ee4bb01eb029819b15ee23c478edab0aada9608b
ari-jorgensen/asjorgensen
/SimpleSubstitution.py
1,140
4.15625
4
# File: SimpleSubstitution.py # Author: Ariana Jorgensen # This program handles the encryption and decryption # of a file using a simple substitution cipher. # I created this algorithm myself, only borrowing the # randomized alphabet from the Wikipedia example # of substitution ciphers # NOTE: For simplicity, all char...
f02c4fbf302ec732ca07dbd16679da345682d2f9
DishT/NYU_cusp_summer_course
/HW1/cusp_hw1_3.py
757
3.90625
4
def counter(word): letter_count = 0 dig_count = 0 # Method 2 : dict() for i in range (len(word)): if word[i].isalpha(): #Method 1 : counter letter_count += 1 #Method 2 : dict() letter_count_dic["Letters"] = letter_count_dic.get("Letters",0)+1 elif word[i].isdigit(): # Method 1 : Counter dig_c...
1ce80ccc181792ac261bda4996a931af7702b8c9
VinayHukkeri12345/PythonClass
/Day1PythonPrograms.py
764
3.921875
4
#1 names = ["john", "jake", "jack", "george", "jenny", "jason","john"] set_names=set(names) names=list(set_names) for name in names: if len(name) <5 and 'e' not in name: print(name) #2 word="python" result='c'+word[1:len(word)] print(result) #3 given_dict={"name": "python", "ext": "py"...
fad8dae8385e631c660e8cbd96ca736d6639e2bd
lichtgarage/Python-Kurs-2018
/Homework22102018.py
178
3.71875
4
secret = int(24) guess = int (raw_input("What's your guess?")) if guess == secret: print "Congratulations! You guessed correctly!" else: print "Sorry, you are wrong!"
f09176c324c14916ee1741dd82077dd667c86353
cbarillas/Python-Biology
/lab01/countAT-bugsSoln.py
903
4.3125
4
#!/usr/bin/env python3 # Name: Carlos Barillas (cbarilla) # Group Members: none class DNAString(str): """ DNAString class returns a string object in upper case letters Keyword arguments: sequence -- DNA sequence user enters """ def __new__(self,sequence): """Returns a copy of sequenc...
1be215d53d161ccee3b8c707b0c3f2cfb83c8daf
Abdul89-dev/lesson3
/datatime.py
407
3.671875
4
import datetime d = datetime.date(2020, 2, 22) print( d.day, d.month, d.year) # yesterday import datetime d = datetime.date(2020, 2, 23) print( d.day, d.month, d.year) #today import datetime d = datetime.date(2020, 1, 23) print( d.day, d.month, d.year) #1 mouth ago from datetime import datetime deadline = ...
33dd67fdf5853599c469afda5170d8078eb91cab
RamslyStardust/Basic_Python
/funciones.py
575
3.78125
4
def imprimir_mensaje(): print('Mensaje especial: ') print('Estoy aprendiendo a usar funciones') imprimir_mensaje() imprimir_mensaje() imprimir_mensaje() def conversacion(mensaje): print('Hola como estas?') print('Todo bien?') print(mensaje) print('Adios') opcion = int(input('E...
0b1f631811fc8a7e6fc0e2cfdf2ea64acf82186a
shreyasslshetty/Code-Wars
/5 KYU Directions Reduction/dirReduc.py
318
3.640625
4
def dirReduc(arr): direc_pair = {"NORTH":"SOUTH", "SOUTH":"NORTH", "EAST":"WEST", "WEST":"EAST"} new_arr = [] for x in arr: if new_arr and new_arr[-1] == direc_pair[x]: new_arr.pop() else: new_arr.append(x) return new_arr
dbbff4b485e68719c4b193496538dd6003d83141
itarcan/PythonNotes
/spyder.py
1,872
3.65625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ print("HELLO AI ERA") 9 9.2 type(9) "a" + "b" "a" "b" "a" /3 a = "gelecegi_yazanlar " a= 9 b=10 a*b #STRING METODLARI - upper() & lower() gel_yaz = "gelecegi_yazanlar" gel_yaz.upper() gel_yaz.lower() #STRING METODLARI - replace()...
40e5df8654c280658b3dcb72d3c60a9c81f75475
aoutzen/advent-of-code
/day-01/day-01.py
2,361
3.859375
4
# --- Day 1: The Tyranny of the Rocket Equation --- # Santa has become stranded at the edge of the Solar System while delivering presents to other # planets! To accurately calculate his position in space, safely align his warp drive, and # return to Earth in time to save Christmas, he needs you to bring him measurem...
f56e700ce627a257ac89f7b79bca7f78137607e2
BrunoAntunes23/pythonw
/main.py
969
3.703125
4
usuario=[] nome=str(input("insra seu nome")) print("\n") email=str(input("insira seu email")) print("\n") cpf=int(input("insira seu cpf")) print("\n") cnpj=int(input("insira seu cnpj")) print("\n") telefone=input("insira seu telefone") print("\n") cep=input("insira seu cep") print("\n") logradouro=input("insira o logra...
a3ea1e90877fa654eee78b3e55223e4930d25547
chukiller/python
/python函数/global和nonlocal.py
283
3.703125
4
# glocal 引入全局变量 # nonlocal 引入局部变量 a = 10 # 函数内不允许直接使用外部全局的变量 def func(): a = a + 1 print(a) # 如果强行要使用全局变量,需要用global修饰 def func2(): global a a = a + 1 print(a) func2()
5ef779bc2f964f8e0338b71a527bf752664fdc24
vikrsri/EECS-354
/Projects/Programming Languages/test/python/answer.py
1,106
3.8125
4
#!/usr/bin/python ''' Python is a language with many great strengths. Perhaps the only one that really matters in this class is it's extensive standard library, which can be used as something of a swiss army knife. This means that python scripts can do a lot of heavy lifting in very few lines of code. Subclass the ...
79ec463e65d9d061e090029bb4619b62c73cfd25
nlandolfi/duo
/human.py
2,011
3.640625
4
import numpy as np import geo import opt # A human is a function: # H: (alpha, state, goal, u_r) -> (action) def optimal(alpha, state, goal, _u_r=None): """ optimal generates the optimal control given a particular goal. We can solve for this analytically, it is the vector in th...
5911aa7ac34e627253367cdd4925f1aff96605d7
Gunnstein/fastlib
/fastlib/_template.py
3,303
3.71875
4
# -*- coding: utf-8 -*- import string __all__ = ["TemplateStringFormatter", "TemplateFileFormatter"] class TemplateStringFormatter(object): fmt_dict = {} def __init__(self, template_str): """Use a template from a string Load a template string and substitute the template keys with pr...
3bae71d1ec892d0caef6b3ec6487bc986f09e891
taijiji/NetworkAutomationTutorial
/samplecode/sample_number.py
183
3.890625
4
a = 1 # a: int型として生成 b = 1.1 # b: float型として生成 print(a) print(b) print(type(a)) print(type(b)) c = a + b # c: float型として生成 print(c) print(type(c))
8db2c042802cacea93d08efe36084db87a410409
hkaushalya/Python
/ThinkPythonTutorials/exer_10_1.py
595
4.125
4
def capitalize_all(t): res = [] for x in t: res.append(x.capitalize()) return res ###################### # This can handle nested list with upto depth of 1. # i.e. a list inside a list. # not beyond that, like , list in a list in a list!!! ###################### def capitalize_nested(t): res =...
40ce1341783f5bb4811556027822d42096dc51cc
yangyang0126/PythonDataAnalysis
/matplotlib/mpl_squares.py
466
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 10 16:49:09 2019 @author: Administrator """ # 绘制简单的折线图 import matplotlib.pyplot as plt input_values = [1, 2, 3, 4, 5] # 横坐标 squares = [1, 4, 9, 16, 25] # 纵坐标 plt.plot(input_values, squares, linewidth = 5) # 设置图标标题,并给坐标轴加上标签 plt.title("Square Numbers",fontsize = 24) plt...
ab2ec5ae18025852368884fd7600bdf7425f8693
yangyang0126/PythonDataAnalysis
/matplotlib/scatter_squares.py
901
3.75
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 10 17:08:38 2019 @author: Administrator """ # 使用scatter() 绘制散点图并设置其样式 import matplotlib.pyplot as plt x_value = list(range(1,10)) y_value = [x**2 for x in x_value] plt.scatter(x_value, y_value, c = 'red', edgecolor = 'none', s = 50) # edgecolor: 数据点轮廓 # c:数据点颜色,默认是蓝色 #...
61f68e46f132d34e1eae5115dad6bbc5136e38f6
shadhini/python_helpers
/pandas_dataframes/computations/cumsum.py
377
3.984375
4
import pandas as pd df = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) print(df) # cum sum along columns df1 = df.cumsum(axis = 0) print(df1) # cum sum along rows df2 = df.cumsum(axis = 1) print(df2) # cum sum of part...
cce2bd6249a771e4fae0f31e903b0e78d0a44b3e
datyrlab/selenium-webdriver
/04-automate-web-login.py
4,443
3.53125
4
#!/usr/bin/python3 ###################################### # Selenium Python - Automate a login to a web site - Part 4 # https://youtu.be/Bw9ueo7qFmY # 00:00 - intro # 00:44 - copy and tidy script from previous tutorial. Plus, import module colorama # 14:34 - continuing with automating the imdb.com website, code to cli...
92db81dc42cd42006e58a7acb64347ef443b4afc
mattin89/Autobiographical_number_generator
/Autobiographic_Numbers_MDL.py
1,542
4.15625
4
''' By Mario De Lorenzo, md3466@drexel.edu This script will generate any autobiographic number with N digits. The is_autobiographical() function will check if numbers are indeed autobiographic numbers and, if so, it will store them inside a list. The main for loop will check for sum of digits and if the number of...
df9499c7b5aa5884a149bb092acbad7307630c7b
garetroy/schoolcode
/CIS211-Intermediate-Python/Project 4/payment.py
1,092
3.90625
4
""" Garett Roberts CIS211 Winter payment.py """ from tkinter import * root = Tk() Label(root, text="Loan Amount($)").grid(row=0) #Creates amount label Label(root, text="Rate(%)").grid(row=1) #Creates rate label Label(root, text="Durration of Loan(years)").grid(row=2) #Creates year label amount = Entry(root) #Create...
9b4e8b143b4a21c84e0f18626b786abceb63c970
garetroy/schoolcode
/CIS210-Beginner-Python/Week 1/jumbler.py
1,766
4.09375
4
""" jumbler.py: CIS 210 assignment 2, Fall 2013 author: Garett Roberts Unscrable words """ import sys dictionary = open(sys.argv[2]) jumbled_word = sorted(sys.argv[1]) def main(dictionary, jumbled_word): ''' This function takes the dictionary and the jumbled word. For every word that it ...
801c588912b99c98b0076b70dbbd8d7b2184c23e
garetroy/schoolcode
/CIS210-Beginner-Python/Week 2/counts.py
1,410
4.4375
4
""" Count the number of occurrences of each major code in a file. Authors: Garett Roberts Credits: #FIXME Input is a file in which major codes (e.g., "CIS", "UNDL", "GEOG") appear one to a line. Output is a sequence of lines containing major code and count, one per major. """ import argparse def count_codes(majors_f...
40cd6d4d249a74f144be83a371b8cb1c1d383cb0
MrSerhat/Python
/Fibonacci_Serisi.py
323
4.15625
4
""" Fibonacci Serisi yeni bir sayıyı önceki iki sayının toplamı şeklinde oluşturur. 1,1,2,3,5,8,13,21,34... a,b=b,a+b "a nın değerine b nin değerini atıyoruz" """ a=1 b=1 fibonacci=[a,b] for i in range(20): a,b=b,a+b print("a:", a,"b:",b) fibonacci.append(b) print(fibonacci)
1a6832574e4214f852f894b3463d2918f3be875f
MrSerhat/Python
/enbüyüksayı.py
264
3.96875
4
sayı1=float(input("Sayı 1 giriniz")) sayı2=float(input("Sayı 2 giriniz")) sayı3=float(input("Sayı 3 giriniz")) if sayı1>sayı2 and sayı1>sayı3: print(sayı1) elif sayı2>sayı1 and sayı2>sayı3: print(sayı2) else: print(sayı3)
37e2ef9d7ac4a4e76277fc023e29ceb9af32da02
mjcj31/Tip-Calculator
/tip calculator.py
219
3.890625
4
def tip_calc(): price = input("Enter total price of meal: ") tip_percentage = input("Enter tip percentage: ") tip = float(price) * (float(tip_percentage)/100) print("Tip to be payed: ", tip) tip_calc()
176c053fed816c2b082705db36080f998b8d506f
3rikthered/python
/bitwise.py
1,510
3.734375
4
####################### # verification method # ####################### def check(): string = input('Enter a 16-digit binary: ') string = string.strip() #require string length to be 16 if len(string) != 16: print('Use 16 chars: ') return False #require characters to only be 0 and 1 if not all(i in '10'...
de927f531263b661458c422f16e23d4897236fca
agzsoftsi/holbertonschool-higher_level_programming
/0x03-python-data_structures/4-new_in_list.py
181
3.5
4
#!/usr/bin/python3 def new_in_list(my_list, idx, element): newl = my_list.copy() if idx < 0 or idx >= len(newl): return newl newl[idx] = element return newl
2e18fd51ae66bc12003e51accf363523f227a76e
agzsoftsi/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,007
4.46875
4
#!/usr/bin/python3 """Define a method to print a square with #""" class Square: """Class Square is created""" def __init__(self, size=0): """Initializes with a size""" self.size = size @property def size(self): """method to return size value""" return self.__size ...
bd082d0830972772329a45ded63c4d3507717a3a
agzsoftsi/holbertonschool-higher_level_programming
/0x0A-python-inheritance/101-add_attribute.py
269
3.53125
4
#!/usr/bin/python3 """Module to Task 101""" def add_attribute(self, attribute, value): """To add attribute if it's possible.""" if hasattr(self, '__dict__'): setattr(self, attribute, value) else: raise TypeError("can't add new attribute")
81c9ef926d71a36fe01f3f717ab306c648677081
agzsoftsi/holbertonschool-higher_level_programming
/0x0B-python-input_output/10-my_class_2.py
451
3.546875
4
#!/usr/bin/python3 """ My class module """ class MyClass: """ My class """ score = 0 def __init__(self, name, number = 4): self.__name = name self.number = number self.is_team_red = (self.number % 2) == 0 def win(self): self.score += 1 def lose(self): ...
f46154474454e704f6a175e42b5f77cde8537848
agzsoftsi/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
246
3.703125
4
#!/usr/bin/python3 """Module Task1 - class MyList that inherits from list.""" class MyList(list): """Module to MyList.""" def print_sorted(self): """Print the list and sort it in ascending order.""" print(sorted(self))
5075f5c904992aeaddb5e2663b518ca90f8e85c9
agzsoftsi/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
444
3.75
4
#!/usr/bin/python3 """Module For Task100""" def append_after(filename="", search_string="", new_string=""): """To append a line of text after line containing a specific string.""" with open(filename, 'r') as f: newtext = f.readlines() with open(filename, 'w') as f: s = '' for line...
83b4d7089f9b1fc1af639270ef964d0932a8589c
alineayumi/python-appbrewery
/day002/exercise-2-1.py
309
3.84375
4
# 🚨 Don't change the code below 👇 two_digit_number = input("Type a two digit number: ") # 🚨 Don't change the code above 👆 #################################### #Write your code below this line 👇 print(type(two_digit_number)) d = int(two_digit_number[0]) u = int(two_digit_number[1]) print(d+u)
6ead12f7633cf0131bec2d772940456c8fa52cf2
alineayumi/python-appbrewery
/day018 - turtle graphics and GUIs/drawing-different-shapes/main.py
489
3.890625
4
import turtle as t import random tim = t.Turtle() ########### Challenge 3 - Draw Shapes ######## colors = [ "bisque", "light salmon", "tomato", "red", "crimson", "dark salmon", "salmon", "indian red", ] def draw_polygon(sides, polygon_size): angle = 360 / sides tim.color(ran...
6ede673905934668e4823c5b72fc657ee647b0e6
alineayumi/python-appbrewery
/day025 - csv and pandas library/weather/main.py
1,068
3.921875
4
# with open("./weather_data.csv", "r") as data_file: # data = data_file.readlines() # print(data) # import csv # with open("./weather_data.csv", "r") as data_file: # data = csv.reader(data_file) # temperatures = [] # for row in data: # if row[1] != "temp": # temperatures.append(int(row[1])) # print(temperat...
f900eb59dc0743a97712d24c6493aa18c93df762
alineayumi/python-appbrewery
/day031 - Intermediate - Flash Card App Capstone Project/main.py
2,138
3.5625
4
from tkinter import * import pandas import random BACKGROUND_COLOR = "#B1DDC6" try: df = pandas.read_csv("data/words_to_learn.csv") except FileNotFoundError: df = pandas.read_csv("data/french_words.csv") words_to_learn = df.to_dict(orient="records") current_card = {} # ---------- CREATE NEW FLASHCARDS ------...
8d4e99983c8b49e2ba839952b9d05c2320fda0f0
superzhc/PythonLearning
/base/Common.py
5,380
3.625
4
# coding=utf-8 ''' @Description: 示例所用的通用工具类 @Author: superz @Date: 2020-01-02 22:23:47 @LastEditTime : 2020-01-03 23:37:42 ''' class Student(): """ 在Python中可以使用class关键字定义类 """ def __init__(self, id, name): self._id = id self._name = name def __repr__(self): return "id="+s...
3e43507fcce5bb31cf34b2611826fe89fc0d9953
superzhc/PythonLearning
/arithmetic/排序算法.py
1,342
3.96875
4
# coding=utf-8 ''' @Description: 排序算法(选择、冒泡和归并) @Author: superz @Date: 2020-01-04 21:57:57 @LastEditTime : 2020-01-04 22:18:15 ''' def select_sort(origin_items, comp=lambda x, y: x < y): """ 简单选择排序 """ items = origin_items[:] for i in range(len(items)-1): min_index = i for j in ra...
4a0364686062670d6e4145c3f5993b92aa68c1f2
AnthonyTalav/First-steps-in-Python
/practice4.py
395
3.71875
4
def foreign_exchange_calculator(amount): sol_to_dollar=0.30 return sol_to_dollar*amount def run(): print('**--CALCULADORA DE SOLES A DOLARES--**') amount=float(input('Ingrese la cantidad de soles a convertir: ')) result=foreign_exchange_calculator(amount) print('S/{} soles a dólares america...
cd645e5a9539e669093b26ca4681a8943ea5b15d
wangdongfrank/LeetCode-python
/ValidPalindrome.py
378
3.578125
4
class Solution: # @param s, a string # @return a boolean def isPalindrome(self, s): New = [] for ch in s: if (ch>='0' and ch<='9') or (ch>='a' and ch<='z'): New.append(ch) elif ch>='A' and ch<='Z': New.append(chr(ord(ch) - ord('A') + or...
18c3740be21c20355bfc6807aa74abef4eabf816
wangdongfrank/LeetCode-python
/SearchinRotatedSortedArrayII.py
937
3.609375
4
class Solution: # @param A a list of integers # @param target an integer # @return a boolean def search(self, A, target): left = 0 right = len(A)-1 while(left<=right): mid = (left+right)/2 if(target == A[mid]): return True else:...
bec138b6bec18aea247b14af9cdecb705090b108
CuriosityLabTAU/tensorflow_curiosity_loop
/loop/test.py
1,475
3.578125
4
from __future__ import print_function # # import tensorflow as tf # # # Basic constant operations # # The value returned by the constructor represents the output # # of the Constant op. # a = tf.constant(2, name='adult') # b = tf.constant(3) # # # Launch the default graph. # with tf.Session() as sess: # print("a=2,...
5c1d5421c0e93ea0f3c6a8808b4b146350680ac1
dariocazzani/World-Models-TensorFlow
/stateless_agent/display_rewards.py
1,015
3.609375
4
import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import draw, show import time def display_rewards(rewards): rewards = np.array(rewards) x = np.linspace(0, len(rewards)-1, len(rewards)).repeat(rewards.shape[1]) mean = np.mean(rewards, axis=1) mx = np.max(rewards, axis=1) m...
9f2c898e76c862293d577d6d50d07536b4baf4c4
Ryan-Mirch/cs471
/danny_yu_hw1/YuAs1Ex1.py
212
3.59375
4
#!/usr/bin/python #YuAs1Ex1.py - Answer 1 #Author - Yu, Danny (dyu6) #Date - 9/5/13 def powerR(pow, base): if pow == 0: return 1 else: return base * powerR(pow-1, base) #print powerR(6,2)
253c7f65e0c13b368a97bb1eae0a795876d5f301
jbrady1985/Personal-
/pokermanager.py
1,946
3.6875
4
#Basic poker program for tracking bankroll #libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as stats def pokermanager(): bankroll = float(input('What is your current Poker Bankroll? ')) choice = 1 while choice!='2': choice=...
3803718ae762e2d99a04423bb4a0fb19c3d8b0a7
armstrongnate/school
/cs2420/sorts/bubble_sort.py
1,165
4.03125
4
# Functions I need to write: # CreateRandomList # BubbleSort # Compare import random def CreateRandomList(listAmount=10): l = [] for i in range(listAmount): l.append(random.randint(0,listAmount)) return l def BubbleSort(A, counts): # switch things around until the list A is sorted # do a series of passes, co...
bcfc2dd2e8043ed60beab5b17022ad23d237a34a
armstrongnate/school
/cs2420/card_shuffler.py
545
3.6875
4
# CARD SHUFFLING PROBLEM ## SOLUTION 1 ## import random def createRandomUniqueArray(size=52): # generate an array of random numbers between 0 and 51 a = [] count = 0 while count < size: r = random.randrange(0, size) if r in a: a.append(r) count += 1 return a ## SOLUTION 2 ## import random def createRa...
9c12c141f69093bf17c00988aed93c8928572471
Timur1986/work-with-FILE
/io_conor.py
430
3.734375
4
# Копировать файл с новым названием (способами без with) x = input('Укажите имя файла для копирования: ') y = input('Введите новое имя файла: ') n_conor = open(x, 'rb') n_chicken = open(y, 'wb') n_chicken.write(n_conor.read()) n_conor.close() n_chicken.close() print('Файл с новым именем успешно создан!')
d7bcc3b55ac4ba0da360d5326c47d02d6ef3b9a7
poojarkpatel/Student_Repository
/HW08_Pooja_Patel.py
4,880
3.703125
4
""" HW08 implementation file""" from datetime import datetime, timedelta from typing import Tuple, List, Iterator, Dict, IO from prettytable import PrettyTable import os import string def date_arithmetic() -> Tuple[datetime, datetime, int]: """The function uses date airthmetic operations and return a tuple""" ...
2ace71f86edfd5baefb3977c0bfca12c675295e4
meysamparvizi/mesal
/avereg.py
183
3.828125
4
n=int(input('enter numers dars: ')) a= [] for i in range (0,n): x = float(input(f'enter numbers nomre {i+1}: ')) a.append(x) avg=sum(a)/n print('is avaerg: ' , round(avg,2))
224658642a91ef67570e2d661c2d65e0f13f2fed
logicxx88/Learnpy
/01-笨方法学python/ex05.py
596
3.765625
4
my_name='Zed A. Shaw' my_age=35 my_height=74 my_weight=180 my_eyes='Blue' my_teeth='White' my_hair='Brown' add=my_age+my_height+my_weight print("Let's talk about %s"%my_name) print("He's %d inches tall"%my_height) print("He's %d pounds heavy"%my_weight) print("Actually that's not too heavy") print("He's got %s eyes an...
be9c8abfc6a30a7a5c61347467e5020076904cfd
Ariyohalder2007/PythonCodes
/linked-list.py
590
3.5625
4
class Node: def __init__(self, data=None): self.data=data self.nextval=None class SLinkedList: def __init__(self): self.headval=None def display(self): printval=self.headval while printval is not None: print(printval.data) printval=printval.ne...
b8b7553f268126c5b45656b4787d746a244c1bb6
Ariyohalder2007/PythonCodes
/linked-list2.py
1,060
3.671875
4
class Node: def __init__(self, dataval=None): self.dataval=dataval self.nextval=None class LinkedList: def __init__(self): self.headval=None def display(self): printval=self.headval while printval is not None: print(printval.dataval) printval=p...
fc4c783cc026f19ce5f2e40c154c11d052d8e1ed
RyanUkule/Python_Demo
/01.py
119
3.84375
4
# -*- coding: UTF-8 -*- # Python num = input('请输入数字:') if num == 1: pass else: print('not equal to 1')
464df5ad7de3fec6c12af84c377c6cfa27e5f3ac
MySunShine123456/Object
/Excrise/Prime_number.py
306
3.703125
4
#打印100以内的素数 def prime(numbers): for i in range(1,numbers+1): flag = True if i>1: for j in range(2,i): if ( i % j == 0): flag=False break if flag: print(i,' ',end="") prime(10)
ee38d910ee28d68d8c630cf08da3707418462dad
MySunShine123456/Object
/Content/Sum_index.py
420
3.640625
4
#在数组里面返回两个索引值,若两个值得和是target def two_sum(numbers,target):#输入和输出 for i in range(len(numbers)-1):#len(numbers)-1的目的是使最后一个元素留给j for j in range (i+1,len(numbers)): if(numbers[i]+numbers[j])==target: return i,j return -1,-1#找不到时返回-1 print(two_sum([2,7,11,15],17)) print(two_sum([2,7...
4d76ef4edf36797105e0906e239458142c003f69
nickmatsnev/ArtificialIntelligence
/semestral/almost.py
18,728
3.671875
4
import pygame import random game_width = 10 game_height = 20 # R G B GRAY = (185, 185, 185) BLACK = (0, 0, 0) RED = (155, 0, 0) LIGHTRED = (175, 20, 20) GREEN = (0, 155, 0) LIGHTGREEN = (20, 175, 20) BLUE = (0, 0, 155) LIGHTBLUE = (102, 178, 255) YELLOW = (155, 155, 0) LIGHTYELLOW = (175, 175, 20) BACK_C...
80781a6278237e91f7e39cc37dd05c1f4c40ce2a
rohan-blah/ducs_source_code
/python/practical/tri_recursion.py
179
3.8125
4
def triRecursion(k,result): if k>0 : result=k+triRecursion(k-1,result) print(result) #else: result = 0 return result result=0 triRecursion(6,result)
a495741466b32983d67b5831cb0d89cb20d98f58
Anupam02/Codeforces
/8A/train_and_peter.py
1,837
3.78125
4
def main(*args, **kwargs): input_str = raw_input() pattern1 = raw_input() pattern2 = raw_input() main_ptr = pattern1_ptr = pattern2_ptr = 0 is_forward = is_pattern1 = is_pattern2 = False while pattern1_ptr < len(pattern1) and main_ptr < len(input_str): if pattern1[pattern...
9de80962071c5a725dd7a8427ecb182471752980
Izzy1647/Image_Procession
/resize.py
1,000
3.578125
4
import cv2 import os #gtding@t.shu.edu.cn img = cv2.imread('lena.jpeg',-1) print("img:",img) height, width = img.shape[:2] print("h&w:",height,width) # 缩小图像 size = (int(width * 0.3), int(height * 0.5)) shrink = cv2.resize(img, size, interpolation=cv2.INTER_AREA) # 放大图像 fx = 1.6 fy = 1.2 enlarge = cv2.resize(img...
5af359db053d541566c925cfef7718f6d17e1de6
Zantosko/digitalcrafts-03-2021
/week_1/day5/fizz_buzz.py
266
3.5625
4
# Fizz Buzz num_list = list(range(1, 101)) for n, i in enumerate(num_list): if (i % 3 == 0) and (i % 5 == 0): num_list[n] = "FizzBuzz" elif i % 3 == 0: num_list[n] = "Fizz" elif i % 5 == 0: num_list[n] = "Buzz" print(num_list)
14dad0cf4a68beb8a2eb67d05fb3aa32caffb821
Zantosko/digitalcrafts-03-2021
/week_2/day2/practiceRunGame.py
2,434
4
4
""" # * You have two charcaters, a Hero and a Goblin # * Your goal is to let them fight, whoever wins, will be printed out in a victory message (fancy way of saying a function that prints) # * Whoever is defeated can be printed out in that message as well # ? Human name attack defense hp # ! Goblin name attack defens...
15c852d2d567f3334eb8c3dea00bf41cc1fa38e8
Zantosko/digitalcrafts-03-2021
/week_1/day5/fibonacci_sequence.py
755
4.34375
4
# Fibonacci Sequence sequence_up_to = int(input("Enter number > ")) # Inital values of the Fibacci Sequence num1, num2 = 0, 1 # Sets intial count at 0 count = 0 if sequence_up_to <= 0: print("Error endter positive numbers or greater than 0") elif sequence_up_to == 1: print(f"fib sequence for {sequence_up_to}"...
55d9ae4ca9c5fba55861ccccc1179fc005263e57
clomcc/data-science-homework
/HW8_code.py
2,133
3.515625
4
''' CME594 Introduction to Data Science Homework 8 Code - Decision Tree Learning (c) Sybil Derrible ''' #Libraries needed to run the tool import numpy as np import pandas as pd from sklearn import tree from sklearn.ensemble import RandomForestClassifier from sklearn import metrics from sklearn.model_selection import t...
749836f86d6db3a3b356623435c0d87856cf1cd5
clomcc/data-science-homework
/HW3_code.py
3,011
3.6875
4
''' CME594 Introduction to Data Science Homework 3 Code - Principal Component Analysis (PCA) (c) Sybil Derrible ''' #Libraries needed to run the tool import numpy as np np.set_printoptions(suppress=True, precision=5, linewidth=150) #to control what is printed: 'suppress=True' prevents exponential prints of numbers, 'p...
fb9f602648821d0c95ceaa030e7b358d58f2c68f
sergey-igoshin/pythone_start_dz2
/task_2_3.py
975
4.375
4
""" Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить, к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и dict. """ seasons_list = ['зима', 'весна', 'лето', 'осень'] seasons_dict = {0: 'зима', 1: 'весна', 2: 'лето', 3: 'осень'} month = int(input("Введи...
a6abb593940667d113d354fc04fd1b26fd250a5f
chenne69163/pythondemo
/api_back/linknode.py
1,436
3.984375
4
class linkNode: def __init__(self, data): self.data = data self.next = None class sigLink: """ 链表3要素:长度,head,tail """ def __init__(self, item): self.length = len(item) if self.length <= 0: return i = 0 self.head = linkNode(item[i]) self.tail = self.head i += 1 while i < self.length: sel...
0520b6ddfde7e869f564758b7f3b9398287cb41f
4179e1/pyalgo
/bintree/bintree.py
1,110
3.8125
4
def new_tree_node (value): return { "value": value, "left": None, "right": None, } def tree_from_list (l): if (len(l) == 0): return None root = new_tree_node(l[0]) queue = [root] parent = [] for item in l: node = queue.pop(0) ...
3a00ae5cadcf7be853d52c574208860373bb0072
Heo0916/Python_algorithm
/week_3/homework/02_is_correct_parenthesis.py
1,289
3.5625
4
s = "(())()" ''' 1. ( 괄호가 열림 # stack = [(] 2. ( ( 괄호가 또 열림 stack = ["(","("] 3. ) 괄호가 닫힘 그럼 아까 열린것 중 현재 열린 괄호는 ( ["("] 4. ) 괄호가 닫혔다! 열린 괄호 X [] 5. ( 괄호가 열림 ["("] 6. ) 괄호가 닫힘. 열린 괄호 X -> 올바른 괄호 쌍. [] 바로 직전에 조회한 괄호를 저장 -> Stack 자료구조 최적 ''' def is_correct_parenthesis(string): stack = [] for i in range(len(stri...
504c40851728bbb23c9079f1e3647b278e6746d4
Heo0916/Python_algorithm
/week_1/homework/02_find_count_to_turn_out_to_all_zero_or_all_one.py
1,019
3.671875
4
input = "011110" # 모두 0으로 만드는 방법에서 최소로 뒤집는 숫자 # count_to_all_zero # 0->1로 문자열이 전환되는 순간 count_to_all_zero += 1 # 모두 1으로 만드는 방법에서 최소로 뒤집는 숫자 # count_to_all_one # 1->0로 문자열이 전환되는 순간 count_to_all_one += 1 # 1) 뒤집어질때, 즉 0에서 1 혹은 1에서 0으로 바뀔 때 # 2) 첫 번째 원소가 0인지 1인지에 따라서 숫자를 추가. def find_count_to_turn_out_to_all_zero_or_al...
e6e3fb65e165ec1b9e9f584539499c22d545d2f2
nelsonje/nltk-hadoop
/word_freq_map.py
628
4.21875
4
#!/usr/bin/env python from __future__ import print_function import sys def map_word_frequency(input=sys.stdin, output=sys.stdout): """ (file_name) (file_contents) --> (word file_name) (1) maps file contents to words for use in a word count reducer. For each word in the document, a new key-value pair...
a161e37760313e68d2e4ff31894b85ba6d43b9e8
larteyjoshua/Advanced-Python
/joinstrings.py
112
3.546875
4
words = [ "Hello", "World"] def join(words): joint= " ".join(words) print(joint) join(words)
4ae67ce6e14049800c548b11f775593d6e6996fe
rashmierande/practice
/strings/anagram.py
554
3.65625
4
def anagram(str1,str2): str1=str1.replace(' ',"").lower() str2=str2.replace(' ',"").lower() cnt={} if len(str1)!=len(str2): return False if len(str1)==1: return True for letter in str1: if letter in cnt: cnt[letter]+=1 else: cnt[letter]...
8f702b3f28a741405eee4ca8bb17ba163eedc88d
rashmierande/practice
/strings/cnt_words_freq.py
599
3.5625
4
def get_word_freq(filename): cnt={} with open(filename,"r") as f: lst=f.read().split() for word in lst: if word in cnt: cnt[word]+=1 else: cnt[word]=1 return cnt print(get_word_freq("word_cnt.txt")) def get_word_freq1(filename,findword): cnt={}...
35751092f60f394caa98463fc2e4be4cb6b6448b
goingenrage/PIPCO-Faceident
/scripts/CreateTables.py
899
3.578125
4
import sqlite3 import configparser def createTables(dbpath): try: # Define the path to the .db-file . If not provided, the file will be created connection = sqlite3.connect(dbpath) cursor = connection.cursor() # open file, which has to be located within the project dir ...
3ff26ff968410c3f06031903aa2035a1f5e33105
ebrandiao/fundamentos_de_python_TP1
/calculo_fatorial.py
837
4.3125
4
"""3. Escreva uma função em Python que calcule o fatorial de um dado número N usando um for. O fatorial de N=0 é um. O fatorial de N é (para N > 0): N x (N-1) x (N-2) x … x 3 x 2 x 1. Por exemplo, para N=5 o fatorial é: 5 x 4 x 3 x 2 x 1 = 120. Se N for negativo, exiba uma mensagem indicando que não é possível calcu...
e460c1e9ffc44f41ddf0e41cf5946a7903afc412
chinmay28/leetcode
/python/practice/amazon_oa/optimal_utilization.py
1,109
3.828125
4
def get_optimal_pairs(alist, blist, target): alist.sort(key=lambda x: x[1]) blist.sort(key=lambda x: x[1]) # we pick smaller number from a and bigger number from b i = 0 j = len(blist) - 1 pair_list = [] import sys max_sum = -sys.maxint - 1 while i < len(alist) and j >= 0: ...
b2f563a315d94bb0cdfcbb3d2ced6aeca42af702
chinmay28/leetcode
/python/practice/microsoft_oa/min_moves_string_without_3char.py
497
3.515625
4
def min_count(string): acount = string.count('a') bcount = string.count('b') small_count = bcount if acount > bcount else acount if not any(['aaa' in string, 'bbb' in string]): return 0 if small_count == 0: return 0 if small_count > 8: return (n-8)/2 + 3 if small_coun...
c2fdb16038edda468c57387d07710bf295ac6e3d
XinheLIU/Coding-Interview
/Python/Data Structure/Binary Tree/Level Order/Binary Tree Zigzag Level Order Traversal.py
1,059
3.5625
4
class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] # use two stacks ret, s1, s2 = [], [], [] # or queue does not really matter s1.append(root) while ...
5c53b02335048a3dd639803e6bf3053c80ffb813
XinheLIU/Coding-Interview
/Python/Data Structure/Binary Tree/Traversal/429.n-ary-tree-level-order-traversal.py
1,530
3.9375
4
# # @lc app=leetcode id=429 lang=python3 # # [429] N-ary Tree Level Order Traversal # # https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/ # # algorithms # Easy (60.85%) # Likes: 351 # Dislikes: 36 # Total Accepted: 50K # Total Submissions: 82K # Testcase Example: '{"$id":"1","children":...
5a58819502bda4370add1e106c3213f63b3a2e23
XinheLIU/Coding-Interview
/Python/Algorithm/Sorting/Templates/Quick Sort.py
1,787
3.859375
4
import random class Solution(object): def quickSort(self, array): """ input: int[] array return: int[] """ self.helper(array, 0, len(array) - 1) return array def helper(self, array, l, r): if l < r: pivot = self.partition(array, l, r) self.helper(array, l, pivot - 1) ...
bfd6ca125e7be564756a746a214074b1f1eadab8
XinheLIU/Coding-Interview
/Python/515.find-largest-value-in-each-tree-row.py
1,394
3.625
4
# # @lc app=leetcode id=515 lang=python3 # # [515] Find Largest Value in Each Tree Row # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def largestValues(self, root: ...
131549eb18d31fffab90ed5b014ad9122ca507ba
XinheLIU/Coding-Interview
/Python/Data Structure/Heap:PriorityQueue/295.find-median-from-data-stream.py
1,128
3.5
4
# # @lc app=leetcode id=295 lang=python3 # # [295] Find Median from Data Stream # # @lc code=start import heapq class MedianFinder: def __init__(self): """ initialize your data structure here. """ self.maxheap, self.minheap = [], [] def addNum(self, num: int) -> None: ...
66f8c7e5f71056f6ad65f671e8f6ec6a0e4ac808
XinheLIU/Coding-Interview
/Python/Data Structure/Linear List/Array/2D Array/289.Game of Life.py
949
3.515625
4
class Solution: def liveNeighbors(self, board, m, n, i, j): lives = 0 for x in range(max(i - 1, 0), min(i + 1, m - 1) + 1): for y in range(max(j - 1, 0), min(j + 1, n - 1) + 1): lives += board[x][y] & 1 lives -= board[i][j] & 1 return lives def gameO...