blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
58620656ab0d5e96d2fec08613e65bb9fb7a001a
TNortham112/python-code
/Week 8 Q6-2.py
153
3.515625
4
def mystery(n): if n <= 0: return 0 else: return n + mystery(n//2) + 1 def main(): print(mystery(20)) main()
fd8b8db220d04f61768a66408da1a0fb5f377e42
vishaalprasadsjsu/sudoku-ai
/SudokuAILoops.py
23,254
3.625
4
from copy import deepcopy import time # Agent that solves Sudoku puzzles present_mode = True; # step by step class Sudoku: def __init__(self): self.boards_so_far = [] self.sudoku_table = [0]*9 self.read_table() self.heuristic = 0 # number of zeros for i in range...
2b799866475375bd338325c22ecd9e76189da999
sbabicki/cmput410lab2
/practice/accept_single_connections_server.py
782
3.84375
4
# References Used: # # http://www.binarytides.com/python-socket-programming-tutorial/ # Article by Silver Moon # # import socket HOST = '' PORT = 9999 # socket is created and socket descriptor is returned s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("\nSocket created\n") # bind socket to a host and ...
f9460d3ae1d8c06dce1ec694032619a24cb69c1e
pavoli/fluentpython_LucianoRamalho
/chapter14/fibo_by_gen.py
263
3.9375
4
# -*- coding: utf-8 -*- __author__ = 'p.olifer' __version__ = '1.0' def fibonacci(num): a, b = 0, 1 while num: yield a a, b = b, a + b num -= 1 if __name__ == '__main__': f = fibonacci(10) for i in f: print(i,)
d8fd2d3e613463d3feb8963ec2568d18709d547c
hiyeshin/rwet
/week_2/hw/minigrep2.py
212
3.546875
4
import sys searchstr = "more" for line in sys.stdin: line = line.strip() fr = line.find(searchstr) if searchstr in line: print line[fr:] # else: # print "Hey, every line here is so short."
a704105c7f3c754035dcd38b96bc4e6697f9559c
hiyeshin/rwet
/week_2/practice/cat.py
500
3.625
4
import sys # below means standard input. is used for all interpreter input except for scrips for line in sys.stdin: line = line.strip() # as a default, 'strip' strips off the white space including white spaces. # if there're arguments such as characters, then it omits that specific characters. # it's because usu...
df6faf28204eb43c974f8afcf25b526ed4c6e779
abdulllkhan/first
/Camel Case.py
1,403
3.859375
4
class TrieNode: def __init__(self): self.children=[None]*26 self.end=False self.word=[] class Trie: def __init__(self): self.root=TrieNode() def peace(message): print("peace was never an option") def insert(root,key): cur=root for i in range(len(ke...
3edfcbbddac22e90918360cb33af6318996c55cb
pavithra181/infytq
/profit or loss.py
438
3.734375
4
def calculate(distance,no_of_passengers): price_per_litre_of_fuel=70 Mileage = 10 price_per_ticket=80 total_inversement=((distance/Mileage)*price_per_litre_of_fuel) total_gain=price_per_ticket*no_of_passengers if(total_gain>total_inversement): profit=total_gain-total_inversement ...
4b1bb8a4e501b50680d29d4688405b1a5c0f8bf4
mgtz505/algorithms
/implementations/sorting_algorithms/quicksort.py
518
4.15625
4
print("Implementation of Quicksort") test_data = [3,11,4,0,7,2,12,7,9,6,5,10,3,14,8,5] def quickSort(N): length = len(N) if length <= 1: return N else: larger, smaller = [], [] pivot = N.pop() for num in N: if num < pivot: smaller.append(num) ...
32c2360fff6979a2361eb3b6dc29792de3ad8ddf
rahuljain2104/python
/food_subscription.py
1,810
4
4
# Food Subscription # You want to buy a food subscription package for the upcoming month. You know exactly the days on which you will eat. # This month has 30 days and there are 3 types of packages that available : # # 1-Day Package - 199 valid for one day. # 7-Day Package - 699 valid for 7 consecutive days. # 30-Day P...
158e535b0d1729b903013a3a924dd50b7f6a76ee
eirikdahlen/TDT4120-AlgDat
/Oving8/ratatosk.py
1,683
3.546875
4
from sys import stdin # Node-klasse class Node: def __init__(self): self.children = [] self.ratatosk = False self.visited = False # Dybde-først-søk def dfs(root): stack = [(root,0)] if root.ratatosk: return 0 depth = 0 while len(stack) != 0: node = stack.pop() ...
76c659b822af7a0db54f83f4e038d9ae5fa53427
opensourceoptions/numpy-tutorials
/numpy003_CreatingArrays.py
422
3.828125
4
# import numpy package import numpy as np #create and print array containing a single value of 1 a = np.array(1) print a #create and print a 1D array a1d = np.array([1,2]) print a1d #create and print a 2D array a2d = np.array([ [1,2,3], [1,2,3], [1,2,3] ]) print a2d #create and print a 3D array a3d = np.array([ [ [...
faf89153d332a8f109c7b2ed36050b588b24c6a6
AshleighWong/GWC-AshleighsChatbot
/main.py
659
4.0625
4
print("Hey how was your day my brochochocho") answer = input("You:") print("Hey do u play Fn?") answer2 = input("You:") if(answer2 == "yes"): print("Lets try playing then!" \ + "My username is namiuw." \ + "Whats yours?") elif(answer2 == "no"): print("Oh okay, thats fine! You can try to play right now!"\ + "M...
3e36b2f72dbe1c248365e51566f81a21e6e18b3e
alex-mucci/ce599-s17
/18-Design and Classes/Car.py
2,655
4.4375
4
#constansts START_NORTH = 0 START_SOUTH = 0 START_EAST = 0 START_WEST = 0 # Define the class class Car(object): """ Base class for a car """ def __init__(self, color,location = [0,0],direction = 'N'): if len(location) < 2 or len(location) > 2: print('location is the x,y coordina...
8969c70857b05f92b3cec8f3339bb543498b39e3
kolevatov/python_lessons
/simple_object.py
550
4.15625
4
# Simple object class Simple(object): """Simple object with one propertie and method""" def __init__(self, name): print("new object created") self.__name = name def __str__(self): return "Simple object with name - " + self.__name @property def name(self): return sel...
eac53491810c8dddec3291357cb6b8a0be52c9ee
kolevatov/python_lessons
/week_2/2_22.py
820
4.09375
4
# Максимум последовательности """ Последовательность состоит из натуральных чисел, не превосходящих 10⁹, и завершается числом 0.Определите значение наибольшего элемента последовательности. Формат ввода Вводится последовательность целых чисел, оканчивающаяся числом 0 (само число 0 в последовательность не входит, ...
ef6ba14bad42d13b10f93472fd0e5cf21254d531
kolevatov/python_lessons
/week_1/task_1_15.py
404
3.75
4
# Следующее четное # Дано целое число N. Выведите следующее за ним четное число. # Формат ввода # Вводится целое положительное число, не превышающее 1000. # Формат вывода # Выведите ответ на задачу. N = int(input()) N = N + (N % 2)*-1 + 2 print(N)
fd4890d93ad997451e2fb0a222e793c5beb4a3bb
kolevatov/python_lessons
/calculation table.py
711
4.34375
4
# Составить программу вывода таблицы умножения на число M # Таблица составляется от M * a, до M * b, где M, a, b запрашиваются у пользователя. print("Программа ввывода таблицы умножения на число M") m = int(input("Введите число M: ")) a = int(input("Введите число a: ")) b = int(input("Введите число b: ")) while a > b:...
d292c79ff8ba065bf89bc0b190bcf775262ef9e2
kolevatov/python_lessons
/week5/5_18.py
708
3.984375
4
# Переставить соседние """ Переставьте соседние элементы списка (A[0] c A[1],A[2] c A[3] и т.д.). Если элементов нечетное число, то последний элемент остается на своем месте. Формат ввода Вводится список чисел. Все числа списка находятся на одной строке. Формат вывода Выведите ответ на задачу. """ N = list(m...
6adbf67f5a3648af64957d83d515b669c934ff6c
kolevatov/python_lessons
/week_2/2_29.py
892
4.0625
4
# Максимальное число подряд идущих равных """ Дана последовательность натуральных чисел, завершающаяся числом 0. Определите,какое наибольшее число подряд идущих элементов этой последовательности равны друг другу. Формат ввода Вводится последовательность целых чисел, оканчивающаяся числом 0 Формат вывода Выве...
71ecdecf27800ad7d75cd6e119fba2697297550e
kolevatov/python_lessons
/week_2/2_16.py
671
4.3125
4
# Сколько совпадает чисел """ Даны три целых числа. Определите, сколько среди них совпадающих. Программа должна вывести одно из чисел: 3 (если все совпадают), 2 (если два совпадает) или 0 (если все числа различны). Формат ввода Вводятся три целых числа. Формат вывода Выведите ответ на задачу. """ A = int(inpu...
d53aa56fa01ed85a564a542ece3f9922d428b3a3
kolevatov/python_lessons
/week_2/2_28.py
815
4.125
4
# Количество элементов, равных максимуму """ Последовательность состоит из натуральных чисел и завершается числом 0. Определите, какое количество элементов этой последовательности, равны ее наибольшему элементу. Формат ввода Вводится последовательность целых чисел, оканчивающаяся числом 0 Формат вывода Вывед...
2e150173fbf230165c28208251024f5b2ae63acf
kolevatov/python_lessons
/config_file_parser.py
623
3.625
4
# Config file parser # File has format "key = value" or "key : value". COMMENT = '#' SEPARATOR = '=' def parse_config(filename): options = {} f = open(filename) for line in f: line = line.replace(':',SEPARATOR) if not (line[0] is COMMENT) and (SEPARATOR in line): option, value =...
bf025227d713aa6d50b3ebfd798c4b4972b3fe79
kolevatov/python_lessons
/week5/5_14.py
547
3.78125
4
# Больше предыдущего """ Дан список чисел. Выведите все элементы списка, которые больше предыдущего элемента. Формат ввода Вводится список чисел. Все числа списка находятся на одной строке. Формат вывода Выведите ответ на задачу. """ N = list(map(int, input().split())) for i in range(1, len(N)): if N[i]...
8a67eea89f7418421671b4dd7b23a316bbab0a5f
kolevatov/python_lessons
/week5/5_7.py
640
4.3125
4
# Замечательные числа - 1 """ Найдите и выведите все двузначные числа, которые равны удвоенному произведению своих цифр. Формат ввода Программа не требует ввода данных с клавиатуры, просто выводит список искомых чисел. Формат вывода Выведите ответ на задачу. """ def proc(n): a = n // 10 b = n % 10 ...
4048eb07a6284b0990534fa16e5eb619dda48808
kolevatov/python_lessons
/links.py
194
3.578125
4
list_1 = ['aaa','bbb','ccc'] list_2 = list_1 list_3 = list_1[:] print ('1 - ',list_1) print ('2 - ',list_2) print ('3 - ',list_3) list_3.append('ddd') print('1 - ', list_1) print ('3 - ',list_3)
6f348b214f3e1ca724a7fbd014fc6c9542b2430c
kolevatov/python_lessons
/week4/4_6.py
1,089
4.1875
4
# Проверка числа на простоту """ Дано натуральное число n>1. Проверьте, является ли оно простым. Программа должна вывести слово YES, если число простое и NO, если число составное. Решение оформите в виде функции IsPrime(n), которая возвращает True для простых чисел и False для составных чисел. Количество действий в п...
51991312ddcb06ce0b84c16e8ec7f2b83725c6da
kolevatov/python_lessons
/list_management.py
1,559
4.15625
4
# Управление списком значений. # Поддерживает операции: добавить элемент, удалить элемент, распечатать список, сортировать, удалить дубликаты значений # scores = [] menu = None while menu != '0': print(""" 0 - Выход 1 - Добавить элемент 2 - Удалить элемент 3 - Распечатать список ...
49eff6a3e334561bab3bb588d93af3338f46d0fd
smilejakdu/python_algorithm_study
/kor-solidarity/2_addTwoNumbers.py
546
3.5625
4
# Definition for singly-linked list. # this is wrong. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: num1 = '' num2 = '' for i in l1: num1 ...
86d58fefedb09f5a7b19544b108216253a2036a2
qianqianjun/DCGAN
/data_provider.py
2,699
3.53125
4
""" write by qianqianjun 2019.12.20 """ import numpy as np from PIL import Image class MnistData(object): def __init__(self,images_data,z_dim,img_size): """ 建立一个data provider :param images_data: 传进来的图像数据的集合 :param z_dim: 生成器输入的随机向量的长度 :param img_size: 传进来的图像的大小 """...
47f6f9941be972f884a54081fad928481f1945a3
KWONILCHEOL/Python
/KAKAO/level1/[kakao][2018][blind]다트 게임.py
662
3.59375
4
# [kakao][2018][blind]다트 게임 # https://programmers.co.kr/learn/courses/30/lessons/17682 import re def solution(dartResult): dir = {'S':1, 'D':2, 'T':3, '':1, '*':2, '#':-1} p = re.compile('(\d+)([SDT])([*#]?)') dart = p.findall(dartResult) for i in range(len(dart)): if dart[i][2] == '*': ...
b3b5d4be84d6a81f2c36a4913fcf47d9f9f0a4d4
KWONILCHEOL/Python
/KAKAO/level2/[kakao][2018][blind]캐시.py
1,471
3.65625
4
# [kakao][2018][blind]캐시 # https://programmers.co.kr/learn/courses/30/lessons/17680 from collections import deque def solution(cacheSize, cities): answer = 0 cities = [city.lower() for city in cities] if cacheSize == 0: return len(cities) * 5 que = deque() for city in cities: if ci...
c1ee6cdff2953302b0778699ec0bd973c516a420
KWONILCHEOL/Python
/KAKAO/level2/[kakao][2020][blind]괄호 변환.py
720
3.59375
4
# [kakao][2020][blind]괄호 변환 # https://programmers.co.kr/learn/courses/30/lessons/60058 def step(w): if w == "": return "" cnt = 0 u, v = "", "" correct = True for i in range(len(w)): if w[i] == '(': cnt += 1 else: cnt -= 1 if cnt < 0: correct = False if cnt...
ce77d88997f9bdcecdcc91e87b0d1d6e981942b6
Alexico1969/AI-tictactoe
/core_phase07.py
1,827
3.890625
4
import random board = [[0,0,0],[0,0,0],[0,0,0]] symbol = [".","X","O"] def draw_board(): print() print("--A---B---C--") row_nr = 1 for row in board: print("-------------") print('|', symbol[row[0]], '|', symbol[row[1]], '|', symbol[row[2]], "|", row_nr ) row_nr += 1 print("...
ef5efede1db142e41aba118dc0d78efa371ad209
vishnuk1994/ProjectEuler
/SumOfEvenFibNums.py
1,045
4.46875
4
#!/bin/python3 import sys # By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms. # creating dict to store even fib nums, it helps in reducing time at cost of extra space # by rough estimate; it is better to use space as for high value of n, it will re...
e8d2b52838a796220bf848d2fa9841e140b481a3
EionLight/Python_Learning
/exception.py
159
3.71875
4
try: z=int(input("Enter the Year")) y=2020-z print("The Age is",y) except ValueError: print("Please enter Correct Year in correct format")
219c4ea411df7c2e43e1d279bd481524886889e9
pratikkumar399/DSA
/leetCode/binSearch.py
347
4.09375
4
nums = [1,3,5,6] target = 2 def binsearch(nums, arr): left = 0 right = len(nums)-1 while(left<=right): mid = (left+right)//2 if nums[mid] == target: return mid elif nums[mid] < target : left = mid+1 else: right = mid-1 return left pri...
293ce0be3a376936fa9bb79693b0b2cff961a074
pratikkumar399/DSA
/leetCode/reduceOperations.py
588
3.6875
4
nums = nums1 = [5,1,3] max = count = 0 target = list(set(nums)) while (len(target)>1): for i in nums: if i>max: max = i nums_modified = list(set(nums)) second_highest = nums_modified[-2] for i in range(len(nums)): if nums[i]==max: count+=1 nums1[i]...
eaa6806de2fe05241bff57d9af695b1492209b64
FredericBourgeon/python-exercises
/Fibonacci/fibonacci-1.py
182
4.0625
4
""" Fibonacci sequence Returns the first n terms Simple algorithm """ def fib(n): a, b = 0, 1 i = 0 while i < n: print a a, b = b, a + b i += 1
57cbe58cbd4a4867d3dbd583dcb8d2760bd274f5
FredericBourgeon/python-exercises
/Prime sieve/prime-sieve-1.py
289
3.6875
4
""" Compute prime numbers in 0 - 99 """ import numpy as np is_prime = np.ones((100,), dtype=bool) # Cross-out 0 and 1 is_prime[:2] = 0 N_max = int(np.sqrt(len(is_prime))) for j in range(2, N_max): is_prime[j*j::j] = False prime = np.nonzero(is_prime) for j in prime: print j
49ed95fe2f9d21f93d7b503641c698ff00849a58
Gryphonclaw111/CS50
/mario.py
450
3.75
4
import cs50 def main(): while(True): print("How many stories tall do you want your pyramid to be?") height = cs50.get_int() if(height > 0 and height < 24): break h = 0 for i in range(height): print(" " * (height - h), end="") print("#", end ="") pr...
72d09c72cf32fb125a05df5faf3fa113ec8e24e6
Avi9394/python-training
/5-primes/primes.py
179
4
4
# Write a python program to print on a line, the nth prime and the nth prime of the form 3x + 1 # Continue printing until the user presses Ctrl+C # Eg: # 2 7 # 3 13 # 5 19 # ....
f2c0bda23f4292e676e3d246d28f6f158145f7e9
ibbur/LPTHW
/16_v4.py
1,017
4.25
4
print "What file would you like to open?" filename = raw_input("> ") print "Opening the file %r for you..." % filename review = open(filename) print review.read() target = open(filename, 'w') print "\n" print "I will now clear the file contents..." target.truncate() print "I will now close the file..." target.clos...
2e8c4abaa87be49c3b43f16b2ec2a654d568d2e7
reddington123/HackerRank_Python_Solutions
/Basic Data Types/nested_list.py
930
3.703125
4
""" Title : Nested Lists Subdomain : Basic Data Types Domain : Python Author : Sachin Kumar Tiwari Problem : https://www.hackerrank.com/challenges/nested-list/problem """ def sort_second(val): return val[1]; if __name__ == '__main__': list_arr=[]; for _ in range(int(input())): name = i...
d1e3db1fb097ef33d0d55dfe5b24565981bb105c
reddington123/HackerRank_Python_Solutions
/Strings/text_wrap.py
719
3.53125
4
""" Title : Text Wrap Subdomain : Strings Domain : Python Author : Sachin Kumar Tiwari Problem : https://www.hackerrank.com/challenges/text-wrap/problem """ import textwrap def wrap(string, max_width): str_len=len(string); i=0; res=""; while((str_len-max_width)>0): str_len=str_len-m...
e725aa3094b8f1cbf4796b62aa418d9bb02efc4d
GMattimoe/Miscellaneous-Mini-Projects
/Augmented_Hangman/hangman_python/HangmanManager.py
5,557
4.0625
4
#This class can be used to in a hangman game that doesnt pick a word until there #is no other word within an inputted dictionary that it could be. Hence "Evil Hangman" class HangmanManager: def __init__(self, dictionary, length, max): """Pre: Input a Collection of Strings which will be the available word...
3dc2910eea2580527783d8e35114c110e44b3f11
GanSabhahitDataLab/PythonPractice
/Fibonacci.py
661
4.3125
4
# Find PI to the Nth Digit - Enter a number and have the program generate π (pi) up to # that many decimal places. Keep a limit to how far the program will go def fibonaccisequence_upton(): askForInput() def askForInput(): n = int(input("Enter number of Fibonnacci sequence")) fibgenerate...
92cc9281df12a00a39cff6306e53f098914bd0e0
thu-hoai/daily-coding-practicing
/python/bear_and_game.py
692
3.859375
4
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/673/A # Time complexity: O(n) def calculate_interesting_minutes(minutes_list): minutes_list.insert(0, 0) interesting_minutes = 0 for i in range(len(minutes_list) - 1): if minutes_list[i+1] - minutes_list[i] > 15: inter...
226d0e9c413049435046484715560a1a1861dd57
thu-hoai/daily-coding-practicing
/python/night_at_the_museum.py
468
4.125
4
#!/usr/bin/env python # https://codeforces.com/problemset/problem/731/A # Time complexity: O(n) def calculate_rotations_number(string): string = 'a' + string total = 0 for i in range(len(string)-1): num = abs(ord(string[i+1]) - ord(string[i])) if num < 13: total += num e...
702b9b5e2aaf8d21a04ce2bd33df2ca1ff1967b8
Skanda-Bharadwaj/TensorFlow
/tf_mnist_basic.py
1,613
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 3 19:26:04 2017 @author: Skanda Bharadwaj @topic: Basic MNIST classification using Softmax Regression """ #%% Download and fetch input data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/...
4f78143c16d6626c8af4dbbc68bda5403d22e1ba
Inolas/python
/alarmClock.py
1,402
3.5625
4
# https://jugad2.blogspot.in/2013/11/a-simple-alarm-clock-in-python-command.html # https://stackoverflow.com/a/29590673/8343049 import sys import string import subprocess from time import sleep sa = sys.argv lsa = len(sys.argv) f = open('text.txt') message = f.read() #message = raw_input("Enter the message :\t") if...
2fd69a1a6b94cce842ee715bf72d132d9b439ecf
Inolas/python
/edX(MIT)/dec2bina.py
272
3.859375
4
num = raw_input('ENTER AN INTEGER') if(num<0): num = abs(num) isNeg = True else: isNeg = False result ='' if(num==0 | int(num)==1): result = num while(num>0): result = str(num%2) + result num = num/2 if(isNeg): result = '-'+result print result
599ad30470de923b7c91fbe2c8c81231529d4c45
unclexo/problem-solution-stack
/prime-number/sieve_prime.py
659
4.0625
4
import math def prime(n): """ Returns the number of primes from the given number """ # Creates a list with values of True primes = [True] * (n + 1) # Makes 0 and 1 False as they are not prime number primes[0] = primes[1] = False # Sieves all primes numbers # Sets False to those are not p...
2651c168d0f874b4c897227b11d17cf6678032c9
roycekumar/C168-Project
/BOOKSHELF.py
877
4.25
4
class Book: def __init__(self,name,author,price,publishing_year): self.Book_name=name self.Book_author=author self.Book_price=price self.Book_year=publishing_year def add_book(self): print("Book Name: "+str(self.Book_name)) print("Book Author: "+str(self.Book_auth...
b9d8e29e7e9ac9f73b7786906e84937f101e20c6
SrCarlangas1/Pr-ctica-1
/Exercici_05.py
121
3.515625
4
print "Voy a imprimir del 1 al 10" int(raw_input()) n=1 while n<=10: print n n+=1 print "Solución"
0eac1db59ffbdb4cb2281f9538d31efdf9225ded
icesarani/FDLI
/TP7/TP7_Ej1y2.py
1,489
3.84375
4
import random def ingresarNum(): #crear lista con numeros ingresados entre dos paramentros lista = [] a = int(input("Ingresar el primer numero de parametro: ")) b = int(input("Ingresar el segundo numero de parametro: ")) num = int(input("Ingrese el numero que desea sumar a la lista, para termin...
c6ed5f208c4612db06cd3c28942b6de4ca09ce14
icesarani/FDLI
/TP8/TP8_Ej4.py
1,355
3.796875
4
import random def crearMatrizA(filas,columnas): #relleno con numeros random (no olvidar incluir el random) matriz = [] #lista que contiene listas for f in range(filas): #armo una fila matriz.append([]) for c in range(columnas): #le agrego las columnas num = random.randint(100...
590e205eef5fd50c398178c778ec5394bb0f690e
icesarani/FDLI
/TP9/TP9_Ej1P.py
963
3.546875
4
legajos = [] notas = [] legajo = int(input("Ingrese el numero de legajo del alumno, para terminar el programa ingresar -1: ")) while(legajo != -1): legajos.append(legajo) nota = int(input("Ingrese la nota del alumno: ")) while(nota<1 or nota>10): nota = int(input("El valor ingresado par...
8b0b6aca0a84612171f50af0aebe8c811b6fd885
icesarani/FDLI
/TP7/TP7_Ej6.py
1,062
3.765625
4
def ingresarNum(): lista = [] a = int(input("Ingresar el primer numero de parametro: ")) b = int(input("Ingresar el segundo numero de parametro: ")) num = int(input("Ingrese el numero que desea sumar a la lista, para terminar el proceso ingresar -1. ")) while(num!=-1): if (num < a or...
969074ed551a080733d1edbb3313a1288b980ced
ztwu/kg_api
/tools/algo_test.py
3,915
3.65625
4
# -*- coding: utf-8 -*- # @Time : 2021/1/27 9:11 # @Author : ztwu4 # @Email : ztwu4@iflytek.com # @File : algo_test.py # @Software: PyCharm #冒泡排序 data = [2,1,6,3,2,1] for i in range(len(data)-1): print(i) for j in range(len(data)-1-i): if data[j] > data[j+1]: temp = da...
3865e1e3cf60023a368f629cb21a3b163d61fa59
claudiamorazzoni/problems-sheet-2020
/Task 6.py
435
4.4375
4
# Write a program that takes a positive floating-point number as input and outputs an approximation of its square root. # You should create a function called sqrt that does this. # Please enter a positive number: 14.5 # The square root of 14.5 is approx. 3.8. import math num = float(input("Please enter a posit...
aa2aa46c32dd1e5b14021778aa2fb2090321c6ad
prashant956/workspace
/par.py
107
3.75
4
for i in range(1,6): for j in range(i,i+1): print(j,end='') j=j+1 print()
00fef7edafd96636dfa62c390f6b54ce90236ecc
prashant956/workspace
/even.py
136
4.21875
4
num=int(input('enter a number:')) if(num%2)==0: print('num is even',format(num)) else: print('num is odd',format(num))
bc82c8bfc73ef32085ab465df908aca3bec1302f
prashant956/workspace
/dict(add).py
293
3.796875
4
l=[] one=input().split() two=input().split() three=input().split() four=input().split() five=input().split() l.append(one) l.append(two) l.append(three) l.append(four) l.append(five) print("type of list we have created",type(1)) print(l) d=dict(l) print("here is your result as dictionary",d)
165ec36f0e7be60efc0ed8d0975189e2eea2bb63
yolunghiu/dl-papers
/deep-learning/01_Batch Normalization Code.py
6,749
3.59375
4
import numpy as np def batchnorm_forward(x, gamma, beta, bn_param): """针对全连接层的 Forward pass for batch normalization. During training the sample mean and (uncorrected) sample variance are computed from minibatch statistics and used to normalize the incoming data. During training we also k...
7485663d07d8803e5765d6097c136028e46b3f5e
YudongHao/MIT-6.00-1x-intro-to-programming-using-python
/P2_1.py
380
3.734375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Nov 4 12:00:51 2016 @author: yudonghao """ def minimumdebt(balance, AIR, MPR): ''' AIR = annualinterestrate MPR = monthlypaymentrate ''' r = AIR/12 b = balance for i in range(0, 12): ub = b*(1-MPR) b = ub*(1...
b4ca460e7df22914c48ac0243ed7ae5385e0979b
sooraj-sudhakar/Udemy-python3-bootcamp
/tic_tac_toe.py
4,406
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from IPython.display import clear_output board=["","","","","","","","","","",""] def display_board(board): clear_output() print(("\n| {0} | {1} | {2} |").format(board[7],board[8],board[9])) print("----------") print(("| {0} | {1} | {2} |").format(board[...
7e5a41db08a6e8bf91c7ec3a8f3b127d94778528
boluwaji11/Python-Project
/Step 4/Boluwaji_Noureen_step4-a.py
4,369
4.4375
4
def main(): print('Welcome! This program performs Sentiment Analysis.') print('-----------------------------------------') positive_words() # Function to open and read the positive words negative_words() # Function to open and read thenegative words text = input('Please enter the text you want t...
1e609cd242d24f22779ec345ac56558dd6218f18
maxlancaster/cryptopals_solutions
/set2/challenge_9.py
326
3.859375
4
def pad_to_size(to_be_padded, size): if len(to_be_padded) > size: raise ValueError("input {} is larger than the desired pading size: {}".format(to_be_padded, size)) else: PAD = "\x04" padded = to_be_padded + PAD*(size - len(to_be_padded)) return padded def test(): print pad_to_size("YELLOW SUBMARINE", 20) t...
4aa1f93e007fa33dd301be4b726eeee6de02b850
Daiver/jff
/py3/torch_tutor1/nlp_tutor1.py
1,030
3.53125
4
import torch import torch.autograd as autograd x = torch.randn((2, 2)) y = torch.randn((2, 2)) z = x + y # These are Tensor types, and backprop would not be possible var_x = autograd.Variable(x, requires_grad=True) var_y = autograd.Variable(y, requires_grad=True) # var_z contains enough information to compute gradie...
3452b3dd9e93768914732cbd70efe6d65b837b86
StevenGeGe/pythonFromIntroductionToPractice01
/com/chapter_07/section_03/task_7.3.2_listRemove.py
530
3.921875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/20 18:19 # @Author : Yong # @Email : Yong_GJ@163.com # @File : task_7.3.2_listRemove.py # @Software: PyCharm # 删除列表中所有包含特定的值 # list.remove(): 删除列表中的特定值, 从列表首位开始删除。 pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) # 从列表...
a74f59d23c398718989bfab8cf794e1891a3e84a
StevenGeGe/pythonFromIntroductionToPractice01
/com/chapter_11/section_01/task_11.1.1_testFunction.py
652
3.578125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/30 20:12 # @Author : Yong # @Email : Yong_GJ@163.com # @File : task_11.1.1_testFunction.py # @Software: PyCharm # 测试函数 # unittest模块 # formatted_name(): 需要加括号, 不然会报错。 from name_function import get_formatted_name print("Enter 'q' at any time to qui...
0e3c2f1d4fa120eb0ab2db3e536e37066fbd45ec
StevenGeGe/pythonFromIntroductionToPractice01
/com/chapter_07/section_02/task_7.2.3_whileMark.py
913
3.53125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/19 21:00 # @Author : Yong # @Email : Yong_GJ@163.com # @File : task_7.2.3_whileMark.py # @Software: PyCharm # 使用标志退出while循环 # 定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志。 # 让程序在标志 为True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行。 # 在while 语句中就只需检查一个条件——标志的当前值是否为True ...
69b2f2da13bc89c63b12b13d2aee13a2314cd0b2
StevenGeGe/pythonFromIntroductionToPractice01
/com/chapter_08/section_03/task_8.3.2_functionChoose.py
1,272
3.71875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/20 21:06 # @Author : Yong # @Email : Yong_GJ@163.com # @File : task_8.3.2_functionChoose.py # @Software: PyCharm # 让实参变成可选的 # 可选值让函数能够处理各种不同情形的同时,确保函数调用尽可能简单。 def get_formatted_name(first_name, middle_name, last_name): """返回整洁的姓名""" full_...
ef5b19f95abba18a4bda577860a903678fca0e81
StevenGeGe/pythonFromIntroductionToPractice01
/com/chapter_09/section_04/car_most.py
2,270
3.9375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/25 20:22 # @Author : Yong # @Email : Yong_GJ@163.com # @File : car_most.py # @Software: PyCharm class Car: """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """初始化描述汽车的属性""" self.make = make # 制造商 self.mode...
62ccbb87ebf804be3ecb1a5d5d652999cf606913
StevenGeGe/pythonFromIntroductionToPractice01
/com/chapter_07/section_02/task_7.2.4_whileBreak.py
891
3.953125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/19 21:05 # @Author : Yong # @Email : Yong_GJ@163.com # @File : task_7.2.4_whileBreak.py # @Software: PyCharm # 在python3中,break退出while循环 # 立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何 # break 语句用于控制程序流程,可使用它来控制哪些代码行将执行, # 哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。 # ...
3cc80ca720ff0154ca28d4819279fb736048532b
Arcia125/python-RPS
/RPSGame.py
3,015
3.75
4
import random import sys class RPSGame: def __init__(self): self.wins = 0 self.losses = 0 self.ties = 0 self.choices = {'R': 0, 'P': 1, 'S': 2} @property def games(self) -> int: return self.wins + self.losses + self.ties @property def win_rate(self) -> int...
75bbc4eb119aeaaa61254b47e3848114c0d16436
songda515/algorithm
/programmers_printer.py
1,436
3.796875
4
# programmers_printer """ 들어온 순서대로 인쇄 -> First In First Out -> Stack 중요도가 높은 문서를 먼저 인쇄 -> 우선순위 Stack 1. 가장 앞에 있는 문서 J 꺼냄 2. 나머지 인쇄 목록 중 J 보다 중요도가 높으면 J 를 대기목록의 마지막에 삽입 3. 그렇지 않으면 J 를 인쇄 """ from collections import deque # priorities : 현재 대기목록에 있는 문서의 중요도가 순서대로 담긴 배열 # location : 내가 인쇄를 요청한 문서가 현재 대기목록의 어떤 위치에 있는지 # ...
e96e79ec40c9cbbd802f053997b6184486e29c88
kayzhou/exp_finance
/big_board_analysis/src/paint.py
6,462
3.515625
4
# -*- coding: utf-8 -*- __author__ = 'Kay' import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression def number2emotion(num): if num == '0': return 'anger' elif num == '1': return 'disgust' elif num == '2': return 'joy' elif num == '3...
02a11bf65defec6e1280af02fabf2411dea09e85
Nithinnairp1/Python-Scripts
/lists.py
1,073
4.25
4
my_list = ['p','r','o','b','e'] print(my_list[0]) print(my_list[2]) print(my_list[4]) print(my_list[-1]) n_list = ["Happy", [2,0,1,5]] print(n_list[0][1]) print(n_list[1][3]) my_list = ['p','r','o','g','r','a','m','i','z'] # elements 3rd to 5th print(my_list[2:5]) odd = [1, 3, 5] odd.append(7) print(...
c8c1f92540bd6d71b04988e5aea24e4a76f04239
escaduto/PostgreSQL-mini-project
/src/movie_watchlist/database.py
692
3.65625
4
import datetime import sqlite3 CREATE_MOVIES_TABLE = """ CREATE TABLE IF NOT EXISTS movies ( title TEXT, release_timestamp REAL, watched INTEGER ) """ INSERT_MOVIES = "INSERT INTO movies (title, release_timestamp, watched) VALUES (?, ?, 0);" SELECT_ALL_MOVIES = "SELECT * FROM movies;" SELECT_UPCOMING_...
48deac89bd866662febf721d972be90746ed468b
abhi2k1/Phone-Book
/phonebook.py
6,666
3.53125
4
from Tkinter import * import sqlite3 from tkMessageBox import * from edit import edit1 from search import * from intro import * root=Tk() con=sqlite3.Connection('phone_data') cur=con.cursor() #introd() def clear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) e4.delete(0,END) e5.delete(0,EN...
03b7069926fe1190dbf81f43cfa9b93ce8578882
andymakespasta/Tactile_Reader
/from usb/File_IO.py
256
3.859375
4
try: f = open("txt_books\Frankenstein.txt", "r") except FileNotFoundError: print("Cannot find file!!!") print("heyo") lines = f.readlines(); for line in lines: thisline = line.split(" "); for word in thisline: print(word) f.close()
588ef1376e5f793c00bff694bb846ed470bc71f1
cbillet/ATM-practica-3
/EB1P1/DerX.py
1,016
3.65625
4
""" Función para derivar en la dirección x tomando en cuenta la esfericidad de la tierra INPUTS array_2D: numpy array de dos dimensiones dy: paso espacial en dirección x OUTPUTS dUx: array de dos dimensiones con las derivadas """ #%% # Funcion derivada segun x tomando en cuenta la esfericidad de la tierra def de...
104cc32dbbc22fbb8caf82e33dbd06fc1f8ebd8d
Cherrydomini/PersonalProjects
/Perceptron_XOR_calculator.py
1,932
3.5625
4
import numpy as np import math import PyQt5 x1 = float(input("please enter x1")) x2 = float(input("please enter x2")) yd = float(input("What is the desired output: ")) a= .1 epoch = int(input("how many epochs?: ")) w13 = .6 w23 = .3 w14 = .8 w24 = 1.1 w35 = 1.2 w45 = 1.0 theta3 = .7 theta4 = .2 thet...
9e76ed8832052f6d5066700f222bea4d4df69b50
TrihstonMadden/Python
/plot-dictionary.py
1,226
4.125
4
# plot-dictionary.py import tkinter as tk import turtle def main(): #table is a dictionary table = {-100:0,-90:10,-80:20,-70:30,-60:40,-50:50, -40:40,-30:30,-20:20,-10:10,0:0, 10:10,20:20,30:30,40:40,50:50, 60:40,70:30,80:20,90:10,100:0, } print(" KEYS ") print(table.keys()) print(" V...
365bd6f724bff5dd8d5936a10edfa08f79279a2d
TrihstonMadden/Python
/random_list_name.py
487
3.671875
4
from random import randint def randlist(r): alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] c = alpha[r] return c # this is belongs to ranlist(r) def main(): count = 0 checklist = [0]*26 while True: r = randint(0,25) p...
0703db33dd214dbb0213c3a07abe621114077294
MarissaSalcido/Othello
/othello/othello_logic.py
8,116
3.5625
4
# Marissa Salcido 86569875 salcidom class GameState(): def winning_value(self, winning_choice: str) -> None: '''sets the winning rule attribute''' self._win_choice = winning_choice def check_winner(self) -> str: '''compares the player's scores and checks if there is a winn...
cebf9666318ffbad59804bb4f8a164f09fa02d9d
eridanletalis/Python
/stepik/base_course_2/objects/equal_objects.py
190
3.59375
4
# считаем кол-во различных объектов в списке objects = [1, 2, 3, 4, 1, 5, 3, 4, 5, 5, 5] set = set() for i in objects: set.add(id(i)) print(len(set))
5ff6f5085203d4f3b1deb6eac075dc2340be722a
eridanletalis/Python
/stepik/algorithms_course/greedy/huffman/huffman_encoding.py
1,416
3.609375
4
from collections import Counter, namedtuple from heapq import heapify, heappush, heappop class Node(namedtuple("Node", ['left', 'rigth'])): def walk(self, code, acc): self.left.walk(code, acc + "0") self.rigth.walk(code, acc + "1") class Leaf(namedtuple("Leaf", ["name"])): def walk(self, cod...
958035a0daae1a5fc17c5e85a8dde3445518d6df
eridanletalis/Python
/stepik/base_course_1/sets_and_maps/update_dict.py
354
3.953125
4
def update_dictionary(d, key, value): if d.get(key) is None: if d.get(2 * key) is None: d[2 * key] = [value] else: d[2 * key].append(value) else: d.get(key).append(value) d = {} print(update_dictionary(d, 1, -1)) print(d) update_dictionary(d, 2, -2) print(d) upd...
36063a59f1994b2e05e3db1b20c8749b661b268d
eridanletalis/Python
/stepik/base_course_2/iterators_and_generators/prime_generator.py
638
3.921875
4
def isprime1(n): if n == 2: return True for x in range(2, n): if n % x == 0: return False return True def isprime2(n): if n < 6: if n == 2: return True for x in range(2, n): if n % x == 0: return False return T...
111b780e317205805f1d5c230bc16d8f9f55eb78
jpeggreg/CP1404
/cp1404practicals/prac_02/Automatic_password_generator_custom.py
1,931
4.40625
4
import random LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz" UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\" def main(): """Program to get password length and number of each type required.""" password_length = int(input("Enter the password length do you...
d93268feaa89045829e6522bf3da7836a0c14c14
jpeggreg/CP1404
/cp1404practicals/prac_04/strings_repeated.py
388
4.09375
4
string_list = [] string_input = input("Enter a word: ") while string_input != "": string_input = input("Enter a word: ") string_list.append(string_input) else: for i in range(1, len(string_list)): if string_list[i] == string_list[i - 1]: print("Strings repeated: {}".format(string_list[i...
9feb8bfd3e003af033421c3636af84b22644bf75
Jethet/Practice-more
/python-katas/EdabPie.py
729
4
4
# Create a function that determines whether or not it's possible to split a pie # fairly given these three parameters: # Total number of slices. # Number of recipients. # How many slices each person gets. # It's fine not to use the entire pie # The function will be in this form: # equal_slices(total slices,...
b69b7c234efbb185cca0b60b504b72962ad6dfb4
Jethet/Practice-more
/python-katas/EdabCharIdent.py
316
4.0625
4
# Write a function that returns True if all characters in a string are identical # and False otherwise. def is_identical(s): return len(set(s)) == 1 print(is_identical("aaaaaa")) #➞ True print(is_identical("aabaaa")) #➞ False print(is_identical("ccccca")) #➞ False print(is_identical("kk")) #➞ True
6e89e32f81b2c9913b5bef7005de98a8af52ff54
Jethet/Practice-more
/python-katas/Edab2ASCII.py
361
4.03125
4
# Return True if the sum of ASCII values of the first string is same as the sum # of ASCII values of the second string, otherwise return False. def same_ascii(a, b): return sum([ord(c) for c in a]) == sum([ord(c) for c in b]) print(same_ascii("a", "a")) #➞ True print(same_ascii("AA", "B@")) #➞ True print(same_a...
0cb9dbd2051790e0992b5a5c55456efe184911d3
Jethet/Practice-more
/python-katas/EdabPalin.py
778
4.3125
4
# A palindrome is a word, phrase, number or other sequence of characters which # reads the same backward or forward, such as madam or kayak. # Write a function that takes a string and determines whether it's a palindrome # or not. The function should return a boolean (True or False value). # Should be case insensitive ...
5ee216eb2c2c409ed9b51aaf088daae4cfc4755d
Jethet/Practice-more
/python-katas/EdabCodedStr.py
599
3.640625
4
# Create a function that takes a string as an argument and returns a coded # (h4ck3r 5p34k) version of the string. In order to work properly, the function # should replace all 'a's with 4, 'e's with 3, 'i's with 1, 'o's with 0, # and 's's with 5. def hacker_speak(txt): hack = txt.replace('a','4').replace('e','3')....
b447f6804b1aaf41f103aa9b75afd2814c207163
Jethet/Practice-more
/small-projects/inverseRandNum.py
720
4.21875
4
import random # instead of the computer generating a random number, the user is giving the number def computer_guess(x): low = 1 high = x feedback = "" while feedback != "c": # you cannot have low and high be the same: if low != high: guess = random.randint(low, high) ...