blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e64bc951c27896293f8b1da440cc731de5ff8f3e
sabhishekpratap5/Python_Programs
/tuple/program10.py
284
4.21875
4
# # Write a Python program to reverse a tuple. # # tuple1 = "abhishekSingh" # rev_tuple = reversed(tuple1) # print(tuple(rev_tuple)) import time st = time.time() a = tuple(range(0, 100000000)) a = set(a) a = list(a) print(a) ed = time.time() to = ed - st print(time.time() - st)
9aac6d23d587955773c791cc7d597de0c30fb98d
PPerminov/python
/stuff/chessboard.py
1,028
3.546875
4
import sys sys.setrecursionlimit(20000) def chessBoard_loops(): board = "----------\n" for r in range(8): line = '|' for c in range(8): if ((c + r) % 2 == 0): line += "x" else: line += " " board += line + "|\n" return board + ...
3d64f6a5db4532b004e3ee92e2e45bb111f23f9e
chenlei0x/leetcode
/728/728.py
419
3.59375
4
#! /usr/bin/env python3 class Solution: def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ res = [] for i in range(left, right + 1): cur = i while cur != 0: digit = cur % 10 if digit == 0: break cur = cur// 10 if i % digit !=...
c74db4ea2fc30a2797d899c8e2828781ad8e0291
AlbanerPabaMandon/IA
/nqueens_FINAL.py
2,309
3.5625
4
import random tablero=[] DIMENSIONES=15 #Establece la matriz vacia para el tablero def establecer(): global tablero for i in range(DIMENSIONES): tablero.append([]) for j in range(DIMENSIONES): tablero[i].append(None) for x in range(DIMENSIONES): for y in range(DIME...
d4cfa42d8dcc953856c25b20e828a3d800ba2aa3
bradstrat/ContinuousAveragelist
/average_via_input.py
981
4.03125
4
from functools import reduce def programy(): running = True print("I output the average of a list that you add files to. \nType MENU to access the menu. \n") listy = [] while running == True: def listaverage(givenlist): print(sum(listy) / len(listy)) currentn...
5d3211bb98c70a56db6b1ff6ebfd881c488bc219
CallumTCarter/Python-Code-
/mazeSolver.py
5,557
3.765625
4
# def addTempBlock(): # global tempBlock # # currentPos[0][1] = position(y,x) # global currentPos # y = currentPos[0] # x = currentPos[1] # try: # if (maze[y+1][x] != 1) and (y+1!= height+1): # possibleDirection +=1 # print 'can move down' # except: pass # ...
777a61fecc4184078a49b8a29c97545315492d35
raswolf/Python
/module6/more_functions/inner_functions_assignment.py
707
4.5
4
""" Program: inner_functions_assignment.py Author: Rachael Wolf Last date modified: 10/03/2020 The purpose of this program is to. """ def measurements(m_list): """Takes the length and width of a rectangle and describes the perimeter and area :param m_list, a list containing the side measurements of the recta...
f9df93cca75e97d2db761e5100ca81b99894e42c
dp1608/python
/LeetCode/1806/180612implement_strstr.py
1,185
4.28125
4
# -*- coding: utf-8 -*- # @Start_Time : 2018/6/12 16:13 # @End_time: # @Author : Andy # @Site : # @File : 180612implement_strstr.py """ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle =...
396d27598c32e1d62655b7fbfd3c2fd42f3133c6
sbsdevlec/PythonEx
/Hello/Lecture/Day04/Tuple/06. TupleEx.py
671
4.5625
5
# empty tuple # Output: () my_tuple = () print(my_tuple, type(my_tuple)) # tuple having integers # Output: (1, 2, 3) my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes # Output: (1, "Hello", 3.4) my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple # Output: ("mouse", [8, 4, 6],...
f2f3bc568c9e7696c48658432c1ce5ed84e6094e
Kailash-Sankar/learning_python
/day3/ping.py
695
3.671875
4
''' ping a list of hosts to check status ''' import os def clean_hosts(x): x = x.strip() print x if not x.startswith('#'): return x return None fin = open("hosts.txt", "r") # hosts = map(lambda x: x.rstrip() if not x.lstrip().startswith('#') else pass , fin.readlines()) # hosts = filter(lam...
8d78ec28fd6910f170b11d3e316e8ce609d1f5fa
suzywho/Million-Song-Database
/asn2.py
6,445
4.1875
4
## CS 2120 Assignment #2 -- Zombie Apocalypse ## Name: Shi (Susan) Hu ## Student number: 250687453 import numpy import pylab as P #### This stuff you just have to use, you're not expected to know how it works. #### You just need to read the plain English function headers. #### If you want to learn more, by all means ...
60edb9e2614232e5fc35fa876e47af3e5e1c49f7
tehs0ap/Project-Euler-Python
/Solutions/Problems_20-29/Problem_29.py
813
3.796875
4
''' Created on 2012-12-26 @author: Marty ''' ''' Consider all integer combinations of a**b for 2 <= a => 5 and 2 <= b => 5: 2**2=4, 2**3=8, 2**4=16, 2**5=32 3**2=9, 3**3=27, 3**4=81, 3**5=243 4**2=16, 4**3=64, 4**4=256, 4**5=1024 5**2=25, 5**3=125, 5**4=625, 5**5=3125 If they are then placed in numerical ...
7dca0bcc61a7eff04a45a22e9dae87afc02972a3
karolinaewagorska/lesson2
/str.py
1,095
4.125
4
# Вывести последнюю букву в слове word = 'Архангельск' print(word[-1:]) # Вывести количество букв а в слове word = 'Архангельск' print(len(word)) # Вывести количество гласных букв в слове word = 'Архангельск' vowels_sum = 0 for letter in word: if letter in "а, А, е": vowels_sum = vowels_sum + 1 print(...
5d9548eb01f4c012e96ff9fb68bbe9738a00aadd
einorjohn/Pycharm
/Lec 10 Ex. 1.py
460
3.609375
4
fname = input('Enter file name: ') try: fhandle = open(fname) except: print('File cannot be opened:', fname) exit() emails = dict() for line in fhandle: if line.startswith('From '): line = line.split() email = line[1] emails[email] = emails.get(email,0) + 1 emailslist = [] for email, count in ema...
363d4f9d7f6a17bbab322c10fcb0db8bf8c5642d
generationzcode/question-13
/main.py
244
3.65625
4
Registered = input("Are you registered with us?") if Registered == "Y": username = input("user:") password = input("pass:") elif Registered == "N": print("go to the registration page") else: print("please try again. Input Y/N")
edc5bb48d56e8c065d92cb8473a4426267aa8e13
JoseVictorHendz/estudo-de-inteligencia-artificial
/aula3/terceiroNeoronio.py
1,148
3.921875
4
def calculoDeSaida(soma): saida = 0 if (tipoCalculo == 1): if (soma < 0): saida = 0 elif (soma >= 0 & soma <= 1): saida = soma elif (soma > 1): saida = 1 elif (tipoCalculo == 2): if (soma <= 0): saida = -1 elif (soma ...
3e1fce5c0ff0bf5de817f9a58e5e98a3c0262d2b
ephillips408/cribbage_repo
/declarations.py
2,110
3.609375
4
import random import scoring as score values = { "Ace": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9, "Ten": 10, "Jack": 10, "Queen": 10, "King": 10, } straight_ranks = { "Ace": 1, "Two": 2, "Three": 3, ...
f8882e85f00f79b59cc2d563da472cd423320fc6
sp33daemon/design_patterns
/python/iterator.py
304
4.125
4
def month_name(number): list_of_month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] iterator = zip(range(number),list_of_month) for position, monthname in iterator: yield monthname val = month_name(4) print(type(val)) for month in val: print("{}".format(month))
2e0d27b414109d56736df8df10dcd69b6e6ba981
cuibjut/binary_tree
/binary_tree_traversal.py
2,220
4.21875
4
#!coding=UTF_8 """ 参考:http://www.cnblogs.com/freeman818/p/7252041.html """ class Node: """ 如何表达一棵树: 使用一个类的__init__()方法,方法中含有3个参数,分别是value, left, right, 并为其赋初识值 """ def __init__(self, value=None, left=None, right=None): self.value = value self.left = left self.right = right ...
5b8f2c835b193f3dd0fbbd3d7abdfb693a70ee2d
pron1n/HH
/task_2.py
240
3.65625
4
def strToList(n): list = [] for i in n: list.append(i) return(list) for i in range(10, 10000): x5 = strToList(str(i * 5)) x5.sort() x6 = strToList(str(i * 6)) x6.sort() if x5 == x6: print(i)
f0d3e5fab08eea30ef57af8b37848642cf05c47a
benfred/py-spy
/tests/scripts/recursive.py
93
3.625
4
def recurse(x): if x == 0: return recurse(x-1) while True: recurse(20)
4175702418560f8aee1f2c04bd740e068e21bc0f
screechingghost/Calculator-1.0
/Calculator-1.0.py
1,314
4.1875
4
print("Hello") print("welcome to calculator-1.0") start=input("PRESS 'R' TO ACTIVATE OR PRESS ANY KEY TO CLOSE- CALCULATO") try: if start=="R" or start=="r" : import math print("mode of calculation:") print("+~Add") print("-~Subtract") print("x~Multiply") print("/~Divide") print("s~Square root...
c9fb18b668e8de811e9c8a7841ed394d47bfd8e9
xiaojinghu/Leetcode
/Leetcode0090_Backtrack.py
742
3.75
4
class Solution(object): def backtracking(self, nums, i, path, res): res.append(path) # for each number in nums[i:], we choose one to add into our path # we need to avoid duplicate in this situation for j in range(i, len(nums)): if j == i or nums[j]!=nums[j-1]: ...
53c13339f8c20e1d15c12fc617d35aa39904b225
peterjpierce/project_euler
/solutions/010.py
534
3.671875
4
""" Problem 10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from shared import util def run(): start_time = util.now() total, count = 0, 0 maximum = 2000000 for prime in util.primes(maximum, verbose=True): count += 1 tot...
284a0900bc95b98dc107c1e714be92967779bd43
jngmk/Training
/Python/Programmers/[2019카카오공채] 징검다리 건너기/solution2.py
640
3.5625
4
# 통과 def check(stones, num, k): impossible = 0 for stone in stones: if stone < num: impossible += 1 else: impossible = 0 if impossible >= k: return False return True def solution(stones, k): answer = 1 left = 1 right = max(stones) + ...
d79aa165cf588cf944c9629999f1423d272e3640
camohe90/mision_tic_G6
/s14/13.10_ejercicio2.py
448
3.8125
4
"""Escribir un programa que permita al usuario ingresar dos años y luego imprima todos los años en ese rango, que sean bisiestos y múltiplos de 10""" anio1 = int(input("Ingrese el primer año que desea validar")) anio2 = int(input("Ingrese el segundo año que desea validar")) for anio in range(anio1,anio2): ...
1fa0d38cc1b2618e766308333a3bf4bd2eaf67c0
EverettBerry/ie336
/hw1/stocksimulation.py
435
3.90625
4
import matplotlib.pyplot as plt import random def binomial_model(): up = 500 price = 1 stock = [] for x in range(1000): if random.random() < up / 1000: price = price * 1.02 up -= 1 else: price = price / 1.02 up += 1 stock.append...
9a9d2d0727521adfe19c206327327c1dda8f6fba
YeasirArafatRatul/Python
/SortingAlgorithms/InsertionSort.py
1,359
4.375
4
#insertion sort def insertion_sort(a_list): n = len(a_list) for i in range(1,n): #assign the vlaue of a_list[i] in the variable item item = a_list[i] j = i-1 while j >= 0 and a_list[j] > item: a_list[j+1] = a_list[j] j = j-1 a_list[j+1] = i...
d75a05dfd428b9b8dc19dbe88e5dbe7b5d6071e1
lungen/algorithms
/chapter-4/423-01-reverseString.py
226
4.15625
4
# a function that takes a string and returns a reverse def revString(s): s = str(s) if len(s) == 1: #BASE CASE return s[0] else: return s[-1] + revString(s[:-1]) print(revString('salami'))
47457fca82689454308e6644e7a489a80718dd9c
AnthonyDeFallo/F19352
/ADMDProg1.py
532
3.78125
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ def bSort(listT) : for cnt in range (0, len(listT) - 1): for cnt2 in range(0, len(listT) - 1 - cnt): if listT[cnt2] > listT[cnt2+1]: listT[cnt2], listT[cnt2+1] = listT[cnt2+1], listT[cnt2]...
05c542b502d90a2bafc5134b273ae1dadbdbf877
MHakem/Axelrod
/axelrod/strategies/axelrod_second.py
6,186
3.703125
4
""" Additional strategies from Axelrod's second tournament. """ import random from axelrod.action import Action from axelrod.player import Player from axelrod.random_ import random_choice C, D = Action.C, Action.D class Champion(Player): """ Strategy submitted to Axelrod's second tournament by Danny Champi...
4b2399b5af397bf62a13cf3458e6bc5432566a89
lucNovais/Caminho-Minimo---Grafos
/teste.py
105
3.5
4
q = [1, 2, 3, 4] e = [0, 3, 5, 2] for i in q: print(i) q.remove(3) print() for i in q: print(i)
c8c8f7b9d127d2762ccddabf54e7e6b917ffb167
agalyaswami/infytq-python
/circle color.py
331
3.734375
4
alex.color("green") # alex has a color alex.right(60) # alex turns 60 degrees right alex.left(60) # alex turns 60 degrees left color = ["green", "blue", "red"] for i in range(0,3): alex.color(color[i]) for counter in range(1,5): alex.circle(20*counter) alex.right(120) alex.le...
ad50ab5335c7ecc42e9a71c0141a96df6ab21689
cseshahriar/The-python-mega-course-practice-repo
/function_and_condition/func.py
1,005
3.96875
4
""" functions """ def mean(value): """ isinstance(object, type) The isinstance() function returns True if the specified object is of the specified type, otherwise False """ if isinstance(value == dict): the_mean = sum(value.values()) / len(value) else: the_mean = sum(value) ...
8359b4b2795185252a9f18dc0276fc46f78d1f52
Mohammad-Nobaveh/count-votes
/count-votes-2.py
598
3.75
4
#importing library collections for counting items import collections #creat a list to save inputs(candidates) list1=[] votes=int(input()) #bring iterable for set range for i in range(0,votes): candidates=input() #add input items to list1 list1.append(candidates) #sort list of strings list1.sort()...
495f25772b7196ba065ee32306b0f2f95edb6ad1
filbertlai/Image-Processing
/image_processing.py
31,257
3.546875
4
import subprocess import sys import os subprocess.check_call([sys.executable, "-m", "pip", "install", 'PySimpleGUI']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'Pillow']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'opencv-python']) import PySimpleGUI as sg from PIL import...
634ac1cc131f9af01f7fedd450a5c17edebb3896
sdpython/teachpyx
/teachpyx/practice/rues_paris.py
17,689
3.640625
4
# -*- coding: utf-8 -*- from typing import Callable, Dict, List, Optional, Tuple import random import math from ..tools.data_helper import download_and_unzip def distance_paris(lat1: float, lng1: float, lat2: float, lng2: float) -> float: """ Distance euclidienne approchant la distance de Haversine (uniqu...
1519e6d70a647222cc8c97744987ed69dac524e8
martinaoliver/GTA
/ssb/m1a/exercise_answers/ex7a.py
508
4
4
months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August',9:'September', 10:'October', 11:'November', 12:'December'} for m in months.keys(): print (m, "is", months[m]) # Or if the keys are stored as strings: months = {'1':'January', '2':'February', '3':'March', '4'...
b920f867017fd8e708fe0ed96633b251aff5304a
brunorijsman/euler-problems-python
/euler/problem068.py
3,030
3.59375
4
import math import itertools from tkinter import * canvas_width = 800 canvas_height = 800 ring_radius = 100 point_radius = 20 def point_location(point, nr_points): arm = point // 2 nr_arms = nr_points // 2 mid_x = canvas_width // 2 mid_y = canvas_height // 2 base_angle = -math.pi / 2 one_arm_angle = 2 * m...
b711961aa017e140327e8ccdc681619e3a85611a
jimmus69/python-projects
/Ch10_OO/Classic_vs_New_Classes/New/TomCat.py
254
3.546875
4
from Cat import Cat class TomCat(Cat): def talk(self): """ To call a method in the superclass when the method is overridden in the current class. use super(current_class_name, self).method() """ super(TomCat, self).talk() print "Burp!"
cc184e3a4546ada02065c7216610341e791e9931
khygu0919/codefight
/Intro/matrixElementsSum.py
904
4.15625
4
''' After they became famous, the CodeBots all decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms. Each cell in the matrix contains an integer that represents the price of the room. Some rooms are free (their cost is 0), but that's probably because they are...
ca44d1179fb8094ef56c2290b4ffa59ac45b3e23
dongqui/problemSolving
/structure/Stack.py
752
3.78125
4
import unittest class Stack: def __init__(self): self.items = [] self.max = 5 def push(self, item): if len(self.items) < max: self.items.append(item) else: print("stack overflow") def popitem(self): self.items.pop() def peak(self): ...
c8fa6e5addfc64a1cf7cc203f1d5e295c343bc44
SaanyaV/RSAEncryption
/testTimeForPrime.py
1,583
3.953125
4
# -*- coding: utf-8 -*- """ Code to create PrimeNumbers """ import math import time def testPrimeBrute(a): if a <= 1: return False elif a == 2: return True for i in range(2, math.ceil(a**.5)+1): if a % i == 0: return False return True def firstPrim...
194cd1716c79d967d656779d7698e4be6982a7ed
CRHS-Winter-2021/project---tic-tac-toe-TylerKennedy1660
/main.py
2,740
3.703125
4
# Tic Tak Toe # Tyler Kennedy # Feb 17th 2021 import sys #constants turn = 0 stop = 0 X_O_pos = [] def print_board(): the_board = (' | | \n '+ X_O_pos[7] + ' | '+ X_O_pos[8] + ' | '+ X_O_pos[9] + ' \n_____|_____|_____\n | | \n '+ X_O_pos[4] + ' | '+ X_O_pos[5] + ' | '+ X_O_pos[...
4708f35ef7dd0de9f716643970b0f242e17cd736
aderas2/Zuri
/OOP deep dive.py
2,406
4.0625
4
class Animal: animal_type = 'Mammal' counter = 0 def __init__(self,name,number_of_legs): self.name=name self.number_of_legs =number_of_legs Animal.counter +=1 def can_run(self): print('Animal %s runs with %s' %(self.name,self.number_of_legs)) @classmethod #class mwthod comes with all the de...
822880148669ac16f0428a0ce163ed646a46cc4a
prabhurd/DataScientistPython
/exerciseleetcodeArraysStrings.py
2,244
3.625
4
from typing import List class Solution: def moveZerosToBack(self, nums:List[int]) -> None: print("moveZerosToBack") print(nums) j = 0 for num in nums: if num != 0: nums[j] = num j = j+1 else: for c_index in range(j,len...
669e61e7b45996d477f77dc8413ca545a0b926f1
Wyqq-kerio/Lab2
/lab2/fun3.py
903
3.953125
4
import string import os import re # Count the number of "if else" structures def count_if_else(lines): # Number of structures if_else_num = [] if_else_total=0 for line in lines: line1=line.strip().split('\n') # Convert the list to a string line2=''.join(line1) ...
5ac8c4d1a16c14a2ed34e072f71e57c33a3de963
Jayshri-Rathod/loop
/sum.py
319
3.890625
4
# counter = 0 # while counter < 5: # print ("NavGurukul") # counter = counter + 1 # print ("one time print" ) # number=0 # sum=0 # while number <= 10: # sum=sum+number # number=number+1 # print(sum) # num=10 # sum=0 # while num>=0: # sum=sum+num # num=num-1 # print(sum)
d24fa0880322cfab9bd4c687a8f3e092dbcdc6af
Ca11me1ce/PSU-CMPSC122-LAB
/LAB8.py
2,242
3.65625
4
class Node: def __init__(self, value): self.value = value self.next = None def __str__(self): return "Node({})".format(self.value) __repr__ = __str__ class OrderedLinkedList: def __init__(self): self.head=None self...
1bc83d914187103ec00d3e15a9e1113fd91ddc64
xuyanlinux/code
/module04/chapter01/09线程的互斥锁.py
789
3.515625
4
#Author:Timmy from threading import Thread import time n = 100 def task(): global n num = n time.sleep(0.1) n = num - 1 if __name__ == '__main__': t_l = [] for i in range(100): t = Thread(target=task) t_l.append(t) t.start() print(len(t_l)) for t in t_l: ...
8d52912d9fe99cf044f9e24063faaa284f34d7d1
alanaalfeche/ml-sandbox
/kaggle/data_cleaning/scaling_and_normalization.py
2,995
3.78125
4
# # Get our environment set up # To practice scaling and normalization, we're going to use a [dataset of Kickstarter campaigns](https://www.kaggle.com/kemical/kickstarter-projects). import pandas as pd import numpy as np # for Box-Cox Transformation from scipy import stats # for min_max scaling from mlxtend.preproc...
0453665d8a19a952cc781c8bbdfbc3b621236cb6
InimigoMortal/Casino
/Casino2.py
3,201
3.640625
4
import tkinter as tk from random import * class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.msg = tk.Label(self,text="Quantidade de dinheiro apostado:") self.msg.pack() self.en = tk.Entry(self) self.en.pack() self.banco = float(500) s...
b44b7669d5697f2dda9fa909ba4104929aeff70d
liliancor/cursoemvideo
/desafio08.1aula07.py
159
3.734375
4
m = float(input('metragem: ')) print('O valor de {}m corresponde a {}km, {}hm, {}dam, {}dm, {}cm e {}mm.'.format(m, m/1000, m/100, m/10, m*10, m*100, m*1000))
dfa5055c60f77e2d511af6da21e4ed07ae48bfd5
xxw1122/Leetcode
/Python/Linked-List-Cycle-II.py
621
3.65625
4
#!/usr/bin/env python class ListNode: def __init__(self, x): self.val = x self.next = None # @param head, a ListNode # @return a list node def detectCycle(self, head): if head == None: return None node1 = head node2 = head while node1 != None: node2 = node2.next ...
0cb61163cd2888fa76f8fb2c4671da98b85f89cc
yubanUpreti/IWAcademy_PythonAssignment
/Python Assignment/Data Types/question29.py
173
3.6875
4
dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} for key,value in dic2.items(): dic1[key]=value for key,value in dic3.items(): dic1[key]=value print(dic1)
0b0e7597bc21a71b267b2426225bd341cf6fc35f
Kayransteelink/F1M1PYT
/ditbenik3.py
533
3.953125
4
import datetime print('hallo!') print('ik ben kayran') naam = input('') print(f"hallo {naam}") print(f"datum en tijd is {datetime.datetime.today()}") print(f"{naam} wil jij dit programma nog een keer doen?\nType Y/N") option = input ('') if option.lower() == 'yes': print("wil je hem im stukjes?") else:...
afcc520df8830d7804404e90fe4a34540d6d5dcc
VenkataChadalawada/Machine-Learning
/Apriori_Python/apriori_mine.py
1,488
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 7 17:39:50 2018 @author: vchadalawada """ # we are going to use apyori.py in the same directory which we got from python community import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the dataset dataset = pd.read_cs...
9726c0156515cc567a57aa75647ed990f339bb09
rbangamm/algos
/dcp254.py
1,068
3.90625
4
def prune(node): if node.left is None and node.right is None: return node if node.left is not None and node.right is not None: node.left = prune(node.left) node.right = prune(node.right) return node if node.right is None: return prune(node.left) if node.left is No...
36f3f34cb2a65f30750fe0cc99eec96e975f57f4
amandabrosseau/planets
/planets.py
1,156
4.125
4
#!/usr/bin/env python3 worlds = { "mercury" : "burning", "venus" : "greenhousy", "earth" : "comfy", "mars" : "ruddy", "jupiter" : "biggly", "saturn" : "ringy", "neptune" : "bluey", "uranus" : "buttly", "pluto" : "NOT A PL...
9843995d491549aaf05cbc767d4616aea48b05eb
brynelee/gk_dataanalysis_practices
/dataminingDemo1/xdtools.py
214
3.5
4
def print_line(char,times): print(char * times) def print_one_line(): print_line('*', 50) def print_lines(): row = 0 while row < 5: print_line("*",50) row += 1 print_lines()
f8316ffaf8958285dbdbcce324f6e9a6b4b539cb
dylanplayer/ACS-1100
/lesson-8/example-1.py
669
4.125
4
''' Let's practice using .read()! .read() reads the entire file. If want it to read a number of characters, pass the number (int) between the parentheses. ''' # STEP 1: Store file name in a variable input_file_name = 'languages.txt' # STEP 2: Open the file in read mode ('r') infile = open(input_file_name, "r") # S...
4b36dbeec9ce211536bc602a56613b0b7402a7ad
nicoglennon/project-euler
/problem-1.py
367
4.0625
4
# Problem 1: Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # my solution: i = 1 sum = 0 while i < 1000: if (i % 3 == 0) or (i % 5 == 0): su...
b032b929a6b2b37e6c254dad6db7665980b11c5f
hlissner/practice
/codeeval/hard/014stringpermutations/solution.py
459
3.71875
4
#!/usr/bin/env python from sys import argv def permutations(word): if len(word) == 1: return [word] first = word[0] perms = permutations(word[1:]) result = [] for perm in perms: for i in range(len(perm)+1): result.append(perm[:i] + first + perm[i:]) return result f...
21c0978fc961abe52c49ac489715a591a0259427
wsims/CS434
/src/assignment_3/mlp_relu.py
2,987
4.09375
4
"""Use this to complete part 2 Usage: $ python mlp_relu.py Trains a three layer neural network using the relu function as the activation function. Trains on four different learning rates (0.1, 0.01, 0.001, 0.0001) and plots the results. Finally, performs a classifier test on ...
70b8cc0039e61655f3b38eb26a141e7b359f7c79
rudzy123-zz/Py2
/A11.py
2,314
4
4
#Rudolf Musika #CIS 1400 #Chapter 11 Assignment ConstantMealPlan1 = 560.00 ConstantMealPlan2 = 900.00 ConstantMealPlan3 = 1300.00 def main(): while True: displayMenu() if menuSelectedNumber ==1: calcNumberOfSemesterTot() if menuSelectedNumber ==2: calcNumberOfSemeste...
c2357a66972665c4c40431bbd189bf150a811c62
cbass2404/bottega_homework
/day08/string_index.py
170
3.953125
4
sentence = 'The quick brown fox jumps over the lazy dog' # sentence = 'T' if len(sentence) < 2: print('Empty String') else: print(sentence[0:2] + sentence[-2:])
16c3986a4505e8b657f12b80991c3317e79906fb
UnixLoverSaurabh/AssistantYui
/tasks/2048/2048.py
4,349
3.859375
4
import random import single_input class Board(object): def __init__(self, size): self.size = size self.board = [[0] * self.size for i in range (self.size)] self.empty_cell = [] def update_empty_cell(self): self.empty_cell[:] = [] for i in range (self.size): for j in range (self.size): if self.boar...
99fd98d9c1165ebec531b144afedb9942a5502be
MSDubey25/Python-Programs
/Python_Progs/DictionaryPython.py
842
4.21875
4
print("Accessing elements from a Dictionary") dict1={1:1,2:2,3:3} print(dict1) print(dict1[1]) print(dict1.get(6)) print("adding a value") dict1[4]="Namaste" print(dict1) print("creating dictionary of squares") squares={1:1,2:4,3:9,4:16,5:25} print(squares) print("removing a particular item :25") print(squares.pop(...
81447881ee0e3dd76ed4e5efd2369a7a735efab5
akshatakulkarni98/ProblemSolving
/DataStructures/stacks/remove_adjacent_dups.py
625
3.59375
4
# https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string #TC:O(N) #SC:O(N-D)D=duplicates class Solution: def stack_helper(self, S): stack=list() for i in range(len(S)): ch=S[i] if not stack: stack.append(ch) else: ...
2357cd42f5eacbc449c3410adb17b18016167afa
kriti-ixix/ml830
/python/dictionary hw.py
452
3.921875
4
students = [] keys = ['Name', 'Roll No', 'Marks', 'Percentage'] for i in range(3): studentDict = {} for key in keys: if key == 'Name': studentDict[key] = input("Enter your " + key + ": ") elif key == 'Percentage': studentDict[key] = (studentDict['Marks'] * 100) / 50 ...
254977ce67f3fd6df19edc592334e5cf893c7015
jmorgancusick/micheals-project
/calculator.py
551
4.09375
4
print 'Welcome to my calculator!' x = raw_input('Enter your first number: ') y = raw_input('Enter your second number: ') operation = raw_input('Enter your operation (+-*/): ') answer = 0 if operation == '+': answer = float(x) + float(y) elif operation == '-': answer = float(x) - float(y) elif operation ==...
0c5c6f5374ca68d35a13bac473ae09925eb17d5a
nguyentrantrung986/python
/pythonLearnToProgram/test_palindrome.py
1,910
3.734375
4
import unittest import palindrome_v3 class TestPalindrome(unittest.TestCase): def test_palindrome_1(self): """Test is_palindrome with an empty string ''""" actual = palindrome_v3.is_palindrome_v3('') expected = True self.assertEqual(actual,expected) def test_palindrome_2(s...
4d4e8d75d7a21560c19ff350e441a2834c64871c
alinemitri/Python_para_zumbis
/Lista_II/L2E4.py
290
3.921875
4
n1 = float (input ('Digite o primeiro valor: ')) n2 = float (input ('Digite o segundo valor: ')) n3 = float (input ('Digite o terceiro valor: ')) if n1 > n2 and n1 > n3 : print ('%f é o maior' %n1) elif n2 > n3 : print ('%f é o maior' %n2) else : print ('%f é o maior' %n3)
40779b8cb5b68d58d1894cc85d1edfd97e661a68
jim1949/car_controller
/src/kalman_1D.py
2,415
3.921875
4
# Kalman filter example demo in Python # A Python implementation of the example given in pages 11-15 of "An # Introduction to the Kalman Filter" by Greg Welch and Gary Bishop, # University of North Carolina at Chapel Hill, Department of Computer # Science, TR 95-041, # http://www.cs.unc.edu/~welch/kalman/kalmanIntro.h...
aa98aab4fa9a956c0abc16bb4c7036dcaff7528d
caoxiang104/Practical_Python
/ins_sort.py
320
3.65625
4
# O(n^2) def ins_sort(seq): for i in range(1, len(seq)): j = i while j > 0 and seq[j] < seq[j - 1]: seq[j], seq[j - 1] = seq[j - 1], seq[j] j -= 1 def main(): seq = [1, 5, 3, 4, 6, 2] ins_sort(seq) print("".join(str(seq))) if __name__ == '__main__': main()
e212ea22916e688fde81bcdc65f16d7d3382d727
sbhavisha/As_Practical
/pra33.py
673
4.21875
4
#!/usr/bin/python ####### Code written by Shah Bhavisha ########## ####### This code is for comparing that the no is divisible by 2 and 3 ###### import sys import math def compare(): try: a = raw_input("Enter an number:") ####Taking An input#### n = int(a) print "Number:",n while n >=0: if n%2 == 0 and n...
9ec5a04acbbe7c60d00d927e90497f2be0e1187a
CynthiaYbz/coder-algorithm
/algorithm/strings/last_word_length.py
279
4.03125
4
def get_last_word_length(s: str) -> int: result = s.rstrip() return len(result.split(" ")[-1]) if __name__ == "__main__": print(get_last_word_length("hello world ")) print(get_last_word_length("hello world")) print(get_last_word_length(" hello world "))
b9dcb17056eb66317404d7b088bf27f2ed5ecaee
Riversubs/PythonElementaryCourses
/认识python/py_24迭代遍历.py
212
3.59375
4
name_list = ["czh","lhz","river","chenzhihe","subs"] """ 顺序的从列表中依次获取数据 每次获取的数据都将保存在my_name中 """ for my_name in name_list: print("我的名字叫%s" % my_name)
712e614caeb29f21b795ab8b61dc0867f610bd1f
Eric-J-G/Eric-J-G
/Chess Stuff.py
1,565
3.546875
4
#Permutations mapped to the board from itertools import permutations list = list(range(8)) perms = permutations(list) for perm in perms: print(perm) table = [[0]*8 for _ in range(8)] def print_table(): for row in range(8): print(table[row]) def put_queen(x,y): if table[y][x] == 0: ...
4f6bc663340501d5742237bdf6e1d0d20cb2171c
lihongwen1/XB1929_-
/ch02/strtoint.py
251
3.640625
4
no1=input("請輸入甲班全班人數:") no2=input("請輸入乙班全班人數:") total1=no1+no2 print(type(total1)) print("兩班總人數為%s" %total1) total2=int(no1)+int(no2) print(type(total2)) print("兩班總人數為%d" %total2)
8f867909f42278e959735c0133059efc457923b9
x0215hui/learnpython
/openpyxlstudy.py
5,404
3.671875
4
''' 要使用Python对Excel表格进行读取,我们需要安装一个用于读取数据的工具 openpyxl 。openpyxl 是一个用于读、写Excel文件的开源模块。 安装openpyxl非常简单,在终端中输入代码:pip install openpyxl即可。 如果在自己电脑上安装不上或安装缓慢,可在命令后添加如下配置进行加速: pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple/ ''' import openpyxl # 在安装和导入openpyxl之后,读取指定路径的工作簿需要使用函数:openpyxl.load_workbook(...
8b4e4066d54d94f63d324415fd65e356be989ac7
VaibhavSi47/CB
/covid_bot_test4/text_to_speech.py
688
3.515625
4
# import the required module for text to speech recognition import os import subprocess from gtts import gTTS # The text that you want to convert to audio mytext = "Welcome to Covid-19 Fighting bot!" # language in which you want to convert language = 'en' # Passing the text and language to the engine, # here we hav...
b132edf3ca3db843191f6c40d5939df7f4c0e5db
pettybai/my_practice
/function/closure.py
897
4.25
4
# 一个函数返回了一个内部函数,该内部函数引用了外部函数的相关参数和变量,我们把该返回的内部函数称为闭包(Closure) def make_pow(n): def inner(x): return pow(x, n) return inner a = make_pow(2) print(a(7)) ################################################## # 闭包的最大特点就是引用了自由变量,即使生成闭包的环境已经释放,闭包仍然存在。 # 闭包在运行时可以有多个实例,即使传入的参数相同。 # 闭包实现类 class point(object)...
19613f6ff6cf5ab1bf888c6b817f28c91d8e0f46
fitzcn/oojhs-code
/functions/deck.py
950
4.0625
4
# coding: utf-8 import random """ write a function that prints a random card in the deck. """ def selectRandom(lst): index = random.randint(0,51) print lst[index] """ write a function that will print each card in a deck. hint: use a "for/in" loop. """ def nameYourFunction(nameYourVariable): None """ write a funct...
1e7127a4ba6cf8a3d89b32e1cb756e93c7c50708
nebofeng/python-study
/03python-books/python3-cookbook/第一章:数据结构和算法/1.6 字典中的键映射多个值.py
1,984
3.765625
4
#怎样实现一个键对应多个值的字典(也叫 multidict)? #可以很方便的使用 collections 模块中的 defaultdict 来构造这样的字典。 # defaultdict 的一个特征是它会自动初始化每个 key 刚开始对应的值,所以你只需要关注添加元素操作了。比如: from collections import defaultdict #允许多个重复 d = defaultdict(list) d['a'].append(1) d['a'].append(2) d['a'].append(2) d['b'].append(4) #重复 只有一个 dset = defaultdict(set) dset[...
f416e7b2495b4c3f5459ca3ad02507883e344a56
akimasa-l/aidemy
/learned/supervised-learning/H1juFh8jIeG.py
655
3.90625
4
# 必要なモジュールのインポート from sklearn.linear_model import LinearRegression from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split # データの生成 X, y = make_regression(n_samples=100, n_features=10, n_informative=3, n_targets=1, noise=5.0, random_state=42) train_X, test_X, train_y, test_y =...
779968d8357a729a4e0142ba19eafda9a9251fa3
pruhnuhv/Historical-Stock-Data
/Getdata.py
2,225
3.515625
4
import urllib.request import sys from datetime import date default_date=date(int("2019"),int("01"),int("01")) #Python3 can't take 0 as the first char here due to octal interpretation default_equivalence=1546300800 print("Welcome! Keep Starting-Ending dates and Stock Tickers handy as w...
b6df3a2729ccb35b58d91efab8b63e2557028fbe
ji3g4freddy/NBA3PointContest
/Three_Pointer_Contest.py
11,296
3.578125
4
import random import math import csv import matplotlib.pyplot as plt # Define the class player class player: name='' FG_3PCT = 0 stamina = 0 onfire = 0 variance = 0 def __init__(self,attr_list,bonus=1,strategy=0): self.name = attr_list[0] self.FG_3PCT=eval(attr_list[1]) ...
2356c82bf653aa6061863ba3654ccfb812cd8c4f
dzhao14/HackerRank_code
/practice/algorithms/DP/fibonacci_modified.py
486
3.9375
4
#https://www.hackerrank.com/challenges/fibonacci-modified def solution(f1, f2, n, memo): key = n if key in memo: return memo[key] if n == 1: return f1 elif n == 2: return f2 else: memo[key] = pow(solution(f1, f2, n-1, memo), 2) + solution(f1,f2, n-2, memo) re...
9ead14450e474c717142142a3d909fc05f9a47f5
enzngin/Guessing-a-number-Binary-Search-
/Part3.py
938
3.921875
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 28 23:14:32 2020 @author: USER """ from random import randint def guess_number_pc(upper_bound): a_number = randint(0, upper_bound) #7 up= upper_bound down = 0 attempts = 0 print("A: I guess a number from 1 to {upper}".format(upper = uppe...
218a5781eb0cef4203307dcc05ad2617a3149739
yosef8234/test
/hackerrank/python/math/triangle-quest-1.py
866
4.25
4
# -*- coding: utf-8 -*- # You are given a positive integer NN. Print a numerical triangle of height N−1N−1 like the one below: # 1 # 22 # 333 # 4444 # 55555 # ...... # Can you do it using only arithmetic operations, a single for loop and print statement? # Use no more than two lines. The first line (the for statement...
bfb3370c8ac7d9af56d3f44b2551d4d321160f60
zzdxlee/Sword2Offer_Python
/位运算/不用加减乘除做加法.py
2,750
3.53125
4
# -*- coding:utf-8 -*- # 写一个函数,求两个整数之和,要求在函数体内不得使用 +、-、 * 、 / 四则运算符号。 # https: // blog.csdn.net / zhongjiekangping / article / details / 6855864 # 用位运算实现加法也就是计算机用二进制进行运算,32 # 位的CPU只能表示32位内的数,这里先用1位数的加法来进行,在不考虑进位的基础上,如下 # # 1 + 1 = 0 # 1 + 0 = 1 # 0 + 1 = 1 # 0 + 0 = 0 # # 很明显这几个表达式可以用位运算的“ ^ ”来代替,如下 # # 1 ^ 1 = 0 # 1 ^...
e940071fc294ac24363b86f6feb0a5a1eaf5ae87
Sefan90/AdventOfCode2020
/Day10/Day10.py
979
3.65625
4
def Part1(): f = open("input.txt","r") currentsum = 0 jolt = [0,0,1] #your device's built-in adapter is always 3 higher than the highest adapter inputlist = sorted([int(i) for i in f.readlines()]) for i in inputlist: jolt[i - currentsum-1] += 1 currentsum = i print(jolt[0]*jolt[2...
338f8ea126e9f6d585b9ade56a50110db4ead224
VD2410/Data_Structure_And_Algorithms
/Basics of Python/Task4.py
1,539
4.1875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to i...
51f765a32817a1141edd8115869a8ed789566ced
Nehal31/Python
/PProgramz/pz11.py
366
4.3125
4
''' check the given year is leap or not ''' #taking the given year y = int(input('Enter the year : ')) #check the Leap year if y % 4 == 0: if y % 100 == 0: if y % 400 == 0 : print('Leap Year') else: print('Not leap Number') else : print('Leap year '...
08989484c0b5ed100c5203aa10102812439acb30
maike-hilda/pythonLearning
/count_items.py
390
4.125
4
#Count items in a loop nums = [3, 41, 12, 9, 74, 15] count = 0 for itervar in nums: #itervar is the iteration variable count = count + 1 print 'Count: ', count #Add up items in a loop total = 0 for itervar in nums: total = total + itervar print 'Total: ', total #But there are built-in functions ...
f8840974a55f960b4a9bcf8b236bb3f7a331c90f
Kblens56/ccbb_pythonspring2014
/2014-05-21_class_pt2.py
2,969
3.546875
4
import pandas import numpy cd documents/ccbb_pythonspring2014/ # open sites_complicated in pandas as an Excell file and then parse out Sheet 1 xl_c = pandas.ExcelFile('sites_complicated.xlsx') df_c = xl_c.parse('Sheet1') # how to output file in pandas # to write file in pandas and make csv will be called output.csv ...
db486b71520901b6b817e2696bf40e354de504dd
Snehal2605/Technical-Interview-Preparation
/ProblemSolving/450DSA/Python/src/arrays/MaximumProductSubarray.py
1,047
4.09375
4
""" @author Anirudh Sharma Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. """ def maxProduct(nums): # Special cases if nums is None or len(nums) == 0: return -1 # Overall maximum product globalMaxima = ...
6179f1b62ff82ca0972f5414654e5734b4f1a290
mgijax/lib_py_misc
/symbolsort.py
3,042
3.703125
4
# Name: symbolsort.py # Purpose: provide a splitter() function that can be shared across Python products to # consistently split an alphanumeric string into a tuple of integers and strings for # sorting. # global dictionaries used by splitter() for speedy lookups: sdict = { '' : ('') } digits = { '1' : 1, '2' :...
eca23bf18497424a3c47d939e717251934041869
tiagolsouza/exercicios-Curso-em-video-PYTHON
/exercicios/exe030/exe030.py
108
3.859375
4
a = int(input('Digite um numero inteiro: ')) b = a % 2 if b != 0: print('impar') else: print('par')