blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
22fefd7fa371833a153e85ab999ed9ede6f54978 | chenbiao123/python | /project/project1/authentication.py | 598 | 3.625 | 4 | #!/usr/bin/env python
"""this model provides function for authentication users"""
def login(username, password):
try:
user_file = open('/etc/users.txt')
user_buf = user_file.read()
users = [line.split("|") for line in users_buf.split("\n")]
if[username,password] in users:
... |
d1fdd9fb1aefa4f2926492baf1a09f38f7133ce4 | TERADA-DANTE/algorithm | /python/acmicpc/solved/_11653.py | 243 | 3.546875 | 4 | n = int(input())
def solution(n):
answer = []
i = 2
while n != 1:
if not n % i:
answer.append(i)
n /= i
else:
i += 1
return '\n'.join(map(str, answer))
print(solution(n))
|
31b62d01b5fdbcfb93e6d5b9b35aef329d49a5fe | swiffo/Text-Mimicry | /Trie.py | 5,629 | 4.21875 | 4 | import random
class Trie:
"""A light-weight trie (or prefix tree)."""
def __init__(self):
"""Initialise Trie()."""
# The following lists must have the same lengths at all times. The elements are linked by index across
# the lists. E.g., if _letters[2] == 'k', we find in _children[2] th... |
bcc735b67c85a8d5b9be1345b55c76ecef345a10 | Jiss-Joss-42/PYTHON | /CYC1.3.9-sort-dict-asc.py | 116 | 3.828125 | 4 | prices={'banana':40,'apple':100,'guava':35}
print(sorted(prices.items()))
print(sorted(prices.items(),reverse=True)) |
4a226019f683aa634394df386eef1d34188f4915 | Abooow/BattleShips | /BattleShips/framework/ai.py | 5,926 | 3.703125 | 4 | ''' This module contains the AI class
'''
import random
import utils
import sprites
from framework.board import Board
from framework.ship import Ship
class AI():
''' Base class for all AI's
'''
def __init__(self):
self.board = Board()
Board.place_ships_randomly(self.board)
... |
ede5fc3847bd066f66fb0f65518e8f076c0f85fa | jemtca/CodingBat | /Python/List-2/shift_left.py | 431 | 4.0625 | 4 |
# return an array that is "left shifted" by one, so {6, 2, 5, 3} returns {2, 5, 3, 6}
# you may modify and return the given array, or return a new array
def shift_left(nums):
new_list = []
if len(nums) > 0:
for x in range(len(nums) - 1):
new_list.append(nums[x+1])
new_list.append(n... |
6d841c02c394c0d1f210594d398ff013d3056393 | pahuja-gor/CodePath-Technical-Interview-Exercises | /Week 2 - Session 1/parse_address.py | 927 | 4.3125 | 4 | ## Given an address
test_1 = "123 Main St., City Anystate USA 12345"
test_2 = "456 Commerce St., Colorado USA 54321"
# Print the street number and name on one line
# the city and state on the next line
# and the zip on the last line
"""
123 Main St.
Anystate, USA
12345
"""
# by the way this is called a "multiline ... |
5b4bff730a148ff8541ac79b4e17f425a6cde9a7 | Dinzine/python_projects | /convert_string_list/average_words.py | 1,213 | 3.921875 | 4 | # Calculating the average number of words per sentence in a paragraph.
input = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit nisl quam, eu auctor elit fermentum eu. Fusce faucibus ipsum erat, a semper ante pretium non. Proin blandit at diam eget tincidunt. Nunc efficitur nunc at nisi auctor... |
65d74406a13447bb8b084b5cb039aca2f45c8fd2 | adihipo/Python-thingz | /classesAndConstructor/dog.py | 200 | 3.640625 | 4 | class Dog:
def __init__(self, isMale, isFat):
self.isMale = isMale
self.isFat = isFat
def display(self):
print("Is your dog a male? %s \nAnd is it fat? %s \n"%(self.isMale,self.isFat)) |
ef3dca2dec55bcbe92fd23bebb79fbac32edbffd | Shahrein/Python-Training-Projects | /Factoral Function.py | 262 | 4.09375 | 4 | def factorial_function(n):
if n < 0:
return None
if n < 2:
return 1
product = 1
for i in range(2, n + 1):
product *= i
return product
for n in range(1, 6): # testing
print(n, factorial_function(n)) |
79446fcf6250705fbb739acc79e18d75adb53fa3 | Luolingwei/LeetCode | /DepthFirstSearch/Q1088_Confusing Number II.py | 578 | 3.625 | 4 |
# 思路: dfs搜索,每次加一位valid number,track它的rotation,比较n和rn是否相等
class Solution:
def confusingNumberII(self, N):
valid=[0,1,6,8,9]
flip={0:0,1:1,6:9,8:8,9:6}
self.ans=0
def dfs(n,rn,digit):
if n!=rn:
self.ans+=1
for i in valid:
if n==... |
a8c136f535405989c1194637dc3aaa3184d99d18 | PrangeGabriel/python-exercises | /ex029.py | 245 | 3.71875 | 4 |
vel = float(input('Qual sua velocidade em km/h?'))
if vel > 80:
print('''parabens! voce foi multado por excesso de velocidade!
A multa irá custar {} reais'''.format((vel - 80)*7))
else:
print('voce não foi multado :(') |
6626672d6765009f70b6376ac65201ccb58a7539 | Sahil94161/python- | /pro.py | 277 | 3.640625 | 4 | import random
cpu=random.randint(1,100)
player= int(input("Enetr a number b/w 1-100:-"))
while player!=cpu:
if player>cpu:
print("Too high")
else:
print(" Too low")
player = int(input("Enetr a number b/w 1-100:-"))
else:
print("Well done")
|
4572ceb52080514bd18b150bdad201ea78052395 | ViktoriaFrantalova/basic-python | /7_ChybyTest/7.2_ZoznamCisel.py | 736 | 3.859375 | 4 | # Zoznam čísel
# Napíšte definíciu funkcie cisla, ktorá prijíma reťazec. Reťazec rozdeľte podľa ";" a prvky, ktoré nemožno previesť na číslo, ignorujte. Návratovú hodnotou funkcie bude zoznam čísel (float).
# Vaša funkcia bude volaná takto:
# retezec = input()
# print(cisla(retazec))
# Sample Input:
# 8;1;2.2;_;5.3... |
2349161e91907b0c8a718a97e9cfbb44f29f3c79 | ElykelwinCosta/my_uri_programs | /python/1012 - Área/1012.py | 443 | 3.640625 | 4 | linhaLida = input()
lista = linhaLida.split()
A = float(lista[0])
B = float(lista[1])
C = float(lista[2])
areaTriangulo = A * C / 2
areaCirculo = 3.14159 * C * C
areaTrapezio = (A + B) * C / 2
areaQuadrado = B * B
areaRetangulo = A * B
print("TRIANGULO: %.3F" %areaTriangulo)
print("CIRCULO: %.3F" %areaCircul... |
2e5e5ec4667b6ce2113651e68683dace68790b2f | jeffpignataro/Tin-Man | /cipher.py | 824 | 3.59375 | 4 | import sys
def decryptTinMan(numbers):
return charToNum(numbers)
def charToNum(number):
return chr(int(number) + 96)
# 505091 02411030 02108002 9121515160 5021209021211270 508002 815160 9190 0291819060 508002
# The first one is for the gullible fools that cant see
decryptedText = ""
for i in sys.... |
83f4796b0cfe44f79641ab5b9cf0ef40aa30ad5b | Rainlv/LearnCodeRepo | /Pycode/Crawler_L/filetype/csv/csv00_read.py | 851 | 4.03125 | 4 | import csv
# 通过迭代器下标获取
def read_csv():
with open(r'Crawler_L\csv\test.csv','r') as r:
reader = csv.reader(r) # reader是个迭代器
next(reader) # 跳过第一行(即标题),从第二行开始遍历
for x in reader:
date = x[0]
number = x[1]
name = x[2]
print({
'dat... |
4abc590229c28d449e32981b63902b9a2faea7e4 | Felixwbh/leetcode | /哈希/#1 List.py | 1,090 | 3.796875 | 4 | #2021.2.23
#给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
#你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
#你可以按任意顺序返回答案。
#示例 1:
#输入:nums = [2,7,11,15], target = 9
#输出:[0,1]
#解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) ->... |
038402ef81a92190ae443096050ca0cd2ab5738d | YuweiHuang/Basic-Algorithms | /leetcode/tree/144.二叉树的前序遍历.py | 732 | 3.75 | 4 | #
# @lc app=leetcode.cn id=144 lang=python3
#
# [144] 二叉树的前序遍历
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __traverse(self, root, data_li... |
54bc3e482330ba82959ffe609050673906844825 | lindsaymarkward/CP1404-2016-2 | /dict_demo.py | 482 | 3.9375 | 4 | __author__ = 'Lindsay Ward'
ages_dict = {"Bill": 21, "Jane": 34, "Jack": 56}
# print(ages_dict["Bill"])
# print(ages_dict.get("Bob", -1))
# ages_dict['Bob'] = ages_dict.get("Bob", 0) + 1
# print(ages_dict.get("Bob"))
# print(ages_dict)
# name = input("Name: ")
# age = int(input("Age: "))
#
# ages_dict[name] = age
# ... |
ee68694df814b01ec5cff60d7999cbd2d09cc252 | Arcob/HuaweiAutomatedTesting | /Classes/DictRange.py | 1,193 | 3.59375 | 4 | from Classes import Range
import MutateTool
class DictRange(Range.Range): # 固定范围参数 只有一个值(一般为字符串)
def __init__(self, value_list):
self.value_list = value_list # 储存字典的list
def mutate_from_value(self, value, mutate_strategy=0): # 如果突变策略在可处理之外就返回空值
if mutate_strategy == MutateTool.MutateType.... |
2f26f3d5039e5ff4221121a01036b27b02c5f4ab | jrluecke95/python-project | /hero.py | 1,221 | 3.5625 | 4 | from character import Character
class Hero(Character):
def __init__(self, items=[], name="", health=0, power=0, armor=0, evasion=0, ability=0, coins=0):
super().__init__(name, health, power, armor, evasion, ability)
self.items = [["healing potion", 5, 1], ["poison potion", -5, 0], ["bow and arrow",... |
5e14d74c22da2988d91d2147b479d3786ba45925 | FrankCasanova/Python | /FICHEROS/442.py | 208 | 3.875 | 4 |
file_name = input('File name: ')
with open(file_name, 'r') as file:
count = 0
character = file.read(1)
while character != '':
count += 1
character = file.read(1)
print(count)
|
f361354f412f998d8c246d2957b0e5a7e9514457 | Aidan-Pettit/Code-Writer | /in_out/str-str.py | 426 | 3.546875 | 4 | from re import search, sub
def str_str(data):
code_list = []
pair = []
unincluded = []
conditions = []
if data[0] == data[1]:
code_list.append('output = input')
return code_list
for _pair in data:
if _pair[0][-1] == 1:
pass
for _pair in data:
... |
693118d8d5b966a4ac32c60adfd349afb0d05529 | sunshinexf3133/Python_BronzeIII | /hanjia/.svn/pristine/b3/b3f71c6dcb6f1d126370536c55614da81514ddfc.svn-base | 796 | 4.3125 | 4 | #coding:utf-8
#使用列表解析进行筛选
###下面函数使用列表解析删除字符串中的所有元音
#[c for c in s if c.lower() not in 'aeiou'],这是一个筛选型列表解析,
#它以每次一个字符的方式扫描s,将每个字符转换为小写,再检查它是不是元音。
#如果是元音,则不将其加入最终的列表,否则将其加入最终列表
#
#该列表解析的结果是一个字符串列表,因此我们使用join将所有字符串拼接成一个,
#再返回这个字符串。
#eatvowels.py
def eat_vowels(s) :
"""Removes the vowels from s."""
return ''.join... |
9e60bd69d7058b6d69400048f82c59eb7d01c2d2 | haseenarahmath/Retina | /demos/basics/bold.py | 1,178 | 3.671875 | 4 | """
A demo of the Layer2D.bold()/Layer3D.bold() function.
"""
import matplotlib.pyplot as plt
import retina.core.axes
import numpy as np
import time
plt.ion()
fig = plt.figure(figsize=(20, 20))
ax = plt.subplot('111', projection='Fovea2D')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Boldface Plot Demo')
sinc = ax.add_... |
8df494e1a058339ae664cf2569f947e2b6ecb507 | gistable/gistable | /all-gists/7618531/snippet.py | 196 | 3.75 | 4 | from collections import Iterable
def flatten(iterable):
for item in iterable:
if isinstance(item, Iterable):
yield from flatten(item)
else:
yield item
|
d0616bdfd18d0a1a91e7a51da474723e4790476d | 1string2boolthem/CST-205 | /mod6lab14.py | 2,299 | 4.1875 | 4 | #Sevren Gail
#Christopher Rendall
#Team 3 - Lab 14
import re #For regular expressions, to replace an undetermined number of spaces in eggs.txt.
#wordCount counts the number of total words in wordDict and returns the result.
def wordCount(wordDict):
count = 0
for key in wordDict:
count += wordDict[key]
return... |
9935c72b0e17a89e1c59fcce87ac39f448e84b8e | hazrmard/Agents | /src/agents/helpers/spaces.py | 11,889 | 4.1875 | 4 | """
Defines functions that convert space variables to and from tuples of floats.
Defines functions to analyze spaces like size of tuple, size of space,
continuous or discrete etc.
"""
from collections import OrderedDict
from itertools import product, zip_longest
from typing import Callable, Iterable, List, Tuple, Unio... |
8e55b2916f1c23233e710fd2b146d2c62b8ac746 | aimdarx/data-structures-and-algorithms | /solutions/_Patterns for Coding Questions/_Other/Parenthesis/longest_balanced_parenthesis.py | 4,072 | 3.703125 | 4 | """
Longest Valid Parentheses:
Given a string containing just the characters '(' and ')',
find the length of the longest valid (well-formed) parentheses substring.
https://leetcode.com/problems/longest-valid-parentheses/
https://paulonteri.notion.site/Parenthesis-b2a79fe0baaf47459a53183b2f99115c
"""
class Solutio... |
7c7b991c5d76f3a915ae5fc1d6f1c2e40235a4f2 | bMedarski/SoftUni | /Python/Fundamentals/Dictionaries and Functional Programming/02. Count Real Numbers.py | 278 | 3.625 | 4 | list_input = list(map(float, input().split(" ")))
items_count = {}
for item in list_input:
if item in items_count:
items_count[item] += 1
else:
items_count[item] = 1
for key in sorted(items_count.keys()):
print(f"{key} -> {items_count[key]} times") |
ab3c8f81a0158c0ddc5e48e66a7a06add225a905 | epson121/principles_of_computing | /cookie_clicker.py | 7,838 | 3.515625 | 4 | """
Cookie Clicker Simulator
"""
import simpleplot
# Used to increase the timeout, if necessary
import codeskulptor
import math
codeskulptor.set_timeout(20)
import poc_clicker_provided as provided
# Constants
SIM_TIME = 10000000000.0
class ClickerState:
"""
Simple class to keep track of the game state.
... |
93661ba2f6bba475f195e409125987868f5097ea | SooDevv/Algorithm_Training | /CS Dojo/if_else.py | 280 | 4.21875 | 4 | name = input("What's your name : ")
height_m = int(input("Write your height : "))
weight_kg = int(input("Write your weight : "))
bmi = weight_kg / (height_m ** 2)
if bmi < 25:
print("%s, you are not overweight" % name)
else:
print("WARNING %s, you are overweight" % name) |
4863817cfc0fa0acfd127acb965fbefbcc84c2b1 | deebika1/guvi | /codeketa/basis/give_two_number_N_and_K_if_K_is_persent_in_the_N_list_print_yes.py | 355 | 3.640625 | 4 | # program which is used to print yes if K is persent in the list
def function1(N,K):
l=list(map(int,input("").strip().split()))[:N]
for i in range(0,N):
count=0
if(K==l[i]):
count=count+1
return count
# get the value of N and K form the user
N,K=list(map(int,input("").split()))
res=function1(N,K)
if(res==1)... |
0d165e47659f509fad71cfdcd726c287ad555d33 | yjthay/Python | /Python for Data Analysis/PythonDryRun.py | 1,202 | 3.75 | 4 | letters = "a/b/c"
delimiter = "/"
jlist = letters.split("/")
#print jlist
#print len(jlist)
del jlist[len(jlist)-1]
#print jlist
jlist.append([4])
#print jlist
orig = jlist[:]
jlist.sort()
#print orig
#print jlist
#mbox-short.txt
emailfile = raw_input("Whats the file name? \n")
fhand = open(emailfile)
count =0
fo... |
a1adb38ba23296bbe303e997b2a0aeb16b394090 | Luckyaxah/leetcode-python | /二叉树_判断完全二叉树.py | 875 | 3.734375 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isCBT(head):
if not head:
return
from queue import Queue
q = Queue()
isMeet = False
q.put(head)
while not q.empty():
cur = q.get()
l = cur.left
... |
4f8f62b7bfd5d381756f4a99ba5cdaba9e145a01 | heyitshenrylin/ArduinoCostCalculator | /modules/csvIO.py | 3,945 | 3.84375 | 4 | # Authors: Eric Claerhout, Henry Lin
# Student IDs: 1532360, 1580649
# CMPUT 274 Fall 2018
#
# Final Project: Price Finder
###########
# Imports #
###########
from sys import exit
from csv import reader, DictReader, DictWriter
#############
# Functions #
#############
def getSupportedSites():
""" Get Supported S... |
055de7907d3ff7bbed2bf78395965126af5ce606 | alexmatros/codingbat-solutions | /python/string-2/cat_dog.py | 243 | 3.765625 | 4 | def cat_dog(str):
cat = 0
dog = 0
for i in range(len(str) - 2):
if str[i:i+3] == "dog":
dog += 1
elif str[i:i+3] == "cat":
cat += 1
else:
continue
if dog == cat:
return True
else:
return False |
d04bf6cf8400adbde17ea8a5330b3aad71bfac06 | Sonalsutar/assignments | /reversearray.py | 140 | 3.734375 | 4 | #Program to reverse the array
a=[11,22,33,44,55]
L=(len(a))
for i in range (int(L/2)):
n=a[i]
a[i]=a[L-i-1]
a[L-i-1]=n
print(a)
|
857ad05329cfd9323d4d6954e6f03b928b06899f | bfontaine/Katas | /KataPotter/KataPotter.py | 2,042 | 3.765625 | 4 | #! /usr/bin/python3.2
# Note :
# I don't think that this program is *really* working for
# books > 8, but I don't have more tests to test it
#
class TooManyBooksException(Exception):
def __init__(self,*args):
super(*args)
# returns the price with as big discount as
# possible. Format: list of books, e.g.... |
e9549c96c867696c13ceb49ede8d36fb7edbf4c4 | Fahad1192/programming-with-shazzal | /Class-2/palindrome.py | 479 | 3.5 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = ''.join(char for char in s if char.isalnum())
s = s.lower()
start = 0
end = len(s) - 1
start = 0
end = len(s) - 1
while... |
77e7f95efb1d5ab19077266f6596f5b97466afa0 | esethuraman/SearchEngine | /utils/StopWordsFormatter.py | 572 | 3.875 | 4 | ''' given stopwords file has every word in a new line which might have
newline characters and other noise. So, this utility cleans up all
and write all the stopwords in a single line separated by spaces
'''
from utils import properties
def regenerate_stop_words():
output_file = open(properties.formatted_s... |
aab0e62aad35b3c03d6e29e9dbd066f7b7ea89d9 | AlexNalev/DS | /BST.py | 2,631 | 4.125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
self.ask_elements()
@classmethod
def insert(cls, root, data):
"""
This method is a class method to create a... |
885a0cb8d39778eddd28c20d1e7193a77cf14d6b | marcos-evangelista/Projeto-validando-nota-no-python | /validando.py | 1,803 | 4.125 | 4 | #Esse codigo foi atualizado, pois o if foi trocado por while.
#Caso a nota seja maior que 10, irá informar que a nota foi digitada errada!
#Fará que o usuário, fique em um loop, até que digite a nota correta!!!
nome= str(input('Digite seu nome:'))
a = int (input('\n {nome} digite a nota do primeiro bimestre: '.format(n... |
cf8af6e2ac070b3298da5676b0ffeac62552dd49 | MihaiAnton/University | /Semester 4/Artificial Intelligence/Lab1/Sudoku/DFS/SudokuSolver.py | 1,684 | 3.890625 | 4 | from SudokuLogic.Table import Table
class SudokuSolver:
"""
Solves a valid sudoku grid using DFS(backtracking)
:param - the sudoku table
"""
def solveSudoku(self, table):
treeStack = [table] #the DFS stack
while len(treeStack) > 0: ... |
27da6e733371c8f82b8268d2a0d514b0a44b72a2 | shfjri/learn_from_home | /mechanical_energy.py | 3,142 | 3.953125 | 4 | author = 'shfjri'
def asks_help_again(): # function to asks user, need more help or exit
play = input('\nNeed more help? [y/n] ') # asks user, need more help or exit
if play.isalpha() == True: # if user input a letter
play = play.lower() # convert letter to lowercase
if play == 'y': # i... |
b8873226de4e7ffe1e3500c0ceb9aa35a3454897 | zhangquanliang/python | /学习/day1/强密码判断.py | 784 | 4 | 4 | # -*- coding: utf-8 -*-
def demo(L):
k = len(L)
if k >= 10:
if L.isalnum() and not L.isdigit() and not L.isalpha()and not L.isspace():
return print("是强密码")
else:
L = L.replace("!","")
L = L.replace("_","")
L = L.replace("#","")
L = L.... |
c736afedd997c47409388caee2f1a33e313be117 | abhisheksahnii/python_you_and_me | /simple_calculator.py | 769 | 4.28125 | 4 | #!/usr/bin/env python3
'''
Program make a simple calculator that can add, sub, mul and div using functions
'''
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
print("Select Operation.")
print("1. ADD")
print("2. SUBTRACT")
print("3. MU... |
f508f2adb8b67c02bd314fd95c57df8a16fa7a77 | BavoGoosens/TMI | /Position.py | 475 | 4.1875 | 4 | from math import sqrt
class Position(object):
"""A class used to represent Position"""
def __init__(self , x, y):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def distance(self, other):
return ((self.getX() - other.ge... |
3a50f6e196c1206bf3c913a207099e1121dc8571 | doctor-to-code/number | /r.py | 350 | 3.75 | 4 | a = input('請輸入數字下限')
b = input('請輸入數字上限')
a = int(a)
b = int(b)
import random
r = random. randint(a, b)
i = 0
while True:
i = i + 1
x = input('請輸入數字')
x = int(x)
if x == r:
print('you win')
break
elif x > r:
print('比答案大')
elif x < r:
print('比答案小')
print('已經猜第', i,'次') |
5c98ee140ab31db46bef905417ebeefbdc230573 | EasternBlaze/ppawar.github.io | /Spring2019/CSE101-S19/programs/Lecture5-Examples/find_max.py | 314 | 4.1875 | 4 | # This function finds and returns the maximum value in a list.
def find_max(nums):
maximum = nums[0]
for i in range(1, len(nums)):
if nums[i] > maximum:
maximum = nums[i]
return maximum
ages = [20, 16, 22, 30, 17, 24]
max_age = find_max(ages)
print('Maximum age: ' + str(max_age)) |
8bba3e5b01696ffe21f7a072962a666ece3dfefe | cnrmurphy/python-lessons | /notes/session_3/linked_list_solution.py | 1,086 | 4.15625 | 4 | class Node():
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data # returns 1
class Linked_List():
def __init__(self):
self.head = None
def append(self, data):
if not self.head:
self.head = Node(data)
return
current_node = ... |
8216d661d2cc71c36769b6f1041a2142af1a2220 | YAJINGE/StudyPython | /chapter_2/library.py | 973 | 3.6875 | 4 | book_list = ['坏蛋是怎样炼成的', '上门女婿', 'D调的华丽', 'java', '数据结构与算法']
for num in range(0, 50):
jud = input('借书or还书:')
# 借书
if jud == '借书':
print(book_list)
str_lend = input('请输入要借的书名:')
if str_lend in book_list:
print('图书馆有1本'+str_lend)
str_judge = input('是否要借出:是/否')
... |
522dce7d5f624aaa241fe4b51fb6709b338d4ab3 | Vasu-Eranki/Project_Euler | /Challenge65.py | 773 | 3.828125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import os
def convergence(n):
y = [1, 2]
k = 2
count =1
x=[2,3]
for i in range(2, n):
if(count%3==0):
y.append(2*k)
k+=1
count= 1
else:
y.append(1)
count... |
26059cd97175a43a6c583545daaa5f4e9aacc2d9 | junwoo77lee/Python_Algorithm | /fibonacci_sum_squares.py | 2,541 | 3.953125 | 4 | # Uses python3
import sys
import random
import time
# Problem description
# Input: n is an integer; 0 ≤ n ≤ 10**14
# Output: The last digit of F0^2 + F1^2 + ... + Fn^2
def fibonacci_sum_squares_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
... |
fa8b179cebc011a00a9fda1cbc9beb8a4bd3e3ce | letterbeezps/leetcode-algorithm | /leetcode/STR/1408.stringMatching/1408python3.py | 319 | 3.5625 | 4 | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
ans = []
for word in words:
for s in words:
if s == word:
continue
if word in s:
ans.append(word)
break
return ans |
dae1d1c8b93af26f277b407fa13e4dbd98e0df83 | gschen/sctu-ds-2020 | /1906101073-李闻达/3.31/test.py | 1,512 | 3.859375 | 4 | class Stack(object):
def __init__(self,limit = 10):
self.stack = []
self.limit = limit
def is_empty(self):
return len(self.stack) == 0
def push(self,data):
if len(self.stack) >= self.limit:
print('栈溢出')
else:
self.stack.append(data)
def pop... |
c4c48ddd2b0f2c5cc2686a85d58811582e7f6005 | SullyJHF/python-dev | /uni/numbers.py | 169 | 4 | 4 | a = int(input('Enter your first number: '))
b = int(input('Enter your second number: '))
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a // b)
|
274136af16f83d42c9249cbe767711d7d49f4185 | thedarkknight513v2/daohoangnam-codes | /C4E18 Sessions/Session_8/f-math-problem/freakingmath.py | 1,499 | 3.84375 | 4 | from random import *
def generate_quiz():
# Hint: Return [x, y, op, result]
x_variable = randint(1, 10)
y_variable = randint(1, 10)
operation_list = ["+" , "-" , "*", "/"]
operation_choice = choice(operation_list)
error_list = [-1, 1, 0]
error_choice = choice(error_list)
if operation_c... |
a20e95d2298516cba1cf0cf0401d85f6fe9b7ea1 | anildoferreira/CursoPython-PyCharm | /exercicios/aula20.py | 879 | 3.828125 | 4 | '''def linha():
print('-------------')
linha()
print('Curso em vídeo')
linha()
def título(msg):
print('-------------')
print(msg)
print('-------------')
título('Testando Função!')
título('Outra teste')
def soma(a, b):
print(f'A = {a} e B = {b}')
s = a + b
print(f'A soma de A + B = {s}'... |
2414859705c106dd053bb162f5e42089864611e7 | danocando/Axelrod | /axelrod/player.py | 2,154 | 3.59375 | 4 | import inspect
import random
C, D = 'C', 'D'
flip_dict = {C: D, D: C}
def update_histories(player1, player2, move1, move2):
"""Updates histories and cooperation / defections counts following play."""
# Update histories
player1.history.append(move1)
player2.history.append(move2)
# Update player co... |
f251558f1c5df765081f8d5f477a5b17c6b30ffb | pravallikachowdary/pravallika | /pg21.py | 443 | 4.34375 | 4 | # Python 3 Program to
# find nth term of
# Arithmetic progression
def Nth_of_AP(a, d, N) :
# using formula to find the
# Nth term t(n) = a(1) + (n-1)*d
return (a + (N - 1) * d)
# Driver code
a = 2 # starting number
d = 1 # Common difference
N = 5 # N th term to be find
# Display the output
print( "The ",... |
9e5fccbc4007cd46abf4471e6b07b82846f41ddc | szabgab/slides | /python/examples/multitasking/counter_with_locking.py | 595 | 3.59375 | 4 | import multitasking
import time
import threading
multitasking.set_max_threads(10)
counter = 0
locker = threading.Lock()
@multitasking.task
def count(n):
global counter
for _ in range(n):
locker.acquire()
counter += 1
locker.release()
if __name__ == "__main__":
start = time.ti... |
b7a8d6a4aa9c972a7cb653996c38e07b5ea4aa9b | RayGutt/python | /chapter_09_Classes/ex_9.3.py | 697 | 3.71875 | 4 | class User:
def __init__(self, first_name, last_name, username, email):
self.first_name = first_name
self.last_name = last_name
self.username = username
self.email = email
def describe_user(self):
print(f"Username: {self.username}")
print(f"Email: {self.email}")
print(f"Full name: {self.first_name} {se... |
319d4110bb8af0d3bd3ccc7f88908367e4c982fe | Herna7liela/New | /list7.py | 162 | 3.640625 | 4 | # What is an expression using the range function that yields a list of 10
# consecutive integers starting at 0?
for i in range(0,10,1):
print (i)
# DONE |
8e9b898f03f3a2183664aeeaa1e1bf11e7672f70 | Geodit/Homework | /task4_les3.py | 1,302 | 4.4375 | 4 | # 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить
# возведение числа x в степень y. Задание необходимо реализовать
# в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа
# в степень.
# Подсказка: поп... |
cde55aa19b77d10a74fab1856bcb521d8a39263b | ilieandrei98/labs | /python/solutii/stefan_caraiman/fill.py | 1,834 | 4.03125 | 4 | """
Implement paint fill function for a given matrix
"""
from __future__ import print_function
def matrix_print(rows, columns, image):
"""
Prints a matrix
:param rows: rows of the matrix
:param columns: cols of the matrix
:param image: the image/matrix
:return: a printed image/matrix
"""
... |
36b4a4747a53174c8854c5308445a025632e6840 | Jyotirm0y/kattis | /autori.py | 95 | 3.75 | 4 | line = input().split('-')
result = ""
for part in line:
result += part[0]
print(result) |
b6efe20ff22a0062cb4aebf580660916d5df7e6e | 4ions/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/1-last_digit.py | 456 | 3.984375 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
if number < 0:
_number = number * -1
tmp = (_number % 10) * -1
else:
_number = number
tmp = _number % 10
if tmp > 5:
print("Last digit of {} is {} and is greater than 5".format(number, tmp))
elif tmp == 0:
print("Last digit ... |
78419d1cdd5f7cb0a7ee0435f9f157c197ff2d70 | leguims/Project-Euler | /Problem0025.py | 1,102 | 4.1875 | 4 | Enonce = """
1000-digit Fibonacci number
Problem 25
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first... |
c8e676131ea65596bf41b860e2b094555465d28c | srini4547/cumulus | /cumulus/cumulus_ds/terminal_size.py | 2,442 | 3.5 | 4 | """ Functions for calculating the teminal size """
import os
import shlex
import struct
import platform
import subprocess
def get_terminal_size():
""" Get the current terminal size """
current_os = platform.system()
tuple_xy = None
if current_os == 'Windows':
tuple_xy = _get_terminal_size_wind... |
86111f06b3cde48dfbb3c54f111dd4126045351f | rtx34/Calentando-el-brazo | /Calentando el brazo pendiente.py | 8,492 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 3 10:09:41 2021
@author: jorge
"""
import numpy as np
import re
from math import prod
from math import sqrt
from collections import Counter
#=================================1================================
class Solution:
def solve(self, palabras):
... |
9bf8507a6f2e1e6b0974c89e30a56f3dc4e38bb9 | HBharathi/Python-Programming | /Pattern.py | 137 | 3.84375 | 4 | #to print F pattern type
numbers =[5,2,5,2,2]
for x in numbers:
out = ""
for con in range(x):
out += "x"
print(out)
|
a7e1176afb804719b2f7b1b7782dbb2a4c261e37 | dkljajo/Python-for-everybody---Coursera | /1. Programming 4 E/Assignment 5.2/Assignment_5_2.py | 948 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 17:51:48 2019
@author: dk
5.2 Write a program that repeatedly prompts a user for integer numbers
until the user enters 'done'.
Once 'done' is entered, print out the largest and smallest of the numbers.
If the user enters anything other than a valid numbe... |
7ed2e3dce6c283bd6bfa51fbf2554e0f0704ff22 | balder33/codingame | /venv/skynet_revolution_episode01.py | 3,659 | 3.65625 | 4 | from typing import (
List,
Optional,
Set,
Tuple,
)
def get_input_data() -> Tuple[List[List[int]], Set[int]]:
"""Возвращает существующие ссылки между узлами сети и номера узлов, являющихся выходными шлюзами.
Нумерация узлов начинается с нуля, перемещаться между узлами можно в обоих направлениях... |
06a24d1c35a833bbdc1e048c8f0956da1029f89b | franktea/acm | /uva.onlinejudge.org/uva 10878 - Decode the tape/10878.py | 469 | 3.609375 | 4 |
from sys import stdin
def solve(line):
for c in line:
if c == '_':
return
ascii = []
for c in line:
if (c == '|') or (c == '.'):
continue
if c == ' ':
ascii.append('0')
else:
ascii.append('1')
number = int(''.join... |
815407c9127f970c80a70d5f5bd1c431fbecc150 | Sasha2508/Python-Codes | /Others/bytelanc_coin_exchange.py | 1,702 | 3.890625 | 4 | '''
problem statement:
In Byteland they have a very strange monetary system. Each Bytelandian gold
coin has an integer number written on it. A coin n can be exchanged in a bank
into three coins: n/2, n/3 and n/4. But these numbers are all rounded down
(the banks have to make a profit).
You can also sell Bytelandian coi... |
fe682d5d0e549f7e3f1a90ff8f3ca3a54becd9ec | zmx0142857/dminor | /rational.py | 13,650 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""basic rational calculation"""
# 用 hashtable 保存整数因子, 加速有理数乘除?
__author__ = 'Clarence Zhuo'
from poly import Poly
class Rat(object):
"""
Doctest:
>>> r1 = Rat(1,2)
>>> r2 = Rat(2,4)
>>> r3 = Rat(0,1)
>>> r4 = Rat(0,3)
>>> r5 = Rat(-3)
... |
6eb86605ddcd87353650957bc8fa4c8349b517df | tsukasan3/Impractical_Python_Projects | /Chapter2/dictionary_cleanup_practice.py | 482 | 3.828125 | 4 | """リストにある一文字の単語はaかeでなければ削除する"""
word_list = ['stick', 'odd', 'b', 'g', 'a', 'e']
word_cleanup_list = []
permissible = ('a', 'e')
# 一文字の単語はaかeでなければ削除する
for word in word_list:
if len(word) > 1:
word_cleanup_list.append(word)
elif len(word) == 1 and word in permissible:
word_cleanup_list.append(... |
66d068bc1cb4a840ff65774d20a9b8bf81c94bd1 | tansuluu/DataAnalysis | /insertion2.py | 457 | 3.78125 | 4 | def sortingI(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while key<arr[j] and j>= 0:
arr[j+1]=arr[j]
j=j-1
arr[j+1]=key
return arr
print(sortingI([9,6,2,3,6]))
def insr(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
... |
51cfdd34bd47546b852a220fa829c51324cf256d | whisust/jellynote-backend | /api/validators.py | 993 | 3.59375 | 4 | from re import Pattern
from typing import Optional
def non_empty(field: str):
def _test_non_empty(value: str):
if value is None or len(value) == 0:
raise ValueError(field + " should not be empty")
else:
return value
return _test_non_empty
def non_all_empty(fields: li... |
55192b763594e1a84bb4bd9b8913ce1d16382a6b | Redpike/codewars | /Python/d026/d026.py | 1,027 | 3.640625 | 4 | class Plugboard(object):
pairs = []
def __init__(self, wires=None):
"""
wires: This is the mapping of pairs of characters
"""
if wires is None:
wires = ""
if len(set(wires)) != len(wires):
raise Exception("Should not have accepted a second definit... |
407f6cf7af7bfe4c153a1de40cd81cb066c93977 | sabinzero/various-py | /binari to decimal/main.py | 141 | 3.734375 | 4 | a = input("enter a binary number (e.g. 0b00110011): ")
print "decimal: %d" % a
print "hexadecimal: %x" % a
print "hexadecimal: %X" % a
|
36e5d3b0e401891ca62730cdb82ff7408884809e | simranjmodi/cracking-the-coding-interview-in-python | /chapter-04/exercise-4.5.1.py | 622 | 4 | 4 | """
4.5 Validate BST
Implement a function to check if a binary tree is a binary search tree
Solution 1: In Order Traversal (Assuming no duplicate elements)
"""
last_printed = None
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def check_BST... |
b734b6d198302abd85d9b6059c5b3f52f2f265c4 | liuqiangcl/liuqiang | /github/src/ex33.py | 583 | 4.125 | 4 | #-*- coding:utf-8-*-
'''
Created on 2014-3-6
@author: Hunk
'''
# i = 0
# numbers=[]
# #б
# while i<6:
# print "At the top i is %d " % i
# numbers.append(i)
# i+=1
# print "Numbers now:",numbers
# print "At the bottom i is %d" % i
# #бѭ
# print "The numbers:"
# for num in numbers:
# print num
# ... |
134b6c2511e16c53d5886c55d50f624c3695b594 | JeffreyAsuncion/CSPT15_DataStructuresAndAlgorithms3 | /SprintChallenge/uncover_spy.py | 2,153 | 3.953125 | 4 | """
In a city-state of n people, there is a rumor going around that one of the n people is a spy for the neighboring city-state.
The spy, if it exists:
Does not trust anyone else.
Is trusted by everyone else (he's good at his job).
Works alone; there are no other spies in the city-state.
You are given a list of pairs... |
dd8efc35b3e959c3ee5bc93834fb6e06e068b44b | anurag5398/DSA-Problems | /Heaps/KthSmallestElementMatrix.py | 1,243 | 3.625 | 4 | """
Given a sorted matrix of integers A of size N x M and an integer B.
Each of the rows and columns of matrix A are sorted in ascending order, find the Bth smallest element in the matrix.
NOTE: Return The Bth smallest element in the sorted order, not the Bth distinct element.
"""
#Incomplete
import heapq
class Maxheap... |
172dfe71b07dd48f8817859387c7d761b1e94421 | imn00133/PythonSeminar19 | /Users/Jade/convert_fahrenheit_celsius/convert_fahrenheit_celsius.py | 196 | 3.75 | 4 | # 입력
fahrenheit = float(input("변환할 화씨온도(℉)를 입력하십시오: "))
celsius = (fahrenheit - 32) * 5/9
# 출력
print("%.2f℉는 %.2f℃입니다." % (fahrenheit, celsius))
|
1bc93d957e2ea77cd97a52624cf255e85312b606 | hljjj/python_note | /3.2.1.string.py | 1,392 | 4.375 | 4 |
# 新建一个字符串
words = "hello,world"
# 长字符串
context = """
Never give up,
Never lose hope.
Always have faith,
It allows you to cope.
Trying times will pass,
As they always do.
Just have patience,
Your dreams will come true.
So put on a smile,
You'll live through your pain.
Know it will pass,
And strength you will gain
"""
... |
6261a0f25df405ad1dc4bae93dc8a6eb8e424791 | bizkanta/exam-python-2016-06-27 | /test_third.py | 755 | 3.71875 | 4 | import unittest
from third import count_letter_in_string
class TestCountLetters(unittest.TestCase):
def test_empty_string(self):
self.assertEqual(count_letter_in_string('', 'a'), (0))
def test_string_letter_in_it(self):
self.assertEqual(count_letter_in_string('apple', 'p'), (2))
def test... |
f3ce1b3def324707552acaf9f998489d4f299de8 | BrashFlea/CS3030PythonTest | /jonathanMirabile_exam2_p2.py | 1,534 | 4.4375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Jonathan <jonathanmirabile@mail.weber.edu>
#
# Distributed under terms of the MIT license.
import sys
"""
Python exam
Problem 2
Secure password checker
"""
def IsValidPassword(password):
#Password length check
if(len(password... |
1d4ae3151e22c5e7c1e97ab5f163a49d1d56b526 | Roger423/python-tips | /create_random_mac/random_mac_2.py | 814 | 3.859375 | 4 | #! python3
import random, sys
def Gen_random_mac():
mac_al = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
mac_al_2 = ['0', '2', '4', '6', '8', 'A', 'C', 'E']
mac_ls = []
for i in range(6):
if i == 0:
mac_se = random.choice(mac_al) + random.choic... |
954172b3e7a6226dded0faa0ac8f483ee22de652 | gayu2723/python | /evennotinv;id.py | 158 | 4.03125 | 4 | def evennotin():
n=int(input())
if(n%2==0):
print("even")
elif(n<=0):
print("invalid")
else:
print("odd")
evennotin()
|
12829cf8870af69b22379baa5dab09c8295f2856 | itsmrajesh/python-programming-questions | /Day1/reverseNumber.py | 166 | 4 | 4 | num = int(input("Enter a numeber : "))
numCopy=num
rev=0
while num>0:
rem = num%10
rev = (rev*10)+rem
num //= 10
print(f"The rev of {numCopy} is {rev}")
|
fbaa8dceb1b65112f98f12a10f8698d330463777 | abhinavjainR/textbasecaptcha | /textbasedcaptcha.py | 696 | 3.96875 | 4 | # Capcha module is used to convert our text to image
from captcha.image import ImageCaptcha
# PIL module is used to show our captcha image
from PIL import Image
# Captcha variable is used to take input text
Captcha=input("Enter captcha : ")
# Form variable is used to take name of image
Form=input("Enter n... |
9423706d5515927d9bc6dd210d444625a6e4f00a | mmtmn/lightsout | /translator5x5.py | 1,381 | 3.6875 | 4 | # made by Thiago M Nóbrega
# to run this project: python main.py
def translate(pick):
"""
receives numerical state of space, outputs finalpick as a coordenate
"""
#pick = int(input("pick a number: "))
x1 = 0
y0 = 0
if pick == 1:
finalpick = 0,0
elif pick == 2:
finalpick... |
7b68c185011994faaf39432161753f006c2a43d4 | Rob0128/Battleships | /battleships.py | 10,871 | 3.84375 | 4 | import random
def is_sunk(ship):
#finds length of the input ship and compares the int value to the number of hits on the ship
ship_len = ship[3]
count = 0
boat = ship[4]
for hit in boat:
count += 1
if ship_len == count:
return True
else:
return False
... |
f4646daf05c18f3e67f8700cf90e0deee748eeb2 | Jason-Yonghan-Park/PythonML_Practical | /modelsave/tensorflow_model01/tensorflow_model_read01.py | 2,345 | 3.515625 | 4 | # CNN을 이용한 Fashion MNIST 분류 - 98%
# tensorflow와 tf.keras 임포트
import tensorflow as tf
from tensorflow import keras
# 추가로 필요한 라이브러리 임포트
import numpy as np
import matplotlib.pyplot as plt
# 학습 완료 후 저장된 모델 읽어옴
model = keras.models.load_model('D:\PythonML_Practical\modelsave/tensorflow_model01/fashionmnist_cnn01.h5')
# ... |
ba9f6a372d459c6a35bd76efa9c30cb356d60498 | danyuanwang/karatsuba_mult | /array_inversions/main.py | 1,887 | 4 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def extract_file():
handle = open('data_array_coursera_algo_week2.txt')
print(handle)
list = []
for line in ... |
50982d3ce29e4344b20c1c06f8ae676924105780 | BeyondEvil/AoC2017 | /2015/day_01/solution.py | 430 | 3.53125 | 4 |
def read_input():
with open('input.txt', 'r') as f:
return f.read().strip()
def run_it(seq):
floor = 0
position = False
for index, each in enumerate(seq):
floor += 1 if each == '(' else -1
if floor == -1 and not position:
position = index + 1
print('Part 1: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.