blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5d3c19f976eb9ab855cd73c7597a07878076a7d6
VigneshKarthigeyan/DS
/Linked_List/user_inp_ll.py
738
3.75
4
#Add the user input data to Linked list class Node: def __init__(self,val): self.data=val self.next=None class LL: def __init__(self): self.head=None def printll(self): temp=self.head while(temp!=None): print(temp.data,end=' ') ...
78baaad6885ac919eeeda1b29dccdaeed81659a0
ty1cube/Python-Is-Easy
/input and output/Tic-Tac-Toe-Part-B.py
3,298
4.3125
4
## # Tic Tac Toe, Part B Lecture ## # _*_ coding: utf-8 _*_ """ # The game should be similar to # | | 0 #----- 1 # | | 2 #----- 3 # | | 4 """ #!python3 # Define the function drawField that will print the game field # We will try to put our current field into the draw field def drawField(fi...
4021bebd1e31f1c93a086e1db23a136ca007eb57
monalisa6/Titanic-Survival
/visualize.py
2,589
3.515625
4
import pandas as pd import matplotlib.pyplot as plt import utils # panda dataframe for loading csv files df = pd.read_csv("data/train.csv") utils.clean_data(df) fig = plt.figure(figsize=(24, 10)) # shows how many survived and how many died plt.subplot2grid((5,3), (0,0)) df.Survived.value_counts(normalize=True).plot(ki...
6e0ab4c01cbb8ee9d65a78819adef7beb473441c
Utkarsh016/fsdk2019
/day7/currency.py
649
3.78125
4
""" Code Challenge Name: Currency Converter Convert from USD to INR Filename: currecncyconv.py Problem Statement: You need to fetch the current conversion prices from the JSON using REST API Hint: http://free.currencyconverterapi.com/api/v5/convert?q=USD_INR&compact=y Check with ht...
fd8c60f1f70e09e066bd2d87c64af6007ea5a82c
moyehia2020/Mastering-Python
/web-Exercises 1 to 8 .py
2,099
3.8125
4
#[1] my_skills = ["HTML", "CSS", "JavaScript", "PHP", "Python"] x = 0 for i in my_skills: x+=1 print(x,i) #-------------------------------- print("====" * 9) #-------------------------------- #[2] def getNumbersBefore(num): for i in range(1,num): print(i, end="") if num <= 0 : print("Neg...
5776dbdcae93997a6aad93c23c9a13444dbea7c4
VictorBenoiston/Segundo_trabalho_calculo_numerico
/Questao_02/Sistema_linear.py
1,281
3.71875
4
from math import sqrt # Montando o sistema em si, é possível notarmos que c = 6,67 # Daí, ficamos com: # Linha 1: 36a+6b+c=17.33 # Linha 2: 100a+10b+c=42.67 # Achando a e b por meio de escalonamento: matriz = [[36, 6, 10.66], [100, 10, 36]] # Pivô = 36 # mL2 = 100/36 = 25/9 # Achando a nova linha 2: x = [36, 6, 10.66...
3aeab62672665da2514c63d86d3a6fbbe72a6926
aroraakshit/coding_prep
/partition_list.py
995
3.5625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 40ms def partition(self, head: ListNode, x: int) -> ListNode: if not head: return None init = ListNode(None) delete_la...
f175025f24c343e3aa7162cb621f5d69f078ca4e
petertarnue/Python_Projects
/Data Analysis.py
4,080
3.9375
4
from csv import reader opened = open('artworks_final.csv', encoding='utf-8') read_file = reader(opened) moma = list(read_file) moma = moma[1:] print('\n') # Cleaning unwanted characters from the nationality and gender # column of moma dataset. nationality_f = [] gender_f = [] for row in moma: nation...
a909abdc274075fdc76997002d9188e12958049c
Laxmivadekar/lucky-list
/removing empty list.py
371
3.9375
4
a= [5, 6, [], 3, [], [], 9] # print('actual list is'+str(a)) # # Remove empty List from List # # using filter # res = list(filter(None, a)) # print(res) i=0 b=[] while i<len(a): if a[i]!=[]: b.append(a[i]) i=i+1 print(b) # Remove empty List from List # The original list is: [5, 6, [], 3, [], []...
d1249ebcc28881ba2915820ec246d12615162e6e
akilamg/Machine_Learning
/hw1_code_question/logistic.py
4,664
3.953125
4
""" Methods for doing logistic regression.""" import numpy as np from utils import sigmoid def logistic_predict(weights, data): """ Compute the probabilities predicted by the logistic classifier. Note: N is the number of examples and M is the number of features per example. Inputs: ...
d7674c8452d36b885b5d5bf1ba9b05e8822e2b4b
Jyotisri65/Python_development
/method_function_example.py
403
3.5625
4
''' ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter animal_crackers('Levelheaded Llama') --> True animal_crackers('Crazy Kangaroo') --> False ''' def animal_crackers(a): x=[] for y in a.split( ): x.append(y) if x[0][0]==x[1][0]: ...
48249b6b67acc038a99bc1ef9d8301d27642c974
mtargon48/Engineering_4_notebook
/Python/splitlikemyparents.py
176
3.90625
4
#def split(text): text = input("slap a word in there big boi: ") woogoo = list(text) for i in woogoo: if(i == " "): print ('-') else: print(i+"\n")
904016527c39250d3a3b948660552835f30b85cb
GymBoss01/Odd-number
/Латанов ИСиП 1 ПР 8 Нечетные числа.py
138
3.578125
4
a=int(input("")) b=int(input("")) z=[] z.append(a) z.append(b) for i in range(a,b): if(i % 2 !=0): print(i)
3413a8a2721e297b849c28ee56244dfc86907a48
nehabais31/LeetCode-Solutions
/1721. Swapping Nodes in a Linked List.py
1,598
3.859375
4
# -*- coding: utf-8 -*- """ You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). """ class Node: def __init__(self,data = None): self.data = data ...
03aeccb60062fc25b2d215778928a160b209d4c8
SZTankWang/dataStructure_2020Spring
/hw2/question3_has_duplicate.py
901
4.0625
4
def has_duplicate(list1): """ remember to mention your runtime as comment! :param l: List -- list of integers :return: True if list1 has duplicate, return False otherwise. """ mem = {} #----O(1) for n in list1: #-----This for loop has O(n) runtime if n in mem: mem[n]...
bffcde3abadcd715f723580f77fd364dbfa35240
faustfu/hello_python
/iter02.py
339
3.828125
4
# Use iterator to get the first matched item without "break" statement and flags. items = ['book','apple','cup','rock'] def is_short(item:str)->bool: return len(item)<4 try: matched = next( item for item in items if is_short(item) ) print('The first matched item is', matched) except StopIteration: rais...
8858d127e7336c7bf3d4f92664b0a527b23117c1
leilacey/LIS-511
/Chapter 3/pizza.py
1,186
4.34375
4
#4-1 Pizzas pizzas = ["Pepporoni", "Cheese", "Hawaiian", "Philly", "Smoked Mozzerella"] for pizza in pizzas: print ("I like " + pizza + " pizza.") print('I really love pizza') #4-2 Animals animals = ["Penguins", "Chickens", "Flamingos"] for animal in animals: print(animal + " are a bird.") print("All of th...
6de42992acd079ef9638c45c10e29eb9d6e220b1
curiousest/interview-prep
/programming_tests/reverse_list.py
1,462
3.90625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: ...
16876cf9009dee2368fe67df67fa9c69e6308917
henuliyanying/pythonDemo
/countData.py
561
4.0625
4
#定义一个列表,并计算某个元素在列表中出现的次数 # def countX(lst,x): # count = 0 # for i in lst: # if(i == x): # count = count +1 # return count # lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] # x = 8 # print(countX(lst, x)) def countX(lst,x): return lst.count(x) lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print...
34337a96f8368bce2e517a575897374e44dbbcd7
league-python-student/level0-module1-bloobglob
/_03_if_else/_5_circle_calculator/circle_calculator.py
1,051
4.6875
5
from tkinter import simpledialog, Tk, messagebox import math # Write a Python program that asks the user for the radius of a circle. # Next, ask the user if they would like to calculate the area or circumference of a circle. # If they choose area, display the area of the circle using the radius. # Otherwise, displ...
3189215878f345ddf36882f296ae887b45e61805
FeedTheMind/exercise_playground
/python/misc_exercises/reverse/reverse.py
325
4.21875
4
def reverse(iterable): '''Returns reversed version of single iterable item Arguments: iterable = iterable item Returns: Reversed form ''' return iterable[::-1] print(reverse('!olleH')) print(reverse('!eybdooG')) forwards = map(reverse, ['!eybdooG ,!olleH']) print(list(forwar...
4d3d37836f6b5f84a3699021cd41e88d973159a8
MP-C/Python_games_Intro
/JobQuiz.py
3,790
4.28125
4
#environement #print => python <name>.pow #intro print("\n ***** Welcome to my first job founder quiz in Python! *****\n") playing = input("Do you want to play ?") # space in ? " allows visable anwser if playing != "yes": print("I am sorry. It is painfull reading this. I hope you come back later\n") quit...
c7714546430a53c6adb455ff108681ce19c61504
zzlpeter/algorithm_practice
/Part1_Array/Code3_RandomPool.py
886
4.09375
4
"""设计RandomPool结构 功能: 不重复插入、删除、等概率随机返回 """ import random class RandomPool(object): def __init__(self): self.keyIndexMap = dict() self.indexKeyMap = dict() self.size = 0 def insert(self, key): if self.keyIndexMap.get(key) == None: self.size += 1 self.keyIndexMap[key] = self.size self.indexKeyMa...
ef484b7b6462ef6291b4610441686a515599a852
slz37/Personal-Projects
/Project Euler/coded_triangle_numbers.py
1,015
3.703125
4
#Triangle Number Definition def triangle(n): #First Term i = 1 term = 0.5 * i * (i + 1) #Run Until Term >= Sum of Digits while term < n: #Update i i += 1 #New Term term = 0.5 * i * (i + 1) #Boolean if Triangle Word if term == n: return True ...
554ecd7c0b38f9af5a8ed822bdc89d41d6ea0519
johnptmcdonald/pytorch_dl_cv
/walkthrough/linear_regression_03.py
1,646
3.828125
4
import torch import torch.nn as nn torch.manual_seed(1) x = torch.randn(100,1)*10 #100 rows, 1 column y = x + 3*torch.randn(100,1) class LR(nn.Module): def __init__(self, input_size, output_size): super().__init__() self.linear = nn.Linear(input_size, output_size) def forward(self, x): pred = self.linear...
97dab3f15faf1900eea530697b397a2d1277d993
nsmedira/python-for-everybody
/Data Structures/8_lists/exercise4.py
759
4.15625
4
# open the file romeo.txt try : filehandle = open('romeo.txt') except : print('Error opening file.') exit() # create a variable to hold all the words in romeo.txt in a list list_words = [] # read it line by line for line in filehandle : # for each line, split the line into a list of words using the s...
eb3704dfb5f450dd1ec738d60049efd0c79de160
Peixinho20/Python
/python/mundo1/a7/d6.py
329
3.984375
4
''' Crie uma algoritmo que leia um número e mostre o seu dobro, triplo e a raiz quadrada. até a aula 7 ''' n = float(input('Digite um número: ')) a = n*2 b = n*3 c = n**(1/2) print('O seu dobro é \033[4;37;46m{}\033[m, o seu triplo é \033[7;30;46m{}\033[m e a sua raiz quadrada é \033[0;31;40m{:.3f}\033[m'. format(a,b,...
86e0adab45ea6e0a3350b5ac3c79d16c62dc811e
marinasupernova/codewars
/21-vowel-code/index.py
621
3.6875
4
def encode(st): output = st output = output.replace("e", "2") output = output.replace("a", "1") output = output.replace("o", "4") output = output.replace("u", "5") output = output.replace("i", "3") return output def decode(st output = st output = output.replace("2", "e"...
dec10ca970efe66a583435d736aecea063109b7b
lhalbert/Coursera_Intro2Python
/Stopwatch.py
1,808
3.5625
4
# template for "Stopwatch: The Game" import simplegui import math # define global variables counter = 0 msgTime = "0:00.0" attempts = 0 score = 0 # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): global msgTime A = t // 600 B = ((t // 10)...
baabcccdfafcf6f5a6a4ca6a71f1dc4de8e28d95
alpaziz/soultions
/lab_12/fib_while.py
360
3.953125
4
# Solution one: without recursion: def fib(n): first = 1 second = 1 count = 0 while(count < n): # increment the count count +=1 # save old first old_first = first # Update values first = second second = old_first + second return(first) def main(): print(fib(n=6...
21bde3e3dfd586c629d7f0a6fffb786b80e4ce4d
TakezoCan/rpgGame
/RPG_Game/Characters/get_weap.py
1,458
3.59375
4
from utilities import util def weapInput(prompt): weapon = input(prompt) return weapon.strip() def getWeapon(): class weapon(object): weapon_name = "" objects = {} def __init__(self, name, att_die, cost): self.name = name self.att_die = att_d...
11980578a97163f55a927fbd41e6af371fb85ae4
marcoscollares/Python-Scripts
/Aula #7/desafio006.py
342
3.90625
4
print('Desafio 006') print('\033[34mQual número você quer inserir?\033[m') n1 = int(input('Digite o número aqui: ')) dobro = n1*2 triplo = n1*3 raiz = n1*(1/2) print('O número digitado foi \033[1;35m{}\033[m, o seu dobro é \033[1;31m{}\033[m, o triplo \033[1;33m{}\033[m e a raiz \033[1;34m{}\033[m.'.format(n1, dobr...
f42a90bbfaa0ee27ad48cd8806efbd420bb2a0fd
mbg17/superlist
/day22/初始面向对象.py
1,533
3.640625
4
class Dog: def __init__(self, name, blood, aggr, kind): self.name = name self.blood = blood self.aggr = aggr self.kind = kind def bite(self, person): person.blood -= self.aggr print('%s被咬了,掉了%s血' % (person.name, self.aggr)) class Person: def __init__(self, ...
cdd400973110469e0dce2534fcd1e715de1129a0
ae-freeman/Hackerrank-challenges
/dicts-hashmaps/count-triplets.py
1,445
3.953125
4
#!/bin/python3 import math import os import random import re import sys # Complete the countTriplets function below. def countTriplets(arr, r): #initialise dicts and count r2 = {} r3 = {} count = 0 #loop through array for k in arr: #if the current value is in the dict for third numbe...
cc586894f4a036ac7d5c6dc5e346046bf146b399
PlumpMath/SICPviaPython
/Chapter-2/2.2/Exercise-2.27.py
1,251
3.71875
4
# Scheme primitive procedures cons = lambda x, y: lambda m: m(x, y) car = lambda z: z(lambda p, q: p) cdr = lambda z: z(lambda p, q: q) makeList = lambda *items: None if items == () else cons(items[0], makeList(*items[1:])) appendList = lambda list1, list2: list2 if list1 == None else cons(car(list1), appendList(cdr(li...
6ef2481d44864b95c539ec7b297c7727804fa385
Kite1024/DAB-testrun2
/algorithm.py
2,366
3.984375
4
from lib import run_algorithm, Direction, GameState def step(state: GameState): """ This method is called every time the pawn is about to move. :param state: contains the state of the game. See readme.md for the available functions. :return: the direction in which the pawn has to move. """ ret...
e3ec80452888995b0cf027a9dbe122737f58459a
albertoferreirademelo/13-random-programs-bioinformatics
/py1-Ferreira.py
422
3.71875
4
#Sequences input seq1 = "ATACCGGCCTATAACXCGGAA" seq2 = "ATGATATGGAGGAGGTAGCCGCG.CGCCATGCGCGCTXATATTTTGGTAT" #needed variables list_DNA = [] #Task 1 (attaching DNA string from sequence 2 to sequence 1. task1 = seq1+seq2 print (task1) #making a list with legal DNA sequences. for i in task1: if (...
b9fa6441073746288fe4947c541bc4670e75be19
born2trycn/SunNing
/20191207-2.py
448
3.828125
4
month = 1 day = 1 if (month==12): if (day == 24): print('今天是平安夜哦,记得吃苹果) elif (day == 25): print('圣诞老人会给你小礼物哦') if (month == 1): if (day == 1): print('今天是新年哦,新的一年也要好好努力呀') elif (day == 15): print('今天是元宵节!汤圆很好吃!') if (month == 2): if (day == 2): print('二月二,龙...
2ef589a8d6013e81198c54cb8c6505634e87a02d
dbms-ops/learn_python_3
/1_learn_python_3/8-类与对象/8-子类中扩展property.py
2,251
3.75
4
#!/data1/Python2.7/bin/python2.7 # -*-coding:utf-8-*- # @date: 2020/4/16 20:51 # @user: Administrator # @fileName: 子类中扩展property # @description: 扩展定义在父类中的property # ; # class Person: def __init__(self, name): self.name = name # Getter function @property def name(self): return self._nam...
f6824417f791963cf6d7ceca3c8f4561eb1afa21
kpunith8/python_samples
/classes_oop.py
1,561
4.21875
4
class Person: # constructor def __init__(self, real_name): self.real_name = real_name def report(self): print("I'm {}".format(self.real_name)) class Agent(Person): # Agent inherits Person class # class object attribute planet = "Earth" def __init__(self, real_name, eye_color...
acddd3dcaa291a3b854b0da23050fd62fdfdad7e
drdcs/Algorithms-and-System-Design
/StackQueue/nextGreaterElement.py
1,471
3.828125
4
""" Next greater element: input: [18,7,6,12,15] output:[-1,12,12,15,-1] 18, 7, 6, """ class Stack: def __init__(self): self.stack = [] def isEmpty(self): return len(self.stack) == 0 def push(self, val): self.stack.append(val) def pop(self): if self.isEmpty...
1dad04a33f71cb1c922e399113d4b69d4ffa271d
austinma1/Canadian-Computing-Competition-Solutions
/ccc2019j3.py
439
3.96875
4
def count (string): while len(string) > 0: list = [string[0]] for i in range(1,len(string)): if string[i] == string[0]: list.append(string[i]) else: break print(len(list),list[0],end=" ") string = string[len(list):] return ...
7aa86e8db123e4fab33d21ea7872c2d35c8e0d87
alisid03/ACM-Research-Coding-Challenge-F21
/SentiAnalyses.py
1,225
4.03125
4
#string import to remove punctuation and translate text into cleanedText import string #NLTK library that will be used from nltk.corpus import stopwords from nltk.corpus.reader.chasen import test from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.stem import WordNetLemmatizer from nltk.token...
9a73399989fc78a7c22f5d49adf147160b30724a
ccoughlin/SkinDepth
/material/MaterialDB.py
5,589
3.609375
4
'''MaterialDB.py - defines a SQLITE3 backend for Material I/O Chris Coughlin ''' import sqlite3 import Material class MaterialDB(object): '''Handles mapping between the SQLite database and the Material class''' def __init__(self, dbfile): '''Required parameter - filename of database to use. ...
c36daf0819d6280171b39f62bef969be3c969ac5
doraemon1293/Leetcode
/archive/1275. Find Winner on a Tic Tac Toe Game.py
1,367
3.546875
4
class Solution: def tictactoe(self, moves: list) -> str: def f(arrs): f = False for i in range(3): if all([x == "X" for x in arrs[i]]): return "A" if all([x == "O" for x in arrs[i]]): return "B" i...
a2b7bd1fbde4f3f9b4c9622293a9d808fb107a5d
alex-lenk/python_fast_start
/les01.py
229
3.59375
4
# coding : utf-8 print ("Моя первая программа") print ("Привет программист") name = input("Ваше имя:") print ("Привет", name, "добро пожаловать в мир python!")
0c15968a458c8d542ee48711b305cf2cc7ba123e
JulianMendezw/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
119
3.59375
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): return [[x[i]**2 for i in range(len(x))]for x in matrix]
c7b8517ab037ec06752b3319bb45da4343d2bdd4
leinian85/year2019
/month01/code/day07/exercise01.py
309
3.5625
4
''' 字典推导式 ''' list01 = ["张无忌","赵敏","小昭","周芷若"] list02 = [101,102,103,104] dict_all = {item:len(item) for item in list01} print(dict_all) dict_all2 = {list01[i]:list02[i] for i in range(0,4)} print(dict_all2) dict_all03 = {v:k for k,v in dict_all2.items()} print(dict_all03)
2fc3d05f42005193a318967ab445f8b0d674e0e6
EppalaMounika/DS290521E
/W09 D02/27 July Jupyter.py
3,382
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[9]: import time,csv class Product: 'Common base class for all Product' prodCount = 0 prod_list=[] H =[] def __init__(self, PROD, MANF, PRICE, QUAN): self.PROD = PROD self.MANF = MANF self.PRICE = PRICE self.QUAN = QUAN ...
60d9fae4fec7e40d6240b46dfcc7dadab17879ea
JagdishChavan081/diabetes_prediction
/diabetes_Ml/2_code/app.py
2,898
3.921875
4
# Description: This program detets if someone has diabets using machine learning and Python ! #Import the Libraries import pandas as pd from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import Rando...
b242f65a23bc751c3299fa72a76bc04d84e6eba6
tsarep/learning_py
/1.3.py
609
4
4
# Реализуйте при помощи python и библиотеки math (import math) нахождение корней квадратного уравнения по формуле дискриминанта. # На всякий случай общая формула дискриминанта x1,2=−b±√(b2−4ac)/2a import math print('Введите a:') a = int(input()) print('Введите b:') b = int(input()) print('Введите c:') c = int(input())...
5a7d096f2da06b830d4b8ce4b070318c60ecd8b7
jishnusen/pykarel
/run.py
1,442
4.28125
4
#!/usr/bin/env python3 import Karel # Above code is setup # Once you complete a level, check with a programmer! # Then, they will give you the next level level = 5 # Want an extra challenge? # When you get to level 3, try to get the robot to move using the # .front_is_clear() and .check_beeper() functions # Setup co...
83a1c139c3ef685b45c9230af47f3c90ae9ec8d9
Hondral49/Trabalho-Python---ALYSSON-SANTIN
/exercicio_dez.py
790
3.890625
4
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] somapar = maior = somacoluna = 0 for l in range(0, 3): for c in range(0, 3): matriz[l] [c] = int(input(f'Digite um valor para [{l}, {c}]: ')) print('xsz' * 55) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz [l] [c]:^5}]', end= '') ...
3f9c704a8a10cb5df13c53f9ae30fcda8d775ea9
tiwariaditya15/pythonPractice
/decorators.py
525
3.640625
4
class Duck : def __init__(self, **args): self.properties = args def getProperties(self): return self.properties def getProperty(self, key): return self.properties.get(key, None) @property def color(self): return self.properties.get('color', None) @color.se...
395e33e4dc4cafc404b90f7bc55a99b8c84a6688
RIMPOFUNK/FirstLyceumCourse
/Lesson 3 (Простые встроенные функции)/Classwork/Каникулы капризного ребёнка.py
386
4.25
4
town1 = input() town2 = input() towns = ["Пенза", "Тула"] if town1 not in towns and town2 not in towns or town1 == town2\ or town1 in towns and town2 in towns and town1 != town2\ or town2 == "Тула" or town1 == "Пенза": print("НЕТ") elif town1 == "Пенза" or town1 == "Тула" or town2 == "Тула" or town2 ==...
7671eff466be489947203b2e0e316893d7fc3931
Dheeraj-1999/interview-questions-competitve-programming
/python/programs python/factorial using rec.py
143
3.71875
4
def fact(a): global b if a>1: b=a*fact(a-1) return b b=1 a=int(input("enter the number")) c=fact(a) print(c)
3fdf945a4a513edd99c947f557ef84f2fadaaee1
cseharshit/Python_Practice_Beginner
/74.reverse_word_sequence.py
138
3.984375
4
def string_rev(str): str = str.split() str.reverse() return ' '.join(str) print(string_rev(input("Insert some strings: ")))
f493309c134804da7b183c1344c18175a4981c53
sky-dream/LeetCodeProblemsStudy
/[0169][Easy][Majority Element]/MajorityElement_3.py
338
3.640625
4
#solution 3, sort, # leetcode time cost : 152 ms # leetcode memory cost : 13.2 MB # Time Complexity: O(nlgn) # Space Complexity: O(1) or O(N) class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return ...
0a3e870a9b32421cbb888566ae25d5e442fbb4f9
yilunchen27/leetcode_learn
/LeetCode_Python-master/Algorithm-Easy/568_Binary_Tree_Tilt.py
1,151
4.125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 ...
1e81662388d538e549dbd9be334da5a3e2d249a5
DongGeun2/Python_Study
/StuDy/Int_Folder/Int_Treat.py
351
3.671875
4
print(abs(-5)) # 절대값 : 5 print(pow(4, 2)) # 4^2 = 16 print(max(5, 10)) # 최대값 : 10 print(min(5, 10)) # 최저값 : 5 print(round(4.6)) # 올림 : 5 #--------------------------------------- from math import * # math 모든 함수 사용 print(floor(3.99)) # 내림 : 3 print(ceil(3.99)) # 올림 : 4 print(sqrt(25)) # 제곱근 5
79a95c6f3c120202940f94f7f3f942e484c63e43
Sushanthkengunte/analysis
/seperate_Maps.py
279
3.765625
4
import pandas as pd filename = "Data/sample.csv" # columns = ["a","b","c","d","e","f","g","h","i","j","k"] df = pd.read_csv(filename,sep=",",header=None,names = ["a","b","c","d","e","f","g","h","i","j","k"]) print(df) # df2 = df[df.f != "MIRAMAR" ] # df = df[df.f == "MIRAMAR"]
14f76df424a7567c4d11ff7394b305209ddfe4e0
MicahEng/Hazy_star
/Python/19.5.17_spider/analyze.py
1,813
3.5
4
#coding=utf-8 from bs4 import BeautifulSoup #全部的收缩结果 def parseHtml(text): soup = BeautifulSoup( text, features="lxml" ) tags = soup.find_all( 'span' ) #寻找所有的span标签 for tag in tags: cont = tag.string if( cont is not None and cont.startswith( '百度为您找到相关结果约' )): #此处可进行查询优化 ...
128bb67a2bf84ea1ee462828dfc37bdc20e4fc72
TaylorJohnson1024/Python-Assignments
/Assignment 3/Assignment 3 - Taylor Johnson.py
2,211
4.3125
4
#Taylor Johnson #Assignment 3 #September 12, 2016 #This function outputs an 'E' made up of smaller "E's" #The function takes two inputes, the "E's" width and height #The "E" itself is composed of 5 parts #If the user inputs a height non-divisible by 5 than the remainder is appropriately distributed to specific ...
1eb2b3bb6c1e5bb69dc88d0bc870f0222076806f
yibre/Computer_Algorithm
/prob1EX1.py
6,229
3.515625
4
# -*- coding: utf-8 -*- ''' #### problem 1-1. finding minimum #### Input: target change n denomination D = [d1,...,dj] Temporary lists: M[n], denotes a minimum number of coins to make change of n SE380 cents. R[n], denotes a way to make change of n SE380 cents, using M[n] number of cents. Output: Output s...
e0aaf4db06f5cf6b0ba527f5e7e2d925fe551080
owdqa/OWD_TEST_TOOLKIT
/scripts/csv_writer.py
1,663
3.546875
4
import os from datetime import datetime from csv import DictWriter class CsvWriter(object): def __init__(self, device, version): self.device = device self.version = version def create_report(self, fieldnames, row, outfile, daily=True): """Create a new entry in the CSV report file. ...
999ea61d1afb2caaaee2fe0a6e238af259f73f12
monteua/Python
/String/31.py
260
4.25
4
''' Write a Python program to print the following floating numbers with no decimal places. ''' x = 3.1415926 y = -12.9999 print "Original number:", x print "New number:", '{:.0f}'.format(x) print "Original number:", y print "New number:", '{:.0f}'.format(y)
4ffdb036e5903d27dc208adac96281e1f50a00a6
akffhaos95/pythonCode
/basic/sqlite/sqliteTest3.py
234
3.578125
4
import sqlite3 conn = sqlite3.connect("example.db") c = conn.cursor() sql = 'SELECT * FROM STOCKS ORDER BY PRICE' c.execute(sql) rows = c.fetchall() print(rows) print(type(rows)) for i in rows: print(i) c.close() conn.close()
f7c25fb009be5e13a5c966cd5c7716b0653ba811
lopez86/NYCDataTools
/nyc/plotting/MapPlotter.py
3,820
3.578125
4
""" MapPlotter.py Plot a map of data given the data and a mapper object that contains the shapes information. """ __author__ = "Jeremy P. Lopez" __date__ = "2017" __copyright__ = "(c) 2017, Jeremy P. Lopez" from matplotlib.collections import PatchCollection from descartes import PolygonPatch from shapely.ge...
3761a329529f47684b57f059a38906e644ca740c
leonwooster/leonwoo-server-Python
/MLPPytorch.py
1,705
3.65625
4
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F # Get reproducible results torch.manual_seed(0) # Define the model class MLP(nn.Module): def __init__(self, num_inputs, num_hidden_layer_nodes, num_outputs): # Initialize super class super().__init__() ...
59ee506ec48573bf400280401e971011d7f75649
gospelg/oupinger
/main.py
1,309
3.546875
4
import socket from time import sleep #identifies the txt file with the list of computers to resolve the_file = raw_input('Where is the file with the list of computers to test? \n') #this is the file that contains the computers that did not match the ip pattern out_file = 'wrongoucomputers.txt' #this file is the list...
d72f5c8233da8c9a6ee04bd6f955f8a517405f04
chinaylssly/elevator
/schedule.py
7,062
3.5
4
# _*_ coding:utf-8 _*_ from elevator import Elevator from globaltask import GlobalTask from threading import Thread from config import MAX_FLOOR,MIN_FLOOR from time import sleep import random from copy import deepcopy class FactoryElevator(object): count=0 @classmethod def add_elevator(cls,): cl...
edc34c5e917642ceefe9bb067e889e9b79eb0b84
ChrisWilko/Advent-Of-Code-2018
/Day2/Day2AdventOfCode.py
761
3.5625
4
from collections import Counter def first(): two = 0 three = 0 with open('input.txt', 'r') as file: for line in file: freq = Counter(line) if 2 in freq.values(): two += 1 if 3 in freq.values(): three += 1 return two*three d...
9296d476077356af5188ab886cc15a3f1f47239e
shahad-mahmud/learning_python
/day_1/data_types.py
488
4.03125
4
# type() -> returns data type # string -> any type of text # integer -> any type of whole number # float, double -> partial number # boolean -> Ture or False name = 'Saba' # string print(type(name)) age = 10 # integer print(type(age)) income = 10000.5 # float print(type(income)) isStudent = True # boolean ...
6abdf758dc5157ff5752089400052b77f97d563e
danny-hunt/Advent-of-Code-2019
/day6.py
531
3.578125
4
with open('day6.txt', 'r') as text_input: orbitlist = text_input.read().split() orbitlist = [orbit.split(')') for orbit in orbitlist] orbit_dict = dict() for orbit in orbitlist: orbit_dict.update({orbit[1] : orbit[0]}) def count_orbits(object): value = 0 if object in orbit_dict: value += c...
0be472a33e55c6f9d5aa614bcbb7953264187314
CollegeBoreal/INF1039-202-19A-01
/4.Variables/300118196.py
235
4
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 25 15:08:28 2019 """ # déclaration of variable x = 1 print(x*2) x = 4 print(2*x) if(x==4): print('x = 4') else: print('on ne sait pas') # string a = 'x = 4' print ( a )
a3a1b1797558c68a7d46eee8f1132f53d1d04b98
Ameya-k1709/Object-Oriented-Programming-in-Python
/class.py
1,410
4.4375
4
# creating a class named programmers class Employee: company = 'Microsoft' # the company attribute is a class attirbute because every programmers is from microsoft number_of_employees = 0 def __init__(self, name, age, salary, job_role): # This is a constructor self.name = name ...
e8c20e33cfcd17128f4c4ddba59212c7c643020b
bitVil/6.0001
/pset1/ps1c.py
1,608
3.921875
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 20 19:03:52 2019 @author: David Fox Input: A positive real number. Output: the savings rate needed to afford a down payment, given values of parameters. Description: Uses bisection search on range 0 to 10000 (dividing by 10000 to get decimal in computation) checks if curr...
51c1b226905bae98787735f088e2d3ff9cee430e
deborasoliveira/crud-bsi-1
/professorar.py
6,095
3.640625
4
professor = [] #PARA SALVAR CADASTRO, ATUALIZAÇÃO E REMOÇÃO def salvar_cadastrop(): global professor arq = open('professor.txt', 'w', encoding = "utf-8") for i in professor: nome_professor = str(i[0]) cpf_professor = str(i[1]) dpt_professor = str(i[2]) arq.write('%s %s %s\n'...
bdcbf20d1ed0ff304d502279dc3f69133998e0f8
AnonymousWudi/leetcode
/303. Range Sum Query - Immutable.py
822
3.546875
4
# coding=utf-8 """ question url: https://leetcode.com/problems/range-sum-query-immutable/ """ class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.nums = nums if nums: self.value_list ...
1dcf626c29e39cdd32a98ec3e33be11ed6fa0cff
capric8416/leetcode
/algorithms/python3/number_of_music_playlists.py
1,205
3.84375
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip.  You create a playlist so that: Every song is played at least once A song can only be played again only if K other songs have been p...
20b659498d4b4b1af784227508d7c5d0e0cc3eb4
jingruhou/practicalAI
/Basics/BeginnerPython/4-8_list实现队列和栈.py
1,822
4.46875
4
# list实现队列 queue = [] # 定义一个空list,当作队列 queue.insert(0, 1) # 向队列里放入一个整型元素 1 queue.insert(0, 2) # 向队列里放入一个整形元素 2 queue.insert(0, "hello") # 向队列里面放入一个字符型元素 hello print("取第一个元素:", queue.pop()) # 从队列里面取一个元素,根据先进先出原则,输出 1 print("取第二个元素: ", queue.pop()) # 从队列里面取一个元素,根据先进先出原则,输出 2 print("取第三个元素: ", queue.pop()) # 从队列里面...
a06f7cb9f7e2d5ff4eb63fc835ee6aeb92fa6308
jhb86253817/coursera-nlp
/week3/assignment/part1.py
1,874
3.78125
4
#! /usr/bin/python __author__ = "Haibo Jin" import json #part1, exercise of week3, from coursera NLP course lectured by Michael Collins #a program which can replace the infrequent words(count < 5) by symbol _RARE_, in the parse_train.dat def replace_infreq(filename): """replace the infrequent words(count < 5)...
77b1d9ebe3843980a2df2bf8645261bc1f06c9c8
manuck/myAlgo
/프로그래머스/쇠막대기.py
365
3.53125
4
import sys sys.stdin = open('쇠막대기_input.txt') arrangement = input() answer = 0 arrangement = arrangement.replace("()", "ㅣ") # print(arrangement) stack = [] for c in arrangement: # print(stack) if c == '(': stack.append('(') answer += 1 elif c == ')': stack.pop() else: an...
e68d1512bbe4eede186478ee776624d6cd67d272
R-ISWARYA/python
/prime number16.py
179
3.71875
4
lower=900 upper=1000 print("prime number between ",lower,"and"upper,"are:") for num in rang(lower,upper+1): if num>1: for i in range (2,num): if(num%i)==0: break else: print(num)
dbebae2ef32fa258fe929a3792b36748cce4e953
ssar0014/PrimeFactors-of-VeryLarge-Numbers
/primefac.py
517
4
4
from math import sqrt from itertools import count, islice def isPrime(n): if n<2: return False if n==2: return True for i in islice(count(2), int(sqrt(n)-1)): if not n%i: return False return True fact_list = [] def isFact(n): for i in islice(count(1),n): if not n%i: ...
498ef6ecb81b27197762bc4f5d8d301174d56735
danielleberre/satsmt19handson
/sittingresearchers.py
861
3.5
4
#!/usr/bin/python3 import sys def var(i,j,m): """ parameters: i: researcher id between 1 and m j: seat id between 1 and m-1 m: total number of researchers """ return (i-1)*(m-1)+j def at_least_one(i,m): literals=[] for j in range(1,m): literals.append(var(i,j,m)) liter...
3b72ba09916cafcf3efe79df11bb1ae865311d6d
tony36486/Machine-Learning
/Ex3/ex_multi_list.py
431
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 17 19:30:47 2017 python 3.6ver @author: tony this code is a exercise of ML class exercise:multi_dim list """ #multi_dim list multi_dim = [[1,2,3],[4,5,6],[7,8,9]] for index_a in range(len(multi_dim)): for index_b in range(len(multi_dim[index_a])): print('inde...
fcf31090003944cfa243610aa08a4865898638a4
MalarSankar/learning
/class_assignment1.py
680
3.890625
4
class Time: def __init__(self,hours,mins): self.hours=hours self.mins=mins def display_total_min(self): print(self.hours*60+self.mins,"mins") def add(t1,t2): tot_add=t1.hours*60+t1.mins+t2.hours*60+t2.mins tot_hour=int(tot_add/60) tot_min=tot_add%60 print...
dc058007500c0ab57966f2ea43a9e7e554130266
Hindol1234/1
/1.py
289
4.1875
4
marks=int(input("Enter the marks:")) grade='' if marks>75: grade='o' elif marks>60 and marks<=75: grade='A' elif marks>50 and marks<=60: grade='B' elif marks>40 and marks<=50: grade='C' else: grade='D' print("GRADE=",grade) input("Please input for exit:")
f593954619f9fc234dd2b1d6fdc64cf21958a787
laoniu85/udacity_nd000
/stage2.py
3,680
3.96875
4
import random from quiz_lib import * welcom_message="""\ It's a quize about oppsite word. got 5 point first. if your answer is wrong you ponit will +1(if combo will +2) if your point is below 0 you will fail. if the answer is pharse you should connect the word with ' ' eg. "to free" """ level_choose_message="""Input...
6ad3db3cf885e8f1c8bbada742e88600db3d9298
ludamad/7DayRL2013
/source/geometry.py
3,773
3.84375
4
import math # Lots of ugly operator overloading, but it makes the rest of the code prettier. class Pos: def __init__(self, x, y): self.x = x self.y = y def distance(self, pos): dx, dy = pos.x - self.x, pos.y - self.y return math.sqrt(dx*dx+dy*dy) def sqr_distance(self,...
d1c30d87f1a0906d36e3ba870360eb427471a44c
enginaryum/python-functional-programming
/code_samples.py
1,916
3.796875
4
# from __future__ import print_function class1 = [20, 10, 90, 10, 80, 70] class2 = [50, 40, 90, 30, 80, 70] class3 = [70, 90, 90, 80, 80, 70] all_exam_results = [class1, class2, class3] all_exam_results_dict = { 'class1': [20, 10, 90, 10, 80, 70], 'class2': [50, 40, 90, 30, 80, 70], 'class3': [70, 9...
6d3da136a39ca1be35bea639f01682531094241f
rmarren1/code_problem_snippets
/bit_twiddling/pow.py
304
3.90625
4
def pow(x, y): "Given a double x and an integer y, compute x**y" s = 1 while y: if y & 1: s *= x x *= x y >>= 1 return s assert pow(2, 4) == 2**4 assert pow(1, 0) == 1**0 assert pow(4, 8) == 4**8 assert pow(1, 10) == 1**10 assert pow(10, 1) == 10**1
e8ccd79b9f1d0dd560865fce1cc285b1d78dcc41
devferx/platzi-curso-python-basico
/05-operadores-logicos.py
406
4.03125
4
es_estudiante = True print("es estudiante", es_estudiante) trabaja = False print("trabaja", trabaja) print(es_estudiante and trabaja) print(es_estudiante or trabaja) print("es estudiante:", not es_estudiante) numero1 = 5 numero2 = 5 numero3 = 10 print(numero1 == numero2) print(numero1 != numero2) print(numero3 > n...
602a94f6cbca9808b8dbf1614ff2a001b8efaeee
balajiramesh138/ML-project
/problem_statement_3.py
1,787
3.59375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns dataset=pd.read_csv("used cars and bikes.csv") #print(dataset.columns) sns.heatmap(dataset.isnull()) #plt.show() plt.scatter(dataset['owner'],dataset['selling_price']) plt.xlabel('owner') plt.ylabel('selling_pri...
e644554fed5aef54f0e8685e8313572c36208f91
chelvanai/pytorch-regression-classification
/regres2.py
1,300
3.640625
4
import numpy as np from torch import nn import torch from sklearn.model_selection import train_test_split import pandas as pd df = pd.read_csv('house-price-only-rooms-and-price.csv') x = df[['rooms']] y = df["price"] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) input_rows = x_train.shape[...
74a0529f5744252e36a11889392dd3882fadd7f6
AdGw/PracticalTasks
/Python/Money, Money, Money.py
944
3.9375
4
'''Mr. Scrooge has a sum of money 'P' that he wants to invest. Before he does, he wants to know how many years 'Y' this sum 'P' has to be kept in the bank in order for it to amount to a desired sum of money 'D'. The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly. After paying taxes 'T' for the...
e43de700059c31e5db0c7a7f6e837c0556186b3b
ChiselD/pyglatin
/pyglatin.py
2,946
4.21875
4
# THINGS TO FIX # 1. multiple consonants at start of word - DONE! # 2. printing on separate lines - DONE! # 3. non-alphabetical strings # 3a. if user includes numbers, return error - DONE! # 3b. if user includes punctuation, move it to correct location # 4. omitted capitalization # separate variables for the two possi...
763f0da71e14a1f0a7fd8305f3ea7cb36e46c52f
guilherme-witkosky/MI66-T5
/Lista 5/L5E03.py
237
3.953125
4
#Faça um programa, com uma função que necessite de três argumentos, e que forneça a soma desses três argumentos. #Exercicio 3 def exe3(num1, num2, num3): print("A soma do argumentos é:", (num1 + num2 + num3)) exe3(1, 2, 3)
14a18b2b0a03d9e52759ce48859d4ebc752b539a
zzandland/Algo-DS
/GrokkingDP/5/min_del_add.py
1,393
4.03125
4
# Problem Statement # # Given strings s1 and s2, we need to transform s1 into s2 by deleting and inserting characters. Write a function to calculate the count of the minimum number of deletion and insertion operations. # Example 1: # Input: s1 = "abc" # s2 = "fbc" # Output: 1 deletion and 1 insertion. # Explan...