blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
86cfe3a786b0ba3f548b743bb35990a81b021a2c | bastikr/pyqo | /pyqo/utils/list_functions.py | 425 | 3.75 | 4 | '''
def _conjugate_indices(indices, ndim):
"""
Return all numbers from 0 to ndim which are not in indices.
"""
if isinstance(indices, int):
indices = (indices,)
return set(range(ndim)).difference(indices)
'''
def sorted_list(iterable, reverse=False):
"""
Transform an iterable to a so... |
e9f71af62a38c89f38145034cf14896bb3e847a7 | realpython/materials | /python-list/matrix.py | 198 | 3.5625 | 4 | matrix = []
for row in range(5):
matrix.append([])
for _ in range(5):
matrix[row].append(0)
matrix = [[0 for _ in range(5)] for _ in range(5)]
matrix = [[0] * 5 for _ in range(5)]
|
af39e9a770317784ace4420a98689ed84357f0d4 | Official-BlackHat13/100_days_of_python | /day_1_5/day_2.py | 378 | 4.03125 | 4 | print('welcome to the tim calculator!')
bill = input('bill: ')
tip_percentage = input('percentage of the tip you want to give: ')
persons = input('number of people who eated: ')
tip = (float(bill) * float(tip_percentage)) / 100
total_bill = (float(bill) + float(tip))
bill_per_person = float(total_bill) / float(persons... |
c4082c1f2b83b01f8044e8989ed6e7b00438d50c | Racheltrq/CS1134 | /HW4/rt1726_hw4_q7.py | 532 | 3.5 | 4 | def split_by_sign(lst, low, high):
if low > high:
return
else:
if lst[low] < 0:
temp = lst.pop(low)
lst.insert(0, temp)
if lst[low] == 0:
index = low - 1
found = False
while index >= 0:
if lst[index] < 0:
lst.pop(low)
lst.insert(index + 1, 0)
found = True
br... |
190d162c5930d02d25742f57b4a5e6046031adda | pathologicalhandwaving/sqrtApprox.py | /sqrtAprox.py | 3,574 | 3.96875 | 4 | #! usr/bin/env python
# K. M. Short
# Math180 Numerical Analysis
# Mills Fall 2014
# HWK#1: Binary Search and Bisection Algorithms: Square Root Approximation
# sqrtAprox.py
# imports
import sys
import csv
import math
# define Array
vals = []
# initialize Vars
n = 0
itr = 0
root = 0
sqRoot = 0
apr... |
ed941c024129098338f843edc4d4e1b4ddbcb61f | slowrance/advent_2020 | /day07/day07.py | 2,109 | 3.546875 | 4 | with open('input.txt') as f:
real_input = [line for line in f.readlines()]
test_input = '''light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 fa... |
9a41e47950e974bb597ed08d6068694c71e6d254 | divx89/100DaysOfCode-Python | /Day017-21226-The_Quiz_Project/question_model.py | 411 | 4.21875 | 4 | class Question(object):
""" Class Question stores questions, their answers, and methods to manipulate them"""
def __init__(self, text, answer):
"""Initialize a Question object
Parameters:
text (String) - The Text of the Question
answer (String) - Answer of th... |
5089dc9cf2ea41b452314441c2b96c30d86370d4 | Eroica-cpp/LeetCode | /001-Two-Sum/Python/Solution03.py | 1,487 | 3.71875 | 4 | #!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: Jul 27, 2015
# Question: 001-Two-Sum
# Link: https://leetcode.com/problems/two-sum/
# ==============================================================================
# Gi... |
4ffbe6931a81db58ddcbd1f880a35dc55ae0a98b | chaitanyakulkarni21/Python | /Balguruswamy/2_Functions/Review_Excercises/sumofNaturalNum.py | 166 | 4 | 4 | def sum_nat(n):
s = 0
for i in range(1, n+1):
s = s + i
print("Sum of",n,"Natural numbers: ", s)
x = int(input("How many natural numbers ? : "))
sum_nat(x) |
65b6b082eaf7283b88166946413ef3796d330343 | muskan09/PythonCodes | /perm.py | 174 | 3.640625 | 4 | from itertools import permutations
def perm(str):
a=permutations(str)
for x in list(a):
print (''.join(x))
if __name__=="__main__":
str='SOJA'
perm(str)
|
9a0563f3dee257862ed1ce65d64ed79e3ca5c748 | ashwani311/30-Days-Of-Code | /python/Day-3.py | 374 | 4.125 | 4 | #!/bin/python3
# SheBang! for Python 3
import sys
N = int(input().strip())
# Define the range for the number
if N < 1 or N > 100:
print("Weird")
else:
# Check for Odd / Even
if N%2:
print("Weird")
else:
if N>0 and N<6:
print("Not Weird")
elif N<21:
print(... |
5cbd491aa0b2d737dd8e26fdeffbd36ff4f9bac7 | medialab/casanova | /casanova/contiguous_range_set.py | 3,298 | 3.90625 | 4 | # =============================================================================
# Casanova Contiguous Range Set Collection
# =============================================================================
#
# Simplistic implementation of a contiguous range set in python relying on a
# sorted list of contiguous intervals.... |
0fe1d27bae934a01dc7c93e023d1bba924fc780a | AndreSlavescu/DMOJ | /RollTheDice.py | 317 | 3.609375 | 4 | #https://dmoj.ca/problem/ccc06j2
m = int(input())
n = int(input())
total = 0
for i in range(1, m+1):
for j in range(i,n+1):
if i+j == 10:
total = total + 1
if total == 1:
print(f"There is {total} way to get the sum 10.")
else:
print(f"There are {total} ways to get the sum 10.")
|
39d52d4535695ed6622ed2914631d989489ce904 | msramalho/fcup-abi | /exercises/abi.py | 1,231 | 3.53125 | 4 | # globals for efficiency
DICT_AMINOACIDS = None
# return a valid dna sequence as an example
def dna_valid():
return "ATGAAATTATGAATGAGCCTCAGCTGAAGCATCGCGCATCAGACTACGCTCAGACTCAGACTCAGCATTATAGTGAATGTTAATAAATAAAATAA"
# return an invalid dna sequence as an example
def dna_invalid():
return "xGAAATTATGAATGAGCCTC... |
1d3002dcad2f52e49237c2793298fa591e681b73 | mlastovski/kse-olympics-parse | /olympics.py | 8,415 | 3.859375 | 4 | # import libraries
import csv
import argparse
# add console arguments to program
parser = argparse.ArgumentParser(description='Process some data.')
parser.add_argument('path', metavar='PATH', type=str, help='Path to the file')
group = parser.add_mutually_exclusive_group()
group.add_argument('-medals', metavar='COUNTRY... |
43496a167f3c97adc658b714ce3bdcc18ed04a1c | k18a/algorithms | /interview_prep/binary_tree_height.py | 2,564 | 4.09375 | 4 | # define tree node
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
# string method for tree node
def __str__(self):
return str(self.info)
# define binary search tree
class BinarySearchTree:
# in... |
d7b5fce55bc484a527fa8e43dbeeccb721a0586c | wonny-Jo/algorithm | /알고리즘 정리/완전탐색/문제풀이/카펫.py | 444 | 3.5625 | 4 | from math import sqrt
from math import floor
def solution(brown, yellow):
answer = []
total=brown+yellow
for i in range(1,floor(sqrt(yellow))+1):
if yellow%i==0:
w=i+2
h=(yellow//i)+2
if w*h==total:
answer.append(h)
answe... |
8f7281567c3434beeaf0e6c74742c0f995548b2b | Pedro0901/python3-curso-em-video | /Python 3 - Mundo 3/Desafios das Aulas - Mundo 3/Ex110/teste.py | 329 | 3.78125 | 4 | '''
Exercício Python 110: Adicione o módulo moeda.py criado nos desafios anteriores,
uma função chamada resumo(), que mostre na tela algumas informações
geradas pelas funções que já temos no módulo criado até aqui.
'''
#Programa principal ex108
import moeda
p = float(input('Digite o preço: R$'))
moeda.resumo(p)
|
6aea7a049f3552d384569e12f527986531cb66c6 | SueAli/cs-problems | /LeetCode/Search a 2D Matrix II.py | 754 | 3.6875 | 4 | import bisect
# Time complexity is O( n + m log m )
# space complexity is O(1)
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
rows = len(matrix) if matrix else 0
cols = l... |
7640a8e10f45506c68e30ca3fe2bc44c0a4d89be | daniel-reich/ubiquitous-fiesta | /H2EyqacEnijCozCWs_23.py | 194 | 3.5625 | 4 |
def first_n_vowels(txt, n):
vowels = "aeiou"
txt_vowels = "".join(char for char in txt if char in vowels)
if len(txt_vowels) >= n:
return txt_vowels[:n]
else:
return "invalid"
|
4b0dcab72e96e652e7449ded4321772f81111c02 | eugenia1984/PoloticMisiones-FS-JS-Python | /clase1/clase1-ejercicio3.py | 526 | 4.46875 | 4 | """
3. Escribe un programa en Python que acepte una cadena de caracteres y cuente el tamaño de la cadena y cuantas veces aparece la letra A (mayuscula y minúscula)
"""
#Le pido al usuario que ingrese un número
my_string = str(input("Por favor ingrese un texto corto: "))
#cuento el tamaño de la cadena
tamanio_cadena = ... |
341a0bd23dbe5080070e03cc25c328df4fbc5b6c | hargup/bioinformatics | /bioinformatics/frequent_words.py | 2,175 | 3.703125 | 4 | def count_occurances(text, pattern):
count = 0
for i in range(len(text) - len(pattern) + 1):
if text[i: i + len(pattern)] == pattern:
count = count + 1
return count
def frequent_words(text, k):
"""
find the most frequent k-mers in the text
"""
frequenent_patterns = set(... |
9102b106d8a83067bda7a61e150fa62661f4f12f | chldydgus777/Algorithm | /1316.py | 460 | 3.609375 | 4 | # 그룹단어 체커 [https://www.acmicpc.net/problem/1316]
#----------------------------------------1316----------다시풀어보기
n = int(input())
num = 0
for _ in range(n):n = int(input())
num = 0
for _ in range(n):
word = input()
for i in range(len(word)):
if i != len(word)-1 :
if word[i] == word[i+1]:
... |
0d7f587f6eafe2a22200cbc36102f2e0668db28e | antoninabondarchuk/algorithms_and_data_structures | /binary trees/min_depth.py | 624 | 3.953125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def minDepth(root: TreeNode) -> int:
if not root:
return 0
left_depth = minDepth(root.left)
right_depth = minDepth(root.right)
if left_depth !... |
5142de8f1455090714b7abcf0bde980885605778 | rabiajamil/Python-Challenge | /PyBank/main.py | 3,609 | 3.734375 | 4 |
#Import/Path:
import os
import csv
PyBankcsv=os.path.join("Resources", "budget_data.csv")
#Lists
profit = []
monthly_changes = []
date = []
#Variables
count = 0
total_profit = 0
total_change_profits = 0
initial_profit = 0
# profit_loss_average = 0
# increase_date = 0
# decrease_date = 0
# greatest_increase_profits ... |
75907d9bf034b9a9f11a17a8abdd17a644f400f9 | jedzej/tietopythontraining-basic | /students/myszko_pawel/lesson_02_flow_control/07_King move.py | 811 | 3.921875 | 4 | # Chess king moves horizontally, vertically or diagonally to any adjacent cell.
# Given two different cells of the chessboard, determine whether a king can go from the first cell to the second in one move.
# The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two... |
bb65afefbc99e106bd7800b1c2ef0d50478bfbcb | Snooker4Real/Python_files | /Algorithme cours/maximum dans une liste.py | 428 | 3.796875 | 4 | t#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 21:01:21 2018
@author: jonathancindanomwamba
"""
def Max(L):
N = len(L)
max = L[0]
i0 = 0
for i in range(N):
if L[i] > max :
i0 = i
max = L[i]
return i0
L = [1,2,3,4,5,6,7,80,45,9,0,10]
c = M... |
3b1eb63c7c5b22c4c784c696ff03a3b0f8430efc | uk-gov-mirror/nhsconnect.ndop-nojs | /ndopapp/main/ndop_validator.py | 1,349 | 3.53125 | 4 | import re
NON_ALPHA_RE = re.compile("[^A-Z0-9]+")
POSTCODE_RE = re.compile("^[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}$")
class PostcodeValidator:
@staticmethod
def normalise_postcode(postcode):
""" Return a normalised postcode if valid, or None if not."""
postcode = NON_ALPHA_RE.sub("", post... |
f90c92fa4968430cd986da241521e2f4087f112e | lanemoseley/CodeChef | /python/Beginner_ChefAndTyping.py | 2,916 | 4.125 | 4 | '''
Chef is practising his typing skills since his current typing speed is very low.
He uses a training application that displays some words one by one for Chef to type.
When typing a word, Chef takes 2 seconds to type the first character; for each
other character of this word, he takes 2 seconds to type this charact... |
98a60ea09bf52bfc52a67665ca87e4df6f5b2296 | pbollepally/Python_tutorials | /Drawsquareart.py | 480 | 4.09375 | 4 | import turtle
def draw_square(some_turtle):
some_turtle.color("yellow")
some_turtle.shape("turtle")
some_turtle.speed(50)
for nooflines in range(1, 5):
some_turtle.backward(100)
some_turtle.left(90)
nooflines += 1
def draw_art():
myscreen = turtle.Screen()
myscreen.bg... |
b3bec32ed02f72dda63db8a00f10c4f3384a9ff2 | git-athul/Letter-invaders | /gamewindow.py | 2,361 | 3.703125 | 4 | import curses
class Window():
"Functions to display letter-invaders-game"
def __init__(self, screen, height, width):
self.win = screen
self.height = height
self.width = width
self.score_value = 0
self.setup_colors()
self.win.nodelay(True)
curses.init_col... |
8902a7f6bbb25fa4e1cdd62c40581c454adaa5cd | saraNersisian/Introductory-Python | /L3_Q1_pyramid.py | 399 | 4.03125 | 4 | def pyramid_volume(base_length, base_width, Pyramid_height):
base_area = base_length * base_width
Volume = base_area * Pyramid_height * 1/3
return Volume
base_length = int(input("length: "))
base_width = int(input("Width: "))
Pyramid_height = int(input("Height: "))
volume=pyramid_volume(b... |
3eb498cdef3ee46afab59f45d7b1364dfd031b6b | venkateshelangovan/IIT-H-Course-Work- | /IIT H Semester 1 Course Work/ADSA/CODING PRACTICE/3.Sort 0 1 2.py | 1,472 | 4.1875 | 4 | # Question Link : https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/
"""
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array.
The functions should put all 0s first, then all 1s and all 2s in last.
"""
# function to sort 0,1,2
def Sort012(input_... |
b7445723e6cd8543b025092bc221b3d9f13ec0df | remcohaszing/python-syringe | /syringe.py | 4,150 | 3.78125 | 4 | # -*- encoding: utf-8 -*-
"""
A simple dependency injection library.
Usage
=====
First decorate a class with ``@provides('a lookup name')``.
>>> import syringe
>>>
>>> @syringe.provides('cure')
... class Syrup:
... def drink(self, person):
... print('Nom nom')
... person.health = 100
...
Instant... |
043ce926b1fc3e2768d3d1205374cbf997994b29 | Rahulpandey81/Python_Programming | /Converter.py | 623 | 4.1875 | 4 | a=float(input("Enter The Feet to Convert"))
print("Select your option")
print("\n 1:- Feet to inches \n 2:- Feet to Yards \n 3:- Feet to miles \n 4:- Feet to Melemeters \n 5:- Feet to Centemeters \n 6:- Feet to meters \n 7:- Feet to kelemeters")
n=int(input("Select Your Option"))
if n==1:
a=a*12
print(a,"Inches... |
2927d366a737df7c0dd905d1c08692ec86fb5557 | EMendy/Homework-6 | /Dataset ONE - Beer cans_Mendenhall.py | 10,768 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Homework 6, Part One: Lots and lots of questions about beer
# ### Do your importing and your setup
# In[1]:
import pandas as pd
# ## Read in the file `craftcans.csv`, and look at the first first rows
# In[2]:
df = pd.read_csv('craftcans.csv', na_values = ['Does not ap... |
387c86766223ae789ae95ad79043797ba43eb05c | aaronmatei/Payroll-System | /test.py | 2,138 | 4.125 | 4 | # from datetime import datetime
# birthday = datetime(1992, 11, 22, 9, 30, 45)
# print(birthday.day)
# print(birthday.month)
# print(birthday.date())
# print(birthday.hour)
# print(birthday.weekday())
# print(birthday.now())
# sq_iterator1 = [x**2 for x in range(0,11)]
# print(sq_iterator1)
#
# sq_iterator = (x**2 for... |
4532a6e85539b7d7c8d9711fc9bc287cfcfd621c | DHRUVSAHARAN/python- | /ch 2/practice_3.py | 144 | 3.59375 | 4 | # make a program to get the variable aasigned using input () Syntax
# ok
a = input ("give the value of int a ",)
print (type(a))
# done |
4ef8d8aa5869e32781f18340761f4fcbcbc5c64d | ecastrojr/AprendendoPython | /ordem.py | 241 | 4.125 | 4 | n1=int(input("Entre com um número inteiro: "))
n2=int(input("Entre com um número inteiro: "))
n3=int(input("Entre com um número inteiro: "))
if n1 < n2 and n2 < n3:
print("crescente")
else:
print("Não está em ordem crescente") |
0cb928ec10b00d779360336e07db5ddd360dd12b | Dcon1/flasktryout | /Prac-4/quick_pick.py | 603 | 4.125 | 4 | """ I struggled with this, do we have to import csv? I could not figure a way to efficiently added columns to a list"""
import random
MIN_NUM = 1
MAX_NUM = 45
def main():
game_lines = int(input("How many quick picks"))
for i in range(0, game_lines, 1):
game_numbers = []
for i in range(0, 6, 1... |
db52412ecb778413233b4813c49760a0727919e4 | Mybro1968/AWS | /Python/02Basics/example/03BooleanWords.py | 290 | 4.1875 | 4 |
word1 = input("please input the first word: ")
word2 = input("please input the second word: ")
if word1<word2:
word1first = True
else:
word1first = False
if word1first:
print(word1 + " comes before " + word2)
else:
print(word1 + " comes after " + word2)
|
d5915b1a49bc6bb01763e8991dabf0ac4e3faa57 | evajanka/Enterprise_project | /common.py | 7,431 | 3.96875 | 4 | """ Common module
implement commonly used functions here
"""
import random
import data_manager
def generate_random(table): # kH38Jm#&
"""
Generates random and unique string. Used for id/key generation:
- at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letter
... |
a9fbfe6dd68234161222b607b3e1c10feb881fdb | JiangongChen/Recipes | /hist_ver_generator/generator_v0.1.py | 1,172 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 28 23:50:15 2021
@author: chenj
"""
import numpy as np
from datetime import date
RECIPE_NUM = 13
RECIPE_LIST_NAME = 'recipes_list_v1.txt'
if __name__ == '__main__':
all_recipes = []
# read all recipes from the file that stores the list
with open(RECIPE_LIST... |
320a451052ab9a3cc34f03430ad0b29f25b511df | mkieft/Computing | /Python/Week 8/Lab 8 Q 2.py | 515 | 4.3125 | 4 | #Lab 8 Q 2
#Maura Kieft
#10/20/2016
#2. Write a function which take as input three numbers from the user and prints the largest of the three numbers
def main():
x=eval(input("Enter first number: "))
y=eval(input("Enter second number: "))
z=eval(input("Enter third number: "))
biggestNumb(x,y,z)
def bi... |
125ff694b781443949dfb2341b6b23c99ac81120 | sbm1/regex | /regex/parse_tree.py | 1,615 | 3.546875 | 4 | from itertools import chain
class ParseTree(object):
"""
Parse Tree built using Parser.root
"""
def __init__(self, v):
"""
@param v -- node value
"""
self.value = v
self.children = []
def __repr__(self, level=0):
if self.value is None:
... |
8dcaa00aa10ff36149446b86292f72213beb8e31 | GraceDurham/intro-class | /film.py | 333 | 3.625 | 4 | from urllib2 import urlopen
from json import load
#sf open data source: film location in sf
apiUrl = "https://data.sfgov.org/resource/yitu-d5am.json?"
#open the apiUrl and assign data to variable
response = urlopen(apiUrl)
json_obj = load(response)
for film in json_obj:
if film["release_year"] == "2000":
print f... |
3f553b0d1f65508c30dba5b4c030ad63bd5cbfaa | LCzoboriek/Python3 | /calculating test scores.py | 806 | 4.3125 | 4 | #This program averages test scores input from a teacher
#First im going to aquire the number of students
num_students = int(input('How many students do you have? '))
#Next im going to get the number of test scores to acquire
num_test_scores = int(input('How many different test scores do you have per student? '))
#De... |
31fd9f0200cfef9d5f9b37fa30b8612b1fa8b06a | xuyuanxin/notes | /language/python/packages/numpy/matrix_np.py | 2,351 | 3.953125 | 4 | http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html
class numpy.matrix:
'''
Returns a matrix from an array-like object, or from a string of data. A matrix is -
a specialized 2-D array that retains its 2-D nature through operations. It has cer-
tain special operators, such as * (matrix multipl... |
4fe18fc1b9db8990bee675f8b8813842426b500a | safkatjaman/PYTHON-3 | /Python - Code Challenges/Control Flow - Advanced/5 Max Number/script.py | 377 | 4.0625 | 4 | def max_num(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
elif num3 > num1 and num3 > num2:
return num3
else:
return "It's a tie!"
print(max_num(int(input('Enter number 1: ')), int(inp... |
2ad477cfd3a6d1005292b95e409f9b66ccc12954 | shurj0/CSE-231 | /Project 4/proj04.py | 6,903 | 4.46875 | 4 | """
Project 4
Algorithm
Prompt to pick an option
Match the option to a function
If function requires any, prompt for an argument
Evaluate the function with the passed argument
Compare the result with the math module values
Print the result, th... |
4c1c0b9d66717679e7246d2025a159346df3e6e6 | Akasurde/Algorithms | /Backtrack/sudoku.py | 1,496 | 4 | 4 | # -*- coding: UTF-8 -*-
# Sudoku
def isSafe(board, size, row, col, value):
if row < 0 or row >= size or col < 0 or col >= size:
return False
# check for all the columns for current row
for i in range(size):
if board[row][i] == value:
return False
# check for all the rows for current column
for j in ra... |
5dbd40b13544e5a586a7041351b953a7293f0dd3 | imvivek71/LearningPython | /PSIAADSByHemantJain/InheritingAbstractClassShapeMethod2.py | 377 | 3.890625 | 4 | import math
from AbstractClass import Shape
class Rectangle(Shape):
def __init__(self, w=1,l=1):
self.width=w
self.length=l
def setWidth(self, w):
self.width = w
def setWidth(self, l):
self.length = l
def area(self):
return self.length*self.width
def perim... |
f23af08147983b5ff2af8e4419137aeff95ae42d | RZaga09/practicepython | /9.py | 888 | 4.28125 | 4 | # Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
# (Hint: remember to use the user input lessons from the very first exercise)
# Extras:
# Keep the game going until the user types “exit”
# Ke... |
89df61d79f5f9c79ea141eb69e9566a27dc1496e | songjon93/Projects | /AI/Chess/Chess/MinimaxAI.py | 4,822 | 3.625 | 4 | import chess
from random import *
class MinimaxAI():
TURN = chess.WHITE
PIECE_SCORE = [0, 1, 3, 3, 5, 9]
def __init__(self, depth, is_active=False, is_silent=False):
self.depth = depth
self.max_util = 0
self.is_active = is_active
self.is_silent = is_silent
self.mi... |
3e0127974494e841a9f4038ca84a256ef6ce507b | MotownMystery/Exercises-for-Programmers-57-Challenges-Python | /ee33.py | 167 | 3.53125 | 4 | import random as r
Num = r.randint(1,4)
L = {1 : "Yes", 2 : "No", 3 : "Maybe", 4 : "Ask again later"}
Ans = L[Num]
Q = input("What is your question? ")
print(Ans)
|
397579299faeacce783471aa7c0c4ffb22f556fd | kllay/InterfaceTestFramework | /utils/GetTime.py | 562 | 3.578125 | 4 | #coding:utf-8
import datetime
import time
class GetTime:
#获取当前时间
def get_current_time(self):
cur_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#print(cur_time)
return cur_time
#秒转为毫秒
def delaytime(self,times):
if times==None:
return
if i... |
3203603a7c64b2919e7f93b57ece4f9d97368eeb | lcnzg/mc920 | /trabalho-4/decodificar.py | 1,213 | 3.5 | 4 | #!/usr/bin/python3
from sys import argv
import cv2
def _args():
if len(argv) != 4:
print("Usage: python3 decodificar.py image-input bit-plane text-output")
exit(1)
bit_plane = int(argv[2])
if bit_plane not in range(0, 3):
print("Bit plane value must be 0, 1 or 2")
exit(1)... |
d707aa31000aadf9a5631ac10fe828673be3c752 | centralpark/LeetCode | /37_Sudoku_Solver.py | 1,905 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 13:54:04 2015
@author: HSH
"""
class Solution(object):
def isValid(self, board, irow, icol):
val = board[irow][icol]
# check row & col
for i in range(9):
if board[irow][i] == val and i != icol:
return False
... |
33dff651ff518aaa46a56049953486d5842daf0e | loc-dev/CursoEmVideo-Python | /Fase11/Desafios/Desafio_009.py | 848 | 4.34375 | 4 | # Fase 09 - Utilizando módulos
# Desafio 009
# Um professor quer sortear um dos seus quatro alunos
# para apagar o quadro. Faça um programa que ajude
# ele, lendo o nome deles e escrevendo o nome do escolhido.
print('$' + '-' * 20 + '$')
print('$ DESAFIO 009' + ' ' * 6 + '$')
print('$' + '-' * 20 + '$')
print('')... |
5dd75f62bb06dd5be24a9359113f9e6aa04e8472 | dbychkar/python_lessons | /python_coursera/4_week/58_Сократите дробь.py | 711 | 3.953125 | 4 | """
Даны два натуральных числа n и m.
Сократите дробь (n / m), то есть
выведите два других числа p и q
таких, что (n / m) = (p / q) и дробь
(p / q) — несократимая.
Решение оформите в виде функции
ReduceFraction(n, m), получающая
значения n и m и возвращающей
кортеж из двух чисел (return p, q).
"""
def gcd(n, m):
... |
589273711b61f34f0a5759eae4f371d7d352937f | qingxi2020/PythonLiaoXueFeng | /20-Decorator.py | 2,698 | 3.890625 | 4 |
'''
假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
'''
#因为它是一个decorator,所以接受一个函数作为参数,并返回一个函数。
def log(func):
def wrapper(*args, **kw):
print('现在在调用 %s():' % func.__name__)
# 从下面这一步可以看出func是一个函数,否则不可能有输入参数
return func(*args, **kw)
# 一个装饰器的返回值是一个函数
return wrapper
... |
41310e7d2cb40d3fbc1c5a8ae59ba0be7e08b34a | pixelblacksmith/megacode | /polynomial.py | 1,888 | 3.828125 | 4 | def eval(x, poly):
'''Evaluate at x the polynomial with coefficients given in poly.
The value p(x) is returned.'''
sum = 0
while 1:
sum = sum + poly[0] # Add the next coef.
poly = poly[1:] # Done with that one.
if not poly: break # If no more, done entirely.
... |
096bdc412d4ad01bac49e8fad891195918141dc0 | jesliwang/ProjectEuler | /Package/1-50/21/main.py | 625 | 3.5 | 4 | import os, sys
dict = {}
def sumDivisor(num):
sum = 0
index = 1
while index * index <= num:
if num % index == 0:
sum += index
if num / index != index:
sum += num / index
#print index, num/index
index += 1
return sum - num
result... |
4d3f46722416e20e76f32c2af4df304a89fad5f0 | saliedugit/DeepLearning-for-cv-starter | /pyimagesearch/nn/neuralnetwork.py | 5,532 | 3.5 | 4 | import numpy as np
class NeuralNetwork:
def __init__(self, layers, alpha=0.1):
self.W = [] # weights
# eg: if [2,2,1]=> 2 input nodes, 2 hidden, 1 output
self.layers = layers
self.alpha = alpha # learning rate
# initializing weight matrix to connect every node in curent... |
92aec1cad09981aed8e6eff4ffbc7d6aae1289ba | LBMercado/Contiki-APC-Sensor-Mote | /MQTT-Server/sensor_aggregator.py | 1,875 | 3.5 | 4 | from typing import List, Dict
# This class expects normalized sensors_data fields
class SensorAggregator:
def __init__(self, sensors_data: List[Dict], tolerance: float = 0.001):
self.sensors_data = sensors_data
self.average_sensor_data = {}
self.tolerance = tolerance
def aggregate(sel... |
7fea1579ebb3db8ed38ea76a70f48dc2ecaec04b | gshakya/dynamicProgramming | /05_bestSum_tab.py | 543 | 3.703125 | 4 | def howSum(targetSum :int , numbers: [int]):
table = [None]*(targetSum+1)
table[0] = []
for i in range(targetSum+1):
if(table[i] != None):
for num in numbers:
if ((i+num)<=targetSum):
numCol = [num]+table[i]
if(table[i+num] == None or len(numCol)<len(table[i+num])):
... |
cbafa5ce2d87c08c5d1bef3918fdd5cecda4c573 | EoJin-Kim/CodingTest | /구현/3진법 뒤집기.py | 259 | 3.625 | 4 |
def solution(n):
answer = ''
result=0
while n>0:
answer+=str(n%3)
n=n//3
answer=answer[::-1]
for i in range(len(answer)):
result+=int(answer[i])*(3**i)
return result
print(solution(45))
print(solution(125)) |
e96ece5c261f1d75e7a8d48ad6c31620247ddd4a | supriyorudraskhnaskar/IBM-Python | /Grocery.py | 10,257 | 3.734375 | 4 | Finalcart= []
Finalquantity= []
Finalamount= []
Product = ["1: Shampoo", "2: Toothpaste", "3: Soap"]
CategoryShampoo = {"1: Loreal": 65, "2: Pantene": 60, "3: Head & Shoulder": 75}
CategoryToothpaste = {"1: Colgate": 45, "2: OralB": 75, "3: Close Up": 70}
CategorySoap = {"1: Dove": 25, "2: Pears": 20, "3: Nivea":... |
25d25c7647864d136d0e68863c2158da2f317792 | JonathanDegardin/Python | /Exo 32.py | 202 | 3.65625 | 4 | import itertools
listNombre = [1,2,3,4]
permutations = itertools.permutations(listNombre)
allList = list(permutations)
print ("Voici toutes les possibilités de listes issu de permutation", allList) |
8cce761dbfb64e3b11a07ea61c27dac14148c05a | arifkhan1990/Codeforces-accepted-solution | /A/C++/58/5A.py | 69 | 3.5625 | 4 | import re
print('YES' if re.search('h.*e.*l.*l.*o',input())else'NO')
|
44f5b239a22be7c0fa9770283c2131aeb6356bcf | mrillusi0n/compete | /char_par.py | 210 | 3.9375 | 4 | def digit_prop(symbol):
symbol = ord(symbol)
if not ((symbol >= ord('0')) and (symbol <= ord('9'))):
return 'not a digit'
symbol = symbol - '0'
return 'odd' if symbol & 1 else 'even'
|
e96ac060285cd68c8177c8da4bad7ddbbad37f58 | gravypod/restful_example | /restful_example/models.py | 937 | 3.625 | 4 | from dataclasses import dataclass
from typing import Optional
class Thing:
id: Optional[str]
name: str
size: int
def __init__(self, thing_id: Optional[str], name: str, size: int):
self.id = thing_id
self.name = name
self.size = size
def __eq__(self, other):
if isi... |
87d34c777f43a0f9176481836848c875294051b4 | Song367/machine_learing | /特征工程/特征预处理.py | 1,856 | 3.5 | 4 | #特征预处理
#解释:将特征值数据转换成机器容易识别的数据 例如0-1
#1.归一化
#计算方式:
#x'=(x-min)/(max-min) x''=x'*(mx-mi)+mi
#数据解释
#x是当前数据 也就是特征值中需要计算的当前数据 min,max是特征值中最小值和最大值 mx,mi是你选取的范围最大值和最小值。默认为1和0
#影响
#容易受到最大值和最小值的影响
#2.标准化
#是将数据转换为均值为0,标准差为1范围内
#计算公式:
#x'=(x-mean)/std
#数据解释
#x当前值 mean是一列平均值 std标准差
#标准化比这个更不容易受到影响
#适合大数据场景
from sklearn.datas... |
938ceceaa47ac97c7a1219dd07729eb3ab267af9 | Fundamental-Basic/Fundamental-Python | /if_else.py | 1,497 | 3.984375 | 4 | #CONDITIONS AND IF STATEMENTS
a = 10
b = 20
if b > a:
print("b is greater than a")
#INDENTATION
c = 30
d = 40
if d > c:
print("d is greater than c") # ada indentation
#ELIF
e = 30
f = 30
if e > f:
print("e is greater than f")
elif e == f:
print("e and f are equal")
#ELSE
g = 50
h = 40
if h > g:
print... |
0d237761ab649fea67c6d86a236aa9707cf47657 | ggorlen/euler | /p022.py | 912 | 4.03125 | 4 | """
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For exam... |
292d75e67b0fd08a02859a1c1160f63ac219e603 | zhangxianyou33/python_demo | /hunjia_16/day06_0819/teshu_fangfa/huoqu_zilei_shilihua.py | 405 | 3.953125 | 4 | # 子类获取父类的实例化
class Parent:
def __init__(self):
print("parent的初始化init")
def __init_subclass__(cls, **kwargs):
print("父类parent_subclass:", cls)
print("父类parent_subclass:", kwargs)
class Sub(Parent, url="www.baidu.com", title="百度"):
def __init__(self):
print("子类sub的init")
if ... |
3756da24d7683169e71f4fe8eb2159d8890778a3 | Nikson88/pythonEdu | /lesson5.py | 644 | 4.375 | 4 | print(2 + 3) # 5
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 2) # 5.00.30000000000000004 Результатом деления в 3 Python ,будет всегда дробное число!
print(7 % 2) # 1 Остаток от деления
print(9 // 2) # 4 Деление без остатка
print(3**3) # 27 Возведение в степень
print(25**0.5) # 5.0 Корень числа с помощью возведения... |
35686d24f6461204e488985d672b19b7a808ffd9 | thomasdeanwhite/pythonteaching | /training_plot.py | 821 | 3.546875 | 4 | import csv
import re
def read_csv(filename, headers=True, heads=[]):
with open(filename) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
data = {}
for row in csv_reader:
# construct a table of headers
if headers:
headers = False
... |
f129c874603ca06e636701251e8753e5c3900613 | Pauloa90/Python | /ex042.py | 581 | 4 | 4 | l1 = float(input('Digite o valor de um dos lados do triangulo: '))
l2 = float(input('Digite o valor de um dos lados do triangulo: '))
l3 = float(input('Digite o valor de um dos lados do triangulo: '))
# Conferindo possibilidade de ser triangulo
if l1 < l2 + l3 and l2 < l1 + l3 and l3 < l1 + l2:
# conferindo equila... |
957d07ff3116a8437cc9453c3d24a1f6c33c449a | LayaFlo/PythonProgramming | /PythonProgramming/2.2.CountingWithVariables.py | 132 | 3.5 | 4 | num1 = 1000
num2 = 24
calc = num1 + num2 + 15
result = calc * calc
print("The final results of the calculation was: ", result)
|
45d5c7dabcd6cbe8e495d4be0fb55ca8dabdf548 | Sumsan38/learning-algorithm | /Seah-An/programmers/hash/programmers_hash_02.py | 386 | 3.71875 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42577
def solution(phone_book):
answer = True
dict ={}
for cell_num in phone_book:
dict[cell_num] = 1
for cell_num in phone_book:
test=""
for number in cell_num:
test += number
if test in dict and tes... |
862e37a538426dea447cdf2dccacbf7ba7f2aa65 | Mbyrne28/46_Python_Exercises | /q11.py | 611 | 4 | 4 | # Define a function generate_n_chars() that takes an integer n and a character c
# and returns a string, n characters long, consisting only of c:s.
# For example, generate_n_chars(5,"x") should return the string "xxxxx".
import unittest
def generate_n_chars(n, c):
result = ""
while n>0:
result += c
n -=1
re... |
5928c9dbd29fb24fbb2d8b0ba0cc3156f98a302d | yaoyc/python_project | /list_tuple_dict.py | 2,501 | 3.71875 | 4 | #coding:utf-8
##########################################################################
### List-Tuple-Dict convert ###
##########################################################################
init_List = ['a', 'b', 'c', 1, 2, 3 ]
init_Tuple = ('one', 'two', 'three', '4', '5', '6')
init_Dict = {
'x': 'bj',
'y': 'cn'... |
ce68e924d791f5a823222356a5589b17e405138d | IceFree2014/python_study | /03_functions_Modules/functions.py | 969 | 4.5 | 4 | #!/usr/bin/env python3
# encoding:utf-8
# In addition to using pre-defined functions,
# you can create your own functions by using the "def" statement
# The code block within every function starts with a colon(:) and is indented.
# my_func() // You must define functions before they are called.
def my_func():
print(... |
31ac95a3da7f13edaba83d18b64e290c46797193 | wangleixin666/Zhunbei | /刷题/Coding/DPofLongsunqueue.py | 1,293 | 3.53125 | 4 | # coding:utf-8
# 采用动态规划DP算法解决
# 1、最长公共子串的问题
# 2、最长公共子序列
"""动态规划仅适用于子问题是离散的情况,且不依赖于其他子问题时,独立且离散才可以"""
def longsubqueue(a, b):
# 求两个字符串相同的位数,不过时间复杂度也很高
cell = [[0 for col in range(len(a))] for row in range(len(b))]
for i in range(0, len(a)):
for j in range(0, len(b)):
if a[i] == b[j]:
... |
5e5f361fa57de2300af8a4e44c4dda6531cdb6ae | artexercise/CaptureTheFlagRoguelike | /ctf_Floor.py | 1,057 | 3.875 | 4 | __author__ = "jjeskiewicz"
class ctfFloor():
def __init__(self):
self.uid = "" # track the Floor
self.floor = "" # Address
self.roomA = "" # Room Floor-A
self.roomB = "" # Room Floor-B
self.roomC = "" # Room Floor-C
self.roomD = "" # Room Floor-D
self.roomE = "" # Room Floor-E
self.roomF... |
e43813da9f93bcd33f20405e4355c42c3739bcf1 | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_12_debugging/validated_user_base.py | 3,360 | 3.90625 | 4 | """
Validated user base - write script that takes email,
password, phone number and postal code, validates these
fields and if validation passes, saves it to a file as CSV
with email considered as unique field. If a record with the
same email is already in the file, the old record should be
altered by new one. Use vali... |
6de465e483fd53c61907be2ebd61786e1bce13eb | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc007/B/4963557.py | 161 | 3.546875 | 4 | import sys
s = input()
if s == 'a':
print(-1)
sys.exit()
if s[0] != 'a':
# print(chr(ord(s[0])-1))
print('a')
sys.exit()
print(s[:1]) |
f5cbcbf3d578051d468d9a6f2b1048eb9c2927ea | GodamSwapna/list-Question | /logicalqs1.py | 64 | 3.53125 | 4 | a=input("enter any set of character: ")
for x in a:
print(x) |
521ab61bfcbfbf04fd1da1297772e211a4af90db | Watotacho/python-classes-and-object | /pyquiz/python_test.py | 1,075 | 3.9375 | 4 | x=[100,110,120,130,140,150]
for b in x:print(b*5)
#2
def divisible_by_three(n):
for number in range(1,n):
if number%3==0:
print(number)
divisible_by_three(16)
#3
x = [[1,2],[3,4],[5,6]]
new_list = []
for lists in x:
for numbers in lists:
new_list.append(numbers)
print(new_list)
... |
6b268cecf1234713d3dd3e425a01efdc842045bf | daniel-reich/ubiquitous-fiesta | /GPodAAMFqz9sLWmAy_3.py | 136 | 3.546875 | 4 |
def one_odd_one_even(n):
b = str(n)
return int(b[0]) % 2 == 0 and int(b[1]) % 2 == 1 or int(b[0]) % 2 == 1 and int(b[1]) % 2 == 0
|
5f4851d8da0a14d1fd420dc9717d87d170c50aec | timothyha/project-euler | /0041_0050/problem_0047.py | 2,516 | 3.53125 | 4 | # https://projecteuler.net/problem=47
# The first two consecutive numbers to have two distinct prime factors are: 14 = 2 x 7 and 15 = 3 x 5
# The first three consecutive numbers to have three distinct prime factors are:
# 644 = 2^2 x 7 x 23, 645 = 3 x 5 x 43, 646 = 2 x 17 x 19.
# Find the first four consecutive integer... |
96b9e3177968604401731c80d5d0e19e7a5eca02 | jersson/mit-intro-cs-python | /week-01/02-core-elements/ex-04-while/while3.py | 101 | 3.671875 | 4 | end = 6
total = 0
counter = 0
while counter <= end:
total += counter
counter +=1
print(total) |
8193bc7a9b8af272fb72ced4165b48df21e6bdfe | shalemppl/PythunTuts | /Top5.py | 840 | 3.96875 | 4 | #Finding the most common word in a file (from Dict.py):
fname = input('Enter file name: ')
if fname == '' : fname='clown.txt'
fhandle = open(fname)
di = {}
for line in fhandle:
line = line.rstrip()
wds = line.split()
for w in wds:
di[w] = di.get(w,0) + 1
fhandle.close()
print(di,'\n')
#New code, ... |
be767442c760cc1f06ec3ba968338eaccc7efcf0 | wenhaoliang/leetcode | /newcoder/排序/两数之和.py | 1,159 | 3.59375 | 4 | """
两数之和
https://www.nowcoder.com/questionTerminal/2025b57a0f4b464eb85a63fc617ab5b1
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
示例1 输入 [2, 7, 11, 15],9 输出 [0,1]
"""
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
... |
45a8fba145e84ad1dfc50622d19a1e0df0cb8145 | lalobaez120304/actividad-1-y-2 | /listas.py | 183 | 3.90625 | 4 | # ejercicio 1 eliminar los elementos repetidos de una lista
lista = [1, 2, 3, "alejandro",2,2,1,"alejandro",3]
conjunto = set(lista)
lista = list(conjunto)
print(lista)
|
3042e46df7f99756da6fbcced2452152c6b9b999 | AdityaSP/ora-aug5-python | /04-controlstructures.py | 1,712 | 3.96875 | 4 | Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a = 100
>>> a= 10
>>> if a < 10:
print("Single Digit")
>>> a < 10
False
>>> if a < 10:
print("Single Digit")
else:
print("May ... |
739582801a8cc99a8beb254f31a3bbcff6109e75 | devdiogofelipe/Introduction-to-python | /Módulo 2/Module 2 Code Files/square_exercise.py | 77 | 3.5625 | 4 | def square(x):
y = x * x
return y
result = square(10)
print(result)
|
5a0f69a3f2a6632bb42efd8591cd0301fb02fdf9 | jiez1812/Python_Crash_Course | /CH7_User_Input_And_While_Loops/7-1_Rental_Car.py | 140 | 3.59375 | 4 | car = input("いらっしゃいませ, what kind of car you would like? \nAnswer: ")
print("Let me see if I can find you a {0}".format(car)) |
024d31fa85e21b6de1661fc410a9502b5bd88c28 | watchirawit/ProblemSolving | /Lecture_3/use_times.py | 3,177 | 3.65625 | 4 | import timeit
def reverse_slicing(s):
return s[::-1]
def reverse_for_loop(s):
sl = ''
for c in s:
sl = c + sl
return sl
def reverse_while_loop(s):
sl = ''
length = len(s) - 1
while length >= 0:
sl = sl + s[length]
length -= 1
return sl
def reverse_str_join(s):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.