blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1d5828e8540c6c1dd5b3734271cfcab63400cb78
clodiap/PY4E
/test.py
874
3.96875
4
x = 25 if x < 10: print("smaller than 10") if x > 20: print("bigger than 10") print("finished\n\n\n") ############################## x = 5 for i in range(5) : print(i) if i > 2 : print("bigger than 2") print("Done with i", i) print("all done\n\n\n") ############################## chif...
e8a2e60a71bbfbc8bdac6df68d210140d96c2208
clodiap/PY4E
/12.7.assignment_scraping.py
782
3.5625
4
# To run this, you can install BeautifulSoup # https://pypi.python.org/pypi/beautifulsoup4 # Or download the file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file from urllib.request import urlopen from bs4 import BeautifulSoup # import ssl # Ignore SSL certificate errors # ctx =...
c833cef237250826cfaaece5abf734c7ae3113d4
clodiap/PY4E
/08_4_exercice.py
661
4.40625
4
# Exercise 4: Download a copy of the file from www.py4e.com/code3/romeo.txt # Write a program to open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split function. # For each word, check to see if the word is already in a list. If the word is not in the list...
2fb6d64bcd5552bafa009518c996dc7b4f1652c4
clodiap/PY4E
/11_assignment.py
2,290
4.40625
4
# The file contains much of the text from the introduction of the textbook except that random numbers are inserted throughout the text. Here is a sample of the output you might see: # Why should you learn to write programs? 7746 # 12 1929 8827 # Writing programs (or programming) is a very creative # 7 and rewarding ac...
27fd5c01b9a6a2987d3df7b6007ede90f9e64762
clodiap/PY4E
/11_regular_expressions.py
2,385
3.59375
4
# hand = open("mbox-short.txt") # for line in hand: # line = line.rstrip() # if line.find("From:") >= 0: # print(line) # import re # hand = open("mbox-short.txt") # for line in hand: # line = line.rstrip() # if re.search("From:", line): # print(line) # hand = open("mbox-short.txt") #...
30148e7eb6c67903a20eb0d6c955a02223ce4132
Alasdairlincoln96/210CT
/Week 7/Question 1 and 2.py
4,629
4.28125
4
import os class Graph(object): '''Class for the graph''' def __init__(self): '''Creates an empty list for verticies to be stored in''' self.verticies = [] def insert(self, n): '''takes a vertex and appends the value of the vertex to the list verticies''' self.verticies.appe...
d63517aa025e0c447ab69b7e244fce8cb17b86e5
Alasdairlincoln96/210CT
/Week 0/Question 3.py
228
4.125
4
floatv = False while floatv == False: try: floatvalue = float(input("Please enter a float: ")) floatv = True except ValueError: print("Thats not a float, please enter a float") print(floatvalue)
d8b1c15a58d44a274871b35cdb7e84d5ac8c5777
Nata-Almeida/tdd-exercicios
/massa-corporal.py
385
3.78125
4
peso = float(input('Digite seu peso: ')) altura = float(input('Digite sua altura: ')) imc = peso / (altura * altura) print('O seu IMC é {:.2f}'.format(imc)) if imc < 18.5: print('Você está abaixo do peso ideal') if imc <= 24.9: print('Parabéns você está em seu peso normal') if imc <= 30: print('Você está ac...
42385d1f91cd3d3afa80504e48bbfb050a2d42bd
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/primitive types/type_conversion.py
586
4.03125
4
x = input("x: ") # in built function to get input from the user # y = x + 1 # print(type(x)) # get the type of an object # some in built type conversion functions # int(x) # convert to integer # float(x) # convert to float # bool(x) # convert to bool # str(x) # convert to string y = int(x) + 1 print(f"x: {x}, y:{y...
1704f9db618a89dd28c6d43629831490eccf8dbc
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/popular python packages/pycrawler/app.py
1,360
3.78125
4
import requests from bs4 import BeautifulSoup response = requests.get("https://stackoverflow.com/questions") # response.text # returns the HTML content of this webpage # soup mirrors the structure of our HTML document # so we can easily navigate this HTML and find various elements soup = BeautifulSoup(response.text,...
49af25dc999d799eb4e90a5b608bc10b63e280fa
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/classes/duck_typing.py
946
4.09375
4
from abc import ABC, abstractmethod # let's modify what we had from the last lesson class TextBox(): def draw(self): print("TextBox") class DropDownList(): def draw(self): print("DropDownList") # controls parameter is purely a label (name) # the type is not specified. # we can pass any kin...
d7d1596b18239dc2519e5011169a82c0a286a4dc
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/python standard library/generating random values/app.py
1,233
4.09375
4
import random import string # generates a random value between 0 and 1 # print(random.random()) # returns a floating point number # generates a random integer between two numbers # print(random.randint(1, 10)) # randomly picks one of the items in a list # print(random.choice([1, 2, 3, 4])) # returns a number of ra...
6f58186853163d8f3687226bd467146d90afcfb1
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/classes/multiple_inheritance.py
941
4.03125
4
class Employee: def greet(self): print("Employee greet") class Person: def greet(self): print("Person greet") class Manager(Employee, Person): # this is called mutliple inheritance pass manager = Manager() # we get `Employee greet` because we added it first # so python checks the ...
9f617cc80fdebd3affa5545e4e536683ae77c601
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/python standard library/working with json files/app.py
676
3.828125
4
import json from pathlib import Path # let's create a list of movie objects # movies = [ # {"id": 1, "title": "Terminator", "year": 1989}, # {"id": 2, "title": "Kindergaten Cop", "year": 1990} # ] # get a string that includes the movie data formatted as json # data = json.dumps(movies) # print(data) # we can...
00e0b67f1727cec8201ee45c63efd88262d16c2c
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/primitive types/primitive_types.py
829
3.8125
4
# Basics of variables students_count = 1000 print(students_count) # floating point number rating = 4.9 # boolean is_public = False # can also be True # string course_name = "Python Programming" # you can also use single quotes course_description = 'Introduction to Machine Learning' # using triple quotes for long ...
9c8ea90881145eaee9da11cfa48b43a3eae85fb2
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/data structures/accessing_items.py
866
4.46875
4
letters = ["a", "b", "c", "d"] # print(letters[0]) # returns the first item # print(letters[-1]) # returns the first item from the end of the list. letters[0] = "A" # print(letters) # the first item has been modified `['A', 'b', 'c', 'd']` # use two indexes to slice a list print(letters[0:3]) # returns first thre...
8b5a9ea1b228787a82a1a7bdac8c32b28e642a36
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/control flow/for_else.py
410
4.0625
4
# successful = True # jump out of a loop with break # for number in range(3): # print("Attempt") # if successful: # print("Sucessful") # break successful = False for number in range(3): print("Attempt") if successful: print("Sucessful") break else: # this will run if ...
94669b51f768dd429858d17ad09bf3f8e3cbbfb7
tobitech/code-labs
/machine learning/ai_programming_with_python/quiz_string_methods/format().py
289
4.03125
4
# Write two lines of code below, each assigning a value to a variable animal = 'dog' action = 'ate' object = 'bone' # Now write a print statement using .format() to print out a sentence and the # values of both of the variables print('The {0} {1} a {2}'.format(animal, action, object))
f256767dd4818d352c0b7df4b1138ac73c085db4
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/control flow/logical_operators.py
625
4.3125
4
high_income = True good_credit = False # if high_income and good_credit: # result is true if both conditions are true # print("Eligible") # else: # print("Ineligible") # result is true if at least one of the conditions is true # if high_income or good_credit: # print("Eligible") # else: # print("Not E...
9d36409ddee7310f6ef3d018081b75173e22075f
Spellwamp/fun
/task2.py
344
4.09375
4
""" Написати функцію is_year_leap, приймає 1 аргумент - рік, і повертає True, якщо рік високосний, і False в іншому випадку. """ def isYearLeap(year): return 'Leap' if year % 100 != 0 and year % 4 == 0 or year % 400 == 0 else 'No leap year' print(isYearLeap(2019))
bae5be82d68cd97abaf13b6bf625c81d5a0bbe0a
Manzood/Pong
/V2.py
12,344
3.65625
4
import pygame import time import random pygame.init() #The equivalent of #define in languages like c, c++ #Use this one variable to change the speed/intensity of the game at any point #upon testing, 10 or 9 seem like the ideal values for difficulty speed = 10 MAX_SCORE = 10 #basic initialization of all variables w...
3e2cbd756ec9a372530ab0ac4bc61b30cbdd6e88
astizm/intermediate-python-course
/dice_roller.py
923
4.15625
4
"""random dice game""" #main function def main(): #import random package import random #set player detail player = str(input("What's your name? ")) #set roll limit and dice details roll = int dice_rolls = int(input('How many dice would you like to roll? ')) dice_sum = 0 dice_size = int(input('How...
77153dc6d37629f31c1e3a587fe109004d846d01
sephirothx/AdventOfCode2020
/utils.py
189
3.5
4
UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 DIR = { UP: (0, 1), DOWN: (0, -1), LEFT: (-1, 0), RIGHT: (1, 0) } def manhattan(x1, y1, x2, y2): return abs(x2 - x1) + abs(y2 - y1)
a6c1846b0ac3cee2e557c0c6035e79e8c56729b3
m2007j17c/sass
/whilrandom.py
526
3.796875
4
import random count = 0 source = 0 while count < 10: print(count) k1 = random.randint(0, 100) k2 = random.randint(0, 100) print("k1 is {}, k2 is {}\n".format(k1, k2)) answer = "" while not isinstance(answer, int): answer = int(input("k1+k2 is ? input your answer")) if int(answer...
b4ada8a503d4d95e4bdbf3ad0033861a018959fa
CASISCAS/machine_learning_python
/linear-regression/LinearRegression_L2.py
3,212
3.578125
4
import numpy as np from util.tools import scale class LinReg(object): """ multivariate linear regression using gradient descent with regularation! """ def __init__(self, learning_rate=0.01, iterations=50, verbose=True, l2=0, tolerance=1e-6, intercept=True): """ :param...
6fec4cbe5decc1ec1dbd6ca89b0234c0d7f83ff4
richardcsuwandi/data-structures-and-algorithms
/Recursive Algorithms/binary_sum.py
372
3.765625
4
def binarySum(list_, start, stop): if start >= stop: return 0 elif stop == start + 1: return list_[start] else: mid = (start+stop)//2 return binarySum(list_, start, mid) + binarySum(list_, mid, stop) def main(): list_ = [1, 2, 3, 4, 5, 6, 7] print(binarySum(list_, 0,...
abc4e6f3ae04285a0155395bc46613662e2a4779
andrezzadede/Curso_Python_Guanabara_Mundo_1
/9Aula.py
2,264
4.21875
4
# Manipulando Texto frase = str (input('informe o nome')) print (frase[0:5]) #Vai mostrar apenas as letras do 0 ao 4 print (frase[2:]) #Aqui vai do 2 até o final print (frase[2::6]) #Vai começar no nove, vai ate o final, mas ele vai pular de tres em tres len(frase) #Vai mostrar quantos caracteres tem na frase fra...
908b4ac57c1cfa42ca2d80f9c6bffbf6220e362d
andrezzadede/Curso_Python_Guanabara_Mundo_1
/Exercicios/19Exercicio.py
452
3.84375
4
# Faça um programa onde leia o nome de todos os alunos e sorteie um para apagar a lousa escrevendo o nome do individo from random import choice n1 = str (input('Informe o nome do aluno')) n2 = str (input('Informe o nome do segundo aluno')) n3 = str (input('Informe o nome do terceiro aluno')) n4 = str (input('Informe...
50ff030553e9ff3f5aa8dcc0fa449500a774a08c
andrezzadede/Curso_Python_Guanabara_Mundo_1
/Exercicios/25Exercicio.py
165
3.859375
4
# leia o nome de uma pessoa e diga se ela tem silva no nome nome = str(input('Informe o nome')).strip() print('Seu nome é: {}'.format('silva' in nome.lower()))
ea3eb62e7ca1e5977d84195778eee3b240aa0879
andrezzadede/Curso_Python_Guanabara_Mundo_1
/Exercicios/30Exercicio.py
276
4.03125
4
#Crie um programa que veja se o numero é par ou impar n = int (input('Informe o número')) resultado = n % 2 # & Ele pode ser usado para ver se é impar ou par if resultado == 1: print('O número {} é impar'.format(n)) else: print('O número {} é par'.format(n))
3682a46733d6995e4a1f175440a5a4bfc61eacf2
andrezzadede/Curso_Python_Guanabara_Mundo_1
/Exercicios/35Exercicio.py
408
4.09375
4
#Desenvolva um programa que leia o comprimento de tres retas e diga ao usuario se elas podem ou não forma um triangulo. r1 = float(input('Informe a primeira reta')) r2 = float(input('Informe a segunda reta')) r3 = float(input('Informe a terceira reta')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('É ...
679f88ec00f979f6b3f840e5e211bc6e4e260686
keshavgbpecdelhi/Algorithmic-Toolbox
/Algorithmic Toolbox/2.1 fibonacci.py
209
3.734375
4
# Python3 input_ = int(input()) if input_<=1: print(input_) exit() def func(input_): a, b = 0, 1 for _ in range(input_ - 1): c = a + b b, a = c, b print(c) func(input_)
6cef56b12dbff0b89e1c35ec22a16058e425500e
keshavgbpecdelhi/Algorithmic-Toolbox
/Algorithmic Toolbox/5.2 primitive calculator.py
2,332
3.96875
4
# --------------------Primitive Calculator--------------------------------- # Problem Introduction # You are given a primitive calculator that can perform the following three operations with # the current number 𝑥: multiply 𝑥 by 2, multiply 𝑥 by 3, or add 1 to 𝑥. Your goal is given a # positive integer 𝑛, find the...
03b8b30c59b6f8c18397d6ce95bafe1e2d9fefad
rayvantsahni/DS-and-Algo-Implementations
/Linked List/Python/singly_linked_list.py
3,475
4.28125
4
# LINKED LIST IMPLEMENTATION IN PYTHON # this is the node class class Node: def __init__(self, value, next_node = None): self.value = value self.next_node = next_node # return the value of the node def get_value(self): return self.value # returns the node that the ...
bf496ebfde5fa74b7cd5800d43a6d0aaf4edddbb
rayvantsahni/DS-and-Algo-Implementations
/Linked List/Questions/reverse_linked_list_inplace.py
1,514
4.28125
4
# Definition for singly-linked list. # class LinkedListNode: # def __init__(self, value = 0, next = None): # self.value = value # self.next = next class Solution: def reverseList(self, head): # Reversing the linked list in place i.e, O(1) space if not head or not head.next: # if the ...
7bf20969fea262a0d2792af68c217222293520df
rayvantsahni/DS-and-Algo-Implementations
/Stack/Python/stack_II.py
931
3.96875
4
class Node: def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def set_next_node(self, next_node): self.next_node = next_node def get_next_node(self): return self.next_node def get_value(self): return self.value class Stack: def __init__(...
3092583a57ef313bb69719339c5d28fc7d7ccfd5
rayvantsahni/DS-and-Algo-Implementations
/String Algorithms/Questions/first_non_repeating_character.py
697
4
4
def get_character_index(s): d = {} # will hold values in the format[fist_index, count] for i in range(len(s)): if d.get(s[i]): d[s[i]][1] += 1 else: d[s[i]] = [i, 1] min_index = len(s) + 1 # will hold the index of the first character with frequency 1 for ...
016e33d9110728e2250f62901c8efdb2b2bad796
alexander-fraser/learn-python
/Python_013_Classes.py
1,533
4.1875
4
# Classes # Alexander Fraser # 7 March 2020 """ Refactoring the odd_or_even snippet to use classes. """ class odd_or_even(): # Define the elements of the odd_or_even snippet. def collect_integer(self, user_message, lower_limit, upper_limit): # This method prompts the user for an integer. # I...
ad59d3351ed35f9305e3bc35b43d59f79115f88b
alexander-fraser/learn-python
/Python_105_Cows_and_Bulls.py
2,177
3.96875
4
# Cows and Bulls # Alexander Fraser # 26 February 2020 """ Requirements: - Python_005_Odd_or_Even Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place , they have a "cow". For every digit the user guessed correctly in the wron...
3d12b568b9f86efe660733eb56ac64db8fe98198
GrayHat12/ShardaCodes
/Python/q3.py
172
4.125
4
current = int(input('Current time in hours : ')) travel = int(input('How many hours ahead ? ')) newtime = (current + travel) % 12 print('New hour',str(newtime)+'\'o clock')
333594ae930a737d639434b2ad968e19ea2260ec
Boyapatiramya/python
/icp1.py
616
3.8125
4
import random str1 = input("Please enter the input string:") del_char1_ind = random.randint(0, len(str1)-1) str1 = str1.replace(str1[del_char1_ind], '') del_char2_ind = random.randint(0, len(str1)-1) str1 = str1.replace(str1[del_char2_ind], '') str1 = str1[::-1]; print(str1) x = int(input("Enter first number:...
627fb246c338680ac02b23162114bd3fe5c919a6
Chasexj/Security-and-Privacy
/2/NIDS.py
8,441
3.578125
4
import csv import matplotlib.pyplot as plt from collections import defaultdict from TestNIDS import * def parse_netflow(): """Use Python's built-in csv library to parse netflow.csv and return a list of dictionaries. The csv library documentation is here: https://docs.python.org/2/library/csv.html"""...
4b357fc727be50da6ea55d1206f7f723d4a8450d
eddddddy/QuSim
/qusim.py
19,517
3.625
4
####################################### Notes ####################################### # # This module is an (attempted) implementation of a quantum computer simulator. It # provides several useful classes (QuBit, QuGate, QuScore) to run the simulation. # Note that we only use 9 gates in this implementation, which are ...
98ea28b09889142a4ebabaecfc4263e2498bca28
AgusFiorda/python_Init
/ejercicios/Condicionales_Ejercicios.py
523
3.875
4
#ejercicio 4 """ Construir un programa que simule el funcionamiento de una calculadora que puede realizar las 4 operaciones aritmeticas basicas(sumar, restar,multiplicar y dividir).El usuario debe especificar la operacion con el primer caracter del nombre de la operacion """ op= input(f"Elija la operacion que va a uti...
40aac1933470a0dbf8817924c33f66f3aea4c8c2
macmarcx/PythonCodes
/Manipulando Strings/manipulando_string_swapcase.py
215
3.578125
4
#Manipulando Strings com swapcase frase = "Manipulando strings em Python" #Utilizando a função "swapcase" para deixar as letras que forem maiúscula em minúsculo e as minúscula em maiúsculo frase.swapcase()
ff693749d27f32991f454a2eaabdc67cb88baea9
ydy0416/algorithm
/이진 탐색/백준 1654 랜선자르기.py
628
3.734375
4
def binary_search(): start=1 end=max(data) while start<=end: mid=(start+end)//2 # print('start,mid,end:',start,mid,end) total=0 for i in data: total+=i//mid # print('total:',total) if total>=n: #만든 랜선이 필요만큼, 랜선의 길이 늘림 start=mid+1 ...
d317e35faa9df6f9ac918607b5f66ca7516f3d0e
dinhquang111/excercise
/bai2.py
1,645
3.953125
4
from random import choice import random questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?", "fruity": "Are ye one for a fruity finish?" } ingredi...
a4fa119398aba3d55e3843d89342bfd4d385e916
cravo-e-canela/URI-Online-Judge
/1219.py
1,025
3.59375
4
import math import sys PI = 3.1415926535897 def find_areas(x): a = int(x[0]) b = int(x[1]) c = int(x[2]) # triangle perimeter = float((a + b + c) / 2) total_area_tri = float(math.sqrt(perimeter * (perimeter - a) * (perimeter - b) * (perimeter - c))) # circunference ray = float((a * ...
7cce725b593921f791ec8415886ada37aeeb03be
vinaykath/PD008bootcamp
/exercise_files/class_6_28_2021.py
1,601
4.09375
4
# Data type in Python """ 1) strings (index, mutable) 2) numbers (mutable) 3) list (index, , mutable) array 4) tuple (index, immutable) 5) dictionary 6) set (index) TDD Test Driven Development """ def data_type(*args, **kwargs): # <somename_<someanother name>> no caps str, list, name = args[0][0:8:] # Python s...
e0469af7fc4d230f3a38f65b4c95a4f0616463a6
gracechg/PythonCode
/O.py
521
3.515625
4
# Trust Fund Buddy - Good str = 'Hello World!' print(str) # 输出完整字符串 print(str[0]) # 输出字符串中的第一个字符 print(str[2:5]) # 输出字符串中第三个至第五个之间的字符串 print(str[2:]) # 输出从第三个字符开始的字符串 print(str * 2) # 输出字符串两次 print(str + " TEST") # 输出连接的字符串 print(str[-1:5]) ...
62a78b0ad231107170dcecb8012b484116c7294e
jeffersonvivanco/LeetCode
/python/median_of_two_sorted_arrays.py
2,124
3.5
4
import math def findMedianSortedArrays(nums1, nums2): nums = {} index = 0 nums1_it = iter(nums1) nums2_it = iter(nums2) n1 = None n2 = None while True: if n1 == None: n1 = next(nums1_it, None) if n2 == None: n2 = next(nums2_it, None) if n1 != ...
512422417c8fbb74dfb5a12459f1a32ec2d5c568
johnny2-dotcom/kadai4-submit2
/kadai4-sbmit2/system.py
2,252
3.65625
4
from menu import Menu import pandas as pd from datetime import datetime # 課題1 # menu_item1 = Menu(0,'サンドイッチ',500) # menu_item2 = Menu(1,'チョコケーキ', 400) # menu_item3 = Menu(2,'コーヒー', 300) # menu_item4 = Menu(3,'オレンジジュース', 200) # menu_items = [menu_item1, menu_item2, menu_item3, menu_item4] # 課題2、課題3 def system(): ...
4eafaace17f817ba709f06d179f3835dc067e6d5
elishatofunmi/data-science-preview
/bursar mental health/apply_my_module.py
2,826
3.671875
4
import numpy as np import pandas as pd class apply_module: def __init__(self): self.none_int_float = [] return def check_if_categorical(data): """ #Your input to the function is an array, #it returns either true or false using the pandas #library .dtyp...
ecc7e0e6c1413dbbccda5e5b34b70230a4df8376
manojr27/pythonpracticeprojects
/Logicaloperator.py
221
3.9375
4
a=10 b=20 print(a and b) print(a or b) str1= 25 str2=55 print("str1" and "str2") print("str1" or "str2") a=10 b="Hello" print(a and b) print(a or b) a=10 print(not a) a=10 != 10 print(not a)
d8ea2526c43abd8d227c69b3a326c4ad176e7783
manojr27/pythonpracticeprojects
/Specialoperator.py
950
3.921875
4
a=10 b=10 print(a is b) print(id(a)) print("----------------") print("Strings") str1= "Manoj" str2= "Tech" print(str1 is str2) print(id(str1), id(str2)) print(str1 is str2) a=10 b=10 print(a is b) print(id(a)) print("----------------") print("Strings") str1= "Manoj" str2= "Tech" print(str1 is str2) print(id(s...
c8ff8c6bfed07c8eb275d8b26bcf254d28926303
Fraetor/yande.re-downloader
/yande.re_downloader.py
2,205
3.546875
4
#! /usr/bin/env python3 # This program will read in a file containing line separated URLs from yande.re, # extract the high resolution image URL, and download the image into the CWD. import requests from urllib.parse import unquote import time from requests.models import HTTPError #import argparse #parser = argpar...
ebb74cc8895f9d7520526fbf48d0a6e99b69ee3e
VibhuBalu/hello-World
/q.py
150
3.734375
4
while True: answer = input('Are you bored? (y/n)') if answer == 'n': print('great, you are playing a intresting game!') break
7aae0141a14597b83a83b5e6e14d67634c2b878b
MrDanielBrown/Python-Course-For-Beginners
/answer.py
3,047
4.125
4
## Q1 : # What will the following code produce? a = 2 a = 4 a = 6 print(a + a + a) output=18 # -------------------------------------------------------------------- ## Q2 : # What's wrong with the following script? a = 1 _a = 2 _a2 = 3 2a = 4 #this is wrong # ---------------------------------------------------------...
1161a15df6f48e1777ce70ad276a4af60d3b767d
LucioMaximo/SimpleChallenges
/Pie Chart.py
1,626
4.28125
4
# A pie chart is a circular graphical representation of a dataset, where each category frequency is represented by # a slice (or circular sector) with an amplitude in degrees given by the single frequency percentage over the total of # frequencies. You can obtain the degrees of sectors following these steps: # Calcula...
37ea2034da056b66dff5df95dfdcaa7f9e40227f
LucioMaximo/SimpleChallenges
/Temperature Converter.py
993
4.21875
4
# Create a function that takes a list with temperature type, temperature, and a second temperature type. # The temperature types can be Celsius, Fahrenheit, or Kelvin. Return the temperature type (in the list) # converted into the second temperature type. # converter(["fahrenheit", 3] , "kelvin") ➞ 257.0 # Difficulty V...
8978cc53fef90ac07bc4dbb80f885ac7cfa16310
mherkhachatryan/CodeSignal
/isLucky.py
575
4.03125
4
""" Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half. Given a ticket number n, determine if it's lucky or not. """ def isLucky(n): n = str(n) input_list = list(n) first = 0 ...
07f334d0ad3c1b9a215af02964857a68d1fc946b
WolfgangWindholtz/RPiFun
/neopixelPython/test.py
1,005
4.03125
4
arr =[] import Tictactoe Tic = Tictactoe.Tictactoe() while True: x = (input("enter n for new game , q to quit \n")) if(x == "n"): while True: b = input(" enter x to place x or o to place o, q to quit ") if(b == "x"): row = int(input("what row? ")) ...
e84ce4e96a36794c0e1ce2e626f4b74644998e8c
sghosh246/DSM_Session2_Assignment_2.1
/seqtolist.py
179
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 16 11:50:46 2018 @author: Sourav Ghosh """ numstr=input("Enter comma separated numbers: ") numlist=numstr.split(",") print(numlist)
946ecf8180ddd0ab292b3e78c4d643636e99c346
Gokul-Venugopal/Python_Basics
/python2.py
1,435
4.21875
4
#list list=['sam',98,10.2] ##list can take heterogenous values print(list) #Indexing and Slicing print(list[2]) print(list[:2]) #for slicing syntax list[start:end:steps] list=[0,1,2,3,4.5] print(list[1:4:2]) # [1, 3] from index 1 to 4 in 2 steps print(list[::-1]) # start to end in reverse list[0]='a' ##...
e03eb10354277e643e332070e26a8464dba29155
ptkpyitheim/CSE-511A-Introduction-to-Artificial-Intelligence
/project2/multiAgents.py
14,423
3.5625
4
# multiAgents.py # -------------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero (denero@cs.berkeley.edu) and Dan Klein (k...
508c864abebffc5663ac75335faa5c171b6197ef
Xochitlxie/Leetcode
/263-Ugly-Number/solution.py
317
3.71875
4
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False uglyFactor = (2,3,5) for i in uglyFactor: while num%i == 0: num = num/i return num == 1
34851fa23484c60b5da81b4ed94b4b38d1d9dd4d
Xochitlxie/Leetcode
/117-Populating-Next-Right-Pointers-in-Each-Node-II/solution.py
1,861
4.125
4
# Definition for binary tree with next pointer. # class TreeLinkNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution(object): def connect(self, root): """ :type root: TreeLinkNode :...
db0c1ddf7d0060e7db63aba2c867ef39412219fd
Xochitlxie/Leetcode
/20-Valid-Parentheses/solution.py
454
3.734375
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] bracketMap = {")":"(","]":"[","}":"{"} for char in s: if len(stack) == 0: stack.append(char) elif char in bracketMap and bracketM...
6d7f5dbb37fa9c01601d91c16f94be476e12c4bf
wwstory/wheel
/ai/nn/loss/mse_loss.py
360
3.5
4
import numpy as np def mse_loss(y, p): ''' mean squared error ''' y = y if isinstance(y, np.ndarray) else np.array(y) p = p if isinstance(p, np.ndarray) else np.array(p) n = len(p) return np.sum((y - p) ** 2) / n if __name__ == "__main__": y = [1, 0, 1, 0, 0, 1] p = [.7, .1, ....
7e875a3ff8c57837978bcba40a4724047f915ce7
berceanu/prepic
/prepic/util.py
1,849
3.546875
4
# -*- coding: utf-8 -*- """ Utility functions """ from collections import Iterable from unyt.array import unyt_quantity def iteritems_nested(d): """ Collect dictionary keys until the deepest level. """ def fetch(suffixes, v0): if isinstance(v0, dict): for k, v in v0.items(): ...
88b1b8578655129b3214ceb2b05af1422ae027a8
JuanCarlos-A01376511/Mision_06
/Mision06.py
2,732
3.6875
4
# Autor: Juan Carlos Flores García A01376511. Grupo 02. # Programa que crea figuras al dibujar círculos, usando ecuaciones para que sean similares a las de un espirógrafo. import pygame # Librería de pygame import math import random # Dimensiones de la pantalla ANCHO = 800 ALTO = 800 # Colores BLAN...
1480f9e3332640ee10dac92710f8f685bbf99186
matthieuchoplin/pycity
/week_1/Exercise_bonus02.py
304
4.25
4
''' Program that displays the area and perimeter of a circle that has a radius of 5.5 using the following formulas: area = radius * radius * p perimeter = 2 * radius * p ''' from math import pi radius = 5.5 print('{0:.2f}'.format(radius * radius * pi)) print('{0:.2f}'.format(2 * radius * pi))
6d0cebc5526c334cc43c7032c98f68c8821ca022
Armandres30/PyGames
/CrucigramGrame.py
3,442
3.796875
4
def createCrucigram(size): size = 13 crucigram = [[ 0 for i in range(size)] for j in range(size)] word = getRandomWord() dir = randombool!!!!!!!!!!!!!! printWord(x, y, word, dir) listOfPositions = getRandomPosition(word) grater = 0 for pos in listOfPositions: ...
d51eb10f578743ac5b11f516148fa708076ea7a0
grey-area/advent-of-code-2017
/day24/part1.py
702
3.640625
4
from collections import namedtuple Port = namedtuple('Port', ['left', 'right']) def search(search_value, ports, strengths, acc=[]): for port_i, port in enumerate(ports): if port.left == search_value: search(port.right, ports[:port_i] + ports[port_i + 1:], strengths, acc + [port.left + port.rig...
2482bcfd8f146fb725197bb290e62ebe9982a490
greenXblue/triangle_prog
/main.py
1,235
4.5625
5
import math #массив сторон треугольника sides = [0]*3 print("Данная программа определяет тип заданного треугольника") print("Введите стороны треугольника") #заполняем массив sides[0] = float(input("a : ")) sides[1] = float(input("b : ")) sides[2] = float(input("c : ")) #проверка условия существования т...
cf401359176f6ede9209dd088f2341861b44a232
colinmrees/h1b_statistics
/insight_testsuite/temp/src/h1b_tally.py
1,580
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 20:23:08 2018 @author: Colin M Rees """ # increments the count in the tally for the given catagory # if catagory is not found in the tally, the catagory is appended and set to 1 def increment( tally, catagory ): if ( catagory in tally ): tally[catagory] +...
9a206ead8686028654571462c0f10f0baaef088e
Amyoyoyo/LeetCode
/35. Search Insert Position/BruteForce1.py
345
3.78125
4
class Solution(object): def searchInsert(self, nums, target): for i in range(len(nums)): if nums[i]<target: i+=1 else: return i return i if __name__ == '__main__': nums=[1,3,5,6] target=0 sol=Solution() ans=sol.searchInsert(nu...
46c827175496f3f0254228ecee88f58ccbb46c6c
Amyoyoyo/LeetCode
/27. Remove Element/BruteForce.py
543
3.59375
4
class Solution(object): def removeElement(self, nums, val): i=0 while i < len(nums): if nums[i]==val: nums.pop(i) i+=1 return len(nums) ''' Runtime: 20 ms, faster than 63.55% of Python online submissions for Remove Element. Memory Usage: 11.8 MB, less...
026d45ae52553447e3bc7c8e5298489457531377
RosezClassrooms/final-group-assignment-brain-not-found
/dishwasher.py
2,869
4.21875
4
from abc import ABC, abstractmethod import random class Dish(ABC):#Dish class to see how much dish washer programs clean the dishes. def __init__(self,_dirt = 0): self._dirt = random.randint(1,10) def get_dirt(self): return self._dirt def clean_dirt(self, ammount): #...
4c2fe049905f99204de54a0b5fb4b0a23ce60f94
aditya2305/PaySpace
/garyvee.py
19,492
3.828125
4
import datetime now = datetime.datetime.now() class main(object): def __init__(self): self.amt1=0 self.amt2=0 self.amt3=0 self.amt4=0 self.amt5=0 self.cardno='null' self.cardname="" self.date="" self.cvv=0 self.bal=0 se...
25779f958efb941f26083db46cfeab63940d894e
mandaltu123/learnpythonthehardway
/basics/okay_one_more_exception.py
415
3.75
4
try: f = open('ac.txt', 'r') except FileNotFoundError as fnf: print("Error {}. Please provide a file that exists".format(fnf)) def factorial(n): if n < 0: raise ValueError("Negative integer {} do not have factorials".format(n)) f = 1 for x in range(2, n + 1): f *= x return f ...
7f293477b045f48091440894cd292bda2ea352b7
mandaltu123/learnpythonthehardway
/basics/little_more_exceptions.py
330
3.90625
4
def divide(x, y): try: result = x / y except ZeroDivisionError: print("Division by zero error") except Exception as ex: print("{}".format(ex)) else: print("result is = {}".format(result)) finally: print("finally") divide(2, 4) divide(2, 0) divide(0, 2) divid...
29e8be9b49c933b6af7431941418ba3961188280
vatodorov/misc
/strings_counting.py
1,228
4
4
# -*- coding: utf-8 -*- """ Two alternatives ways to count words/strings """ ################## Solution 1 # opec_words = ['aa', 'bb', 'ff', 'ff', 'aa'] unwanted_chars = ".,-_()/\#%!" opec = open("C:/Users/bre49823/Desktop/opec_newsletter.txt", encoding = "utf8").read() opec2 = opec.replace("\n", " ") opec3 = o...
b40cd6cb52645af54e1f01c1af37329b4c42ec6b
janhavisingh25/python-assingment-1
/mississippi
289
3.921875
4
import operator s=input("ENTER A STRING:") dic={} def most_frequent(s): for i in s: if i in dic: dic[i] +=1 else: dic[i] =1 return dict(sorted(dic.items(), key=operator.itemgetter(1),reverse= True)) fre=most_frequent(s) print(fre)
62bfe22a743b31f9d68266d4e8b23780bf269595
nikkss94/Social-_Pandas_Network
/testpanda.py
1,171
3.546875
4
from panda import Panda import unittest class TestPanda(unittest.TestCase): def setUp(self): self.vladko = Panda('Vladko', 'vladko@pandamail.com', 'male') def test_is_male(self): self.assertEqual(self.vladko.isMale(), True) def test_is_female(self): self.assertEqual(self.vladko.is...
89af9284912cc029006f1134b09da219231af312
PoeBlu/pynet
/learning_python/lesson1/exercise3.py
600
3.625
4
""" Create four different variables the first using all lower case with _ as the word separator. The second with all upper case with _ as the word separator The third with numbers, letters, and _ (but still a valid variable name) Make all three variables refer to strings Use the from future technique so that any st...
474a3abdace34024eef95bf3a57ebf61dc54b472
elisayhi/NCTU-DL
/LAB2/plot.py
380
3.53125
4
import numpy import matplotlib import matplotlib.pyplot as plt matplotlib.use('Agg') def plot(datas, names, figname): """ datas: data to print, [data1, data2, ...] names: name according to data, [name1. name2, ...] """ plt.figure() for data, name in zip(datas, names): plt.plot(data, lab...
495ed4c2243605801c113fbd9350cbf8d1eeac4d
n0y0j/Software-project-2-group
/assignment4_20171616(조합 팩토리얼).py
623
3.734375
4
def factorial(f): return 1 if f == 0 else factorial(f-1)*f def Combination(q,t,r): if q == t : return 1 else : comb = q/((r)*(t)) return comb while True: try: n = int(input("Enter n: ")) if n<0: break elif n>0: m = int(input("Enter m:...
f3e7d9edc566dd6e0de9937c24584e42172af5c7
n0y0j/Software-project-2-group
/assignment8_20171607/calcConstants.py
438
3.53125
4
from keypad2 import constantList def concalc(key): try: if key == constantList[0]: r = '3.141592' return r elif key == constantList[1]: r = '3E+8' return r elif key == constantList[2]: r = '340' return r elif ke...
1d70b611571c7d7fd9fb8272f2c6ea049de8d9c2
bourman/Information-Security
/Wifi_Passwords.py
1,487
3.5625
4
# READ ALL THIS BEFORE YOU START! #------------------------------------------------------# #Extracting Wifi Passwords From Windows With Python! #We need open up a command line (Cmder) #Type in cmd "netsh wlan show profiles" #And by doing that you get the names or the profiles of all the wifi's that you have been ...
c96cae2b3fad85a6374703058783ebcbea6f7b5f
Maudulo/madmc_project
/test_pareto_func.py
3,793
3.625
4
import time import numpy as np import matplotlib.pyplot as plt from MADMC_project import * def test_pareto_functions(func, nmin = 200, nmax = 10000, step = 200, m = 1000, n = 50, proper = False): """ This function returns a list of the average time taken by the function func @params : func : the function to test ...
9f456eeb7de84d9852de88a98fe18b128923ce80
mennaslama/kayles-game
/manona.py
1,522
3.84375
4
player=1 a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] b=['*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'] print(a) while a!=['*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*']: if (player==1): print("player one's will play") ...
1fcdc9f1d77d2d1bee482610a714af3355e69ac4
simjxu/Misc
/FFT/asdf.py
303
3.578125
4
class Number: def __init__(self, x: int) -> None: self.x = x self.minus = lambda y: self.x - y # we'll come back to this def plus(self, y: int) -> int: return self.x + y one = Number(1) Number.times = lambda self, y: self.x * y print(one.times(2)) # automatically valid2
0a9c25db1e8e063c886100ed2de0795a4549a0fc
misterecco/deep_learning
/lab_05/mnist_tf.py
6,800
4.0625
4
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data import os LOG_DIR_TRAIN = 'out/mnist_tf/train' LOG_DIR_TEST = 'out/mnist_tf/test' SESSION_PATH = 'tmp/model.ckpt' '''' Tasks: 1. Train a simple linear model(no hidden layers) on the mnist dataset. Use softmax laye...
9ace72b65f4e38bc32eb78b83e6abe7858cb3cda
daite/code_example
/python/game/chapter_8/maze.py
1,979
3.53125
4
import tkinter import tkinter.messagebox key = "" def key_press(e): global key key = e.keysym def key_release(e): global key key = "" mx = 1 my = 1 yuka = 0 def main_proc(): global mx, my, yuka if key == "Shift_L" and yuka > 1: canvas.delete("PAINT") mx = 1 my = 1 ...
6c0a015627813bcc550d7f68d38e499955156a94
sophie-patras/OOP_Sophie
/marqueurs.py
2,052
3.625
4
# marqueurs.py #!/usr/bin/python # -*- coding: utf-8 -*- import os, sys class Marqueurs: def __init__(self, idt, ville, position): """ id: Nom indique sur la carte """ self.idt = idt self.ville = ville self.position= position def getId(self): return self.id class Individu(Marqu...
8bb3b77dc5f2cb72f5837729387c236f9acb7975
elenabaulina/lesson2
/main.py
1,905
3.59375
4
gifts = [1, 5.6, 1984, 'iphone', -2] for index in range(len(gifts)): print(type(gifts[index])) at = input("Введите что-нибудь : ") r = list(at) o = 0 for i in range(int(len(r) / 2)): r[o], r[o + 1] = r[o + 1], r[o] o += 2 print("Смотрите, элементы поменялись друг с другом: ", (r)) seasons = ["Зима", "Весн...
58617eab065e4a4bea327f529d70e50fa394cdcb
mukulrawat1986/CodeEval
/spiralprint.py
744
3.609375
4
import sys def unwrap(matrix): spiral = [] while matrix: spiral.extend( matrix[0] ) matrix = list( reversed( zip( *matrix[1:] ) ) ) return spiral if __name__ == '__main__': with open(sys.argv[1]) as fp: for line in fp: line = line.strip().split(';') ...
fb4aaa82f0b9a10840fcab5abbf3eece616193eb
chensikl1991/IS590
/multithreading_example.py
2,433
3.859375
4
"""Simple experiment with multi-threading. IS590PR J. Weible With multiple threads active, try running this in PyCharm's "Concurrency Diagram" mode. """ from threading import Thread import concurrent_functions as cf def single_thread_sleepy(data): result = [] for i in data: result.append(cf.f_sleep...
c9fe14a43b65cab15bdf0d5cb36b2f54300fe3de
chensikl1991/IS590
/sieve_of_eratosthenes.py
1,251
4.21875
4
"""Find primes up to some target number, using the Sieve of Eratosthenes""" import numpy as np def find_primes(highest_to_check=100) -> list: def next_nonzero_value(ar: np.ndarray, hint: int): """Return the lowest non-zero value at or after index position 'hint'. :param ar: an ndarray of intege...