blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a81b7e52f47fa4877ac530d00e2ca0d5605fa93a
aflyk/hello
/other/lesson 2/ex2.py
167
3.796875
4
n = int(input("Введите число от 1 до 9: ")) while n <= 0 or n >= 10: n = int(input("Введите число от 1 до 9: ")) print(n**2)
bc487771e45a1b09f4b38b3626d25ec7ec351140
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/sngakh004/question3.py
2,507
3.90625
4
"""Program to check if sudoku puzzle is correct Akhil Singh SNGAKH0004 15 May 2014""" def check_sudoku(): comp_grid = [] #Makes the rows from the input specified for a in range(9): row = [] str_row = input() for b in range(9): ...
4acd896a3716747e77c2ae61adc67f40347aea0c
alvinwang922/Data-Structures-and-Algorithms
/Strings/Valid-Parentheses.py
956
4
4
""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. """ ...
fb3188867367665d3045ea8cbe873987609575ca
JianhuanZeng/Machine-Learning
/hw5_MarkovChain_NonNegativeFM.py
3,307
3.609375
4
################################### Q1 ########################## """ # Markov Chains: Ranking 763 College Football Teams # Rank 763 college football teams based on the scores of every game in the 2017 season. The data provided in CFB2017 scores.csv contains the result of one game on each line in the format: Team A in...
e17a36881418e6bf2ad264f23d62226ba7228718
Nymrinae/EPITECH-Projects
/Mathematics/300/302separation/print.py
391
3.71875
4
def printSeparationDegree(p1, p2, n): print("Degree of separation between %s and %s: %d" %(p1, p2, n)) def printPersonsList(persons): for person in persons: print(person.name) print() def printMatrix(matrix): size = len(matrix) for i in range(size): for j in range(size...
871ea4ff8e42b586d97e2cdce5e7bbf4f0a26cd9
gomathimano/All-Python-codes-of-ZTM-course-by-Andrei-Neagoie
/Basics Part 2/if_else.py
280
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 16 12:30:51 2020 @author: saura """ a = True b = False if a and b: print("Both a and b are true") elif a: print("Only a is true") elif b: print("Only b is true") else: print("Both a and b are false")
6d58c7b5d85258678f07cfea0954570590bac06d
vineetkumarsharma17/MyPythonCodes
/ChageCase.py
59
3.890625
4
str=input("Enter a string:") str=str.swapcase(); print(str)
b9e693eca18a7578170eb14fd672afbb93b0a30f
jinnygym/Prepro-Python
/prepro72.py
127
3.765625
4
"""Descending""" def main(): """function""" num = int(input()) for i in range(num, 0, -1): print(i) main()
019296a7bafc3683b20741d05a37988058b2f2a7
openstake/hacking_rss_and_atom
/ch13_amazon_wishlist_scraper.py
2,531
3.640625
4
""" ch13_amazon_wishlist_scraper.py Use the Amazon API to look up items for a wishlist. """ import sys, urllib, xmltramp from amazonlib import AmazonScraper from httpcache import HTTPCache AWS_ID = open("amazon-key.txt", "r").read().strip() AWS_WISHLIST_ID = "1QWYI6P2JF3Q5" def main(): """ Given an ...
b25bd772495a0fd83748c0101919c19479d5eb4a
MichalSzewczyk/python-learning
/notes/pandas_lib.py
8,061
3.6875
4
import numpy as np import pandas as pd import pylab # Pandas - is an open source library created in order to give support for easy data analysis # Pandas adds two new data structures to python: # Series - like array or list - ordered, single axis data structure where each element has a label. By default labels of # ea...
d85199aedc9953943419c9c45109de34a2f8007e
enosteteo/Introducao-a-Programacao-P1
/1. Estrutura Sequencial/Lista 01/programa 02.py
135
3.625
4
#Programa 02 b = 2 ** 3 print(b) c = b // 4 + 1 print(b, c) a = b - c print(b, c, a) b = b - 2 print(b, c, a) c = a + b print(b, c, a)
bab40818d614c237af1d44ff844a0731692136ba
rahulvairagyam/checkio-solutions
/checkio/Electronic Station/Find Sequence/2/main.py
2,095
3.625
4
def checkio(matr): ''' Given the matrix NxN (4<=N<=10). Check if 4 numbers in sequence in a column or in a row or diagonally exist. ''' def check(arr): return len(set(arr)) == 1 def check2(arr, n): for i in xrange(n): if check(row[i:i+4]): return True ...
f860e721a033c1d744bc40f4c7aa8470557d2d13
yzl232/code_training
/mianJing111111/geeksforgeeks/array/binarySearch/findRowWithMaximum1.py
1,631
4.09375
4
# encoding=utf-8 ''' Find the row with maximum number of 1s Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Example Input matrix 0 1 1 1 0 0 1 1 1 1 1 1 // this row has maximum 1s 0 0 0 0 Output: 2 A simple method is to do a row wise traversal of the matrix, count ...
24f719a5e509f545a9721a5bf56b37d98eefde88
RowleySanchezm/Yr12ComputerScience
/Python practice/Python rock, paper, scissors.py
1,648
4.375
4
#Rock, paper, scissor game import random while True: ### SRC - Please use more meaningful conditions print("Please select: 1. Rock 2. paper 3. scissor ") choice = int(input("Your turn: ")) while choice > 3 or choice < 1: choice = int(input("enter valid input: ")) if choice == 1: ...
a21f811289e50e088b67b753d84474bc83248dd2
SafonovMikhail/python_000577
/000577MyerPy/000577_35_Dict_info_out_20190915.py
1,844
4.59375
5
# 35 How to pick information out of a list of dictionaries customer_29876 = {"first name": "David", "last name": "Elliott", "address": "4803 Wellesley St." } customer_first_name = customer_29876["first name"] customers = [ { "customer id": 0, "fi...
442e29bc3abf48906d258f71f343c9778948da2f
mich2k/OOP
/Python/M2/list.py
3,063
4.0625
4
import operator def list_methods(): l = [1, 2] print(l) l.insert(0, 4) # (index, element) l.append(3) print(l) print(l * 2) print(l + [4, 5]) del (l[0:1]) # delete by index or gap print(l) l.remove(2) # delete by content print(l) ret = l.pop() # is also possible to ...
d29955e2bb1ccf0b240ebe2007cf0cee60045c06
reulan/google_foobar
/bunny_prisoner_locating.py
3,190
3.765625
4
#/usr/bin/python env #bunny_prisoner_locating.py #mpmsimo #9/24/16 # Time limit exceeded import time start_time = time.time() class Point(object): """Creates a point class matching a coordinate and including prisoner_id.""" def __init__(self): """Default constructor if point is given no values.""" ...
e1ac19e33aa8e4d60ebaec9e951c20ed5bc6e1f8
andyczy/czy-study-py-ml-deepLearning
/study_python/基础知识/基础知识/fun.py
765
3.625
4
# 所有的变量都可以理解是内存中一个对象的“引用”,或者,也可以看似c中void*的感觉。 # 通过id来看引用a的内存地址可以比较理解: # https://github.com/taizilongxu/interview_python#20-%E5%89%8D%E5%BA%8F%E4%B8%AD%E5%BA%8F%E6%B1%82%E5%90%8E%E5%BA%8F a = [] def fun(a): print( "func_in",id(a) ) # func_in 53629256 a.append(1) print( "func_out",id(a)) # func_out 53629256 ...
b5e8fa13b768663894e8a1c3bbc4309bd02a4024
Rings-Of-Neptune/Python-Project-Repository
/CIS115_Course_Project_1.py
840
3.921875
4
# Guess the Number - Week 4 # Name: Ian Wallace # Date: 8/8/2019 # Import the random module import random # Program introduction print(""" ========================= Welcome to my Guess the number program! =========================""") # Declare variables mynumber = random.randint(1, 10) # Query user for input # If ...
a0062fd1a12d826629e9b1a00f5e7c5657b2316f
bakuzan/mari
/maze/generator.py
4,679
3.65625
4
from random import randrange, sample, shuffle from time import sleep from maze import constants from maze.tile.passage import Passage from maze.tile.wall import Wall from maze.tile.exit import Exit from maze.tile.tunnel import Tunnel class MazeGenerator: """ Generator object for maze """ def __init__...
eaecce272be60ea98c720e31a01175b81ec7ffa4
mistry-siddharth/Sorting_Algorithms
/bubble_sort.py
663
4.25
4
''' bubblesort: Its a relatively simple and slow algorithm. Works fine for small number of arguments. But becomes slow when it comes to sorting saw millions of items here j goes from len-1-i, because in as the swapping starts, the largest element will be sorted and will be already at the end. So you dont need to go ba...
85172d9e61381aa46f567031a9ec570e651f2d2a
david-aa/euler
/022bis.py
312
3.5
4
#!/usr/bin/env python def get_value(name): s = 0 for c in name: s += (ord(c) - ord('A') + 1) return s f = open('p022_words.txt', 'r') txt = f.read().strip().replace('"', '') names = txt.split(',') names.sort() cont = 1 total = 0 for name in names: total += cont * get_value(name) cont += 1 print total
3c8ee4d7344b5692efcc8b81e6e5f06e749fc79d
yiguid/LeetCodePractise
/finished/092.py
1,089
3.890625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ newHead...
e13f8f621ee237baa805c1052c17d0818563e8d1
angrycaptain19/Python-Bootcamp
/python/day1/main.py
1,927
4.75
5
# # DAY-1 # # Print() Function # print("Day 1 - Python Print Function") # # Output:- Day 1 - Python Print Function # print("The function is declared like this:") # # output:- The function is declared like this: # print("print('what to print')") # #output:- print('what to print') # # Using of "\n" for breaking the li...
d8d5ffa9dad0f4e8ae08ca16ae916df0f4c5a316
ats0stv/Trinity
/NameParsing/IoOperations/InputReader.py
639
3.515625
4
import logging import argparse """ Module to parse arguments """ logger = logging.getLogger('InputReader') class InputReader: def __init__(self): logger.debug('Input Reader Init') def read(self, inputFilePath): logger.debug(f'Reading input from file {inputFilePath}') try: ...
062cb27454fc2db5a4245c4b8a88a2ed51204a6c
tomirendo/SleepSimulator
/elements.py
1,062
3.546875
4
from enum import Enum class Direction(Enum): r = 0 rd = 1 d = 2 ld = 3 l = 4 lu = 5 u = 6 ru = 7 class Action(Enum): move = 0 eat = 1 #look = 2 class Location: def __init__(self, loc): self.x, self.y = loc def __iter__(self): return iter([sel...
b4786c96fe8d654e642f778a98aa78547f1f455a
faisaldialpad/hellouniverse
/Python/dev/graphs/word_search.py
1,503
3.859375
4
""" 79. Word Search https://leetcode.com/problems/word-search/description/ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be ...
58800ac53e11190108bcad5fad748136e758e2c1
laowucqy/git
/test/test4/test4.py
395
3.640625
4
str = raw_input() ll = list(str) ss = [] for i in range(len(ll)): if ll[i]=='(': ss.append(1) if ll[i]=='[': ss.append(2) if ll[i]==')': if(len(ss)==0): # print 0 break elif ss[-1]==1: ss.pop() else : # print 0 break if ll[i]==']': if(len(ss)==0): # print 0 break elif ss[-1]==2: s...
0349e2c65c4b176d7f7943633c89a9927f75daad
afeinsod/Computer-Science-Curricula
/Python/Project Skeletons/TicTacToe.py
423
3.921875
4
#fills up the board with blanks board =[[' ' for x in range(3)] for y in range(3)] def displayBoard(): print " 0 " + board[0][0] + "|" +board[0][1] + "|" + board[0][2] print " --+-+--" print " 1 " + str(board[1][0]) + "|" + str(board[1][1]) + "|" + str(board[1][2]) print " --+-+--" print " 2 " + s...
5d9a5b003c512c3315c96538b8a363c09dd7ddb9
ChineseDr/python
/base/structDemo.py
74
3.734375
4
lis=list(range(0,10,2)) print(lis) for i in range(1,15,3): print(i)
8b9e269e70c8001a3795214c89e569030811cd58
michlee1337/practice
/Fundamentals/trees.py
5,744
4.0625
4
class Node: def __init__(self,val): self.val = val self.left = None self.right = None def __str__(self): return(str(self.val)) class BST: def __init__(self): self.root = None # consider adding size and height? def _traverseIn(self, cur_node): if ...
fef6d247e453e15b59d6f377fdafcf0137cf7a8a
sharo-mello/python
/whileloop.py
292
3.859375
4
#!/usr/bin/env python # coding: utf-8 # In[2]: i=1 while i <=10: print(i) i = i+1 # In[4]: i=0 while i <6: i +=1 if i ==3: continue print(i) # In[5]: i =1 while i < 6: print(i) i +=1 else: print("i is nolonger less than 6") # In[ ]:
e9e832ebc88893a3e9868714637277a0675fcd8c
rsauhta/ProjectEuler
/p493.py
2,292
3.546875
4
# https://projecteuler.net/problem=493 # import math Factorial= [1] fact = 1 for i in range(1,71): fact *= i Factorial.append(fact) # Assume each ball is numbered uniquely. We will try to find out the various combinations # # Total combinations to pick 20 balls from 70 = 70!/(70-20)!20! # # We will...
c6246367e157044b6401478c79cc3d4ece45e4b1
GaPhil/repton
/lecture1/counter_recursive.py
122
3.71875
4
def counter(n): if n == 0: return 0 if n == 1: return 1 else: print(n) return counter(n-1) print(counter(6))
946c70c64d2f852205b910eb90c3b1dae6e7e7f7
SatyaChipp/_Hackerrank
/ListOperations.py
1,916
3.65625
4
""" Sample Input 0 12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print Sample Output 0 [6, 5, 10] [1, 5, 9, 10] [9, 5, 1] """ ##Solution 1 import sys if __name__ == '__main__': L = [] for _ in range(0, int(input())): user_input = input().split(' ') ...
d9211e621f3f8c9af1404fd4a9eea1b3f37e67c4
CerjioNava/Python_ZTM
/Fundamental/Decorators/Decorators.py
2,848
4.40625
4
#DECORATORS #Se declaran con '@' y sobrecargan las funciones para darle funcionalidad extra. #Son funciones que 'envuelven (wrap)' otra función y la mejora. #EXTRA: Las funciones ocupan espacio en la memoria como las variables def hello(): print ('helloooo') greet = hello #Podemos asignar una función a otra. prin...
d48afa11c7a244ce61dc00ed41e21b06b1ede9b7
BauerJustin/Elements-of-Programming-Interviews-in-Python
/Ch.4 Primitive Types/4.9 Palindrome/palindrome.py
739
3.890625
4
# code def palindrome(x): if x < 0: return False length = len(str(x)) divisor = 10**(length-1) for i in range(length//2): if x // divisor != x % 10: return False x %= divisor x //= 10 divisor //= 100 return True #tests import unittest c...
531ab081d8befecf5a39598f248245e1e45b5c02
VitelD/Algorithms
/Sort_merge.py
642
3.90625
4
# my favorite sort algorithm def merge(list): if len(list) <= 1: return list[:] mid = len(list) // 2 L, R = list[:mid], list[mid:] L = merge(L) R = merge(R) return mergesort(L, R) def mergesort(L, R): i = j = 0 C = [] while (i < len(L)) and (j < len(R)): ...
f69b82734765994b0c6049760cac97e310aa5c59
wpnbos/sha256
/eratosthenes.py
590
3.90625
4
import numpy as np def sieve(n): """ returns a list of all positive primes up to n """ p = 2 integers = list(range(p, n)) for i in integers: if i != 0: multiples = list(range(i, n, i))[1:] for m in multiples: integers[m-p] = 0 primes = [i for i in integers if i != 0] return primes def estimat...
ef55e52c2f8d4b4441b4e7f9bb4fdce2f10f6851
after23/Pemrograman-Lanjut
/Program_Alay.py
1,015
3.875
4
def glosarium(huruf): #fungsi untuk memetakan huruf bisa menjadi versi alaynya if (huruf == 'a'): return '@' elif (huruf == 'i'): return '1' elif (huruf == 'o'): return '0' elif (huruf == 's'): return '$' elif (huruf == 'e'): return '3' else: return huruf word = input('Enter a word:') ...
675f5a2e4872029d91aa1303ff228e59748bd517
supermitch/Chinese-Postman
/chinesepostman/my_iter.py
436
3.96875
4
"""Iterator related helper functions.""" def flatten_tuples(iterable): """ Flatten an iterable containing several tuples, into a single tuple. Sum all tuples, which "extends" them, with empty tuple as start value. """ return sum(iterable, ()) def all_unique(iterable): """Returns True if all ...
23adeb7dd627970f433bf0c0b4c7014ca520035b
meetashwin/python-play
/basic/countzeros.py
279
3.703125
4
#This program counts the number of zerod in array # Here's the test array binary_array = [1, 1, 1, 1, 0, 0, 0, 0] zero_count = {"count":0} for i in range(len(binary_array)): if (binary_array[i] == 0): zero_count["count"] = zero_count["count"] + 1 print(zero_count["count"])
e0705e2559034c30e1e7ffc63d1289bdca5e030d
eateren/advent-of-code-2020
/13/aoc2020-13.py
3,441
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 13:32:59 2020 @author: eateren """ datafile = "data.txt" def readDataFile(datafile): with open(datafile) as file: list = file.readlines() startTime = int(list[0].strip()) busList = list[1].split(",") ret...
19a28ef2bb886c4e60eb9ff28862cfdfc7a60b6a
FahimArman/learn_python_the_hard_way
/python_054.py
283
3.984375
4
#!/usr/bin/python #page 54 from sys import argv script, file_name = argv txt = open(file_name) print "Here's your file %r: " % file_name print txt.read() print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read()
ce5342af9322a06a01b9d364946cd4ef76c7cc31
wonkwonlee/leetcode-python
/Arrays-101/1346_checkIfExist.py
782
3.828125
4
""" 1346. Check If N and Its Double Exist Given an array arr of integers, check if there exists two integers N and M such that N is the double of M (N = 2 * M). The target value(arr[i]*2) is in the list AND the index of value is different with the original index. Consider if the value is 0 or 1, the target value is s...
ed00e8b730b2dda98dabce538b4fd9531ecb5639
smitches/Python
/CS 303/EasterSunday.py
1,058
4.09375
4
# File: EasterSunday.py # Description: This program determines what day Easter Sunday falls on in the year # Student Name: Brian Smith-Eitches # Student UT EID: bts867 # Course Name: CS 303E # Unique Number: 51195 # Date Created: 9/11/16 # Date Last Modified: 9/11/16 def main(): # determine year from in...
e37a712219a291d2d675cb79e6a3962f7d90e55c
arnabs542/Data-Structures-And-Algorithms
/Graph/Possibility of finishing all courses given pre-requisites.py
2,537
4.15625
4
""" Possibility of finishing all courses given pre-requisites Problem Description There are a total of A courses you have to take, labeled from 1 to A. Some courses may have prerequisites, for example to take course 2 you have to first take course 1, which is expressed as a pair: [1,2]. So you are given two integer...
c3b5224ba5a4b0fb97c897a8da5a5d5496bd7cb5
victorrrp/Python-Intermediario
/aula10_curso.py
1,151
3.875
4
'''While em python''' x=0 while x<10: #enquanto if x==3: x+=1 continue #pula para o próximo laço (ele para de executar o trecho de cod) print(x) x=x+1 print("Acabou!") y=0 while y<10: if y==3: y+=1 break #para parar de executar o laço print(y) ...
99681369da1ee9d38a15743744cfb3cf5ea341ae
iamaline9477/jianzhi-python
/57二叉树的下一个结点.py
914
3.78125
4
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 思路: 如果有右子树,则找右子树的最左节点 如果没右子树,则找其父节点的父节点的父节点...直到当前节点是其父节点的左节点 退到了根节点仍没找到,则返回None''' class Solution: def GetNext(self, pNode): if not pNode: return None ...
34754dec4b09336d7d354c2f3a8dd6f7801dec88
EmmanuellaAlbuquerque/Curso-Em-Video
/Python Mundo3 - Estruturas Compostas/desafio - 82.py
723
3.78125
4
lista = list() listaPar = list() listaImpar = list() while True: lista.append(int(input('Digite o valor a ADD na lista: '))) desejaContinuar = str(input('S para continuar e N para sair do programa!')).strip().upper() while desejaContinuar not in 'SN': desejaContinuar = str(input('S para conti...
7fbe8eaceaca401dca52212823f442406881f892
geohotweb/programing
/ecuaciones/my_circule.py
2,508
4.09375
4
#Este programa calcula una serie de factores introduciendo vectores para poder dar el resultado. from math import acos, pi, sqrt opcion = '' while opcion != '9': print('1) Introducir el primer vector.') print('2) Introducir el segundo vetor.') print('3) Calcular la suma.') print('4) Calcular la diferencia.') pr...
38254f7dcc5d49987b2748570111012070ca83c5
yoonju-baek/Learn-Python-Programming
/1.basics/functions.py
733
4.03125
4
# Defining a function - the keyword "def" def user_info(username, age): """Display user's information.""" print("\nMy name is " + username.title() + ".") print("I am " + str(age) + " years old.") user_info('lily', 30) # Keyword arguments - the order doesn't matter def describe_dog(name, type): """Desc...
b86ea29e943951ddcd12eb141320905b3e4254fa
AnushavanAleksanyan/lessons
/value_in_dict.py
299
3.953125
4
def find_value(value, dic): if value in list(dic.values()): return True else: return False some_dic = {"one": "Monday", "two": "Tuesday", "three":"Wednesday", "four":"Thursday", "five":"Friday", "six": "Saturday", "seven": "Sunday"} val = "Monday" print(find_value(val, some_dic))
d69c48471a57ac1f5cb05db09889aecda6a5ff9b
bgoonz/UsefulResourceRepo2.0
/_RESOURCES/my-gists/__CONTAINER/825aa98d8f/825aa98d8fddbff215dadd41125cc487f503d563f1179583c1502bfebdb87cf8/audio-2-text.py
4,397
3.515625
4
#!/usr/bin/env python3 import argparse import os import pathlib import progressbar import speech_recognition as sr from pydub import AudioSegment from pydub.silence import split_on_silence class AudioToText: """ Converts an audio file to text. """ def __init__(self, fileInput, fileOutput, language): ...
0d558a04a974c96413e34fc82e039b476a0ba4bd
JasonVann/CLRS
/S1_Foundation/C2_GettingStarted/selection_sort.py
722
3.53125
4
from test_sort import * def selection_sort(data): n = len(data) for i in range(0, n-1): # Find the i-th minimum number and swap with data[i] min_i = None for j in range(i, n): if min_i is None or data[j] < min_i: min_i = data[j] idx = j ...
3efe98708082a323a664552c469e589058497205
gautamgitspace/iGeek
/bit manipulation/binary_rep_of_a_number.py
306
4
4
#!/usr/bin/env python #binary representation of a given number def bin_rep(number): lst = [] while(number): if number&1 == 1: lst.append(str(1)) else: lst.append(str(0)) number = number >> 1 return ' '.join(reversed(lst)) print bin_rep(number=7)
a93065d997e37caa5e314f09b9dcff58e5ad7ece
theref/Computing-For-Mathematics
/Lab Sheet 2/#14.py
298
4
4
def iterX(n): """ An iterative approach Inputs: integers Outputs: integers """ r = 1 for i in range(n - 1): r *= 2 return r print iterX(4) def recX(n): """ A recursive approach Inputs: integers Outputs: integers """ if n == 1: return 1 return 2 * recX(n - 1) print recX(4)
c2c9172be954d1c0f33d75b7bf56078aa7d60d5b
RCoon/CodingBat
/Python/List_1/max_end3.py
511
4.4375
4
# Given an array of ints length 3, figure out which is larger between the # first and last elements in the array, and set all the other elements to # be that value. Return the changed array. # max_end3([1, 2, 3]) --> [3, 3, 3] # max_end3([11, 5, 9]) --> [11, 11, 11] # max_end3([2, 11, 3]) --> [3, 3, 3] def max_end3(...
a36ef8435919b178eb8ab900f5a5165e3edf0075
taslimy/Algorithms
/recipe_batches/recipe_batches.py
964
4.09375
4
#!/usr/bin/python import math def recipe_batches(recipe, ingredients): # initialize batches made batches = 0 # set it true so we got ingredients got_ingredients = True # we make with the recipies we have while got_ingredients: # subtract from the recipies for ing in recipe: if ingredients....
0784050fad275d31ef0f936b66a1ffce6c7ffb00
Shibaruto/cssi
/week3/week3.o/s.py
209
3.765625
4
Person = { "name": { "first": "Jermaine", "middle": "N", "last": "Reid" } } print Person["name"]["first"] print "{2},{0},{1}".format(Person["name"]["first"], Person["name"]["middle"], Person["name"]["last"])
45c20f916e0ced00388b09ede399f7e7cd5c1f3f
mdallow97/InterviewPrep
/SortAndSearch/search_for_range.py
272
3.625
4
# search_for_range.py def searchRange(arr, target): try: begin = arr.index(target) except: return [-1,-1] end = begin while end < len(arr)-1 and arr[end+1] == target: end += 1 return [begin,end] print(searchRange([8], 10))
db2d8464add76feeab2b63b620e7384314da536d
Olivier-Lakoue/ODL_Github_Test
/q1_mapper2.txt
597
3.6875
4
#!/usr/bin/python import sys # input comes from STDIN (standard input) for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # split the line into words delim = , # 1,20/09/1985,PARKER LONG => 1 / date / name words = line.split(",") # verif sur la date key...
411ee921bd43106d4ef0decd61a13a3a7624e33e
OleksandrMakeiev/python_hw
/def find_max.py
819
4.0625
4
# 19 import random num_limit = int(input("Введите количество случайных чисел, которые выберет программа: ")) lower_bound = int(input("Введите нижнюю границу поиска: ")) upper_bound = int(input("Введите верхнюю границу поиска: ")) def find_max(num_limit, lower_bound, upper_bound): max_number = lower_bound fo...
d8027844d6fe97b6d9431aa65d42e25ff3924d23
yusuf963/python-pg
/map-filter.py
1,052
4.0625
4
# ! Map from functools import reduce nums = [10, 2, 3, 6, 6] def double(num): return print(num * 2) double(10) num1 = list(map(lambda num: num * 2, nums)) print(num1) # ! filtering even_num = filter(lambda num: num % 2 == 0, nums) print(list(even_num)) # ! reduce num_to_sum = [33, 55, 6] summed = reduce(...
18498c85d7cc26c71f211f3eb01ed384f1fba6a3
JANGHEEEUN/Keras
/Keras/keras20_tensorboard.py
2,921
3.59375
4
import numpy as np #1. 데이터 x = np.array([range(1,101), range(101,201), range(301,401)]) y = np.array([range(101,201)]) # x= np.transpose(x) x = x.reshape(x.shape[1], x.shape[0], 1) y= np.transpose(y) print(x.shape) #(3,100) print(y.shape) #(1,100) # from sklearn.model_selection import train_test_split # x_train, x...
f49213d732f635f89f5c8aaffef3f51dc41555db
CzJLee/DeepSig-Modulation
/signal_processing.py
5,896
3.53125
4
import numpy as np import matplotlib.pyplot as plt def signal_to_complex(data): """ Converts an IQ datastream recording to complex numbers if not already. Args: data (np.ndarray): Time domain data stream recording. Returns: np.ndarray: Complex valued time domain data stream recording. """ # Check if data ...
f92be9df9cd295adafa585fa6fc4065df53a7c34
vaaishalijain/Leetcode
/July-LeetCode-Challenge-Solutions/14_Angle_Between_Hands_of_a_Clock.py
952
4.09375
4
""" Angle Between Hands of a Clock Q. Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand. Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output...
169b1d7baa552546eb775e233528888b2eb458ea
plan-bug/LeetCode-Challenge
/microcephalus7/categories/hashTable/1365.py
279
3.734375
4
# 2중 컴프레션 from typing import List class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: return [len([j for j in nums if j < i])for i in nums] solution = Solution() print(solution.smallerNumbersThanCurrent([8, 1, 2, 2, 3]))
96a108eea10357ee9db95826fce748825db67b84
mengnan1994/Surrender-to-Reality
/py/XXXX_color_the_ball.py
757
3.65625
4
""" Description N个气球排成一排,从左到右依次编号为1,2,3…N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗? Input 每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。 当N = 0,输入结束。 Output 每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。 Sample Input 3 1 1 2 2 3 3 3 1...
00cfe5215619595178a6af559201a5c106f0246d
Md-Hiccup/code-python-django
/DataStructure/7_Tree/tree_exercise_1.py
1,790
3.640625
4
class TreeNode: def __init__(self, name, desg): self.name = name self.desg = desg self.children = [] self.parent = None def add_child(self, child): child.parent = self self.children.append(child) def get_level(self): level = 0 p = self.parent...
b35efee54138c61cf3a905ea9b1e50e53243ed4e
zyz10086/leetcode
/algorithms/735.py
687
3.5625
4
# 给定一个整数数组 asteroids,表示在同一行的行星。 # 对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左移动)。每一颗行星以相同的速度移动。 # 找出碰撞后剩下的所有行星。碰撞规则:两个行星相互碰撞,较小的行星会爆炸。如果两颗行星大小相同,则两颗行星都会爆炸。两颗移动方向相同的行星,永远不会发生碰撞。 class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: asteroids pass s = Solution() print(s...
13d2584ac22985970530b03c7bd51410a78d87be
kovalevvjatcheslav/euler
/task2/task2.py
213
3.671875
4
current = 1 previous = 0 summary = 0 while current + previous < 4000000: if current % 2 == 0: summary += current temp = current current += previous previous = temp print(summary)
61c9f1f0c71a80c704461eadd397229afb5c3c61
jc0n/programming-problems
/count_digits/count_digits.py
1,989
4.1875
4
#~/usr/bin/env python """ Solutions to count the total number of digits in all of the numbers 0..n """ __author__ = 'John O\'Connor' __version__ = 0.1 from math import floor, log10 # Number of digits in the integer n num_digits = lambda n: int(floor(log10(n)) + 1) # Build the desired string by hand buildstr = lambd...
19b1c93667633e7e2824cd752d54c02c451a8cc8
mfigdore/Genomic-AMD
/CG_Kmeans.py
1,904
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 7 17:09:09 2019 @author: Jasen """ import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score def CG_Kmeans(df, ks, manual, feature_red, want_graphs): ''' input: ...
c4c4667a2ac5d35bfb6a11b5a8a1907ceb056907
jonasht/cursoIntesivoDePython
/exercisesDosCapitulos/04-trabalhandoComListas/4.11-minhasPizzas-Suaspizzas/pizzas.py
547
4.25
4
pizzas = ['brocolis', 'pepperoni', 'mista'] # fazendo copia/passando para pizzas dos amigos friend_pizzas = pizzas[:] # adionando pizza na list() pizzas pizzas.append('vegetariana') # adicionando pizza na list() friend_pizzas friend_pizzas.append('frango') # mostrando pizzas favoritas: print('\nminhas pizzas favori...
e522a3ecd6643dea662338415f1dded8ae7a8b7d
Aasthaengg/IBMdataset
/Python_codes/p02570/s130263635.py
145
3.546875
4
inputs = input().split(' ') D = int(inputs[0]) T = int(inputs[1]) S = int(inputs[2]) t = D / S if T >= t: print('Yes') else: print('No')
a3a44bed7db0c3abe5c8f9a9e58c0d6881f8ffa6
JordanFist/enseirb_matmeca
/python/projects/aquarium/client/src/Queue.py
735
4
4
#!/usr/bin/python3 class Queue: def __init__(self): self.__queue = [] def isEmpty(self): return (self.size() == 0) def push(self, item): self.__queue.insert(0, item) def pop(self): return self.__queue.pop() def peek(self): if not (self.isEmpty()): ...
fc742f39353f408e88e6adad28bf0291b88cd810
IsauraRs/PythonInter
/Basico/Miercoles/Avanzado/Encapsulamiento1.py
1,407
4.15625
4
""" La encapsulacion se refiere a la delimitación del acceso a determinados metodos y atributos de los objetos en una clase. Esto permite crear una interfaz segura entre el usuario y el codigo """ class NumeroComplejo: ParteReal = 0 ParteImaginaria = 0 ##Metodos de la clase ##Constructor de la clase ...
4a6d5f844172708c7084f2760601e2bcc06e36f9
guillermoojeda/CodingChallenges
/python/Overlapping_Intervals.py
1,362
4.21875
4
""" Given a list of possibly overlapping intervals, return a new list of intervals where all overlapping intervals have been merged. The input list is not necessarily ordered in any way. For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return [(1, 3), (4, 10), (20, 25)]. """ def overlaps(pair1, pair...
f721849da74b07f6c022916f0d672c6925d7ea3b
dancr89/New_rep
/main.py
374
3.875
4
def rec_sums(n): if n == 0: return 0, 0, 0 #return n + rec_sums(n - 1) total_sum, even_sum, odd_sum = rec_sums(n - 1) total_sum += n if n % 2 == 0: even_sum += n else: odd_sum += n return total_sum, even_sum, odd_sum total_sum, even_sum, odd_sum = rec_sums(5) pri...
324df06fb95161d7da13a93a190b33de87f9c703
Psp29/basic-python
/chapter 2/04_pract_01.py
71
4.0625
4
a = 45 b = 5 print("The remainder when a is divided by b is:", a % b)
f68c12fc2d03b4787aed5dcd006ea98a8b0b2147
AyushVtejpal123/python-flask-assingment
/day-8.py
2,772
3.90625
4
print("\t\tLets make you'r account") user = { 'name': input("please enter your name: "), 'email': input("please enter your email id: "), 'courses': [] } if "@" not in user['email']: print("Please include a @ ") user['email'] = input("please enter your email id: ") all_courses = ['Pyth...
a860802e070bf92cbe088db785dcdbaa2e4f5d46
ken-power/Foobar_Challenge
/Level_2/2_DontGetVolunteered/solution.py
5,471
4.125
4
import unittest def solution(src, dest): """ Solve a movement puzzle in order to cross the floor. The function returns an integer representing the smallest number of moves it will take for you to travel from the source square to the destination square using a chess knight's moves (that is, two square...
3c64f30caf62372b620eeca0e5611833310b44a7
MarcosCastelo/Atividades-POO
/PensePython_Cap16/functions.py
1,998
3.75
4
from classes import * from copy import copy def print_time(time): hour = "%.2d" % time.hour minute = "%.2d" % time.minute second = "%.2d" % time.second s_time = hour + ":" + minute + ":" + second print("\nHour -> ", s_time) def is_after(time1, time2): return (time1.hour, time1.minute, time1.second) > (time2...
aa4d5f5e9e0f11dd6e0226749604152ccc6cdedc
victorricardo/tutorial-python
/fuentes/Modulos_y_Paquetes.py
4,059
3.578125
4
#!/usr/bin/env python # coding: utf-8 # # Módulos y Paquetes # Para facilitar el mantenimiento y la lectura los programas demasiado largos pueden dividirse en módulos, agrupando elementos relacionados. # # Los módulos son entidades que permiten una organización y división lógica de nuestro código. Los ficheros son s...
7be8a481205a247e85ee14a9f96dd51b3f157120
LoveDarkblue/PythonTest
/test6/test6_1.py
307
3.546875
4
from types import MethodType class Person(object): pass p = Person() def sayhello(self, msg): print(msg) Person.name = 'Mary' # 动态的给类定义一个属性 print(p.name) Person.sayhello = sayhello # 动态的给类设置一个方法 p.sayhello('hello') p1 = Person() print(p1.name)
dafa458c4f2f9abbbdd48e40abc63e615069da80
apoorvkk/LeetCodeSolutions
/problems/797_all_path_from_source_to_target.py
653
3.640625
4
''' URL: https://leetcode.com/problems/all-paths-from-source-to-target/ Time complexity: O(E) Space complexity: O(V) ''' class Solution: def allPathsSourceTarget(self, graph): """ :type graph: List[List[int]] :rtype: List[List[int]] """ paths = [] self.find_paths(gr...
3c91da87ba24340b5e390724d5ca107218f915a3
yjlee0209/kite
/Python/for_1.py
233
3.96875
4
# 반복을 위한 for 구문 for i in range(10): print(i) print('') string_a = "Python" print(string_a) for s in string_a: print(s) list_a = [100, 500, 1000, 321, 99, 11, 1, -9] print(list_a) for l in list_a: print(l)
e1c41fef7c990265fbbd5ebd4eef41de5035b725
pulinghao/LeetCode_Python
/189. 旋转数组.py
797
4.375
4
#!/usr/bin/env python # _*_coding:utf-8 _*_ """ @Time :2021/1/8 3:30 下午 @Author :pulinghao@baidu.com @File :189. 旋转数组.py @Description : """ class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: None Do not return anything, modif...
c2df5e77a9656c7ad3074a407e06d77bbd16aa74
LS-io/statistics_python
/chapter1_fundamentalsofpython/functionsandalgorithms/exercise105_findingmaximum.py
545
4.3125
4
## In this exercise, we will try to find the maximum of an array, or list ## To do this, we wil write a function that returns the index and value of the maximum element within a list def get_max(my_list): running_max_index = 0 # Iterate over the index-value pairs. for index, item in enumerate(my_list): ...
357e594475dacc7139010e33442b841e1f7e24be
BSchweikart/CSC-221
/M1HW2/M1HW2_Q3_Schweikart.py
809
3.921875
4
def main(): pass # variables for three actors # true is near, false is far fox = True chicken = True grain = True #start #update(fox, chicken, grain) # step 1 fox = False print("Step 1") update(fox, chicken, grain) # step 2 fox = True print("Step 2") update(fox, chicken, grain) #step 3 fox = Tru...
4a7a5264ac2d9438862220a511ec069a72f19bb2
dscheiber/CodeAcademyChallenge
/calculator.py
2,099
4.5625
5
# 7. Create a calculator function # Write a Python function that accepts three parameters. The first parameter is an integer. # The second is one of the following mathematical operators: +, -, /, or *. The third parameter will also be an integer. # The function should perform a calculation and return the results. # ...
60323f9647e40f4468b6361a8a7ef89e178eda49
ml4713/assignment8
/ml4713/investment_instrument.py
2,006
3.875
4
# -*- coding: utf-8 -*- """Investment Strategy Mengfei Li """ import numpy as np import pandas as pd import matplotlib.pyplot as plt def single_bet(pos_val): """Imitate a single 'flip' in this gambling problem """ value=np.random.binomial(1,0.51) if value==1: res=pos_val*2 else: ...
614f1450f291a6edec47173f39d50c159d8216e9
Dalelkhanova/WEB
/lab7/codingbat/List-2/count_evens.py
115
3.65625
4
def count_evens(nums): cnt = 0 for n in nums: if n % 2 == 0: cnt += 1 return cnt
aa4751a58abe613bc9639c7c073f3da2b85c283e
SharvariNagesh/ShareScore
/scrapper.py
3,154
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 1 20:10:24 2020 @author: sharvarinagesh """ import requests from bs4 import BeautifulSoup import pandas as pd import re from Util import to_float class FinancialScrapper : def __init__(self, url): self.url = url def getFinanc...
8cbe090f824082eeb3a61f07fb2d01e2ec5bcac0
adnanzaih/ECOR1041_Labs
/lab10.py
8,701
4.03125
4
#lab 10 #Student: Adnan Hafeez 101210710 #Exercise 1 def count_evens(lst: list) -> int: """Returns the number of even integers in a list lst. >>> count_evens([-1,-2]) 1 >>> count_evens([-1,-2,0,1,2,3,5,5,4,4]) 5 >>> count_evens([]) 0 """ num_even = 0 for item in lst: if ...
774be72b86f08554ff0c2106df913b19ccfd1fd2
ZFanxing/Python_learning
/multiprocessing/pool.py
772
3.890625
4
#使用Pool的方法更方便,即不需要人为分配几个核,默认使用机器硬件支持的所用核数目 import multiprocessing as mp def job(x): return x*x def multicore(): #map的方式,自动分配进程 pool = mp.Pool(processes=2)#可以设置具体使用几个核,不设置的话默认硬件的所有核 res = pool.map(job, range(10)) print(res) #async的方式,默认每次只在一个进程里计算,除非设置 res = pool.apply_async(job, (2,)) ...
e200d77d0d010e20253c4a492d50c19fab53d447
benjaminlindsay/python_test_exercises
/Modulo Loop.py
991
4.25
4
# Question 1: #Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, #between 2000 and 3200 (both included). #The numbers obtained should be printed in a comma-separated sequence on a single line. #Hints: #Consider use range(#begin, #end) method l=[] for i in range(20...
dfa3d8e695e0b116ccf6e59075f2cebff0f590dd
ismk/Python-Examples
/02.py
344
3.765625
4
# def front_back(str): # if len(str)<2: # return str # else: # frstchar = str[0] # lastchar = str[len(str)-1] # newstr = lastchar + str[1:len(str)-1] + frstchar # return newstr # print (front_back("START")) def f(x): return ((-5)*(x**5))+(69*(x**2))-(47) print (f(0)) print (f(1)) prin...
b565f93cac734ce60ef82cf293baf7b3f33cf5bb
MrBubb13s/PythonHomework
/파이썬과제/test1.py
79
3.578125
4
a = '1 2 3 4 5 6 7 8 9 10' b = a.split(' ') for std in b: print(std)