blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d3218f0926f505c81450576b0abc5103e854a310 | iamkroot/misc-scripts | /bill-split/bill_split.py | 9,085 | 4.03125 | 4 | """
This is a simple script to split bill expenses among various people.
Its main inputs are
1. A TSV file of Bill with columns- quantity,name,price. Usually OCR'd from some service
The first line of the bill should look like "!paid: 1234.00"
This will be used to account for any taxes/discounts in the final pai... |
e2b94c6772f690650a6f9683b19cce8b9509a01d | Index197511/AtCoder_with_Python | /Kyou45.py | 138 | 3.671875 | 4 | q = int(input())
for i in range(q):
tmp = input()
if tmp == "2":
else:
tmp = tmp.split()
functnion
|
f73a73744f8ec488c89d2731ce487c008bb28859 | subbuinti/python_practice | /functions/atmpinvaidation.py | 511 | 3.8125 | 4 | def validate_atm_pin_code(pin):
# Complete this function
is_valid = True
is_having_four_or_six_char = (len(pin) == 4) or (len(pin) == 6)
if is_having_four_or_six_char:
is_all_digits = pin.isdigit()
if not is_all_digits:
is_valid = False
else:
is_valid =False
... |
81f35419460f1a495cdab5022c474a0a35d26087 | byblivro/meep | /meeplib.py | 6,046 | 3.546875 | 4 | import pickle
"""
meeplib - A simple message board back-end implementation.
Functions and classes:
* u = User(username, password) - creates & saves a User object. u.id
is a guaranteed unique integer reference.
* m = Message(title, post, author) - creates & saves a Message object.
'author' must be a Use... |
4ab4c45c2dce0f816c22a2fa54901dcac8fbf987 | cy-arduino/leetcode | /37. Sudoku Solver.py | 2,021 | 3.75 | 4 | digit=['1','2','3','4','5','6','7','8','9']
def recursive(board: 'List[List[str]]') -> 'bool':
for row in range(9):
for col in range(9):
if board[row][col]=='.':
for i in digit:
#check same row
if i in board[row]:
#... |
a13cd74fbfd9331566d1ba454482a743ad1e74dd | YiFeiZhang2/HackerRank | /python/regex_and_parsing/sub.py | 219 | 3.765625 | 4 | #!/usr/local/bin/python3
import re
for _ in range(int(input())):
#ptrn = re.compile(r"\s([&]|[|]){2}\s")
print(re.sub(r"(?<=\s)([&]{2}|[|]{2})(?=\s)", lambda x: "and" if x.group() == '&&' else "or", input()))
|
927aefdc1411a813c1fae0a821b7a8d8e323c1f5 | ieaiea/studyRepo | /Python/Python/Basic/chap_04/def01.py | 587 | 4.15625 | 4 | # 기본함수
def helloDef():
print('hello Def!!')
helloDef() # hello Def!!
# return
num = 5
num2 = 10
def add(a, b):
return a + b
print(add(num, num2)) # 15
# 함수안에 함수선언
def outter():
print('outter')
def inner():
print('inner')
inner()
outter()
# *args
def add(*args):
result = 0
f... |
4cf77af5e1ca49be2c72f20926b7cc2e1430adc3 | KadonWills/code-snippets | /python/basics/Repetition.py | 604 | 4.34375 | 4 | # Example of a for loop
words = ['I', 'like', 'to', 'learn', 'python']
for word in words:
print(len(word), word)
# example of the range function
for i in range(5):
print(i)
# Break and continue
v = 0
for i in range(1,10):
if i < 5:
continue
if i == 7:
break
v = i
print("v ... |
66a175024183eff296acae1a7df6f1666ed59ccd | robisonJohn/Data-Structures-and-Algos | /closest-value-bst/closest-value-bst.py | 1,643 | 3.8125 | 4 | # Solution 1 - Average case space-time complexity of O(log(n)) time | O(log(n)) space
# Worst case space-time complexity of O(n) time | O(n) space
'''Conceptually, I am still a bit buzzy on Binary Trees. I will need to devote a weekend or two in order to better understand
them. '''
def findClosestValueInBst(tree, tar... |
0c1903d1771688a5ab88944acb032f0db14ac091 | lukaspblima/Estudo_Python | /exe034_aumento_salario.py | 219 | 3.796875 | 4 | sal = float(input('Digite o valor do seu salário: R$'))
if sal < 1250:
print('Seu novo salário é: R${:.2f}'.format(sal+(sal*0.15)))
else:
print('Seu novo salário é: R${:.2f}'.format(sal + (sal * 0.10))) |
13d28090ad002c98cf5d4d78cd135e3ff1fff189 | v1ct0r2911/semana12 | /ejercicio1.py | 216 | 3.828125 | 4 | #1. Elabore una función que
# tome como argumento dos números enteros
# y devuelva el mayor.
def mayor(a, b):
if a>b:
return a
else:
return b
numero_mayor=mayor(10,20)
print(numero_mayor) |
55b95f13f28eab8c0ad70088f421c7bd0d354c0d | ddian20/comp110-21f-workspace | /exercises/ex01/numeric_operators.py | 753 | 4.28125 | 4 | """EX01: Practicing Numeric Operators."""
__author__ = "730292529"
left_hand: int = int(input("Left-hand side: "))
right_hand: int = int(input("Right-hand side: "))
exponent_calculation: int = int(left_hand ** right_hand)
print(str(left_hand) + str(" ** ") + str(right_hand) + " is " + str(exponent_calculation))
divi... |
fdca258634cd1c5d5e80416347e2f0fbc93f33de | cnachteg/Notes_Master_BIOINFO_ULB | /Techniques_of_AI/projectCharlotteetHelene2017/Neuron.py | 573 | 3.578125 | 4 |
import random
import math
class Neuron() :
def __init__(self, inputsSize) :
self.weights = []
for i in range(inputsSize + 1):
self.weights.append(random.random()*6-3)
self.size = len(self.weights)
def setWeights (self, weightsList) :
self.weights = we... |
8dbd355a5f8196db66b70a39facb3c16d7a64abe | lilkeng/CodingChanllege | /leetcode/python/letter_combinations_of_a_phone_number/solution1.py | 857 | 4 | 4 | '''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
'''
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
... |
04422be26f10ef34d4f8c9092d9c94f6d79b3756 | julianconstantine/python-ds | /Introduction/infinitemonkey.py | 609 | 3.78125 | 4 | __author__ = 'Julian'
import random
def randString(lenstr):
alphabet = "abcdefghijklmnopqrstuvwxyz "
randstr = ""
for n in range(lenstr):
index = random.randrange(27)
randstr += alphabet[index]
return randstr
def strScore(test, target):
score = 0
for j in range(len(target)... |
ca582328e42eef489bacf7142aebda37213eb201 | kimth007kim/python_choi | /python/11주차/11_02.py | 734 | 3.640625 | 4 | from tkinter import *
window = Tk()
window.title("My Calculator")
display = Entry(window, width=33, bg="yellow")
display.grid(row=0,column=0,columnspan=5)
button_list=[
'7','8','9','/','C',
'4','5','6','*',' ',
'1','2','3','-',' ',
'0','.','=','+',' ' ]
def click(key):
if key == "=":
result= eval(display... |
4ab83fbef9ab284999b4878227f30138755f6053 | MajorTomaso/DQS | /ViewSummativeAnswers.py | 4,455 | 3.6875 | 4 | from tkinter import *
class introPage(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.createPage()
def createPage(self):
lblProg = Label(self, text='Summative Answers', font=('MS', 12,'bold'), width = "20", height = "3")
lblProg.grid(r... |
e10bcb2b3efeafb3cb260c30b3ee827840011dca | senatn/learning-python | /get-area.py | 1,338 | 4 | 4 | import math
def getArea(shape):
shape = shape.lower()
if shape == "r":
rectangleArea()
elif shape == "c":
circleArea()
elif shape == "t":
triangleArea()
else:
print("Please enter 'r', 'c' or 't' ")
return main()
def rectangleArea():
try:
lenght ... |
baa0b531536d30523ddfd743b4ef69c09b00a78e | MAZTRO/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 491 | 3.75 | 4 | #!/usr/bin/python3
def read_lines(filename="", nb_lines=0):
with open(filename, encoding='utf-8') as my_file:
if nb_lines <= 0:
my_file.seek(0)
print(my_file.read(), end='')
elif (nb_lines > len(my_file.readlines())):
my_file.seek(0)
print(my_file.read... |
85e96f7d7a46a2deda7431af5e92d11fa106c09d | 0xChrisJL/easy-python | /106_不那么枯燥的猜数游戏.py | 1,313 | 3.9375 | 4 | # 作者:西岛闲鱼
# https://github.com/globien/easy-python
# https://gitee.com/globien/easy-python
# 不那么枯燥的猜数游戏
import random
very_happy = "小蟒今天开心极了,你来猜猜我的心情指数?"
happy = "小蟒现在挺高兴,你猜猜我的心情指数是多少?"
so_so = "小蟒现在感觉还行吧,你想知道我的心情指数是多少吗?"
sad = "小蟒现在不太高兴,你猜猜我的心情指数吧。"
very_sad = "小蟒今天很不开心,要猜你就猜小一点的数字吧。"
level_list = [very_sad, sad, s... |
819af40b6a91033b9069539241c797fa9691485f | hallnath1/AdventOfCode2020 | /day2/day2.py | 562 | 3.53125 | 4 | countA = 0
countB = 0
with open('input.txt') as file:
for line in file:
lineList = line.strip("\n").split(" ")
policy = lineList[0].split("-")
min = int(policy[0])
max = int(policy[1])
character = lineList[1][0]
charCount = lineList[2].count(character)
if... |
df3360517501b8c5ff4af909df94f84d05579ffc | anulrajeev/MA-323-Monte-Carlo-Simulation | /LAB 8/180123057_MOHAMMAD_HUMAM_KHAN.py | 2,773 | 3.546875 | 4 | ##To run the code type in terminal: python3 180123057_MOHAMMAD_HUMAM_KHAN.py
import math
import random
import numpy as np
import pandas as pd
import statistics
import matplotlib.pyplot as plt
# Function to read adjusted closing price from csv file
def Read_Data():
df = pd.read_csv('SBIN.NS.csv',usecols=['Adj Close'... |
e0c72964b1294736be1d457254f33beb465d5d37 | HalfMoonFatty/Interview-Questions | /131. Palindrome Partitioning.py | 988 | 3.671875 | 4 | '''
Problem:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
'''
class Solution(object):
def partition(self, s):
def isValid(s,start,end):
... |
d7ce11a933406b42abd6021510c741ca9b9845e8 | alecodigo/Python | /login_system.py | 471 | 3.5625 | 4 | # -*- coding:utf-8 -*-
PASSWORD = '123456*'
def proof_id(passwd):
if passwd:
if PASSWORD == passwd:
return True
else:
return False
if __name__ == '__main__':
print("Welcome Enter Your Secret Password")
passwd = input("password: ")
print(passwd)
if passwd:
... |
647594c027a5e72b5f3227ae5048814e42167f95 | AishaDhiya/python | /pyramid.py | 151 | 3.953125 | 4 | def pyramid(n) :
for in range(1,n+1):
for j in range(1,i+1):
print(i*j , end+"")
print("in")
n= int(input("enter step number:"))
pyramid(n)
|
59a59c41d7eeb90a6bad52dd4472ed9540b20419 | shishuaigang/pythonProject | /3.py | 1,084 | 4.15625 | 4 | # 各种简单的排序
import random
def selectSort(List):
# 选择排序,依次将最小的值放置在列表的最左边
i = 0
while i < len(List) - 1:
minVal = List[i]
for j in range(i + 1, len(List)):
if List[j] < minVal:
minVal = List[j]
List[i], List[j] = List[j], List[i]
i += 1
r... |
0d8eec432e6978f5607a4047912dfc2665ca436e | lostarray/LeetCode | /001_Two_Sum.py | 1,008 | 3.859375 | 4 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
#
# You may assume that each input would have exactly one solution.
#
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
#
# Tags: Array, Hash Table
... |
1c7fcde3e2f10e7c81e993de10eda4205688cb9f | spud-bud/exercism_python | /rna-transcription/dna.py | 321 | 3.75 | 4 | transcription_dict = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
# def to_rna(dna):
# result = []
# for letter in dna:
# result.append(transcription_dict[letter])
# return ''.join(result)
def to_rna(dna):
result = ''
for letter in dna:
result += transcription_dict[letter]
return result... |
14df18b3f8a29ee4fc8e961396c1004cbaf68802 | cvasani/SparkLearning | /Input/Notes/python_course/tuples/practice_exercises/solution_01.py | 328 | 3.921875 | 4 | #!/usr/bin/env python3
airports = [
("O’Hare International Airport", 'ORD'),
('Los Angeles International Airport', 'LAX'),
('Dallas/Fort Worth International Airport', 'DFW'),
('Denver International Airport', 'DEN')
]
for (airport, code) in airports:
print('The code for {} is {}.'.format(airport, c... |
79e4583f1c0207caafb490380de352492cd50475 | cendongqi/python-example | /example/list_tuple.py | 1,082 | 4.34375 | 4 | classmate = ['Mike', 'John', 'Rose']
# 取值
print(classmate)
print(len(classmate))
print(classmate[0])
print(classmate[1])
print(classmate[2])
print(classmate[-1])
print(classmate[-2])
print(classmate[-3])
print('----------')
# 末尾追加
classmate.append('adam')
print(classmate)
# 插入
classmate.insert(2,'Jack')
print(class... |
aafcc9e47a69ea44873fd15619a5db8a889b58a9 | samiCode-irl/programiz-python-examples | /Functions/power_of_2.py | 203 | 4.25 | 4 | # Python Program To Display Powers of 2 Using Anonymous Function
terms = 10
result = list(map(lambda x: 2 ** x, range(terms)))
for i in range(terms):
print(f'The power of 2 of {i} = {result[i]}')
|
3844bea4eece8785a879da84541b98fdc05cb8c3 | imachuchu/Checkers-CCAINN | /board.py | 7,753 | 3.953125 | 4 | """ A representation of a checker board
Ben Hartman 3/4/2012
"""
import random #For random generation functions
import itertools #For sweet fast list functions
import math #For the e constant
import copy
class board():
""" Represents one checker board
"""
def __init__(self):
"""Creates a starter board
The ... |
54f66ece22bdf0f2ef20292fb9a9e9d2f429b5e2 | Th3Lourde/l33tcode | /270.py | 555 | 3.5 | 4 | class Solution:
def closestValue(self, root, target):
self.ans = float('-inf')
def dfs(node, target):
if not node:
return
if abs(target - node.val) < abs(target - self.ans):
self.ans = node.val
if node.val >= target and node.left... |
43b863415585ace675d7034f6ff831753cf05a56 | JunctionChao/LeetCode | /LinkedList/link_list_fun.py | 590 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2019-09-22
# Author : Yuanbo Zhao (chaojunction@gmail.com)
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 根据数据生成链表 逆序生成链表
def generateNum(numList: list) -> ListNode:
root = ... |
962f80e27ded1976bee08f06b2351a51caa45987 | MonaHe123/coding-exercise | /p_code/RL/MDP/test.py | 132 | 3.84375 | 4 | args = []
arg = ["1","2","3"]
args += [i for i in arg]
print(args)
num = [1]
num2 = [2]
num2 += num
print(num2)
print("_".join(arg)) |
f4720554007f9071e2ee4ad4fe291b3f01ceb1bf | mubaarik/AI | /lab5/lab5.py | 11,753 | 3.515625 | 4 | # MIT 6.034 Lab 5: k-Nearest Neighbors and Identification Trees
# Written by Jessica Noss (jmn), Dylan Holmes (dxh), and Jake Barnwell (jb16)
from api import *
from data import *
import math
log2 = lambda x: math.log(x, 2)
INF = float('inf')
############################################################################... |
ce50d1caccd5127e94769b36df37d30f3b664bb0 | victsnet/Geoanalytics-and-Machine-Learning | /SOM-Remote Sensing-Geology/toolbox.py | 6,859 | 3.59375 | 4 | from tqdm import trange
import numpy as np
import matplotlib.pyplot as plt
def window3x3(arr, shape=(3, 3)):
r_win = np.floor(shape[0] / 2).astype(int)
c_win = np.floor(shape[1] / 2).astype(int)
x, y = arr.shape
for i in range(x):
xmin = max(0, i - r_win)
xmax = min(x, i + r_w... |
7970b4a3c3e079573bd61513f6e1670c026cd7d7 | parth3033/python-problems | /sumevennumber.py | 105 | 3.78125 | 4 | sum=0
for i in range (1,31):
if(i==10 or i==20):
continue
elif(i%2==0):
sum=sum+i
print(sum)
|
982793670d17cf2757f19788bd0e4d5ca98a1d5d | kanwar101/Python_Review | /src/Chapter07/pets.py | 116 | 3.796875 | 4 | pets = ['dog','cat','mouse','fish','cat','ant']
print (pets)
while 'cat' in pets:
pets.remove('cat')
print (pets) |
a366d1c83a2f111d1f05a2de03f609a4e158a2ae | MargauxMasson/useful_scripts | /change_file_extension.py | 508 | 3.84375 | 4 | import os
import glob
# Path to directory with the files that need a new extension
path_to_directory = './path_to_directory_with_files_that_need_new_extension'
current_extension = '.png'
new_extension = '.jpg'
list_files = glob.glob(path_to_directory + '/*' + current_extension)
for path_to_file in list_files:
pr... |
1fae33240386d73315c2f17846876414524adf2b | iliyankrastanov/Python | /file39.py | 535 | 3.765625 | 4 | def foo(a):
a = 10
print(f"a = {a}")
def sort_values(values):
values.sort()
def bar(a = [], b = {}):
print(f"a = {a}")
print(f"b = {b}")
print("- " * 20)
n = len(a)
a.append(n)
b[n] = n
if __name__ == "__main__":
#1.
#x = 100
#foo(x)
#print(f"x = {x}")
#2.
... |
61e5beadf41baf3e6905d487f1f1e1ed77e3b90a | edu-athensoft/stem1401python_student | /py210116f_python3a/day10_210403/sample/label_15_config_counter_2.py | 791 | 3.546875 | 4 | """
lable counter 2
optimizing
optimization
optimize
refactor
refactoring
"""
# import tkinter as tk
from tkinter import *
def start_counting(mylabel):
print("entered start_counting()")
counter=0
def counting():
nonlocal counter
counter = counter + 1
mylabel.config(text=str(... |
86c1db89b3397a93110f1c8f4ca4a1e48c042748 | 2017100235/Mix---Python | /Skill curso em video - Python - mundo 2/desafio 65.py | 494 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 00:34:42 2019
@author: juan
"""
soma = maior = menor = num = int(input('Numero: '))
cont = 1
resp = str(input('Quer continuar [S/N]: '))
while (resp.lower()=='s'):
num = int(input('Numero: '))
if num > maior:
maior = num
if num < menor:
me... |
b7a333a93c492c59d08235bd9350af3057c5b06c | ananda-wahyu-nur-said/I0320124_Ananda-Wahyu-Nur-said_Aditya-Mahendra_Tugas4 | /I0320124_Exercise4.9.py | 98 | 3.609375 | 4 | #Exercise 4.9
#string
str = "Hello World"
#substring
substr = str[3:5]
#Otput
print(substr) |
13e2c50f46462545cdf58cb78c0c14e6add57330 | rafaelperazzo/programacao-web | /moodledata/vpl_data/310/usersdata/278/84210/submittedfiles/investimento.py | 276 | 3.5 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
#COMECE SEU CODIGO AQUI
ii = float(input("Digite o valor do investimento inicial: " ))
cp = float(input("Digite a taxa de crescimento percentual [0,1]: "))
t=1
m=0
while (t<=10):
total = ii*(1+cp)+m
print(total) |
f6923d07c5006ccc9777822f320b57c43d0de333 | JamesDoane/practical_python_practice | /num_guess_game.py | 843 | 4.03125 | 4 | import random
def the_game():
num_to_guess = random.randint(1,100)
player_name = input("What's your name?\n")
player_guess = int(input(player_name + ", I'm thinking of a number between 1-100.\nGuess my number:\n"))
counter = 1
while player_guess != num_to_guess:
if player_guess > num_to_... |
7c441a727489fca80448b861b583a35461ab9f5d | pythonnewbird/LeetCodeSolution | /6.13/99.恢复二叉搜索树hard.py | 802 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.pre=None
self.p1=None
self.p2=None
def inorder(self,root):
i... |
910d0f82585e466e0fe03549fdcb535cd6d1e83a | udayt-7/Python-Assignments | /Assignment_1_Basic_Python/s1p21.py | 252 | 4.125 | 4 | #to Calculate the Number of Upper Case Letters and Lower Case Letters in a String
i = input("Enter the string:")
c1=0
c2=0
for ch in i:
if (ch.isupper()):
c1+=1
if (ch.islower()):
c2+=1
print("Uppercase: ",c1)
print("Lowercase: ",c2) |
40470fa87486b21d6978617399824595e4aba44a | daivikvennela/python-udemy | /EZGrader.py | 240 | 3.828125 | 4 | Correct = eval(input("Total Correct: "))
#Total = eval(input("Total Problems: "))
Total = 65
Result = round((Correct/Total)*100,2)
print(Result, "%")
if Result >= 73 :
print("You passed, Congrats!")
else :
print("You failed")
|
dcbd61300fd8da1f75646f0b328158ce6099fc4b | z2labplus/algorithm-python | /algorithm/sort/basic_sort.py | 3,400 | 4 | 4 | """
python3.6.4
@Date : "2018-10-15"
@Author :"HerryZhang"
#Reference :https://time.geekbang.org/column/article/41802
"""
def bubble_sort(raw_list):
"""
冒泡排序
"""
flag = False
list_len = len(raw_list)
for i in range(list_len):
for j in range(list_len - i - 1):
if raw... |
5dcc3a6fe3e9699ca03c05db59813a41961b5a27 | xioperez01/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 364 | 3.609375 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
imput = len(sys.argv) - 1
if imput == 1:
print("{} argument:".format(imput))
elif imput == 0:
print("{} arguments.".format(imput))
else:
print("{} arguments:".format(imput))
for i in range(imput):
print("{... |
2de37bf6e52364dc8f53a84305a9a838ffe66f49 | smuhit/2019-advent-code | /day-01/solver.py | 379 | 3.6875 | 4 |
data = open('input').read().split()
# PART 1
fuel = 0
for datum in data:
fuel += int(datum) // 3 - 2
print('Fuel needed is', fuel)
# Part 2
fuel = 0
for datum in data:
fuel_needed = int(datum) // 3 - 2
fuel += fuel_needed
while fuel_needed > 5:
fuel_needed = int(fuel_needed) // 3 - 2
... |
0faf9ec3892740cf45f0f36508b3410e8a53f1b6 | Leetcode-tc/Leetcode | /python/500/Keyboard_Row.py | 1,021 | 3.671875 | 4 | class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
wordList = ['QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM']
res = []
for x in words:
line = 0
for i in range(3):
if x[0].upper() ... |
7cd9545035216117ec9f87af1746090dd3872075 | iWonder118/atcoder | /python/ABC192/B.py | 346 | 3.8125 | 4 | import string
word = list(input())
odd_count = 0
even_count = 0
for i in range(len(word)):
if (i + 1) % 2 == 1 and word[i] in string.ascii_lowercase:
odd_count += 1
elif (i + 1) % 2 == 0 and word[i] in string.ascii_uppercase:
even_count += 1
if odd_count + even_count == len(word):
print("Ye... |
63503e5276c6a9b5dcd4bf8b34864eb1bc101199 | fedalza/lighthouse-data-notes | /Week_4/Day_5/.ipynb_checkpoints/question_04-checkpoint.py | 1,031 | 3.984375 | 4 | """
- Connect to the hr.db (stored in supporting-files directory) with sqlite3
- Write a query to get the department name and number of employees in the department.
- Sort the data by number of employees starting from the highest.
Expected columns:
- department_name
- number_of_employees
Notes:
- Us... |
2486fa5e6ea3a7f2cb21504dc06aa731e45767e6 | Aasthaengg/IBMdataset | /Python_codes/p03068/s698180922.py | 148 | 3.5 | 4 | N = int(input())
S = [str(x) for x in input()]
K = int(input())
for a in range(N):
if not S[a] == S[K - 1]:
S[a] = '*'
print(''.join(S)) |
d11e38226320958613cd73e7d270db517e3eaff9 | llgeek/leetcode | /37_SudokuSolver/solution.py | 2,424 | 3.640625 | 4 | """
wrong ans
"""
from typing import List
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not any(board) or len(board) != 9 or len(board[0]) != 9:
return
self.solver(board)
... |
55168870a72cb358ad548f8253d7f5436b4275d5 | gomtarus/KH_QClass | /Workspaces09_Python/Python00/opr.py | 852 | 3.96875 | 4 | # 산술연산
a = 21
b = 2
print(a + b)
print(a - b)
print(a * b)
print(a ** b) # a의 b승
print(a / b)
print(a // b) # 몫 (floor division)
print(a % b)
# 비교연산
a, b = 5, 3
print(a == b)
print(a != b)
print(a > b)
print(a >= b)
print(a is b)
print(a is not b)
# 범위연산
list01 = list(range(100)) # 0 ~ 99
print(list01)
# [star... |
5c44dd3664e533ec2f3222d4f1853679227d1c79 | muchikon/Curso-python | /Objetos5.py | 773 | 3.75 | 4 | class Persona():
def __init__(self,nombre,edad,lugar_residencia):
self.nombre=nombre
self.edad=edad
self.lugar_residencia=lugar_residencia
def descripcion(self):
print("Nombre: ",self.nombre," Edad: ",self.edad," Residencia: ",self.lugar_residencia)
class Empleado(Persona):
def __init__(self,salario,antigued... |
8b3c5d4317b91028e765182667ff4404d8fbf875 | RoundingExplorer/rock-paper-scissor | /game/main.py | 856 | 3.921875 | 4 | import random
import os
no_of_games = 3
games_played = 0
choices = ['rock' , 'paper' , 'scissor']
def rock():
computer_choice = random.choice(choices)
if computer_choice == 'paper':
print("Computer wins")
games_played = games_played + 1
else:
print("You win")
games_played = games_played +... |
ab463c8e4ab203f5f8b45c93c88a3c511bf30ddd | yakobie/homework | /exercise 11/eleventh.py | 304 | 4 | 4 | num = int(raw_input("How many fibbonaci numbers would you like to generate?:"))
def fibnum(amt):
loop = 0
first = 0
second = 1
next = 0
while loop < amt:
loop += 1
if loop <= 1:
next = loop
else:
next = first + second
first = second
second = next
print(next)
fibnum(num)
|
e7a8e3081761561f5f5658d36f1026f9fb1cb478 | vaishnavinalawade/Python-Programs | /Find_Armstrong_Number.py | 254 | 4.28125 | 4 | /*
* problem description : program to find if the given number is an armstrong number
*/
n = int(input("Enter the number:"))
t = n
s = 0
while t>0:
r = t%10
s += r**3
t //= 10
if n == s:
print "{x} is an Armstrong number".format(x = n)
|
b7877042a7467dc14cedf32dc116c082cec88e06 | caesarii/learning-python | /chapter-26/first-class.py | 413 | 3.515625 | 4 |
class FirstClass:
def setData(self, value):
self.data = value
def display(self):
print(self.data)
x = FirstClass()
y = FirstClass()
x.setData('caesar')
x.display()
x.data = 'new name'
x.display()
y.setData('qinhge')
y.display()
class SecondClass(FirstClass):
def display(self):
... |
c21dd6f27f9e4b5386570439dd091ae79c28aec9 | jakszewa/Python-Notes | /Examples/what_is_if_name_and_main.py | 1,283 | 4.34375 | 4 | #What is the meaning of 'if __name__ == '__main__':
#let see what is __name__ by default
print('This is first module ' + __name__)
#Other way of writing
print("First Module's Name: {}".format(__name__))
'''
OUTPUT: __main__
what is happening over here?
When python run any code it sets a few special variables
__name_... |
d253f1ad88d60d1e9e0990ed5a0120ff3cc5eb83 | JaD33Z/random-functions-reference-solutions-cheat-sheet | /main.py | 6,246 | 4.09375 | 4 | ########## SPARE-PARTS ##########
########## MY BIN OF RANDOM FUNCTIONS FOR VARIOUS THINGS ###############
######## A PYTHON PROBLEM-SOLVING SOLUTIONS REFERENCE SHEET ##################
############## RETURNING STRINGS:
def greet(name):
return ("Hello, " + name + " how are you doing today?")
... |
cdc76de467aec8a1ca98e96ba9c827af650caa63 | Zchhh73/Python_Basic | /chap15_sql/db_connect.py | 1,021 | 3.59375 | 4 | import pymysql
connection = pymysql.connect(host='localhost',
user='root',
password='1234',
database='MyDB',
charset='utf8')
# 有条件查询
# select name,userid from user where userid > ? order by userid
'''
t... |
d062298505618adcdf47314b6ad7f77b8b25d4cc | saadbinmanjur/CodingBat-Codes | /Logic-2/close_far.py | 431 | 3.796875 | 4 | # Given three ints, a b c, return True if one of b or c is "close" (differing
# from a by at most 1), while the other is "far", differing from both other
# values by 2 or more.
def close_far(a, b, c):
return (is_close(a, b) and is_far(a, b, c)) or \
(is_close(a, c) and is_far(a, c, b))
def is_cl... |
0775cd34abbcfb8c2c25492af8b2628c642bd9ed | jjb33/PyFoEv | /Chapter09/exercise.py | 1,214 | 4.34375 | 4 | """
Write a program that categorizes each mail message by
which day of the week the commit was done. To do this look for lines
that start with “From”, then look for the third word and keep a running
count of each of the days of the week. At the end of the program print
out the contents of your dictionary (order does no... |
b9f1bf0c6e412df48695e7ea1442cc6ecf53bb73 | nancyletranx3/employment_mgmt_system | /employment_mgmt_sys_two.py | 6,852 | 3.671875 | 4 | # CS/IS-151 Spring 2020
# Nancy Tran
# Phase 2
import pickle as p
def main():
intro()
file_name = 'employee.dat'
db = load(file_name)
exit = False
while not exit:
print("Main Menu:")
print("1. Add an Employee")
print("2. Find an Employee (By Employee I... |
5ecdd8a6447f34ab58f95c972891cfc0803a304c | 1411279054/Python-Learning | /Data-Structures&Althorithms/力扣算法/十月份算法题/(10.2)36. 有效的数独.py | 2,831 | 3.5625 | 4 | # class Solution:
# def isValidSudoku(self, board: list[list[str]]) -> bool:
# result = True
# matrix = [[] for i in range(1,10)] #创造九个向量:判断列是否满足条件
# matrix_nine = [[] for i in range(1, 10)] # 创造九个向量:判断九格是否满足条件
# for i in board:
# points = [] # 提取出每行点的数量
# nu... |
49bedf3b24f570d2003fbfe305193372dfc97212 | himanij11/Python---Basic-Programs | /GUI/radio_button.py | 506 | 4.09375 | 4 | import tkinter as tk
root=tk.Tk()
v=tk.IntVar()
v.set(0) #initializing the choice i.e.Python
languages=[("Python",1),("Perl",2),("Java",3),("C++",4),("C",5)]
def ShowChoice():
print(v.get())
tk.Label(root,text="""Choose your favourite programming languages:""",justify=tk.LEFT,padx=20).pack()
... |
86b1339ede28031617e50bc76d36da6394624192 | RossouwVenter/Python-crash-course | /Chap08/Example.py | 1,431 | 3.96875 | 4 | # Functions
def pets(PetType,PetName,PetColour,PetAge):
print('\nmy pets are')
print(f'I have a {PetType}')
print(f'Her name is {PetName}')
print(f'She has {PetColour} fur')
print(f'She is still young at an age of {PetAge}')
pets('Dog','Nyla','White',f'6 months')
pets('Dog','luca','White',f'14 years')
print('\n'... |
f0cec744857518e4065f911639b35305b0ba31ce | Palleri-Aju/Python-files | /Experiment4.py | 6,334 | 4.46875 | 4 | '''
Experiment -4
Name :
Class: SE-IT
Div :
Roll number:
--------------------------------------
Topic : Python Tuple
Aim: Write a menu driven program to demonstrate the use of nested tuples in python
1.Display All student records
2.Search a student and display ... |
58d91fa25fa5afe7bd4ed6c817bd135b24a545ec | priyankapadhu/python-doc | /ex3.py | 152 | 3.71875 | 4 | a=17
b=32
c=31
if(a>b)&(a>c):
print("a is greatest")
elif(b>c):
print("b is greatest")
else:
print("c is greatest")
|
b324dc0ebf997f11053c509237b3cd24b530c6e8 | gvassallo/LeetCode | /235-LowestCommonAncestor.py | 1,148 | 3.8125 | 4 | # Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
#
# According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between
# two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a
# node to be a d... |
9fc546c66dfbbedd4ae246829513f3f96c0321d4 | linmenggui/Udacity-Project-3-Data-Wrangling | /update_phone_number.py | 609 | 4.03125 | 4 | # this code is written in python 3
import re
def is_phone_number(elem):
"""
Return True if the value of the operands are equal. Return False otherwise.
"""
return elem.attrib["k"] == "phone"
def phone_fixer(phone):
"""
Return a phone number after striping its whitespaces or non-digit character... |
e80d7fde0a05a58d964bab752812a6ef43955d01 | tushar-rishav/Upwork | /pyautogui/main.py | 2,543 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Extract textual data from a given html document
sample url:
https://www.sec.gov/Archives/edgar/data/1594109/000156459015001303/grub-10k_20141231.htm
"""
from docx import Document
import openpyxl
from openpyxl import Workbook
from openpyxl.writer.write_only import WriteOnlyCell
import o... |
65e01bb60ae81d74afd8043605c0d34878eea33c | tillyoswellwheeler/module-02_python-learning | /ch08_mobile-data-bundle-programme/databundle-project/project/lib/databundle_lib.py | 2,521 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 09:38:32 2018
@tillyoswellwheeler: 612383362
"""
#Check user state, they are registered or unregistered
class User(object):
def __init__(self, username, passcode):
self.username = username
self.passcode = passcode
def ask_user_state(self, ... |
cae4218512558bcaec98350606d1d7573fa3923b | andreinaoliveira/Exercicios-Python | /Exercicios/090 - Dicionário.py | 460 | 3.921875 | 4 | # Exercício Python 090 - Dicionário
# Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário.
# No final, mostre o conteúdo da estrutura na tela.
aluno = {'Nome': str(input('Nome: ')).strip(),
'Média': float(input('Média: '))}
if aluno['Média'] >= 7:
aluno[... |
4a4e97d18fb1663907f32703ac7914a731df9da4 | siddharth20190428/DEVSNEST-DSA | /DA018_Range_sum_of_BST.py | 1,156 | 3.703125 | 4 | """
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
---------------
Constraints
The number of nodes in the tree is in the range [1, 2 * 10^4].
1 <= Node.val <= 10^5
1 <= low <= high <= 10^5
All Node.val are unique.
"""
def dll(root):
if no... |
ee7c20e7c32f8e88efc4cf1a688d8978cb7b959f | HossamOWL/pyhack | /Pyhack_Python/salle.py | 3,245 | 3.734375 | 4 | #!/usr/bin/python3
"""
Le fichier salle.py crée un objet Salle
en indiquant les coordonnées du point
haut_gauche de la salle, sa largeur et
sa hauteur.
"""
from random import randint, choice
from point import Point
class Salle(Point):
'''
Cette classe, qui hérite de la classe Point,
permet d'afficher des ... |
96d173eabaa882616f1af22bb64d6ad6897bf7cf | manjeet-haryani/python | /exceptionalhandling/demo.py | 534 | 3.734375 | 4 | import logging
logging.basicConfig(filename="mylog.log",level = logging.DEBUG)
try:
f = open("myfile.txt","w")
a,b = [int(x) for x in input("enter two numbers").split()]
logging.info("division in progress")
c = a/b
f.write("writing %d into the file" %c)
except :
print("Division by zero is not allowed")... |
20c5b6cf0604d3d1c14b295cf7bc7ae19b1524d7 | poppindouble/AlgoFun | /word_pattern.py | 693 | 3.765625 | 4 | class Solution:
# def wordPattern(self, pattern, str):
# if len(pattern) != len(str.split()): return False
# ptnDict, wordDict = {}, {}
# for ptn, word in zip(pattern, str.split()):
# if ptn not in ptnDict:
# ptnDict[ptn] = word
# if word not in wordDict:
# wordDict[word] = ptn
# if wordDict[wor... |
d28ea6378ffb6c230b91941ee3424f800d398a0b | IvanOmel/Homework_python_cur | /chapter_03/Ex_05.py | 325 | 3.96875 | 4 |
mass = float(input("Input mass: "))
weight = mass * 9.8
if(weight >= 500):
print("weight: ", round(weight, 2), "H")
print("body is too heavy")
elif(weight <= 100):
print("weight: ", round(weight, 2), "H")
print("body is too light")
else:
print("weight: ", round(weight, 2), "H")
print("body is... |
eb59b50591612cc354acad2340c183a587656a7f | mayartmal/python_course | /control_1_sum_in_for_loop.py | 118 | 3.84375 | 4 | n = int(input())
sum = 0
for i in range(0, n):
your_number = input()
sum = sum + int(your_number)
print(sum)
|
2588891eab3f227667a6803af6632af17d67eae4 | BrandonJonesSDMF/PythonTutorialsForTheHomies | /7_user_input.py | 387 | 4.03125 | 4 | name = input("Enter your name: ")
age = input("Enter your age: ")
'''now lets ask for some user input, we just assigned variables to hold the user input that will be taken from the terminal'''
print("Hello " + name + "!")
print("You're " + age + "? Ha! Nice.")
'''try this with your relatives credit card informatio... |
ee19aa61d1cc42c1139e43f1c5a512e5440778c0 | wdkang123/PythonOffice | /06-pandas_study/pandas_style.py | 935 | 3.765625 | 4 | import pandas as pd
# 实例化Series对象
s1 = pd.Series([1, 2, 3], index=[1, 2, 3], name="s1")
# 输出Series对象
print(s1)
# 输出Series对象的索引
print(s1.index)
# 输出Series对象中索引为1的值
print(s1[1])
# 输出结果
'''
1 1
2 2
3 3
Name: s1, dtype: int64
Int64Index([1, 2, 3], dtype='int64')
1
'''
print("---------------")
# 创建Series对象
s1 ... |
5f4d0246867fbde7bb253868c4e8b080750728f3 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2101/60696/280529.py | 1,356 | 3.59375 | 4 | happy_nums = [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
unhappy_nums = [4, 16, 37, 58, 89, 145, 42, 20]
def is_happy_num(num):
if num == 0:
return False
if num < 10:
if num * num in happy_nums:
return True
elif num * num in unhappy_nums:... |
a63cfe745e79c653f327ce412571f5c1966612a3 | pacospace/Advent_of_Code | /2017/day01_Inverse_Captcha/day1part1.py | 1,383 | 3.75 | 4 | # Advent of Code - Day 1 (Part 1)
def check_match(current_element, next_element, list_matches):
print()
print('---------------------------')
print('Element number:', current_element[1] + 1)
print('Current element is:', current_element[0])
print('Next element is: ', next_element[0])
if curren... |
c52082a6ce75a26cbfdaa4e1c01bb441105f2c21 | ValerianClerc/project-euler | /p2.py | 383 | 3.78125 | 4 | evenFibs = []
a = 0
b = 1
# iterate until larger number reaches 4000000
while b < 4000000:
# if this fibonacci number is even, add to list
if (a+b)%2 ==0:
evenFibs.append(a+b)
# increment fibonacci numbers, keeping b as the larger
temp = a+b
a = b
b = temp
# sum list of e... |
cc789f429a861ecaf3f865bed7652baa1afadd00 | asdfvar/gpnc | /math/ann/pyANN/ann.py | 5,532 | 3.90625 | 4 | #!/usr/bin/python3
# inputs are tensors which are defined as Python lists with dimensions like so:
# [batch, channel, 2-D numpy array]
#
# in some cases, they are expressed as [layer, batch, channel, 2-D numpy array]
import numpy as np
class ANN:
def __init__(self, layers, numChannels, actFunc, beta = 0.9):
... |
b91532ea5d83e32309e784194694e144306e1842 | JosewLuis/Curso-Machine-Learning-en-Espanol | /Validación-Evaluación/utilidad.py | 6,252 | 3.59375 | 4 | #Utilidad para nuestros problemas del curso.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
def ejemplo_regresion():
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from adspy_s... |
b0c56eba3ce98ef79e67ed8c04c40432933ebe10 | Algorant/HackerRank | /30_days_of_code/d09_recursion/recursion.py | 237 | 4.03125 | 4 | # Take in input n
n = int(input())
# Simple factorial function
def factorial(n):
start = 1
if int(n) >= 1:
for i in range(1, (n+1)):
start = start * i
return start
# Prints answer
print(factorial(n))
|
8a4dfd706d16db0a3a5d148d11ba2399def19641 | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_118.py | 940 | 4.1875 | 4 | def main():
SOLID_TEMP_CELSIUS = 0
GAS_TEMP_CELSIUS = 100
SOLID_TEMP_KELVIN = 273.15
GAS_TEMP_KELVIN = 373.15
tempNum = float(input("Please enter the temperature: "))
degreeType = input("Please enter 'C' for Celsius or 'K' for Kelvin: ")
if (degreeType == "C"):
if (tempNum <= SOLID_TE... |
f4b0f89ab16954c433a3a2122bac6564cba7cb13 | Crone1/College-Python | /Year One - Semester One/Week Seven/primes-1.py | 113 | 3.546875 | 4 | #! /usr /bin/env python
total = 0
i = 0
while i < len(a):
if isprime(a[i]):
print a[i]
i = i + 1
|
350c7708a0c3f756e91936580fce7caae89f15b5 | SteeveJose/luminarpython | /pattern/dimond.py | 216 | 4.3125 | 4 | num=int(input("enter the number:"))
def function(num):
for i in range(1,num+1):
print(" " * (num-i) + ("*" + " ") * i)
for i in range(num-1,0,-1):
print(" "*(num-i)+("*"+" ")*i)
function(num) |
ef05872a0f0bc7dcb90b9807d00dbe62128ab714 | peter1314/Space-Trader | /app/py/fleable.py | 537 | 3.765625 | 4 | """file for storing the Fleable ABC"""
from abc import abstractmethod
from .npc import NPC
class Fleable(NPC):
"""Defines an NPC that can flea"""
@abstractmethod
def give_flea_reward(self, player):
"""Gives a reward to a player if the escape"""
@abstractmethod
def give_flea_punishment(sel... |
f28ef5ef7796466a79f01a7976488ff91c78513e | urvib3/ccc-exercises | /hps.py | 1,752 | 3.640625 | 4 | def winner(p1, p2):
if(p1 == 1 and p2 == 2):
return True
elif(p1 == 2 and p2 == 3):
return True
elif(p1 == 3 and p2 == 1):
return True
def main():
try:
filein = open("hps.in", "r")
file = open("hps.out", "w")
print("files opened")
n = int(filein.re... |
5d385e605e5ef16e61030eaa84e327efd9a76dd7 | mark-boute/AandDp1 | /common/input.py | 1,254 | 3.828125 | 4 | """
Algorithms and Data Structures
Practicum 1
Mark Boute s1038503
Mark de Jong s1034829
Subpart:
Contains functions for reading the input from the server.
"""
from common.e_print import e_print
def get_input():
"""
Read the input and insert converted input into a dictionary.
:return:
p... |
32d40bdf37f9db862521b9a34aec36e4c4daf90c | chenp-fjnu/Python | /sqlite.py | 388 | 3.875 | 4 | import sqlite3
conn=sqlite3.connect('test.db')
cursor=conn.cursor()
#print(cursor.execute('create table user (id varchar(20) primary key, name varchar(20))'))
print(cursor.execute('insert into user(id, name) values(\'1\',\'Michael\')'))
print(cursor.rowcount)
print(cursor.execute('select * from user where id=?',('1',))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.