blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5fcb38a7564095a79911de248d482e5ba28f6b8a | pybule/pythonProject | /面试题/32、生成数值和索引都是偶数的列表.py | 206 | 3.828125 | 4 | # _*_ encoding=utf-8 _*_
# author zdh
# date 2021/4/21--22:46
def num_list(num):
return [i for i in num if i%2==0 and num.index(i)%2==0]
num = [0,1,2,3,4,5,6,7,8,9,10]
list = num_list(num)
print(list)
|
e053834384e7634ab1c137c9c18f369bd13cdb58 | Catarina607/Python-Lessons | /6_27.py | 285 | 4 | 4 | num = int(input('Number: '))
c = 0
s = 0
cont = 0
if num <=0:
print('O numero tem que ser maior que zero')
for c in range(1, num+1):
if c==1:
cont = 1
elif c > 1:
cont = cont + 1
s = cont/cont/cont/(s + 1/c)
print('O resultado é ',s) |
063d37b05cabe2485abfcb27f13302f21a6833ea | edursantos/pythontest | /ex006.py | 197 | 3.796875 | 4 | print('===Quantos dólares você pode comprar?===')
n1=float(input('Quanto você tem na carteira?'))
n2 = n1/5.70
print('Você tem R$ {:.2f} e pode comprar U${:.2f}'.format(n1,n2))
print('Teste')
|
951f6d4a1d26cf9bfa91211fa02fa86d83e26ec2 | VaibhaviMandavia/pythoncodes | /missingnum.py | 416 | 3.734375 | 4 | #find the missing number from an array of first n numbers
x = int(input("enter number of elements : "))
print("enter "+str(x)+" elements : ")
lst = []
ans = 0
n = x + 1
for i in range(0,x):
y = int(input())
lst.append(y)
if all(item >= 0 for item in lst) == True:
res = n*(n+1)/2
else :
res... |
0d6c8fc72af375556a7c2a9febde294edbae03e6 | unexpectedCoder/GunProject | /my_parser.py | 3,153 | 4.0625 | 4 | from xml.etree import ElementTree
import csv
def read_txt_with_fieldnames(file, delim):
"""
This function reads data from TXT file with forming field of names
for further converting to CSV file.
:param path: TXT file path
:param delim: delimiter between data elements
:return: data and field of... |
56905404056ac7a20240ee58e4c27a2d86616c2b | Tom520class/AnacondaProject | /pandas/4-6 Preprocess the data using apply.py | 1,202 | 3.515625 | 4 | __author__ = 'zhongyue'
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
# 通过apply进行数据预处理
df = pd.read_csv('../data/apply_demo.csv')
print(df.head())
print(df.size)
# 使用apply进行预处理
# apply可以批量的改变dataframe中的数据。
s1 = Series(['a']*5)
df['A'] = s1
print(df)
print(df.size)
# 将A列改的值为大写
df['A'] = d... |
e00505011a01ab08cb7aaf2a30ebcee9106f1452 | Eeun-ju/Algorithm-Study | /GOORM/약수개수세기.py | 237 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
n = int(input())
count = 0
for i in range(1,n+1):
if n%i == 0:
count +=1
if count%2 == 0:
print('no')
else:
print('yes')
#print ("Hello Goorm! Your input is " + user_input) |
0555c577a8fb746cf2debb929d02b46cd3be4d7b | timliakhor/geekbrains_python | /lesson3/6.py | 352 | 3.9375 | 4 | from typing import List
def uppercase_first_letter(string: str) -> str:
return string[0:1].upper() + string[1:]
string_list: List[str] = input('Please, input string: ').split(' ')
result: str = ''
for i, value in enumerate(string_list):
result += (lambda index: '' if index == 0 else ' ')(i) + uppercase_fir... |
c56b9646629e15dfa9d4eec8927f0fae3ca5364f | clint-ton/astar | /astar.py | 4,960 | 3.90625 | 4 | """Module to implement the A* algorithm using the abstract classes and generic graph search of search.py
Author: Clinton Walker"""
from search import *
import math
import heapq
class RoutingGraph(Graph):
def __init__(self, map_str):
# convert a map string to a 2d matrix of symbols
... |
037a107116515cf14e84f54378a26c719528a1dd | sjlee900211/algorithm | /Code10-06.py | 180 | 3.53125 | 4 | ## 별모양 출력하기 -> 입력한 숫자만큼 차례대로 별모양을 출력
def printStar(n):
if n > 0 :
printStar(n-1)
print('★ ' * n)
printStar(5) |
bda931731047e5d5a598a7a88bcd1d16ddef3ee4 | lehuyl/PythonDataAnalysis | /e1/pd_summary.py | 779 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 16:08:28 2019
@author: Steven
"""
import pandas as pd
totals = pd.read_csv('./e1/totals.csv').set_index(keys=['name'])
counts = pd.read_csv('./e1/counts.csv').set_index(keys=['name'])
cityPrecipitation = pd.Index(totals.sum(axis=1))
print('Row with lowest total prec... |
d155e34d3bcb2b6d54064c6699fd5311b872adbf | zfq308/py | /tree.py | 639 | 3.640625 | 4 | import sys
import os
def printsubfolder(path, name, level):
o = ''
if(os.path.isfile(path + name)):
for index in range(level - 1):
o = o + ' '
o = o + '|---'
print(o + name + '\n')
else:
for index in range(level - 1):
o = o + ' '
o = o +... |
11014d7e99b9a1ee5d9b2f292db272827f32e601 | Shubham-Coader/python | /beginner_python/02-strings.py | 5,533 | 4.59375 | 5 | me = "Caleb"
#escape character example
print("\n")
me = "C\ta\tl\te\tb\n"
print(me)
#can also use single quotes
you = 'Subscriber'
me = "Caleb" #reset to normal
#passing multiple arguments to print
print(me, you)
#double quotes and single quotes work the same way with the exception of working with quotes inside.... |
5485bfe3d04b95096a68e3a297289d5ae4bd23dd | vieiraguivieira/PhytonStart | /strings.py | 654 | 3.75 | 4 | print("Today is a good day to learn Pyhton")
print('Phyton is fun')
print("Phyton's string are easy to use")
print('We can even include "quotes" in strings')
print("hello" + " world")
greeting = "Hello"
name = "Guilherme"
print(greeting + name)
# if we want a space, we can add that too
print(greeting + ' ' + name)
a... |
2630106d3269f8d72a50eeb97f6303e174cb99df | rafaelperazzo/programacao-web | /moodledata/vpl_data/39/usersdata/115/15211/submittedfiles/dec2bin.py | 163 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=int(input('digite um número:'))
b=n
c=0
while b>0:
b=b//2
c=c+1
s=0
for i in range(0,c,1):
|
2aff2c0b9f1548bbb4176a6bcecdefbd0bdebe82 | shekharkrishna/ds-algo-udi-20 | /Data Structures/Trees/2. DFS/1traverse_tree.py | 1,744 | 4.25 | 4 | class Node(object):
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def get_value(self):
return self.value
def set_value(self, value):
self.value = value
def get_left_child(self):
return self.left # PJ: We are c... |
bc061b44f7aec125a26e816bbde444107cf9aa34 | zhucebuliaolongchuan/my-leetcode | /DFS/LC310_MinimumHeightTrees.py | 1,801 | 4.28125 | 4 | """
310. Minimum Height Trees
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and re... |
3148cde7c931a22d9ef1ae5f69f8eda8dde30385 | joelranjithjebanesan7/Python-Programs | /sessionTwo/lab8.py | 504 | 3.78125 | 4 | def selling_price(list_price,binding_type,discount=0.1):
if(binding_type == "HB"):
return list_price
else:
DiscountPercent= float(list_price) * float(discount)
DiscountPrice=float(list_price) - float(DiscountPercent)
return DiscountPrice
list_price = input("Enter the l... |
e7c19f6a6c0c693b51cacdf920dd98b47a85b6e9 | LucasJezap/GeometricAlgorithms | /5. Voronoi/test.py | 623 | 3.75 | 4 | from random import random,seed
from voronoi import Voronoi
def randomFirst(n, left, right):
pts = []
seed(1)
for i in range(0,n):
pts.append((round(left+random()*(right-left),8),round(left+random()*(right-left),8)))
return pts
left=int(input("Welcome to time complexity tester for gen... |
adacfa66037f814c56253bc5e9db92b86bba093f | lauqerm/AlgoExam100 | /501 - Find Mode in Binary Search Tree.py | 1,017 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
a = {}
def travel(self, node):
if node == None:
return
if not node.val in self.a:
... |
33e3f3db57749f123df73e565146da5e56f55c8c | alexanderluong/toUppercase | /toUppercase.py | 770 | 4.625 | 5 | #! /usr/bin/env python3
# toUppercase.py - converts clipboard text or argument to uppercase
import sys, pyperclip
if len(sys.argv) > 2:
print('''Usage: python toUppercase.py - converts clipboard text to uppercase OR
python toUppercase.py [string] - converts string to uppercase and prints to console''')
sys.ex... |
c814e49a7c36cbb3a68c210f32d35aea61df1b08 | dldamian/ProgramasPython | /11-BinarioHexadecimal.py | 2,060 | 3.953125 | 4 | import time
print('Bienvenido al convertidor de Decimales a Binarios y Hexadecimales\n')
while True:
decimal = input('Generaremos una lista de decimales, binarios y hexadecimaneles.\n ¿Hasta que número quieres generar la lista?: ')
try:
decimal = int(decimal)
if decimal <= 0 or decimal == 1:
... |
154b79a2cbdf52b3965098a45a4dbd1a3a0e9049 | TomRobo237/python_practice | /automate_the_boring_stuff/part_3/random_number.py | 794 | 3.84375 | 4 | import random, sys, os, math
amount = ''
rand_top = ''
while not amount:
print('How many random values would you like?')
amount = input()
if amount == 'exit':
sys.exit()
try:
amount = int(amount)
continue
except ValueError:
print('Please enter a whole number!\nIf you... |
cd3d9bd3cfc00c6cfdfe5143662ec823a57e7270 | priyaparshu/Python | /test.py | 912 | 3.671875 | 4 | class StackOverflowUser:
def __init__(self, name="", userid=0, rep=0):
self.name = name
self.userid = userid
self.rep = rep
def __str__(self):
s="Employee:"
s += ('(' + self.name + ',' + str(self.userid) + ',' + str(self.... |
dede8db5e5853b241ba2b5b4abbb294b4eb847c5 | fkadeal/alx-higher_level_programming | /0x0B-python-input_output/11-student.py | 471 | 3.84375 | 4 | #!/usr/bin/python3
"""Module implementing class with method to serialize itself"""
class Student:
"""Class to represent student"""
def __init__(self, first_name, last_name, age):
"""Initialize new student instance with name and age"""
self.first_name = first_name
self.last_name = last_... |
695bfded3d5f22544c02a9abb997d28a174a24bb | sophiadavis/nqueens | /nqueens.py | 3,283 | 3.90625 | 4 | # Written by Sophia Davis and Anna Quinlan, 4/27/14
import random
import sets
# Returns solution to for n by n board.
def nqueens(n):
if n <= 3:
return false
# make the board
board = []
j = 0
for i in range(0, n):
board.append(range(j, j + n))
j += n
printboard(board, n)... |
48c5c3c58c9236ceb57266a85c6311fb513fbf6f | LyaisanN/Homework_Figure | /src/Square.py | 1,094 | 3.84375 | 4 | from src.Figure import Figure
from src.Rectangle import Rectangle
from src.Circle import Circle
from src.Triangle import Triangle
class Square(Figure):
name = 'Square'
def __init__(self, height):
self.height = height
# self.width = width
super().__init__(name='Square', area=None, peri... |
4f6fa34946e31ece1ac1565a2436ffe696cddb96 | seanisoverhere/cs50 | /pset6/sentimentals/cash.py | 657 | 3.84375 | 4 | from cs50 import get_float
def main():
# Prompt user for change owed
while True:
change = get_float("Change owed: ")
# Ensure change is >= 0
if change >= 0:
break
# Rounding off change to cents
cents = round(change * 100)
# Initiailize coins
coins = 0
... |
48cbaff314209e6ba9512e2cb5b905b755abcf18 | shubham-aicoder/100DaysOfCode | /100DoC_D25.py | 624 | 3.890625 | 4 | def check_anagram(sentence_1,sentence_2):
#write your code here
sentence_1=sentence_1.lower().replace(" ","")
sentence_2=sentence_2.lower().replace(" ","")
if len(sentence_1)==0 and len(sentence_2)==0:
return True
for i in sentence_2:
if sentence_1.find(i)==-1:
... |
055768b604caec4b5bfd2e611cfc88285493a256 | BorthakurAyon/Algorithms | /puzzles/DiceTrial.py | 536 | 3.625 | 4 | import random
class Dicetrial(object):
def simulation(self, n):
self.count = 0
for _ in range(n):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
score = dice1 + dice2
if scor... |
98bde0321ebece804a934f960351659d2d458130 | AllenWang314/mpc-attendance | /script.py | 794 | 3.515625 | 4 | import pandas as pd
static_path = "static/"
csv_name = "poker_club_users.csv"
email_file_name = "emails.txt"
missing_accounts_file = "missing.txt"
# get only the columns you want from the csv file
df = pd.read_csv(static_path + csv_name)
result = df.to_dict()
emails_registered = result["Email"].values()
emails_regist... |
373214f74b7f92cff6f8dc8f244df5f5ec02f797 | Khrystynka/LeetCodeProblems | /7_reverse-integer.py | 471 | 3.609375 | 4 | # Problem Title: Reverse Integer
import sys
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
res = ''
neg = False
if x < 0:
neg = True
x = x*(-1)
s = str(x)
res = s[::-1]
res = int... |
280f1927e345e2f1d071526df75d38f2f276aee4 | shiny132/pystudy | /source/quiz01_1.py | 343 | 3.6875 | 4 | str = "Life is too short, You need Python"
str = str.lower()
str = str.replace(" ","").replace(",","")
lst = list(str)
print("lst: ", lst)
# str = str.lower().replace(" ","").replace(",","")
chars = set(lst)
print("chars:", chars)
lst = list(chars)
print("lst: ", lst)
list.sort(lst)
print("lst: ", lst)
print("leng... |
08939f7fcb2c11f1d294eae8fb4b3eee90bc5191 | AzamatGainullin/education_2021_ | /obuchenie_bs4.py | 4,711 | 3.671875 | 4 | from bs4 import BeautifulSoup
import requests
import re
### ПОЛУЧЕНИЕ ИЗ ФАЙЛА ###
html_doc = """<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://exampl... |
6c2caf02084e1b0f4cc055cc416a345297b263d1 | woohyun212/Data_Science_and_AI_introductory_Coding_Solution | /chapter4/ex4_7.py | 232 | 3.515625 | 4 | import random
n1 = random.randint(1, 100)
n2 = random.randint(1, 100)
number = int(input(str(n1) + " + " + str(n2) + " = "))
if number == n1 + n2:
print('잘했어요!!!')
else:
print('정답은 %d 입니다' % (n1 + n2))
|
dc5e65e4f63fe32b7b5519fb1c38b2d0f92c66d0 | hashamtanveer/Crossword-Puzzle-Solver | /solver.py | 2,722 | 3.625 | 4 |
import numpy as np
def find(word):
if checkRows(word) or checkCols(word) or checkDiag(word) or checkDiagRev(word):
return True
else:
return False
def checkRows(word):
found = False
for row in range(board.shape[0]) :
row_array = board[row,:]
row_string = ''.join(row_... |
d88462c3b055970b704cec2f769de2e03f544a89 | csl-ugent/semantic-renewability | /core/parser.py | 2,464 | 3.640625 | 4 | """
Module used for parser related functionality.
"""
import logging
import re
class Parser:
"""
Class used for parsing input files using a parse function
the output is returned and can be written away to an output file.
"""
@staticmethod
def parse_file(input_file, parse_function, output_file=... |
c8002cc6c31f04c52215cba52948dbd113bbfc1e | kjin97/thvln | /THavalonQuest.py | 14,437 | 3.90625 | 4 | #!/usr/bin/env python3
import os
import random
import shutil
def main():
# get the number of players
num_players = int(input("How many people are playing?\n"))
if num_players < 5 or num_players > 10:
print("Invalid number of players")
exit(1)
# get the names of players
players = set() # use a... |
f6506d8340ddf40153d5083be07ffd08b13b7a2d | Vshltayade/Q3_VishalTayade | /Q3.py | 388 | 3.703125 | 4 | inp = list(input().split())
def countingValleys(inp):
level = 0
valleys = 0
for direction in inp:
if direction == "U":
level += 1
if level == 0:
valleys += 1
else:
level -= 1
return valleys
if __name__ == "__main__":
... |
391a33930df1454d5c225b1be3b19949b7996255 | JDer-liuodngkai/LeetCode | /torch/loss_vis.py | 543 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def focal_loss():
"""
段长相同情况下,vis 不同 n 取极大值的位置
乘积: x ** (n / x)
"""
xs = np.arange(1, 100) / 100
# 可见 当 p -> 1 时,loss 趋近 0,确信的样本 更少的 loss
for r in [0, 0.5, 1, 2, 5]: # r=0 就是 CE LOSS
ys = [-(1 - x) ** r * np.log(x) for x in xs]
... |
758df61ffa6ef0e7af009900cbf490e0b120c657 | ankursharma7/100-Days-Of-Code | /Day 8/06_pr_01.py | 304 | 4.09375 | 4 | def maximum(num1,num2,num3):
if (num1>num2):
if(num1>num2):
return num1
else:
return num2
else:
if (num2>num3):
return num2
else:
return num3
m = maximum(3,67,899)
print("The value of the maximum is", m) |
6db8850a9a9fbc271b1ec4a621795ab2bc7af9d0 | AbdelrahmanRadwan/Natural-Language-Processing-Package | /Minimum_Edit_Distance/minimum_edit_distance.py | 13,435 | 3.703125 | 4 | import operator
import math
def suggestions1(lines, search):
clubs = {}
search_club_name= search.split()[0]
for club in lines:
distance = calculate_minimum_edit_distance(club, search)
for club_token in club.split():
distance = min(distance, calculate_minimum_edit_distance(club_... |
a4d5abead572ab81ec886fb1853977d505def2cf | lowones/tic-tac-toe | /ttt.py | 2,526 | 3.71875 | 4 | #!/usr/bin/python
from itertools import cycle
from time import sleep
from os import system
import os
win_lines = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'],
['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9'],
['1', '5', '9'], ['3', '5', '7']]
def main():
print "main"
... |
5092b990cd26299f3b4b0512286ee47c935de43c | JeroenVerstraelen/GegevensAbstractie | /Main (python code)/redblack_tree.py | 13,191 | 3.734375 | 4 | class Redblacktree:
'''
class for the red-black tree
'''
class redblacknode:
'''
class for the node of a red-black tree
'''
def __init__(self,key):
self.key = key
self.red = False #self.red holds the color of the connect... |
7a35a92ef2887f22f265c0821c03c426c38c70eb | goalong/lc | /v2/140.py | 1,075 | 3.578125 | 4 | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
# 7 star, 比较难,这道题立即想到用dfs,结果超时了,而且用dfs还有两处细节需要注意,一个是dfs中for循环的范围,一个是递归调用时path的赋值应该直接在调用中进行,如果单独写一行path.append(s[:i]),就是错误,因为list的可变性
# r... |
3ba9d804227913904d5515d7b7f91fb904357fe2 | LArchCS/Data-Science-and-Computational-Thinking-Using-Python | /Chapter1/fibo.py | 504 | 3.84375 | 4 | def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
def fib3(n):
... |
a5f9e2aab9def077b22d233bbd19bb716fdc2fdc | cheeseaddict/think-python | /chapter-6/exercise-6.8.py | 196 | 3.703125 | 4 | def gcd(a, b):
if a == b:
return a
elif a > b:
return gcd(a-b, b)
elif b > a:
return gcd(a, b-a)
print(gcd(84, 132))
print(gcd(246, 642))
print(gcd(41, 107))
|
fc9cd04d4f696eefadd5a468f15c3ee4f02cfbaa | KarlJJonsson/NumberGuesser | /GuessTheNumber/GuessingGame.py | 1,636 | 4.0625 | 4 | from GameLogic import GameLogic
"""Simple game where the user has to guess a generated number, while getting clues in form of equations for given number.
Takes max_tries (integer) as an argument. No argument when instantiating the object sets a default max_tries = 5.
After instantiation, use the start method t... |
5ceed54e8368ea285bbcf0edb09d864abee2567d | SimeonTsekov/TP | /Files/Python_codes/lesson4-OOP1/class4.py | 604 | 3.65625 | 4 | class BookStore:
def __init__(self, title, author):
self.title = title
self.author = author
self.__privateMember = "private";
def bookInfo(self):
print("Book title:", self.title)
print("Book author:", self.author,"\n")
print("Private Member inside:", s... |
e1a12174204cbcb6946d030a2daf5e45237f13d1 | AlanCFleming/SimulationProject3 | /scripts/pendulum.py | 2,607 | 3.734375 | 4 | import math
import matplotlib.pyplot as plt
import dynamics
class Pendulum(dynamics.Dynamics):
def __init__(self, pendulum_length, time_step):
numEquations = 2 # set the number of state equations
# set constants, if any
self.gOverL = 9.802 / pendulum_l... |
ec2327acb81e546fa1915bc075d8c417e0f79d64 | CyrilHub/GA---GIT | /Class-Notes/L6 - Class/Class Notes 010919.py | 284 | 3.96875 | 4 | class Car:
def __init __(self, size, color):
self.size = size
self.color = color
def print_size(self):
print ("The size is:")
print (self.size)
print ("the color is:")
print (self.color)
ford = Car(1):
ford.print_color_size
|
e19b09829ad8f77b478ff00eafd158cbd2ae006b | Mianmian028/python-study | /python/0307message_233.py | 223 | 3.546875 | 4 | #coding:utf-8
message ='you are ugly.'
message1 ="it is true."
print(message.title())
print(message.upper())
full_message =message +""+message1
print(full_message)
full_message1='hello!'+""+full_message
print(full_message1) |
c65bd44300e2016132e433dc7d5045819c594382 | JMaling/Final_Project | /input_functions.py | 1,257 | 3.5625 | 4 |
def get_good_list(positive_word_list, twitter_list):
'''
:param positive_word_list: uci list of good words or bad words
:param word_list6: twitter feed list of words
:return: list of good or bad words found in twitter words
'''
total = 0
words = []
for word in twitter_list:
i... |
80f6a51c5e033834c5afdabc4c1c8b7342399b21 | arihant-2310/Python-Programs | /sort without sort function.py | 292 | 3.59375 | 4 | n= input('enter how many numbers:-')
l= []
for i in range(n):
e= input('enter elements-')
l.append(e)
for i in range(n):
for j in range(n-1-i):
if l[j]>l[j+1]:
t= l[j]
l[j]= l[j+1]
l[j+1]= t
print'sorted list is:-'
print l
|
a5c27ef09b29297aff35191f06e91b211d6ae54e | thehawkgriffith/BlackJack-by-Shahbaz-Khan | /Blackjack.py | 6,449 | 3.875 | 4 | from random import shuffle
print("Welcome to the game of BlackJack by Shahbaz Khan!")
class Hand():
def __init__(self):
self.cards_in_hand = []
def addCard(self, card):
self.cards_in_hand.append(card)
class Deck():
def __init__(self):
self.cards = ['A', 'J', 'K', 'Q',... |
3a450fa853b4c5801162d148a5cacfdba1805cfe | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 06 (stacks_queues_deques)/reverse_file_using_stack.py | 509 | 3.71875 | 4 | from stack_class import *
def reverse_file(path):
"""Overwrite given file using its context line-by-line reversed"""
s=ArrayStack()
with open(path,"r") as original:
for line in original:
s.push(line.rstrip("\n")) # removing newline characters
# overwrite the contents in LIFO order
... |
b9fd3f47fb6f8c78d7d6ffacf7657897ed140e4d | shahad02/final-project | /final edge project (reserving a table).py | 1,483 | 4.09375 | 4 | class restaurant:
setmenu=["Chines","American", "Italian" , "Indain", "Thai"]
def welcome():
print("WELCOME TO THE 5 STAR international RESTAURANT!!")
print("here you can reseve your table to have a wonderful meal")
welcome()
def __init__(self):
self.output=""
def place(whe... |
d3797f35e69009ca0237aafc2e024641acc741ca | KqSMea8/Learning_Workspace | /Learning_Opencv_python/day5_padding.py | 1,163 | 3.53125 | 4 | '''
cv2.copyMakeBorder()用来给图片添加边框,它有下面几个参数:
src:要处理的原图
top, bottom, left, right:上下左右要扩展的像素数
borderType:边框类型,这个就是需要关注的填充方式
其中填充方式有 默认方式和固定值方式最常用
'''
# 固定值填充
'''
cv2.BORDER_CONSTANT这种方式就是边框都填充成一个固定的值,比如下面的程序都填充0:
'''
import cv2
import numpy as np
img = cv2.imread("/home/sanjay/Workspace/learning/Learning_Opencv_python/l... |
8f9cb889a07147e9bbbbffce7dc0e2b3ae2b3ab8 | layshidani/learning-python | /lista-de-exercicios/Curso_IntroCiênciadaCompPythonParte 1_Coursera/SEMANA_4/S4OP2-digito-repetido.py | 468 | 4 | 4 | print('-=-' * 15)
print('Digito adjacente igual'.center(15, '-'))
print('-=-' * 15)
n = int(input('Insira um número inteiro: '))
print('\nO número', n, 'possui dígitos adjacentes iguais?')
n_anterior = n % 10
n = n // 10
igual = False
i = 0
while n > 0 and not igual:
n_atual = n % 10
if n_atual == n_anteri... |
7706eb0fbf5c2f19a9d5566641f8c660498ef5cf | lixiang2017/leetcode | /problems/0540.0_Single_Element_in_a_Sorted_Array.py | 4,475 | 3.765625 | 4 | '''
xor
Runtime: 64 ms, faster than 92.68% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 16.5 MB, less than 39.56% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
return reduce(... |
91d548e43f21dcd5301be65e89d5a7cae41aa39f | lvsdian/python | /clazz/02-闭包.py | 363 | 3.71875 | 4 | def outer():
x = 10 # 在外部函数里定义了一个变量x,是一个局部变量
def inner():
# 在内部函数如何修改外部函数的局部变量
nonlocal x # 用nonlocal,此时,这里的x就是外部函数的局部变量x
y = x + 1
print("inner里的y = ", y)
return inner
# inner里的y = 11
outer()() |
b30036dd55cf3e208996b1892a2d72a9fcd03335 | ZackSungy/Python | /StupidToLearnPython(BookName)/ex6.py | 378 | 3.71875 | 4 | x="There are %d type of people."%10;
binary="binary";
do_not="dont't";
y="Those who know %s and those who %s."%(binary,do_not);
print x;
print y;
print "I said:%r."%x;
print "I also said:'%s'."%y;
hilarious=False;
joke_evaluation="Isn't that joke so funny?!%r";
print joke_evaluation%hilarious;
w="This is the left ... |
408a0e0f285a66da35c0125f054edb9b6e124351 | nikhiilll/Algorithms-using-Python | /Medium-AE/RemoveKthNodeFromEnd.py | 671 | 3.828125 | 4 | class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeKthNodeFromEnd(head, k):
noOfNodes = 0
node = head
while node is not None:
noOfNodes += 1
node = node.next
nodePosToRemove = noOfNodes - k
if nodePosToRemove == ... |
6535e97a83003cd8fab1814f99f6af2abc7fbeb2 | sakshisangwan/Python-101 | /Problem Set /Pattern2.py | 93 | 3.640625 | 4 | k = 1
for i in range (1, 6, +1):
for j in range( , i+1, +2):
print (k),
k+=1
print("") |
f076687e233c6d298e4b5df84b25d0ae337c2086 | JohnSchlerf/Sternberg | /sternberg.py | 8,465 | 3.53125 | 4 | #!/usr/bin/python
from helperfunctions import *
from random import shuffle, choice
from Tkinter import *
import copy
WIDTH = -1
HEIGHT = -1
FONTSIZE = 36
yesKey = 'f'
noKey = 'j'
encode_color = "green"
probe_color = "white"
encode_time = 2
probe_timeout = 2
set_size = [4,6]
number_of_sets = 20
probes_per_set = 6
... |
f473434e2066a83907bc39244011ccfb08a53b87 | jaggureddy/ZTM | /ZeroToMastery/Assignments/21_CalculateDistance.py | 1,377 | 4.5625 | 5 | """
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps. Please write a program to compute the distance from cu... |
cab6615cb0fdadb4b7f4f832407b6f7be4d447c3 | enterpreneur369/holbertonschool-higher_level_programming | /0x0A-python-inheritance/7-base_geometry.py | 860 | 3.59375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Module 7-base_geometry
This module contains the BaseGeometry class
"""
class BaseGeometry:
"""BaseGeometry class
A simple empty BaseGeometry class
"""
def area(self):
"""Returns an Exception"""
raise Exception("area() is not implemented"... |
c298b6f2cd9894f3f6b6fbbaca8b2e2b529f6e7f | saddam1999/code | /python/project/inline/INLineShell.py | 1,164 | 3.5 | 4 | First_FolderDIRECTORY = ["CODING"]
First_FolderFILE = ["Script.py","Text.txt"]
Second_FolderDIRECTORY = ["Python","Javascript","Php","Html","Css"]
Second_FolderFILE = [""]
class Folder:
def __init__(self,Name,Directory):
self.Name = Name
self.Directory = Directory
def Shell(self):
return f"{self.Name} \nDir... |
18b76ea8c82eb974bf4b353b3d1c7316bd767150 | quocanha/recurrence_solver | /recurrence_solver/solver/solver.py | 1,875 | 3.6875 | 4 | from sympy import *
from recurrence.recurrence import Recurrence
class Solver:
recurrence = None
def __init__(self, recurrence):
if type(recurrence) is not Recurrence:
raise TypeError("Solver requires a recurrence of type Recurrence")
self.recurrence = recurrence
def solve(... |
09cee9a9c8e880fb948b0eb5815ad0c592223b5a | eberlitz/data-analyst-nanodegree | /pj1/problem_sets/ps3/6 - Plotting Residuals.py | 1,402 | 3.578125 | 4 | import numpy as np
import scipy
from scipy import stats
import matplotlib.pyplot as plt
def plot_residuals(turnstile_weather, predictions):
'''
Using the same methods that we used to plot a histogram of entries
per hour for our data, why don't you make a histogram of the residuals
(that is, the differe... |
70e42d6d6efbd0048b7c2850c8048c4b1fcc7340 | Harishkumar18/data_structures | /interviewbit_problems/trees/trie_pgm/shortest_unique_prefix.py | 1,172 | 3.84375 | 4 | """
Find shortest unique prefix to represent each word in the list.
Example:
Input: [zebra, dog, duck, dove]
Output: {z, dog, du, dov}
where we can see that
zebra = z
dog = dog
duck = du
dove = dov
"""
class Trie:
def __init__(self):
self.letters = {}
def addstring(self, s):
letters = self.... |
6c4ec3ddb3a760076af15332548512f1170fcf53 | artkpv/code-dojo | /hackerrank.com/contests/hourrank-24/strong-password/strong-password.py | 644 | 3.8125 | 4 | #!/bin/python3
"""
https://www.hackerrank.com/contests/hourrank-24/challenges/strong-password/problem
"""
import sys
def minimumNumber(n, password):
return max(6 - n,
(1 if not any(c in "abcdefghijklmnopqrstuvwxyz" for c in password) else 0) +
(1 if not any(c in "ABCDEFGHIJKLMNOPQRSTUVWXY... |
05efbb842383e3a6f723a11eef297f2e1fab152d | yatengLG/leetcode-python | /question_bank/counting-bits/counting-bits.py | 717 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:88 ms, 在所有 Python3 提交中击败了92.93% 的用户
内存消耗:20.6 MB, 在所有 Python3 提交中击败了23.45% 的用户
解题思路:
某一数值num的比特位为1的计数,等于其 /2的余数为1 的数量
例:
13 余 6 余
/2 6 1 /2 3 0
/2 3 0 /2 1 1
/2 1 ... |
0205ffacd9f22b8e94f2eff85f6caee95aec8cd8 | Mygithub-projects/python_programs | /threads/three_thread.py | 608 | 3.640625 | 4 | import threading
def sum_of_even_series(n):
i=1
next = 2
sumeven=0
while( i <= n):
sumeven +=next
next+=2
i+=1
print("sum of even numbers = {} \n".format(sumeven))
def checknumber(n):
if (n%2==0):
print("{} is even number\n".format(n))
else:... |
a9c0ba8b4ed748ce19e31d413fe5437bf6d68b91 | diego-pacheco-PE/pythonCookbook_review | /ch01_PythonCookbook.py | 3,507 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 18 13:59:35 2021
@author: DIEGO PACHECO
"""
import numpy as np
# UNPACKING A SEQUENCE INTO SEPARATE VARIABLES
"""
You have an N-element tuple or sequence that you would like
to unpack into a collection of N variables.
"""
p = (4,5)
x, y = p
x
y
data = ['ACME', 50, 91... |
09655dd51519ee0139bca4ef1e342633bca5dbca | fwar34/Python | /test_yield7.py | 949 | 3.640625 | 4 | # async和await
# 弄清楚了asyncio.coroutine和yield from之后,在Python3.5中引入的async和await就不难理解了:可以将他们理解成
# asyncio.coroutine/yield from的完美替身。当然,从Python设计的角度来说,async/await让协程表面上独立于生成器而存在,
# 将细节都隐藏于asyncio模块之下,语法更清晰明了。
# 加入新的关键字 async ,可以将任何一个普通函数变成协程
import time
import asyncio
import random
async def mygen(alist):
while len(al... |
404bce339010302339fef981e1530c693ef11d6d | sakuya13/Study | /python/grok/grok_factorise.py | 325 | 3.984375 | 4 | def factorise(limit):
for i in range(1, limit + 1):
for j in range(1, limit + 1):
if i % j == 0:
print('* ', end='')
else:
print('- ', end='')
print()
def main():
limit = int(input('Maximum number to factorise: '))
factorise(limit)
ma... |
224a16dcd048dc9f524c35231bddaa2c8d831836 | ThomasZumsteg/project-euler | /problem_0050.py | 2,884 | 3.984375 | 4 | #!/usr/bin/env python3
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, a... |
ae232e69150bc4ba9fb6867d0b8d15521414dc1c | noahadelstein/mathemagic | /sample_python/automatedCensor (2013).py | 1,710 | 3.890625 | 4 | #-------------------------------------------------------------------------------
# Name: automatedCensor.py
# Purpose: prompts user for input/output file and wordlength,n; reads in text from a file
# and creates a new file where all n-length words are replaced by n *'s
#
# Assumptions: 1. ignores punctuation, 2... |
95bee9ed7d0024dba765761dc9f801253d1822ee | HsiangHung/Code-Challenges | /Crackingcode_interview/3.stack_and_queues/Q3.5_mimicStack_by_twoStacks.py | 859 | 4.25 | 4 | ## Q3.5: use two stacks to implement a queue
#
# idea: using two stacks to pop can mimic a queue
#
class MyQueue():
def __init__(self):
self.items = []
def push(self,x):
self.items.append(x)
def pop(self):
C = stack()
for i in range(len(self.items)-1,0,-1):... |
9eeb7eb2f8693c317416920e72ecee5794bca984 | AssiaHristova/SoftUni-Software-Engineering | /Python Advanced/first_exam_preparation/problem_2.py | 1,515 | 3.71875 | 4 | import math
def create_matrix(n):
matrix = []
for _ in range(n):
line = input().split()
matrix.append(line)
return matrix
def find_the_player(matrix):
for r in range(len(matrix)):
for c in range(len(matrix[r])):
if matrix[r][c] == 'P':
return r, c
... |
eac76ba05b43e4e57097b0442855f73a8708212d | kwyate/py101 | /Juego_21/funciones.py | 3,153 | 3.71875 | 4 | import random
nombre = input("Por favor digita el nombre del jugador: ")
nombre = nombre.upper()
usuario = []
computador = []
def user(): # funcion retornar lista cartas usuario
return usuario
def pc(): #funcion retornar lista cartas maquina
return computador
def resUser(res):
res += res
... |
519591b63acf9735600117a530d47039e710f453 | arinj9508/algorithm | /알고리즘_이러닝/자릿수의 합.py | 309 | 3.609375 | 4 | # n의 각 자릿수의 합을 리턴
def sum_digits(n):
n = str(n)
if len(n) < 2:
return int(n)
return sum_digits(n[:len(n) - 1]) + int(n[len(n) - 1])
# 테스트
print(sum_digits(22541))
print(sum_digits(92130))
print(sum_digits(12634))
print(sum_digits(704))
print(sum_digits(3755)) |
5a9dde2044547c63061f203526db846738fef62e | musicicon/MIT-6.0001-solutions-to-projects | /Problem Set 2_Hangman Game.py | 12,819 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 16 12:11:21 2020
@author: Varun
"""
# Problem Set 2, hangman.py
# Name:
# Collaborators:
# Time spent:
# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to... |
0668730f3d269c3116dc65b2f302e81df3c1d92c | PrimeMinisters/PrimeMinisters | /PrimeMinistersByPython/primeministers/reader.py | 919 | 3.578125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import io
import table
import tuple
class Reader(io.IO):
"""リーダ:総理大臣の情報を記したCSVファイルを読み込んでテーブルに仕立て上げる。"""
def __init__(self, csv_filename):
"""リーダのコンストラクタ。"""
self._csv_name = csv_filename
print "[Reader]ファイルネーム確認",self._csv_name
return
def table(self):
"""ダ... |
8687c99f0d4318142c6389c59d184029de809f83 | dkl2036/magic-8-ball-game | /magic8ball.py | 1,090 | 4 | 4 | import random
import time
print("Ask Python, the Magic 8 Ball a question!")
time.sleep(5) # waits 5 seconds
print("Searching for an answer . . . ")
time.sleep(2) # waits 2 seconds
print("Please be patient . . .")
time.sleep(1) # waits 1 seconds
for dot in range(10): # prints 10 dots seperated by 0... |
eba2879bd01b0081978591f88cf293339a747fa6 | MaiziXiao/Algorithms | /Leetcode/数组字符串链表/7-easy-Reverse Integer.py | 610 | 3.9375 | 4 | class Solution:
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
"""
def reverse(self, x: int) -> int:
res = 0
sign = -1 if x < 0 ... |
a4d17516505b10e78c2107d64b9ea8dad42fe708 | ggardiakos/bradquant | /NYC时期/pcm_tools/toolbox.py | 12,868 | 3.5 | 4 | """
Contents:
1. Open CSV file
2. Count business days
3. Create multiple graphs
4. Import multi-tickers' close price
5. Stats Arb Pair's Z-score plotting
6. Any single time series's sharpe ratio
7. Fred's economic data import
"""
#--------------------------------------------------------------------------------------... |
afb65d89a6a5a5baba23a8491562a192f4e3e7b9 | AstiV/Harvard-cs50 | /pset6/caesar/caesar.py | 2,469 | 4.4375 | 4 | from cs50 import get_string
import sys
def main():
# => argv = list of command-line arguments
# In C: argc = number of command line arguments
# A python list knows its length, so do len(sys.argv)
# to get the number of elements in argv.
# get the key from command line argument
# argc must be ... |
f9c532f999950b3dc727cc3f397db9414b03506b | zhangjingf/Python | /math.py | 376 | 3.671875 | 4 | import math
def power(x, n = 2):
s = 1
while n > 0:
n = n -1
s = s * x
return s
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
L = []
n = 1
while n <= 99:
L.append(n)
n = n + 2
L1 = ['Michael', 'Sarah', 'Tracy', 'Bob', ... |
3747e2e64b4ebf567b39e4209e16911ba95a7c5f | buriihenry/python_basics | /functions.py | 1,516 | 4.03125 | 4 |
# Sum of two numbers
def add(a, b):
sum = a + b
return sum
res = add(10,5)
print(res)
print ('\n')
# Even or ODD Number
def even_number(n):
if n % 2 ==0:
print('Even Number')
else:
print('Odd Number')
even_number(19)
print ('\n')
# Version 2
def is_even(list1):
even_num=[]
for n in list1:
if n %... |
727e95470fa7f79947831e4b2f577365f81ba387 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/443a8b38e1c74b13b3a060c20bc57613.py | 395 | 3.828125 | 4 | def square_of_sum(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x
total_holder = total_holder ** 2
return total_holder
def sum_of_squares(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x**2
total_holder = total_holder
return total_holder
def differe... |
cbdde55117391d6e3ac3d8940f61188e66068ef8 | deplanty/mini-games | /Stars/src/objects/star.py | 563 | 3.8125 | 4 | import tkinter as tk
class Star:
def __init__(self, canvas:tk.Canvas, x:int, y:int, radius:int, mass:int):
self.r = radius
self.x = x
self.y = y
self.mass = mass
self.iid = None
self.canvas = canvas
def init(self):
"""
Initaliz... |
8e2b626b60fed9b67136ef6be7536f8967c57180 | abhinav33agrawal/Python_Projects | /Date_checker_from_two_differnt_string.py | 1,006 | 3.765625 | 4 | import re
def List_for_dates(all):
month_to_number = {
'January': 1,
'February': 2,
'March': 3,
'April': 4,
'May': 5,
'June': 6,
'July': 7,
'August': 8,
'September': 9,
'October': 10,
'November': 11,
'December': 12}
... |
96f7f4a761520477d45971bb984775f74b9db96a | GabrielTeodoroDomingues/calculadoraDePassagens | /Caluladora.py | 378 | 3.75 | 4 | #Variaveis.
vCartao = float(input('Quanto dinheiro há no seu cartão :'))
vPassagem = float(input('Quanto custa uma passagem :'))
dUso = float(input('Quantos vezes em um dia você utiliza este meio de transporte :'))
#Calculo de quantas passagens é possível utilizar.
print('O total de passagens que podem ser utilizadas é... |
4d82f349a1ada5dfde06821f5782b7f2d38baadb | oh-data-sci/python_exercises | /exercises/09_brandwatch_sdk/sample_scripts/upload_queries.py | 1,641 | 3.515625 | 4 | """ Generates a uploads queries from a CSV file: name, includedTerms, language, samplePercent """
from bwresources import BWQueries
from ps_utils import ps_helper as ps
import csv
import re
#start script
project, username, projname = ps.create_proj_from_user()
queries = BWQueries(project)
#print a template for the c... |
ced82634722c4074b69e5f8fa84022a646eda16f | andyyang777/PY_LC | /383_另外一种解法.py | 1,049 | 3.6875 | 4 | # Given an arbitrary ransom note string and another string containing letters fr
# om all the magazines, write a function that will return true if the ransom note
# can be constructed from the magazines ; otherwise, it will return false.
#
# Each letter in the magazine string can only be used once in your ransom no... |
dcc6534a97d9347cbc29a4332253a3b91dbe6fdb | Cremily/text-adventure | /Chooseyourownadventure.py | 11,167 | 3.5 | 4 | global PLAYER_INV
PLAYER_INV = {}
GAME_ON = True
from colorama import init
init()
from colorama import Fore,Back,Style
def read_inventory():
if len(PLAYER_INV) == 0:
print("You aren't carrying anything!")
return False
inv_string = "You have the "
for count,key in enumerate(PLAYER_... |
f4fd7dd2b920178b27f21762af3cb1f4a1aff91b | iNateDawg/Craft | /normalize.py | 4,663 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import cv2
# Takes height and width as parameters
# sets and gets values in array
# returns and array
class NormArray:
def __init__(self, height, width):
self.height = height
self.width = width
self.array = np.arange(self.height * self.wid... |
9171139f88726e7544264bad4d0a71c022bc51ea | riddhisharma2019/PYTHON-EXAMPLES | /fabonnici.py | 346 | 3.84375 | 4 | def fib(n):
a= 0
b= 1
print(a)
print(b)
for i in range(2,n): # range is from 2 bcz 0 and 1 is already print
c= a+b #this swapping is used for the forward nos
a=b
b=c
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.