blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f0dbc3f098e17c3aa179370e0dc13a092759c6ce
hcl14/cpp_problems_for_position1
/task1.py
2,744
4
4
# -*- coding: utf-8 -*- # The problem is to count numbers from 1 to N and factorize each one. # It means, that numbers aren't supposed to be big and usage of some advanced prime factorization algorithms # like Pollard’s Rho is not beneficial. Trial division is used here: # function that factorizes one positive inte...
df97aa2ef46b3ab6d5f623604e64222d232214d3
dhbandler/unit6
/hw6.py
929
3.671875
4
#Daniel Bandler #5/14/18 #hw6.py """ #Program 1 wordlist = ["dog", "cat", "hamburguesa"] wordguess = input("Guess a word") if wordguess in wordlist: print("yes") else: print("no") file = open("engmix.txt") word = input("guess a word ") for line in file: line = line.strip() if word == line: ...
2408c31f6598155bcf9248554378c2d479cda617
rzngnam/giangnamdeptrai
/20.8.1.py
291
3.515625
4
s = input("Enter string ? ").lower() # lệnh xóa whitespaces nhưng e ko chạy được ¿ # s.replace(' ', '') table = dict() for i in range(len(s)): if s[i] in table: table[s[i]] += 1 else: table[s[i]] = 1 for k, v in sorted(table.items()): print(k, v)
c76cfc05bdcf2ef4b9beff7cb13a4cbd2c61b0dd
rosswilsonmedia/functionsBasicI
/functionBasicI.py
2,239
3.765625
4
#1 def number_of_food_groups(): return 5 print(number_of_food_groups()) # print 5 #2 def number_of_military_branches(): return 5 # print(number_of_days_in_a_week_silicon_or_triangle_sides() + number_of_military_branches()) # Error: invalid arguments for number_of_days_in_a_week_silicon_or_triangle_sides() #3 ...
f7772bec2e3bf98d5f23a9965319133b8c622b1b
joaothomaz23/Basic_Python_Journey
/num_max.py
371
4.125
4
print("Este programa lê três numeros e dia qual deles é o maior: ") num1 = int(input("Entre com o primeiro numero: ")) num2 = int(input("Entre com o segundo numero: ")) num3 = int(input("Entre com o terceiro numero: ")) num_max = max(num1, num2, num3) num_min = min(num1, num2, num3) print("O maior numero e: "...
1dfced69c33ae3ebc077b92ca0d117b7ff8dca78
alammahbub/py_begin_oct
/13. exception handling.py
319
4.125
4
# if try block produce an error then except block will catch that error and response as required try: value = 5/0 number = int(input("Enter a number")) print(number) except ZeroDivisionError as err: print("Input number other than zero: "+str(err)) except ValueError: print("Invalid Input")
bab85bf4b1bb2f31959e5c15607e28a08b76f19f
PatrickJameson/Kursovaya
/2 часть курсовой/10.py
339
3.5625
4
import numpy as np N = 4 M = 5 K = np.random.randint(1, 3) A = np.random.randint(low=-9, high=10, size=(N, M)) print("Матрица:\r\n{}\n".format(A)) K_arr = np.array(A[:, K-1]) K_arr = K_arr[: , np.newaxis] print("K-ый столбец: \r\n{}\n".format(K_arr)) A = A * K_arr print("Новая матрица:\r\n{}\n".format(A))
736c689d915761887dc2a782ed0fbb6cb03c72c0
johni-yoods/session-10-assignment-johni-yoods
/polygon.py
2,484
4.3125
4
import math class Polygon: """ Polygon class to generate polygon of desired vertex and circumradius. """ def __init__(self,no_of_edges:int,circumradius:int): """ no_of_edges: Number of vertices of the plygon circumradius: circumradius of the polygon. """ ...
f5f1a1deaef231feb288d35fd17ba8f0b6b96432
dkspringer/build-a-blog
/hashutil.py
534
3.515625
4
import hashlib import random import string def make_salt(): return ''.join([random.choice(string.ascii_letters) for x in range(5)]) def make_hash_with_salt(password, salt=None): if not salt: salt = make_salt() hash = get_hash(password+salt) return '{},{}'.format(hash, salt) def get_hash(tex...
3a6e3d85968a2aea22d17713f8fbdbdcf1f9971c
TaehoLi/DL-Tensorflow
/RBM_AutoE/.ipynb_checkpoints/예제3-1-checkpoint.py
3,981
3.5625
4
""" 예제 3-1: 이진 입력 RBM을 MNIST 데이터에 적용 """ # 필요한 라이브러리를 불러들임 import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline # MNIST 파일 읽어들임 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data", one_hot=True) # 학습관련 ...
5f0bbd7ca72275903f3e359857f7f9814d7f1709
binkesi/leetcode_easy
/python/n559_NTreeDepth.py
1,152
3.875
4
# https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: def __init__(self): self.depth = 0 self.queue = [] def maxDepth(...
911027e4239d73e94229f9f70c2315243db70db9
AdamZhouSE/pythonHomework
/Code/CodeRecords/2314/60787/305323.py
71
3.625
4
n=int(input()) for i in range(0,n): a=input() print(str(i)+" ")
03ad6b78e2f5a4de8980dfd64469162a3d70be03
makurek/leetcode
/1323-maximum-69-number.py
729
4.1875
4
''' Given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). Example 1: Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 9969. Changin...
55d1ef94ec89dc76ca90a0da58df7a0bf9b0201c
AdamsGeeky/basics
/04 - Classes-inheritance-oops/10-classes-inheritance.py
831
4.59375
5
# HEAD # Classes - Inheritance # DESCRIPTION # Describes how to create a class inheritance using two classes # RESOURCES # # Creating Parent class class Parent(): par_cent = "parent" def p_method(self): print("Parent Method invoked with par_cent", self.par_cent) return self.par_cent # ...
6437d3b6dab4ae399a6d513471d602ee305e0ff4
kwonseongjae/p1_201611055
/w7main_3.py
937
3.5
4
def saveTracks(): import turtle wn=turtle.Screen() t1=turtle.Turtle() t1.speed(1) t1.pu() mytracks=list() t1.goto(-370,370) t1.rt(90) t1.pd() mytracks.append(t1.pos()) t1.pencolor("Red") t1.fd(300) t1.lt(90) mytracks.append(t1.pos()) t1.fd(400) t1.lt...
f195f65f74f3aa4c7ff84858cff39b66dc466d84
AmitAps/advance-python
/intermediate_python/tuples.py
478
3.78125
4
#Tuples: ordered, immutable, allows duplicate elements mytuple = ("Amit", 28, "chhapra") print(mytuple) singletuple = ("Amit",) print(type(singletuple)) for x in mytuple: print(x) mytuple1 = ('a', 'p', 's', 'd', 'k', 'p') print(mytuple1.count('p')) print(mytuple1.index('p')) # mytuple2 = "amitpratapsingh sahad...
e1f10b5e9def0b70243e4f280ca5a7996408c51e
dawnarc/util_scripts
/string/batch_replace_string.py
560
3.640625
4
#batch replace string in a directory recursively import os import glob import io dir = 'D:/test' dic = { "src": "dest", "aaa": "bbb"} def replace_all(text, dic): for i, j in dic.items(): text = text.replace(i, j) return text for file in glob.iglob(dir + '/**/*.txt', recursive=True)...
eb7f284265f24594d9e564118abf5304f197d54c
Ethnrk/Comp_Mthds_HW1
/Percentile.py
3,473
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 22 16:35:53 2017 @author: Ethan """ #test list for checking if code is right listy = [2,14,67,44,67,34,56,78,12,3,3,98,77,88,43,25,46,76,54,36,73,56,23,87,12,67,34,56,23,98,23,65,33,24,26,97,104,45,67,8,81,98,212] ## lets make this a bit more realistic for diamete...
6a979b5b35a901ce6028d9f9e09ea9f33520f144
alegorecki2405/Coding-challanges
/7.py
774
3.875
4
# Good morning! Here's your coding interview problem for today. # This problem was asked by Facebook. # Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. # For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. # Yo...
1569633d00fdf216fc2c8e3c1e3171ea36b31a19
kswr/Python_Mega_Course
/S_6_File_handling/L_58_opening_and_writing_to_a_txt_file/open_and_wrt_to_txt_file.py
219
3.578125
4
file = open('example.txt','w') file.write("Line 1\n") file.write("Line 2\n") file.close() file = open('example1.txt','w') list = ["Line 1", "Line 2", "Line 3"] for item in list: file.write(item+"\n") file.close()
fa2fcb21f4e2bb3d76e299d20544c41ce2bfb4b9
brunofonsousa/python
/pythonbrasil/exercicios/repeticao/ER resp 26.py
1,104
4.125
4
''' Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato. ''' cand1, cand2, cand3 = 0,0,0 print('******************************************************') print('********************** ELEIÇÕES *...
d1080a8f9ea6001db38246da9722c34682fe841a
eyoung8/weathersite
/src/weather/weather.py
5,199
3.796875
4
#/usr/bin/env python """Script that accesses and prints weather information on a city retrieved from yahoo's weather api. On command line specify city (lowercase, no spaces), state (lowercase, abbreviation, eg. ny) to select the location Display options include: temp condition windchill high low humidity date locatio...
6a312d80c034ef0808bae6d8ae63ecd28e1b4111
CSC525AI-Project1/CSC525AI-Project1
/EightPuzzleGame_InformedSearch.py
18,822
3.828125
4
import numpy as np from EightPuzzleGame_State import State ''' This class implement the Best-First-Search (BFS) algorithm along with the Heuristic search strategies In this algorithm, an OPEN list is used to store the unexplored states and a CLOSE list is used to store the visited state. OPEN list is a priority...
fcda751ab005d41d08bfa8790a1edfdcb013d7e5
sakurasakura1996/Leetcode
/leetcode_二刷hot100/problem538_把二叉搜索树转换为累加树.py
948
3.625
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 想了一个比较蠢的思路,就是我先递归算出每个节点包含自身和所有子节点的和,然后再递归一次,减去左节点当前的值 # 突然发现想漏了,如果不是根节点的话,最终节点的值应该是其父节点的值加上自己的值,再加上右子树的节点值啊。 class Solution: ans = 0 def convertBST(self, root: Tree...
b0a3c58c9a4de66e32b9c126ea88e530a448ced1
SamuelHealion/Sandbox
/week_9/person.py
1,106
4.21875
4
""" CP1404 Week 9 Lecture notes - Do this now Define the class Person """ class Person: """Represents a Person object.""" def __init__(self, first_name='', last_name='', age=0): """Initialise the Person instance.""" self.first_name = first_name self.last_name = last_name self....
3051a73fcf10161dc79127be71ce283a5ebe5969
lim1202/LeetCode
/Tree/populating_next_right_pointers_in_each_node.py
1,363
4.34375
4
# What if the given tree could be any binary tree? Would your previous solution still work? # Note: # You may only use constant extra space. For example, Given the following binary tree, # 1 # / \ # 2 3 # / \ \ # 4 5 7 # After calling your function, the tree should loo...
9aa2d8376555689b7efff7287c7e5b46fb427fc4
venkateshvadlamudi/Pythontesting
/pythonPractice/Distionary.py
1,519
3.984375
4
# Creating Distionary friends= {'tom': '123-123-1234' , 'jerry' : '456-789-7854'} print(friends) # retrieving friends= {'tom': '123-123-1234' , 'jerry' : '456-789-7854'} print(friends) #Retrieving element from the distionary print(friends['tom']) #Adding elements into the distionary friends['...
89b802dca88049ee4fb7f5637ba74fdb81bb4dfb
DariaBe/isapy9
/Zadanie_2.py
2,696
3.71875
4
# 1) Stwórz program który przyjmie w parametrze dowolną listę np ['col1', 'col2', 'col3'] i wyświetli: # +------+------+------+ # | col1 | col2 | col3 | # +------+------+------+ # Dodatkowym atutem będzie gdy szerokość kolumn będzie zawsze równa bez względów na zawartość, tekst wyrównany do lewej. # Maks...
6a4317b3078984ead44b8bdb77eedf0351ba040b
tx58/origin
/lab02/dice.py
272
4.03125
4
""" A simple die roller Author: Tianli Xia Date: Sep 6th, 2018 """ import random first=1 last=6 print('Choosing two numbers between '+str(first)+ ' and '+ str(last) +'.') a=random.randint(first,last) b=random.randint(first,last) roll=a+b print("The sum is "+ str(roll) +'.')
919aec0ed45511239a23c00de6878b5f42228810
MCLeitao/Python-Exercises
/download-package/PythonExercises/ex088.py
883
3.984375
4
# Make a program that helps a PowerBall player to make guesses. The program will ask how many games will be generated # and will raffle 6 numbers between 1 and 60 for each game, registering everything in a composite list. from random import randint from time import sleep print('-' * 35) print(f'{"PLAY ON POWERBALL":^...
15cf7defa338dc596efdb1ffc9d71424fbad427a
Maaz-Mehtab/Python
/Assignment4/Question4.py
416
3.671875
4
# Question4 Write a function called favorite_book() that accepts one parameter, title. The function should print a # message, such as One of my favorite books is Alice in Wonderland. Call the function, making sure to # include a book title as an argument in the function call. def favorite_book(title): print(tit...
f53058f09a2e75b095ec3eda26b49963923431df
qmnguyenw/python_py4e
/geeksforgeeks/python/easy/26_3.py
5,175
4.09375
4
MongoDB Python – Insert and Replace Operations **Prerequisites :**MongoDB Python Basics This article focus on how to replace document or entry inside a collection. We can only replace the data already inserted in the database. **Method used :** replace_one() and replace_many() Aim: Replace entire dat...
7c1b3fbe6554c3d0216bad7c69765349615b71a4
fonoempresa/deep-learning-with-python
/forward_propagation.py
815
3.953125
4
import numpy as np print("Enter the two values for input layers") print('a = ') a = int(input()) # 2 print('b = ') b = int(input()) # 3 input_data = np.array([a, b]) # How are the weights created? # The model training process sets them to optimize predictive accuracy. weights = { 'node_0': np.array([1, 1]), ...
0ebeb4427016605f51ccd68a03009b5cd7924bab
unclebae/python3-data-analysis
/ch02/columnStack2D.py
366
3.671875
4
# _*_ coding: utf-8 _*_ import numpy as num a = num.arange(9).reshape(3, 3) print ("num.arange(9).reshape(3, 3) : ", a) b = 2 * a print ("b = 2 * a : ", b) # column_stack print ("column_stack of 2D : column_stack( (a, b) ) : ", num.column_stack( (a, b) ) ) print ("compare column_stack of 2D and hstack : ", num.col...
2caadd54e0ef3cf234fb5553ebc280d2b3a961dd
davidburdelak/exercises-studies
/python/task_5_1.py
1,455
4.375
4
""" Task: Sergeant Thomson decided to censor the letters his soldiers receive. This censorship involves removing every third line from the letter. Help the sergeant: write a program that receives a text file with a letter and creates its censored version - task_5_1_letter_censor.txt. The task_5_1_letter.txt file exis...
26a1f7779b40770d425f104fb7ec64accfcb3d2d
aaronbernal02/backup
/practice2.py
383
4.0625
4
# Aaron, Bernal # 9/27/19 Block 1 print("Input two numbers") num1 = int(input("Enter 1st digit ")) num2 = int(input("Enter 2nd digit ")) print (str(num1) + "+" + str(num2) + "=" + str(num1 + num2)) print (str(num1) + "*" + str(num2) + "=" + str(num1 * num2)) print (str(num1) + "/" + str(num2) + "=" + str(num1 ...
a04bac771101cee12134afd993d25cda0b09b01b
duckha/python_labs
/Lab3/Lab_1/Main.py
267
3.6875
4
class Square: def __init__(self, side): self.side = side def getP(self): return self.side * 4 def getS(self): return self.side ** 2 s = Square(5) s1 = Square(10) print("hello") print(s.getP()) print(s1.getP()) print(s1.getS())
0ff51c02eb3ef57e380b97ad10984b0a67d04d2b
liangel02/ccc2013
/q2.py
868
3.609375
4
totalWeight = int(input()) cars = int(input()) weightList = [] num = 0 for i in range(cars): weight = int(input()) weightList.append(weight) for i in range(len(weightList)): if i == 0: if weightList[i] > totalWeight: break else: weightOfOne = weightL...
7a703fa6224c3c0aded4262764f25cafe00af146
kentronnes/python_crash_course
/python_work/Python Crash Course Chapter 4/4-11 my pizzas, your pizzas.py
423
4
4
pizzas = ['salami and olive', 'peperoni', 'supreme', 'bbq chicken'] for pizza in pizzas: print(pizza.title()) print("I like " + pizza.title() + " Pizza." + "\n") friend_pizzas = pizzas[:] pizzas.append('mushroom') friend_pizzas.append('sausage') print("\nMy favorite pizzas are:") for pizza in pizzas: print("\t" +...
7e714fe4767d9d6553c8c01666582506d4a85fa1
OlehHnyp/Home_Work_10
/Home_Work_10_task_1.py
387
4.0625
4
age = input("Enter your age:") def even_odd(inf): try: inf = int(inf) if inf < 1: raise IndexError status = "odd" if inf%2 == 0: status = 'even' print(f"Your age is {status}") except ValueError: print("It's not a number") except IndexE...
6a821fdccfb3ad277185cae15a15415cbe69ad35
alexaustin456/Preliminary-Code-for-Extended-Project
/is_prime.py
195
4.0625
4
def is_prime(): a = 2 num = int(input("Number:")) while num > a: if num % a == 0 & a != num: return False a += 1 else: return True is_prime()
fea242174ebccf75fbcceecee3ef4f636a485374
bomminisivaprasad/python-for-everybody-coursera-
/Course 3 - Using Python to access web data/ex12/scraping.py
848
3.9375
4
# This program scrapes a website for numbers and returns their count and sum. # Importing from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Initialising the count and total count = 0 total = 0 # Ignoring SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ...
de90606a0dc79fae1ed4eee5a67522827f403d7f
odremaer/some-exercises
/AAABBBCCC.py
215
3.5625
4
def f(s): res = s[0] cur = s[0] for i in range(1, len(s)): if cur == s[i]: pass else: cur = s[i] res += s[i] return res print(f("ABBBBCCCCDDF"))
5a6f61b22a3945ffbf225bb6d8620b574bbe48c0
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/grgvic001/question1.py
377
3.953125
4
#enter values and return all unique values #victor gueorguiev #27 April 2014 def main(): xinput = input('Enter strings (end with DONE):\n') strlist = [] while xinput != 'DONE': if not xinput in strlist: strlist.append(xinput) xinput = input() print() print('U...
4ff9cbeb10f734170e2923956d5bf4646f3bcd1f
TaylenH/learningProjects
/Zenva/Python/VariablesAndOperators/PurchasingReceipt.py
1,256
3.828125
4
#Project printing out a receipt for store purchases made by a customer. #Showcases knowledge of variable assigning and mathmatic operators. #descripton and price of store items lovely_loveseat_description = ''' Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. Red or wh...
55c76712787458bc7a94eb768b20b3c288ae6f44
jasemabeed114/Python-work
/11.47.py
3,099
3.640625
4
from tkinter import * import random class largeBlock: def __init__(self): window = Tk() window.title("Find Largest Block") frame = Frame(window) frame.pack() frame2 = Frame(window) frame2.pack() self.v = [] for i in range(10): ...
6ecfc2518badf9f84645211c6e61f12a0b69c798
f981113587/Python
/Aula 07/Desafios/010.py
276
3.84375
4
# Crie um programa que leia quanto dinheiro # uma pessoa tem na carteira e mostre quantos # dólares ela pode comprar. Consirede U$$ 1,00 = R$ 3,27 reais = float(input('Quantos R$ você tem ? ')) dolares = reais / 3.27 print('Você pode comprar US$ {:.2f}.'.format(dolares))
49a75e97c67535b1c7964bf2d2b3de41259acc2d
estherjulien/HybridML
/train_data_gen.py
4,201
3.734375
4
from NetworkGen.NetworkToTree import * from NetworkGen.LGT_network import * from datetime import datetime import pandas as pd import numpy as np import pickle import time import sys ''' Code used for generating train data. make_train_data: - Make a network and get data points by calling the function net_to_red...
96ce66dac074380f8745904a37802b1338a9fed3
DurdenTyler2008/Tasks_Python
/9.py
809
3.859375
4
#матрица,закрутить против часовой стрелки(надо сделать так): # 1 8 7 1 2 3 # 2 9 6 из 4 5 6 # 3 4 5 7 8 9 m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for i in range (len(m)): for j in range(len(m)): if i == 2: if j==0: print('1:',m[j][0],m[i][1],m[i][0]) for ...
e18776b85243ba60d81ab04d3addc17c70207992
19990423whs/AIDVN2005
/dir/demo.py
614
3.640625
4
""" python 操作 mysql 流程演示 """ import pymysql # 1. 创建数据库连接对象 --> 关键字参数 db= pymysql.connect( host='localhost', port=3306, user='root', passwd='123456', database='student', charset='utf8' ) # 2. 生成游标对象 (游标对象用于执行sql语句,获取执行结果) cur = db.cursor() # 3. 执...
0ce81e87585e72570e101fd960272c12dd11983b
imranzahid81/Python
/8 loops.py
3,068
4.84375
5
# http://www.learnpython.org/en/Loops # Loops # "for" loop # For loops iterate over a given sequence. Here is an example: primes = [2, 3, 5, 7] for prime in primes: print(prime) """ # FOR PYTHON 3 in order to get list from string use syntax : list(range(1,100)) # For loops can iterate over a sequence of numbers...
97e1b1224388f4a0a848dcaf9b663e1ce76f2410
Duologic/python-deployer
/deployer/console.py
16,693
3.9375
4
""" The ``console`` object is an interface for user interaction from within a ``Node``. Among the input methods are choice lists, plain text input and password input. It has output methods that take the terminal size into account, like pagination and multi-column display. It takes care of the pseudo terminal underneat...
e47b48cecb443ebaf6dd71b3bc40cb3d7ae1c4da
G-Jarvey/base-python
/列表元素个数的加权和(1).py
226
3.59375
4
lst = eval(input()) def f(lst,level): sum = 0 for i in lst: if type(i) == int: sum = sum + level else: sum = sum + f(i,level+1) return sum sum = f(lst,1) print(sum)
08e0f11ec04dda78c02d3954cdfa85c35ace9066
brendanmarko/Pygame
/Race/Code/Position.py
741
3.734375
4
# Position.py # Serves as storage for a position (or any data type with two fields!) class Position(object): 'serves as storage for a position (or any structure with two points)' def __init__(self, x, y): # Debug info self.DEBUG=1 self.DEBUG_TAG="[Position]" if (self.DEBUG == 1): print(self...
695d3fb99dfe0af1ba3d93e2a91ac1f7cb7b4aee
KirillGukov/edu_epam
/hw3/tasks/task_1.py
1,488
4.0625
4
"""In previous homework task 4, you wrote a cache function that remembers other function output value. Modify it to be a parametrized decorator, so that the following code: @cache(times=3) def some_function(): pass Would give out cached value up to times number only. """ from typing import Callable def cache(t...
d137b70e471898c1aedc82368663b79afb310f44
YouriTjang/INFDEV02-2
/Code samples from the lectures/Lecture01/Player_class.py
1,019
3.890625
4
class player: def __init__(self, name, posX, posY): self.name = name self.positionX = posX self.positionY = posY # Met de __str__-methode kan je aangeven hoe je deze class wil printen def __str__(self): return "Player {} is at position ({}, {})".format(self.name, self.positi...
99d75561ca5d66aa65a0d4c7383b4bc353b3f8e6
kuchunbk/PythonBasic
/7_Conditional Statements and loops/Sample/conditional_ex40.py
893
4.0625
4
'''Question: Write a Python program to find the median of three values. ''' # Python code: a = float(input("Input first number: ")) b = float(input("Input second number: ")) c = float(input("Input third number: ")) if a > b: if a < c: median = a elif b > c: median = b ...
67a23e86d468db1d29cd83333cba27a17c181ddc
andrewyager/python-asterisk-dialplan
/asterisk_dialplan/ranges.py
2,710
3.671875
4
from .util import common_start import math def split_range(low, high): """ Take a range of telephone numbers in E.164 format between low and high and return the "safe" chunks for the pattern matching script to use :param low: telephone number in E164 format :type low: integer :param high: teleph...
684cfb0e95213ea794c7168edc53aa4dd0b2284d
puccash/py_projects
/basic/p2.py
4,165
3.578125
4
# 단일 데이터(단일 타입) # 문자열(연속이지만, 이쪽으로도 분류한다) # 표기법 # '....' , "....." , '''.....''' , """.......""" # '''....''' , """.....""" 용도 : 여러줄 표현, 구조유지, 여러줄 주석용 a = 'hi' print(a) a = "hi" print(a) # 혼용 표현 a = 'abcd"KKK"efg' print(a) # 이스케이프 문자로 동일 기호를 내부에서 사용 가능 a = 'abcd\kkk\efg' print(a) # 여러줄 사용 a = ''' asdfs safwwd erw2fs...
a39d4cc47fe0f706797e14380f0a62892fd7120e
nicolasgonzalez98/Ejercicios-Python-de-Informatica-UBA-
/TP 7/ej7.py
350
3.625
4
def elim_cadenas(a): a=a.split(" ") b=list(a) print(b) cad=input("Ingrese una cadena a eliminar: ") for i in range(len(b)-1): if b[i]==cad: b.pop(i) for i in range(len(b)): if b[i]==cad: b.pop(i) b=" ".join(b) return b texto="Danilo se fue a Par...
4f14c34cb64ef7daf0cb7f0e68376142392d61e6
cifpfbmoll/practica-5-python-fperi90
/P5ej1.py
295
3.921875
4
for i in range(10): print(i+1,end=" ") print ("\n") for i in range(10): print((i+1)*2,end=" ") print("\n") for i in range(10): print(20+(i*2),end=" ") print("\n") for i in range(6): print(10+(i*4),end=" ") print("\n") for i in range(9): print(40-(i*5),end=" ")
d53fc8e0c349d1553535b7b502692e7585ff1225
arara90/AlgorithmAndDataStructure
/Practice_python/Graph/서로소집합자료구조.py
1,767
3.71875
4
# 특정원소가 속한 집합 찾기 (x는 노드번호) def find_parent(parent, x): # 루트 노드 찾을 때까지 재귀 if parent[x] != x: return find_parent(parent, parent[x]) return x # 두 원소가 속한 집합 합치기 def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b) if a < b: parent[b] = a else: ...
3aff6aa43c7c40b447419fa01c6e7589eb5ca2e4
Cleber-Woheriton/Python-Mundo-1---2-
/desafioAula029.py
543
3.734375
4
#(Desafio 29) Escreva um programa que leia a velovidade de um carro. # se ultrapassar 80km. Mostre uma msg dizendo que ele foi multado. # A multa irá custar R$ 7.00 por cada km acima do limite. print('*-'*15, 'Programa de Velocidade', '*-'*15) vel = int(input('Informe a velocidade: ')) # if verificando se a velocidade...
d9444af2df03c1c731834223d41472842321f617
iajalil/tkinter-demo
/#TASK 2.py
2,050
4.03125
4
#importing tkinter for our interface design import tkinter as tk #using the alias tk instead of the normal tkinter from tkinter import ttk from tkinter.ttk import * #create an instance of tk win = tk.Tk() #Giving the window a title win.title(' App title') ttk.Label(win).grid( column=3 , row = 0) #creati...
30505f751cb1ef2e768681d2ba5832229c014085
GUSTAVOPERALTA1/poo
/semana_8/temp.py
3,037
4.03125
4
repeticiones= 0 #Variable que almacena el numero de repeticiones class Temperaturas: #Clase principal promedio_cent= 0 #Alamacenamos el promedio de °C prmedio_fahr= 0 #aAlmacenamos el promedio de °F fecha= [] #Almacenamos las fechas cent= [] #Almacenamos los °C fahr= [] #Almacena los °F def __init__(self)...
6abe87daa2cbc1da5a445f74997c7f8947c58e21
joydeepnandi/Algo
/Recursion/Interweaving Strings/InterweavingStrings1.py
644
3.96875
4
# O(2^(n + m)) time | O(n + m) space - where n is the lengt # of the first string and m is the length of the second string def interweavingStrings(one, two, three): if len(three) != len(one) + len(two): return False return areInterwoven(one, two, three, 0, 0) def areInterwoven(one, two, thre...
5341f8c8e3d9fac4d0e9675ac00ee1bebf4e911f
rrlins/python3-exercicios
/python_exercicios/ex051.py
369
3.96875
4
# Desafio 051 - Desenvolva um programa que leia o primeiro termo e a razão de uma # PA. No final, mostre os 10 primeiros termos dessa progressão. n = int(input('Digite o primeiro termo da progresão aritimética: ')) r = int(input('Digite a razão da progresão aritimética: ')) for c in range(0,10): prin...
7c2e248869c9527207f54eab080b647f2836427d
MohammedAlewi/competitive-programming
/leetcode/modulus calculation/prime_subraction.py
253
3.609375
4
def subPrimes(a,b): if abs(a-b)==1: print("No") return print("YES") def runner(): val=input() for i in range(int(val)): ans=input() ans=ans.split(" ") subPrimes(int(ans[0]),int(ans[1])) runner()
1b0e58c8f769399f293594ab01b79d43560eada6
mikaelbeat/Modern_Python3_Bootcamp
/Modern_Python3_Bootcamp/List_comprehension/Preview.py
543
4.03125
4
print("\n********** Demo 1 **********\n") numbers = [1, 2, 3, 4, 5] doubled_numbers = [] for num in numbers: doubled_number = num * 2 doubled_numbers.append(doubled_number) print(doubled_numbers) print("\n********** Demo 2 **********\n") name = "Colt" print([char.upper() for char in...
473e0182cb98ec7a71a7e9f386fc17c181f27087
Jack-Attack3000/RPG-Game-Final
/g_map.py
2,465
3.6875
4
# Course: CS 30 # Period: 1 # Date Created: 21/02/28 # Date Last Modified: 21/02/28 # Name: Jack Anderson # Description: Classes for the map and location class Location: def __init__(self, name, description, inv_item, chara, exits): self.name = name self.description = description self.char...
3f3df53a1f7bd4f678b07cb90112ac1e5db8cd4b
FernandoKGA/DesafiosDeProgramacao1
/Lista2/H - Maximum Sum of Digits/maximumSumOfDigits.py
702
3.78125
4
import math def findLargestSum(n): digits = digitsFromNumber(n) if len(digits) == 1: print(n) else: size = len(digits) numberWithNines = 0 i = 0 while i < size-1: numberWithNines += 9 * math.pow(10,i) i += 1 firstDigit = int(digits[0])...
63b0f5bca58e5d5eb66fcc2823c3baad5750a3cb
ebatsell/geo-api
/cities.py
3,894
3.65625
4
import heapq import math import random class City(object): def __init__(self, cityid, name, population, alt_names_str, latitude, longitude, country_code, segment): self.id = cityid self.primary_name = name self.population = population self.country_segment = segment self.latitude = float(latitude) self.lo...
87b00d8065f044647e6fac2d9030d92453331251
dujiaojingyu/Personal-programming-exercises
/编程/8月/8.15/链表成对调换.py
1,290
3.921875
4
__author__ = "Narwhale" class ListNode: def __init__(self,elem): self.elem = elem self.next = None class Solution(object): def __init__(self,node=None): self.__head = node def is_empty(self): return self.__head == None def append(self,item): node = ListNode(it...
c459af8f6d522d43db7da0c213bcd8ff290ee591
paianish62/Anish-s-Calculators
/Square_Cube_and_Pie.py
630
4
4
def cust(a,b): c = 0 ans = a while c < (b-1) : ans = ans*a c += 1 print(ans) while True : x = int(input("Enter No. ")) y = str(input("Function performed on the no. (square, cube, pie or custom) ")) if y == "square": print(x*...
8d24122d84b9695f10de2fe5406b2635d9d563aa
RayNakagami/Atcoder
/2706/2706.py
733
3.609375
4
prime = [2] def check(x): for i in prime: if x % i ==0: return False elif x < i * i: break return True def set(): for i in range(3,10**5,2): if check(i): prime.append(i) set() #print('ok') #print(prime) p,q = [int(i) for i in input().split(' ')]...
3d142f2d4f8c3828d33643e1c0a601464414e97b
simplynaive/LeetCode
/706. Design HashMap.py
2,022
3.859375
4
class ListNode: def __init__(self, key, val): self.key = key self.val = val self.next = None class MyHashMap(object): def __init__(self): """ Initialize your data structure here. """ self.size = 1000 self.map = [None] * self.size def put(se...
c41097cb6c0b6c8319cff5a983171c36d1ed1a45
prince-prakash/practice_session
/pp_multiplicationtable.py
109
3.71875
4
num = int(input('Enter the number for table evaluation: ')) for i in range(10): w = i * num print(w)
c1d938a7b63d27b94cb66c2271feb8674f3fb7a6
anoyo-lin/algorithm
/pre-algorithm/binary_search.py
588
3.921875
4
#!/usr/bin/python3 sample_lst = [ 1, 3, 6, 10, 12 ] target = 22 def binary_search( sorted_lst, target ): low = 0 high = len(sorted_lst) - 1 while low <= high: mid = (low + high)//2 if sorted_lst[mid] > target: high = mid - 1 elif sorted_lst[mid] < target: low...
8921e94e9c2391c2939bdfc27128ee9dd764891e
Asap7772/shpPython
/Class5/ImageManipulation/Color.py
257
3.734375
4
class Color(object): r = 0; g = 0; b = 0; def __init__(self, red = 0, green=0, blue=0): self.r = red; self.g = green; self.b = blue; def __str__(self): return "{} {} {} ".format(self.r, self.g, self.b);
e588e28a48d18c71e9f27965375e2253ba671b4e
mirko-m/restricted_boltzmann_machine
/src/binary_rbm_numpy.py
10,260
3.609375
4
import numpy as np import matplotlib.pyplot as plt import mnist def sigm(x): return 1.0/(1.0 + np.exp(-x)) class RestrictedBoltzmannMachine: '''Implementation of binary Restricted Boltzmann Machine (RBM) using numpy. Both the visible and the hidden units are binary. The weights are initialized using G...
a823b5329a617fa19cdbee490c096ffc5e88755b
LemmiwinksNO/Udacity101
/Units 1-2 PS 1-2/Lesson 3.py
1,155
4.125
4
def find_element(p,t): i = 0 while i < len(p): if p[i] == t: return i i = i + 1 return -1 def find_element(p,t): i = 0 for e in p: if e == t: return i i += 1 return -1 # index method <list>.index(<value>) p = [0, 1, 2] print p.index(3) ...
03ec85aff434b394a505abf6b052779062fd68f4
dackour/python
/Chapter_24/04_Quiz.py
2,775
3.890625
4
# 1. What is the purpose of an __init__.py file in a module package directory? # # The __init__.py file serves to declare and initialize a regular module package; # Python automatically runs its code the first time you import through a directory # in a process. Its assigned variables become the attributes of the module...
2c41a0ca20c589b1fa3fc66cbdc401c220f8ec03
sphars/python-learning-playground
/python-crash-course/chap11/test_name_function.py
568
3.59375
4
import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): """Tests for 'name_function.py'.""" def test_first_last_name(self): """Do names like 'Ned Flanders' work?""" formatted_name = get_formatted_name('ned', 'flanders') self.assertEqual(form...
9f9c1c6c83d53c11a25bd2540dc6f943e61674ae
CristianeNaves/rsa
/funcoes_auxiliares.py
1,013
4.09375
4
""" Recebe um numero grande e simplifica ele em fatores menores de 8,4,2 e 1. num: 23 retorno: [8,8,4,2,1] """ def fatorar_numero(num): resultado = [] quantidade_15 = int(num/15) mod_15 = num % 15 num = num - (15 * quantidade_15) resultado.append(8) if int(num/8) else None num = num % 8 r...
4b5fb414b9f19fec12d42f7997ede49a34ca26e6
yadnyesh/AllPythonYouTube
/durga/section7/printPattern.py
93
3.6875
4
n = int(input('Enter number of rows: ')) for i in range(n): print((str(i + 1) + ' ') * n)
e9b3ead9247d6eb91b18c7d70f59e67d1debed35
nikosninosg/Multi-dimensional-Data-Structures
/Kd_Trees/Mds_Main_Solution.py
643
3.5625
4
import pandas as pd from sklearn.neighbors import KDTree import matplotlib.pyplot as plt df = pd.read_csv("train_x_y_10K.csv") # Num of Rows = 29.118.021 points print("Num of Rows: ", len(df.index)) # print(df.y[0:3]) plt.scatter(df.x[0:99], df.y[0:99]) plt.show() X = df.to_numpy() print(X) print(type(X)) tree = K...
3e533579d9dd97b78444c4a43e7fd7b5549141ea
rainishadass/127
/code/exam1/answers.py
1,444
3.890625
4
import math ############### question 1 ####################### # def f(n,k): numerator = (1+n)**k denomiator = math.sqrt(k+1) return numerator / denomiator ############### question 2 ####################### # def remove_e(sentence): result = "" for letter in sentence: if letter != 'e': ...
cc0eb4cfdc53d06dd09726006c2c626fd4876488
LeighGriffith/python-projects
/code-studio/s1level63.py
801
3.703125
4
'''s1level63 // draw_a_square for (var count = 0; count < 4; count++) { moveForward((50)); turnRight(90); } // draw_a_square for (var count2 = 0; count2 < 4; count2++) { moveForward((60)); turnRight(90); } // draw_a_square for (var count3 = 0; count3 < 4; count3++) { moveForward((70)); // draw_a_square for (v...
12236e1f2f6e474eebd79c9534f8e8bdf54384c3
Code-Law/Ex
/MaxNumber.py
176
4.03125
4
#Input 6 integer.Output the biggest one. m=0 number=[] for i in range(6): num=int(input("number:")) number.append(num) if number[i]>m: m=number[i] print(m)
6dc7db393e69cbf702bb56e4cc280d73c49f2d4b
asanjeevkumar/throw-ball
/scripts/max_touches.py
2,265
3.765625
4
"""Script prints the maximum number of players that can touch a single ball. This script takes csv file location as argument and process csv file to identify the maximum count of players touch a single ball. `python throw_ball/scripts/max_touches.py [file_location]` """ from os import path as osp import csv import cl...
fe7fa911738b41994f63d04e33d361c73b580e97
mibra41/UVA
/TEST1/madlib.py
1,447
3.71875
4
#Muhammad Ibrahim (mi2ye) #Nathan Tumperi (nlt4xp) name = input('Female name: ') noun1 = input('Plural object: ') person = input('Dangerous people: ') mean_animal = input('Mean animal: ') verb1 = input('past tense verb: ') verb2 = input('Malicious past tense verb: ') household_object = input('Household object...
00fec2a4b6053f9982beb005035606a134107957
CarlosAmorim94/Python
/Exercícios Python/ex065_Maior e menor valor.py
796
3.96875
4
""" EXERCÍCIO 065: Maior e Menor Valores Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. """ continuar = 's' soma ...
ff41e00b993e374b1e5e776f4cfd733d184c669e
lygeneral/LeetCode
/Python/Array/middle/73_set-matrix-zeroes.py
1,606
3.546875
4
''' 73. 矩阵置零 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。 示例 1: 输入: [ [1,1,1], [1,0,1], [1,1,1] ] 输出: [ [1,0,1], [0,0,0], [1,0,1] ] 示例 2: 输入: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] 输出: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] 进阶: 一个直接的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。 一个简单的改进方案是...
082dac836fd2a2c5ac7f2c3a15f4130049f2e0e9
ThouArtToFiddy/Past-Projects
/csci1133/TakehomeTest1/wheeloffortune.py
9,080
3.75
4
import random def randomphrase(): #Returns a random phrase from phrasebak.txt and its category number x x = random.randint(0,4) y = random.randint(0,19) phrases = getphrase() return [phrases[x][y].upper(),x] def getcategory(x): #Returns the category ...
7fadeb96acd394e4ee0084a9a5285af8192e6a17
djdavis1420/gilded_rose
/src/models/item.py
322
3.515625
4
class Item: def __init__(self, name, sell_in, quality): self.name = name self.sell_in = sell_in self.quality = quality def update_item(self): if self.sell_in <= 0: self.quality -= 2 elif self.quality > 0: self.quality -= 1 self.sell_in -= ...
f4a7d24840218e5a7513da24164b41d129f4de87
dantru7/PY110-november-2018
/Tasks/train_second.py
710
3.78125
4
""" 2. Считалочка Дано N человек, считалка из K слогов. Считалка начинает считать с первого человека. Когда считалка досчитывает до k-го слогка, человек, на котором она остановилась, вылетает. Игра происходит до тех пор, пока не останется последний человек. Для данных N и К дать номер последнего оставшегося человека. "...
2b253ca3ac1b3a0384d44b900026ae1d2d646fdd
phvv-me/python-switch-if-tree
/src/switch.py
1,663
3.671875
4
# simple switch key = "preposition" default = "..." switch = { "noun": "dog", "verb": "to bark", "adjective": "big", "adverb": "loudly", "preposition": "of", }.get(key, default) assert switch == "of" # functional switch def fibonacci_switch(key): def loop(n): ... def recurrent...
505773eadb095ad2fb79c6b12eecccf96383f4b5
luisdomal/Python
/S8/ejemplos/test_operaciones.py
635
3.578125
4
from operaciones import * def test_suma_cero(): resultado = suma(0, 0) # Espero que resultado sea 0 assert resultado == 0 # Para correr el test tenemos que escibir en consola lo siguiente: "py -m pytest" # Para tener mas detalle podemos escribir al final -v def test_suma_numeros_iguales(): assert sum...
1f01960ee7ee3d5772e57fc474531ece31c0e950
SANJAY072000/PythonInterviewChallenges
/LevelOne/forLoop.py
150
3.71875
4
# print(list(range(0, 20, 5))) # for i in list(range(0, 20, 2)): # print(i, end=' ') for i in ["Sanjay", "Singh", "Bisht"]: print(i, end=' ')
43f30982521c64019f25c41b01b77cccb2cdb92c
Jeffreygrimmie/dice
/roshambo.py
1,121
3.890625
4
###Jeffrey Grimmie 2/17/2019 ###To do: fix bug, if more then one player rolls the same number and the rolls are highest in rolls. ### tap roll the dice game rolls dice on each input for player then returns what player wins. import os import roll_dice def clear_screen(): os.system('cls' if os.name == 'nt' e...