blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
470647bcf21f7e1e6ee0f3e2ea7aea5159c4ade9 | KalaiarasanK/CodeKata | /swap even and odd character.py | 187 | 3.984375 | 4 | #Given a string 'S' swap the even and odd characters starting from index 1(Assume the index starts from 0).
s = input()
t = list(s)
t[::2], t[1::2] = t[1::2], t[::2]
print(''.join(t) )
|
c76c5e46becd6e3c2e2fe9d09817309c601f7c68 | diveshuttam/fods | /hadoop/kmeans/kmeans_mapper.py | 1,507 | 3.5 | 4 | #!/home/ayushjain1144/anaconda3/bin/python
# Manage the fpath: file path of centroid
import sys
import math
import random
# take centroids from file passed in fpath
# There would be a file in which we will keep updating centroids
# This function just parses that
def getCentroids(fpath):
centroids = []
for l... |
68ef4c72fb9d8c4bc3cb0a8786a8b9d8dd40ed3c | petrapes/pyladies | /03/hanka.py | 552 | 3.953125 | 4 | from turtle import *
from random import randrange
shape('turtle')
color("Yellow")
bgcolor("MidnightBlue")
# star.color("yellow")
for stars in range(1):
begin_fill()
for star in range(5):
forward(20)
left(144)
forward(20)
right(72)
end_fill()
penup()
x = randrange(-200,200)
y =... |
f09e9d9b3300248eb8a59a81204ae3f1d4939b4e | petrapes/pyladies | /04/osmicka.py | 449 | 3.53125 | 4 | rc = input("zadej rodne cislo:")
cast1 = rc[0:6]
cast2 = rc[6]
cast3 = rc[7:11]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
odpoved = 0
cast12 = list(cast1)
for _ in cast12:
if _ in numbers:
odpoved = odpoved + 1
else:
False
if cast2 == "/":
odpoved = odpoved + 1
else:
False
cast32 = list(cast3)
for ... |
91da82b1c1e1ed22207f5957904012e1b7c5f3d0 | pajmd/python_programming_tuto | /classes/subclass.py | 129 | 3.5 | 4 | #subclass.py
import dateobj
class SubDate(dateobj.Date):
def stuff(self):
print('stuff')
d = SubDate.today();
print(d.year)
|
abcfbcbc9658a0a597ff99386e1a58269ce0e717 | gsiddhad/Advanced-Algorithms | /Maximum Subset Sum/Maximum Subset Sum.py | 1,030 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# Maximum Subset Sum
# Gourav Siddhad
#################################################################
import numpy as np
#################################################################
# To calculate sum of all elements > 0. Except first element
def maxsum(ar):
res =... |
29be4af3d652948430278ffe545f81c011643a1e | ronaka0411/Google-Python-Exercise | /sortedMethod.py | 222 | 4.125 | 4 | # use of sorted method for sorting elements of a list
strs = ['axa','byb','cdc','xyz']
def myFn(s):
return s[-1] #this will creat proxy values for sorting algorithm
print(strs)
print(sorted(strs,key=myFn))
|
8eb1a19077d17b12ed9fadbb4f5da48d324fec94 | WJLKavanagh/csg | /5char_csg/model_sections/script.py | 192 | 3.765625 | 4 | chars = list("KAWRH")
pairs = []
for i in range(len(chars)):
for j in range(i+1,len(chars)):
pairs += [chars[i] + chars[j]]
for pair in pairs:
print("[choose_" + pair + "],")
|
d53ea1900d1bfc9ab6295430ac272616293cb09d | talebilling/hackerrank | /python/nested_list.py | 1,480 | 4.3125 | 4 | '''
Nested Lists
Given the names and grades for each student in a Physics class of students, store
them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade,
order their names alphabetically and print each name on a new line... |
b7b09170b9470ee6fa394524835145a80c7939ac | talebilling/hackerrank | /python/list_comprehension.py | 305 | 3.609375 | 4 | def comprehension_version(a):
a = [b + 4 if b < 99 else b for b in a]
print(a)
def add_4_to_list_elements(a):
for i in range(len(a)):
if a[i] < 99:
a[i] += 4
print(a)
def main(a):
comprehension_version(a)
add_4_to_list_elements(a)
a = [1, 2, 3, 4]
main(a)
|
2986a73379c33fd3a0c0ff9945b5283e83586441 | talebilling/hackerrank | /python/set_add.py | 458 | 3.921875 | 4 | '''
Sample Input:
7
UK
China
USA
France
New Zealand
UK
France
Output the total number of distinct country stamps on a single line.
'''
def main():
stamps_set = get_input()
print_lenght(stamps_set)
def get_input():
n = int(input())
stamps_set = set()
for i in range(n):
string = input()
... |
1a7ee96a8ccd069b83b43e82e15e3c26815b163b | talebilling/hackerrank | /python/find_the_second_largest_number.py | 485 | 3.671875 | 4 | '''input:
5
2 3 6 6 5
'''
def main():
my_list = get_input()
second_larger = find_second_larger(my_list)
print(second_larger)
def get_input():
n = int(input())
my_list = input().split()
my_list = [int(item) for item in my_list]
return my_list
def find_second_larger(my_list):
larger ... |
9dd75d361e52c9c1e6169b6b3f47d1e202db1a76 | a-soliman/pythonData-structureAndAlgorithms | /sec-15-recursion/hw.py | 2,200 | 4.25 | 4 | '''
'''
#=======================================================================================
# recursive Sum
'''
Write a recursive function that returns the sum from 0 up to n
'''
def sum_down( n ):
if n == 1:
return 1
else:
return n + sum_down(n-1)
print('23- sum_down: '... |
d488278e3314ea01bf877501eab0053fd61dc2e5 | a-soliman/pythonData-structureAndAlgorithms | /sec-13-stacks-queues-deques/deque.py | 977 | 3.890625 | 4 | # implement a Deque class
class Deque(object):
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def addFront(self, item):
self.items.insert(0,item)
... |
401123e1362106e0268f2050533c15048ef5d767 | ruselll1705/home | /home_work3_3.py | 600 | 4.125 | 4 | while True:
print("Type 'quit' to exit")
phrase = input("Your message: ")
if phrase == "quit":
break
elif phrase == "Hello" or phrase == "Hi":
print("Hi! How‘s it going?")
elif phrase == "What is your name?":
print("I don't have name :(")
elif phrase=="я устал":
... |
c11af20155d08e99f65bb64c56b1ec459c3a8c80 | ruselll1705/home | /lection_3_1.py | 482 | 3.71875 | 4 | # s=input()
# if s=='Hi':
# pass
# print('Hellow')
# print('Hellow')
# x=int(input())
# if 0<x<=100:
# print('Correct number')
# else:
# print('Incorrect number')
# x=int(input())
# if 0<x<=100:
# print('Correct number')
# elif x<0:
# print("I don't want a negativ number")
# else:
# prin... |
cc2355c574130c4b5244b930cb6c5c3160af40e3 | KarimBertacche/Intro-Python-I | /src/14_cal.py | 2,289 | 4.65625 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
... |
18149eaedf1caa472ed9ea5ab3fcb41c10aa75b8 | juilijoel/piikki-client-rfid | /database.py | 761 | 3.703125 | 4 | import sqlite3
import sys
class database:
def __init__(self, sqlite_path):
#Connect to database
try:
self.conn = sqlite3.connect(sqlite_path)
self.c = self.conn.cursor()
self.c.execute('CREATE TABLE IF NOT EXISTS users (carduid TEXT, username TEXT)')
exce... |
0a78ecae8ce91f6e2d1a49d6dbbe02113eaeb329 | fcolumbu/Interactive-Python | /Week 3/mini_project_3.py | 3,008 | 3.546875 | 4 | # template for "Stopwatch: The Game"
import simplegui
# define global variables
canvas_width = 350
canvas_height = 200
control_width = 150
tick_count = 0 # sequential count of 100 msec ticks
stop_count = 0 # number of times the stop button is pressed
hit_count = 0 # number of times stop occurs... |
404edbe2eb6f98b869e3124125aad210cd0fac1f | sxmeng2017/nlp- | /flask源码学习/python自带方法/example_of___unicode__.py | 795 | 3.859375 | 4 | """
简而言之就是__str__,方法保证str(class)的结果。
__unicode__能保证str和unicode两个的结果。
"""
class str1():
def __str__(self):
return "str1"
class str2():
def __unicode__(self):
return u"str2"
"""
在werkzeug中有
def implements_to_string(cls):
cls.__unicode__ = cls.__str__
cls.__str__ = lambda x: x.__unicode__... |
62479e785fd68e2ab20f653097f0173d020dfbf9 | israaar/tools_utilities | /aligner.py | 12,668 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 12 23:28:20 2020
@author: Michael
Modified by mt_collaboration_team
"""
from tkinter import *
from tkinter import ttk
# starts from the begining
# line_no_1 = -1
# line_no_2 = -1
# line_no_3 = -1
# starts from a custom start point
line_no_1 = 696
li... |
ceb703f3cab91848805e7980bab1851ff9596ae0 | ninag09/test | /python/test_time.py | 1,823 | 3.640625 | 4 | #!/usr/bin/python
import math
import timeit
numInputs = (int (input()))
start = timeit.default_timer()
circles = list()
for i in range(0, numInputs):
inp = input().split(' ')
circleInfo = list(map(int, inp))
circles.append(circleInfo)
def mergeSort(c):
if len(c) > 1:
mid = len(c)//2
left = c[:mid]
... |
3e4a2892284ba221aaaf50d4d95f5a4c7fdda242 | ninag09/test | /python/co.py | 184 | 3.90625 | 4 | #!/usr/bin/python
def numberOfPaths(m, n):
if(m == 1 or n == 1):
return 1
return numberOfPaths(m-1, n) + numberOfPaths(m, n-1)
m = 2
n = 2
print(numberOfPaths(m, n))
|
cbf4c56377c72d2a000a116c98346a97a581dcb2 | tecoholic/utility-scripts | /excel_manip/split_file.py | 780 | 3.890625 | 4 | '''
This file splits the 3 row census data in TN.csv into 3 different files of 1 row each.
'''
import sys
def main(filename):
''' The main function '''
f = open(filename, 'r')
r1 = open("total.csv", 'w')
r2 = open("urban.csv", 'w')
r3 = open("rural.csv", 'w')
col = f.readline()
r1.write(co... |
017e072c87d7188f3ceaba95e010d2bb11022bd3 | Traccykay/Traccykay | /numberstest.py | 488 | 3.765625 | 4 | import unittest
from mytest import prime_no
class prime(unittest.TestCase):
"""docstring for TestCase"""
def test_is_one_prime(self):
self.assertTrue(prime_no(1))
def test_is_two_prime(self):
self.assertTrue(prime_no(2))
def test_is_a_prime(self):
self.assertTrue(prime_no("a"))
def test_is_a_n... |
f75c86dc2cb29bd1c661c65f5308e97f9934ff97 | 15BEC083/python-programming | /Player level/holiday.py | 89 | 3.734375 | 4 | day=raw_input()
if ((day=='Sunday')|(day=='Saturday')):
print("yes")
else:
print("no")
|
5fc9c31d16441d4c815014351b1820d13b18b903 | 15BEC083/python-programming | /fibonacci.py | 84 | 3.5625 | 4 | N=int(raw_input())
a=0
b=1
print(b)
for i in range(1,N):
c=a+b
a=b
b=c
print(c)
|
3f516bdfa47df4ba3fb0594e84fa60804503e8b4 | JimYin88/ProjectEuler | /Problem029.py | 470 | 3.65625 | 4 | # Created on May 26, 2022
#
# @author: Jim Yin
# How many distinct terms are in the sequence generated by a**b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
import time
def main():
print(len(set((a**b for a in range(2, 101) for b in range(2, 101)))))
if __name__ == '__main__':
start_time = time.perf_counter()
mai... |
bc90e84d0872c9c5b54d6c2c102252a34b62918c | JimYin88/ProjectEuler | /Problem045.py | 1,231 | 3.796875 | 4 | # Created on Jun 2, 2022
#
# @author: Jim Yin
import time
def triangle(n):
"""
:param n: nth member of the triangle number series
:return: value of the nth member
"""
return int(n*(n+1)/2)
def pentagonal(n):
"""
:param n: nth member of the pentagonal number series
:return: value of t... |
d4d8154d2ec8ed2e344aa82dd07417226eb9f57d | JimYin88/ProjectEuler | /Problem092.py | 688 | 3.609375 | 4 | # Created on Jun 2, 2022
#
# @author: Jim Yin
import time
square_digit_chain_dict = {}
def square_digit_chain(n):
d = sum(int(d)**2 for d in str(n))
if d in square_digit_chain_dict:
return d, square_digit_chain_dict[d]
nn = d
while nn != 1 and nn != 89:
nn = sum(int(x)**2 for x in str... |
32ace0ae86c7c1b44c278a80c862c6fff9cf690b | JimYin88/ProjectEuler | /Problem012.py | 1,065 | 3.71875 | 4 | '''
Created on May 21, 2022
@author: Jim Yin
'''
'''
The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven tri... |
88d478acae2a6ea72ac4017a158abaf1c8edf9ea | dev-taewon-kim/Algorithm | /baekjoon/10992.py | 417 | 3.625 | 4 | #!/usr/bin/env python3
# Title : 별 찍기 - 17
# Link : https://www.acmicpc.net/problem/10992
from sys import stdin
# 입력 빠르게 받기
input = stdin.readline
n = int(input())
for i in range(n):
if i == 0:
print(" " * (n - i - 1) + "*")
elif i == n - 1:
print("*" * ((2 * n) - 1))
else:
str ... |
517a31dee0b65e3651dcc7e38dbcce3f5d7b33fc | Ansh2103/User_Registration_Using_Python | /MainUserRegistration/UserRegistration.py | 3,675 | 3.78125 | 4 | import re
from MainUserRegistration.UserRegistrationException import UserException
class UserRegistration:
FIRST_NAME_PATTERN = r'^[A-Z][a-z]{3,}$'
LAST_NAME_PATTERN = r'^[A-Z][a-z]{3,}$'
EMAIL_PATTERN = r'^[0-9a-zA-Z]+([._+-][0-9a-zA-Z]+)*[@][0-9A-Za-z]+([.][a-zA-Z]{2,4})*$'
PHONE_NUMBER_PATTERN = r... |
a146a5df40c5219722208f5898c56f279f038b04 | basoudy/LPTHW | /ex6.py | 642 | 4.09375 | 4 | #explaining different types of people by using x as a variable.
#the number should not be previously mentioned.
#line 4 is a string inside a string
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
#string inside a string
y = "Those who know %s and those who %s." % (binary, do_not)
print x
p... |
dc66e3ff4ebdebedf4cc1bbd7371ead1055e81c8 | cameronse68/classification-methods | /methods/evaluate.py | 2,262 | 3.5625 | 4 | from sklearn.metrics import confusion_matrix, roc_curve, auc
import seaborn as sns
import matplotlib.pyplot as plt
def evaluate_classification(y_test, y_pred, labels, method):
"""
A method to evaluate the classifier
Args:
y_test (numpy.ndarray): The array for y_test
y_pred (numpy.ndarray... |
b4193994dfeaae87bf659fdf1712a50dc831cedb | mdsalieri/1.-JetBrains-Python-Rock-paper-scissors | /game.py | 1,704 | 3.828125 | 4 | import random
# Write your code here
current_rating = 0
rating_dict = {}
rating_file = open("rating.txt", "r")
for line in rating_file:
nick, score = line.split()
rating_dict[nick] = score
rating_file.close()
def rating_check(nickname):
if nickname in rating_dict:
print(f"Your rating: {current_ra... |
1387e63d50e7170a0733e43c95da207acf0f5925 | kagekyaa/HackerRank | /Python/005-for_while_loop_in_range.py | 488 | 4.28125 | 4 | '''https://www.hackerrank.com/challenges/python-loops
Read an integer N. For all non-negative integers i<N, print i^2. See the sample for details.
Sample Input
5
Sample Output
0
1
4
9
16
'''
if __name__ == '__main__':
n = int(raw_input())
for i in range(0, n):
print i * i
'''
A for loop:
for i in ran... |
b37decf98504f790fa8d0049c2860d04d5107f4b | kagekyaa/HackerRank | /Python/004-Integer_float_Division.py | 469 | 3.71875 | 4 | '''https://www.hackerrank.com/challenges/python-division
Task
Read two integers and print two lines. The first line should contain integer division, a//b . The second line should contain float division, a/b .
You don't need to perform any rounding or formatting operations.
Sample Input
4
3
sample Output
1
1.33333333333... |
307fb5cb68e13b38fc667469a25d8c9d50ffb45f | manonabiteboul/python | /Hello.py | 498 | 4.03125 | 4 | import os
name = input("Please enter your first name ")
if name!="Frank":
print("Hello ", name, " this program was not made for you")
else:
print("Hello ", name," are you impressed with my Python Skills?")
answer = input("Answer Yes or No ")
if answer== "Yes":
print("You don't need much to be impressed")
elif ... |
ce8574a13843332eaeb3d2ad3ea90ea9d33d8531 | hm14/LeetCode-Problems | /singleNumber.py | 338 | 3.671875 | 4 | # Problem Prompt
# Given an array of integers, every element appears twice except for one.
# Find that single one.
def singleNumber(nums):
output = 2*sum(set(nums)) - sum(nums)
return output
# test cases
numbers = [[1,2,3,1,4,2,3],
[99,99,0,7,6,4,3,4,3,7,6],
[0,0,1]]
for i in range(len(numbers)):
print singleN... |
3c8ab1d36b68413e76e0ee2a1be305bf2762f7aa | hm14/LeetCode-Problems | /romanToInt.py | 1,117 | 3.8125 | 4 | # Problem prompt
# Given a roman numeral, convert it to an integer.
# Input is guaranteed to be within the range from 1 to 3999.
def romanToInt(self, s):
intValue = 0
previous = ''
for c in s:
if c == 'I':
intValue += 1
elif c == 'V':
if previous == 'I':
... |
3da04a79c732be4e5337fa2d45b72be9a11f01aa | ryanjdillon/pyaha | /organism.py | 400 | 3.515625 | 4 | class Organism(object):
def __init__(self, organism_id, age, biomass, mature, x, y, z):
import random
self.id = organism_id
self.alive = True
self.age = age
self.sex = round(random.random()) # 0: female; 1: male
self.biomass = biomass
self.mature = mature
... |
9aa653db7e963d6daeee0ba49ee765453c6ec71d | Schlutz1/ProjectEuler | /Problem49PrimePermutations.py | 2,857 | 3.59375 | 4 | # problem 49 - Prime Permutations
'''
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330,
is unusual in two ways:
(i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-,... |
8c8eb5ce0bb03de6ff286adf1fc2d694ee911f27 | Schlutz1/ProjectEuler | /Problem53CombinatoricSelectors.py | 2,010 | 3.734375 | 4 | # problem53, combinatoric selectors
'''
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
In general,
nCr = (n! / r!(n−r)!)
,where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, th... |
46d4f920524ef8f706c86bf07e52c6f7f80f03c4 | Schlutz1/ProjectEuler | /Problem39:Integerrighttriangles.py | 817 | 3.640625 | 4 | #q39 python implem
import operator
def valid_square(a, b, c) :
if a**2 + b**2 == c**2 :
return True
else :
return False
if __name__ == "__main__" :
soln_dict = {}
for p in range(1, 1000) :
print p
a, b, base = p/3 - 1, p/3, p/3 + 1
soln_counter = 0
for counter, c in enumerate(range(base, p)) : #... |
ce47e4d0845aef473a3939f93b2d4646f5bf2c0c | kathdez7/Mision_03 | /Auto.py | 1,188 | 3.921875 | 4 | #Autor: Katia Hernández Barrera
#Descripción: programa que calcula el rendimiento de un automovil
def main():
km = int(input("Teclea el número de km recorridos: "))
l = int(input("Teclea el número de litros de gasolina usados: "))
rend = calcularRendimientoKM(km,l)
rendimiento = calcularRendimie... |
261a252acbfe4691fbee8166a699e3789f467e8b | franciscoguemes/python3_examples | /basic/64_exceptions_04.py | 1,328 | 4.28125 | 4 | #!/usr/bin/python3
# This example shows how to create your own user-defined exception hierarchy. Like any other class in Python,
# exceptions can inherit from other exceptions.
import math
class NumberException(Exception):
"""Base class for other exceptions"""
pass
class EvenNumberException(NumberExce... |
73cccc2cd1bbcea2da0015abc9ea0157be449844 | franciscoguemes/python3_examples | /projects/calculator/calculator.py | 1,434 | 4.3125 | 4 | #!/usr/bin/python3
# This example is the typical calculator application
# This is the calculator to build:
# #######
# 7 8 9 /
# 4 5 6 *
# 1 2 3 -
# 0 . + =
# Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s
import tkinter
window = tkinter.Tk()
#window.geometry("312x324")
window.resizable... |
7244b8b9da478b14c71c81b2ff299da0e4b18877 | franciscoguemes/python3_examples | /basic/06_division.py | 697 | 4.4375 | 4 | #!/usr/bin/python3
# Floor division // --> returns 3 because the operators are 2 integers
# and it rounds down the result to the closest integer
integer_result = 7//2
print(f"{integer_result}")
# Floor division // --> returns 3.0 because the first number is a float
# , so it rounds down to the closest integer and ret... |
e83ee865e27bc54b1c58fb9c220ef757d2df4de3 | franciscoguemes/python3_examples | /advanced/tkinter/03_click_me.py | 557 | 4.125 | 4 | #!/usr/bin/python3
# This example shows how to handle a basic event in a button.
# This basic example uses the command parameter to handle the click event
# with a function that do not have any parameters.
# Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s
import tkinter
window = tkinter.... |
949d9ce6282c13e586222dbc78e0388312bd5c91 | franciscoguemes/python3_examples | /basic/81_db_05.py | 5,794 | 3.9375 | 4 | #!/usr/bin/python3
# In this example I will show how you can use databases to improve the "MCM (MOVIE COLLECTION MANAGER) LTD." that
# I did in the last example of the serialization.
import sqlite3
class Movie:
# In Python is not allowed the method overload so to have many constructors you use default argument... |
776a51053306a024ab824003e63255c89cdbb6d4 | franciscoguemes/python3_examples | /basic/09_formatting_strings.py | 673 | 4.625 | 5 | #!/usr/bin/python3
# TODO: Continue the example from: https://pyformat.info/
# There are two ways of formatting strings in Python:
# With the "str.format()" function
# Using the Old Python way through the "%" operator
# Formatting strings that contain strings
old_str = "%s %s" % ("Hello", "World")
new_str = "{}... |
aa2f2dcd6d0222a69481df7a715fcc6019020da5 | franciscoguemes/python3_examples | /advanced/tkinter/menu.py | 1,457 | 3.625 | 4 | #!/usr/bin/python3
# This app simply generates a window with a menubar.
# http://effbot.org/tkinterbook/menu.htm#Tkinter.Menu.add_command-method
# http://effbot.org/tkinterbook/menu.htm#menu.Menu.add-method
import tkinter
from tkinter import Menu
from tkinter import Label
def handle_menu(menu):
print(f"You ... |
54d9784f7a4120a472bb7620ad1b4629d3e7469d | franciscoguemes/python3_examples | /advanced/linux/executeCommandWithoutOutput.py | 1,194 | 3.890625 | 4 | #!/usr/bin/python3
# This example shows how to execute a command (i.e. an application) that will run in a separate child
# process. This separate child process is detached from the parent process on which this program is being
# executed, therefore the child process will continue running once this programme has finish... |
8f13c30b19f88a6ef7c76dc0b9ca7583477a889c | akhilajay/Python | /PythonBasic/DictonariesDataType.py | 588 | 3.8125 | 4 | print('Dictonaries')
#key value pair
#similar to list, but cant join using "+"
##Map Declaration, with key:value
super_cars={'BMW': '$40K', 'Audi': '$41k', 'Benz': '$44k'}
print(super_cars)
#gettting value with key
print(super_cars['BMW'])
#delete
del super_cars['Benz']
print(super_cars)
#replace an item
super_cars['B... |
a66ba87d4140440d3e0bc39fdf635471751699ae | pierre-dejoue/python-notebooks | /fibogrowth.py | 751 | 3.5625 | 4 | """
References:
- Helmut Vogel (1979) A better way to construct the sunflower head
"""
import math
golden = (math.sqrt(5) + 1.0) / 2.0
phi = (math.sqrt(5) - 1.0) / 2.0
phi_rad = 2.0 * math.pi * phi
def fibo(n):
"""Returns the nth Fibonacci number"""
if n < 2:
return 1
else:
return int... |
995e3bcb8ec97fdf9645c4ccd73921dda0de2d20 | hfrankst/NSS-bangazon-exercises | /bangazon.py | 11,928 | 3.59375 | 4 | import random
class Department(object):
"""Parent class for all departments"""
def __init__(self):
self.employees = set()
def add_employee(self, employee):
self.employees.add(employee)
def remove_employee(self, employee):
try:
self.employees.remove(employee)
... |
2f5e6c92c05a9f3980beb15b4a2651cf25258552 | folsec/Training | /new.py | 238 | 3.765625 | 4 | '''def main():
print('Welcome to GPA App')
semester = int(input("Enter the number of semester :"))
if semester > 0:
while semester >= 1:'''
def total():
from main import first_gp
print(main.first_gp())
|
1ebf6fa152bd3d40cf46ede923f9beb99c69df56 | sasir74/Assignments | /progess.py | 920 | 4.0625 | 4 | #Student Progress Report App
rollno = int(input("Enter Your RollNo : "))
name = input("Enter Your Name :")
sub1 = int(input("Enter Subject 1 Marks : "))
sub2 = int(input("Enter Subject 2 Marks : "))
sub3 = int(input("Enter Subject 3 Marks : "))
sub4 = int(input("Enter Subject 4 Marks : "))
sub5 = int(input("Enter Subj... |
b7b6ef640a68e960cce579cee5316e6425702358 | anazalea/zestlife | /temperature.py | 551 | 3.609375 | 4 | from datetime import date
FLOTEMPS = {
1: 10.7,
2: 12.6,
3: 15.8,
4: 18.9,
5: 23.5,
6: 26.8,
7: 27.8,
8: 27.7,
9: 25.7,
10: 20.8,
11: 15.7,
12: 11.8
}
def get_temperature(dt: date) -> float:
return FLOTEMPS[dt.month] if dt.month in FLOTEMPS else 10.
if __name__ =... |
122c95ffdf730f6f59f5fc7ea486043052da0367 | nncastil/astr-119-session4 | /python_exceptions.py | 370 | 3.921875 | 4 | #when we get unexpected results
try: #to attempt to run something
print(a)
except: #even though a is not defined
print("a is not defined!")
try:
print(a)
except NameError: #when error message shows up
print("a is still not defined")
except:
print("Something else went wrong.")
print(a) #... |
396fdab3fc3c56d1345f32cf1d29139e2decef00 | dallinsuggs/CS241 | /prove03.py | 2,363 | 4.03125 | 4 | class Robot:
# Initializing variables
def __init__(self):
self.x = 10
self.y = 10
self.fuel_amount = 100
# Moves up
def move_up(self):
# Checks if there is enough fuel
# if no fuel
if self.fuel_amount < 15:
print("Insufficient fuel to perform ... |
380ac40a79d2cea253904d211f33ec41ae9d99f0 | dallinsuggs/CS241 | /DSweek07.py | 273 | 4.125 | 4 | def fibonnaci(number):
if number <= 0:
return 0
elif number == 1:
return 1
elif number == 2:
return 2
return fibonnaci(number - 1) + fibonnaci(number - 2)
for i in range(0,20):
print("Fibonacci({}) = {}".format(i,fibonnaci(i))) |
9a4f4c6955792a1db216f0f791ae74b98a70896b | peteballs/Labs-4-7 | /Emoticon.py | 685 | 3.875 | 4 | import random
print("Welcome to our site!")
print("We generate different emoticons")
while True:
play = input ("Do you want to continue?...(yes or no)...").lower()
if play == "yes":
eyes =['*', ':', ';', 'B']
eye =random.choice(eyes)
print(eye)
mouths =['(', ')', ']', '[']
mouth =rando... |
512f28abaaceb1007df3ce3b788b960238e2f32f | needhourger/university | /数据结构/cacheSimulator.py | 8,883 | 4.125 | 4 | # coding: utf-8
from random import randint # randint model,used to populate the main memory with random data
"""
you are require to implement cache simulator in either Java or Python. Your program should do the following.
1.ask user the size of main menory,memory block,cache.
2.validate the user input.
3.Simulate... |
bee8724057832125bca758650e195bda9c317882 | ChidambaramR/MyPythonScripts | /Calculator/calc.py | 2,217 | 3.734375 | 4 | from Tkinter import *
import pdb
root = Tk()
root.geometry("460x460") # How big in the screen
calc = Frame(root)
calc.grid()
# Entry widget is used to accept a single-line text strings from the user
# w = Entry(master, option...)
text_box = Entry(calc, justify=RIGHT)
text_box.grid(row=0, column=0, columnspan=6, pady=... |
22f68b5c6baea1193bfb5730f828bc4e874bdc3d | ShenYuCN/Algorithms | /Python/Array/A08_Max_Consecutive_Ones.py | 1,352 | 3.90625 | 4 | '''
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
'''
class Solution:
def findMaxConsecutiveOnes(self, nums)... |
d49589e9db5410ee5e2913105dce3de24cad0a2c | Salmasherif33/Memory-Allocation-using-Segmentation | /Block.py | 644 | 3.6875 | 4 | class Block:
def __init__(self, name: str, start_address: int, size: int):
self.name = name
self.start_address = start_address
self.size = size
def __str__(self):
return f"(name: {self.name}, start address: {self.start_address}, end address: {self.end_address})"
def __repr_... |
23ca17ae6bbee520cf2160ca613642924f9678ea | MikeTango30/KITM_DB_PYTHON_conn_crud | /database/database.py | 10,764 | 3.734375 | 4 | import sqlite3
import pprint
from book import book
from publisher import publisher
def execute_query(db_name, query, entry=None):
connection = sqlite3.connect(db_name)
connection_cursor = connection.cursor()
connection_cursor.execute(query, entry)
connection.commit()
connection.close()
def creat... |
6e9229c5674c48601379d3d6142b6dd847f46b4b | huzefa26/Programming-Templates | /max difference among elements in a list.py | 452 | 3.5625 | 4 | __author__ = 'huzef'
# do max(list) - min(list)
def maxDistance(array):
max1 = -2147483648
min1 = +2147483647
max2 = -2147483648
min2 = +2147483647
for i in range(len(array)):
max1 = max(max1, array[i])
min1 = min(min1, array[i])
max2 = max(max2, array[i])
... |
d34d47a333e559a7885951d029f970004329a2b7 | Pieerre988/CI_CD | /calculator.py | 173 | 3.71875 | 4 | def add(a,b) :
return a+b
def multiply(a,b):
try:
x = a*b
except ValueError:
print ("Cannot multiply valid number")
x = False
return x
|
e5c82e510f98c1ea6529025317ea1a9fbd47c0d8 | njanirudh/Python-DataStructures | /Queue.py | 597 | 3.84375 | 4 | __author__ = 'ANIRUDH'
# FIFO --> First in First out
# Used in OS scheduling processes.
class Queue:
def __init__(self):
self.items = []
# Checks if the given stack is empty or not. Returns True or False
def isEmpty(self):
return self.items == []
# Adds the data to the first index of the ... |
7e1c430bc00c8269f174c52f3a431c91fb1c651b | AS-AmanSinghal/PythonLearning | /LogicalOperationProgram.py | 385 | 3.953125 | 4 | isMagician = True
isExpert = False
if isMagician and isExpert:
print("You are a master magician")
elif isMagician and not (isExpert):
print("At least you're getting there")
elif not (isMagician):
print("You need a magic power")
# exercise two - - -> Tricky Counter
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10... |
2c3d9b62f3ad2635d6cf15ba25e34d2da3b542b7 | AS-AmanSinghal/PythonLearning | /venv/FileHandling/FileHandling.py | 452 | 3.734375 | 4 | # with open('test.txt',mode='r+') as myFile:
# text = myFile.write("hey bndr kesa hai")
# print(text) #count
# print(myFile.readline())
# myFile.seek(0)
# print(myFile.readlines())
# with open('test.txt',mode='a') as myFile:
# text = myFile.write("AMAN")
# print(text)
try:
with open('... |
f55e7f50bb0d25d647fd5bee1a7e94be65e43038 | debjanipaul/code-snippets | /python/grp_lst_of_dicts.py | 1,183 | 4 | 4 | """
Snippet to group a list of dictionaries based on values for one or more keys
"""
import itertools
from operator import itemgetter
test_list = [
{'metric': 'metricA', 'metric_group': 'metricGroupA', 'metric_owner': 'abc'},
{'metric': 'metricB', 'metric_group': 'metricGroupA', 'metric_owne... |
00197ad4d7044de34ae36182f60d4fd46b9d0018 | preethamwilfredjohn/BigData | /Question8/authorAvgCitaitonReducer.py | 1,149 | 3.515625 | 4 | #!/usr/bin/env python
import sys
current_author = None
current_count = 0
finalDict = {}
for line in sys.stdin:
line = line.strip()
author,count = line.split("\t")
count = int(count)
#calculation for authors most cited paper
if current_author == author:
tempList.append(count)
else:
if current_author:
#cal... |
cfa5db0bf84fc5bd407dac99fa0289e511a0b7f6 | preethamwilfredjohn/BigData | /Question6/authorsPaperReducer.py | 791 | 3.625 | 4 | #!/usr/bin/env python
import sys
current_Id = None
current_count = 0
Id = None
maxCount = None
moreRef = {}
# input comes from stdin which is an output of mapper function
for line in sys.stdin:
try:
#remove the spaces before and after each line of input
line = line.strip()
#parse the input we got from mapper... |
ef4394d3b129adcb46ae944f84d722625eb81933 | a-willis/algos | /linked_list/sum.py | 410 | 3.828125 | 4 | class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
def sum(node):
if not node:
return 0
else:
return node.value + sum(node.next)
# Test Cases
LL1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
LL2 = ListNode(1, ListNode(4, ListNode(3)))... |
b9cd6bce59d7ba0c2113928bfcdf806d82ec7fe9 | a-willis/algos | /linked_list/insertTarget.py | 927 | 3.875 | 4 | # iterative
class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
def arrayify(head):
array = []
ptr = head
while ptr != None:
array.append(ptr.value)
ptr = ptr.next
return array
def insert(head, target):
curr = head
if curr is None:
return ListNod... |
b859251dd302e9dc52e7af7b41089781bf8ac360 | v-nys/python-controlegroep | /python-while.py | 487 | 3.671875 | 4 | number_of_host_addresses = 7 # naar eigen keuze, test wat opties uit
number_of_host_bits = 1
available_host_addresses = 0
while available_host_addresses < number_of_host_addresses and number_of_host_bits < 33:
number_of_host_bits += 1
available_host_addresses = (available_host_addresses + 2) * 2 - 2
if number_o... |
9b486d10903c4c84fbbbc41ef57487ceb05a76b8 | v-nys/python-controlegroep | /python-geneste-for.py | 84 | 3.65625 | 4 | for digit in "123":
print(digit)
for letter in "abc":
print(letter)
|
6238695d451ad7f38ad8009bae4af26454d043c2 | v-nys/python-controlegroep | /rem_ip_adressen_verwerken_en_verzamelen.py | 304 | 3.578125 | 4 | def verzamel_ip_adressen():
result = []
ip = input("Wat is het volgende IP-adres? Duw meteen op enter om af te sluiten.\n").strip()
while ip != "":
result.append(ip)
ip = input("Wat is het volgende IP-adres? Duw meteen op enter om af te sluiten.\n").strip()
return result
|
1390dae44425094498d42b7e8587616b8fd65d1f | akirwski/forecast | /HoltWinterForecast/test.py | 591 | 3.859375 | 4 | ##Test Code
#initilize the class with your data file, a number of period, a index of the column(where actual sales are stored)
holt = HoltWinterForecast('holtwinter.csv', 52, 3)
#input alpha, beta, gamma
holt.calcForecast(0.4, 0.4, 0.4)
#show original data and data with forecast
holt.df.head()
holt.dfForecast.head()
... |
60be97d66b34a97d3639aa8b4a385f42eda0a829 | stianbm/tdt4113 | /03_crypto/persons/hacker.py | 1,579 | 3.546875 | 4 | """File contains hacker"""
from persons.person import Person
class Hacker(Person):
"""Brute force hacker"""
def __init__(self, cipher_key, cipher_algorithm):
super().__init__(cipher_key, cipher_algorithm)
self.type = 'hacker'
def operate_cipher(self, text):
"""Brute force the en... |
b162c9b137501edd3030763e5397f5fafd2dd9f9 | stianbm/tdt4113 | /02_RPS/many_games.py | 1,352 | 3.734375 | 4 | """Holds class that can hold tournaments of single games"""
from single_game import SingleGame
import matplotlib.pyplot
class ManyGames:
"""Class that plays n single games and visualize the result"""
def __init__(self, player1, player2, number_of_games):
self.player1 = player1
self.player2 =... |
b315f178386a8072670a9087e791c0f978cd2212 | stianbm/tdt4113 | /03_crypto/ciphers/cipher.py | 1,223 | 4.28125 | 4 | """The file contains the parent class for different ciphers"""
from abc import abstractmethod
class Cipher:
"""The parent class for the different ciphers holding common attributes and abstract methods"""
_alphabet_size = 95
_alphabet_start = 32
_type = ''
@abstractmethod
def encode(self, te... |
e36cb84902abb12854c88b9f255692631081a5b7 | stianbm/tdt4113 | /04_calc/container/stack.py | 442 | 3.640625 | 4 | """Stack, subclass of Container"""
from container.container import Container
class Stack(Container):
"""FILO stack"""
def __init__(self):
super().__init__()
def peek(self):
"""Return the last element of the list"""
assert not self.is_empty()
return self._items[-1]
de... |
463e2afe02f4aa5b49ad4b9c33384c885e38cdbd | jcr179/ds-algo-libraries | /algos/insertionSort.py | 372 | 4.09375 | 4 | def insertionSort(a):
# Time O(n2). Could perform better than (nlogn) for small lists
# Memory O(1) for item being moved
# a: array of length n
n = len(a)
for i in range(1, n):
j = i
while j > 0 and a[j] < a[j-1]:
a[j], a[j-1] = a[j-1], a[j]
j -= 1
... |
07cf1c2b0ab69fe66d0f84bd8d1dacc98404213c | xiaoke321/niuke-shuati | /2020-11-27/机测/demo1.py | 1,385 | 3.703125 | 4 | # TODO 给定一个二叉树,但会该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
# TODO 列如:
# TODO 给定的二叉树是{3, 9, 20, #, #, 15, 7}
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @param root TreeNode类
# @return int整型二维数组
class Solution:
def levelOrder(self, root):
result =... |
8e38d39074839cae704cf4df4134f0c1a4eb6ede | shaneweisz/OCR-Character-Confusion | /weighted_lev.py | 2,246 | 3.671875 | 4 | """
Implements a Weighted Levenshtein on two words.
Uses weights resulting from the confusion matrix that has generated
(confusion_matrix_base.pkl or confusion_matrix_base.xlsx).
"""
import numpy as np
import pandas as pd
import weighted_levenshtein as wl
import sys
import os
def normalise(df):
"""Return the no... |
b211e0c725cf9741a7144ec97c841a7f10677d26 | AnthonyQuantum/python-course-tasks | /decrypt.py | 374 | 3.625 | 4 | from simplecrypt import decrypt
with open("encrypted.bin", "rb") as input_file:
encrypted = input_file.read()
with open("passwords.txt", "r") as passwords:
for password in passwords:
try:
decrypted = decrypt(password.strip(), encrypted)
print(decrypted)
... |
b8ff0a0d7afffca32131a1e0836c905fc2e4fdbd | AnthonyQuantum/python-course-tasks | /cipher.py | 564 | 3.625 | 4 | letters = input()
symbols = input()
dict_ls = {}
dict_sl = {}
for i in range(len(letters)):
dict_ls[letters[i]] = symbols[i]
dict_sl[symbols[i]] = letters[i]
text = list(input())
cipher = list(input())
res_text = []
for let in text:
if let in dict_ls:
res_text.append(dict_ls[let])
else:
... |
67970a61787ce0ebff7418c8193d24ab9727510e | Henrique1301/Python-exercicios | /ex005_(Antecessor e sucessor de um número).py | 191 | 3.8125 | 4 | print('==='*40)
print('Antecessor e sucessor de um número')
print('==='*40)
n = int(input('Digite um número?'))
print('O antecessor de {} é {}\nO sucessor de {} é {}'.format(n,n-1,n,n+1)) |
a84b2ca62ea2a64073f5a54f8ea19657079819ad | smh128/jtc_class_code | /challenges/04_NBA /nba3pts.py | 2,821 | 4.3125 | 4 |
print("Challenge 2.1:")
jamal_murray_3pts_made = 46
Vanvleet_3pts_made = 43
Harden_3pts_made = 39
print("Challenge 2.2:")
print("In the 2020 NBA playoffs Jamal Murray made this many 3 point shots:")
print(jamal_murray_3pts_made)
print("In the 2020 NBA playoffs Fred Vanvleet made this many 3 point shots:")
print(Van... |
a4e681a54c136fce15a0693b4396a061b2f1d58d | timkuel/4500-Software-Profession-Projects | /HW1.py | 11,623 | 4.1875 | 4 | """ Author: Timothy Kuelker
Date: August 23, 2019
Course: CMPSCI 4500
Description:This program reads "game" information from a file named HW1infile.txt and generates a game board
from the provided information. The program will start in the first circle, and then
... |
9c20ceec0fdccd3bc2bb92815e56b7a99855058a | cindy859/COSC2658 | /W2 - 1.py | 721 | 4.15625 | 4 | def prime_checker(number):
assert number > 1, 'number needs to be greater than 1'
number_of_operations = 0
for i in range(2, number):
number_of_operations += 3 #increase of i, number mod i, comparision
if (number % i) == 0:
return False, number_of_operations # returning multip... |
bdc290072854219917fe8a24ef512b26d38e93f9 | TecProg-20181/02--matheusherique | /main.py | 1,779 | 4.25 | 4 | from classes.hangman import Hangman
from classes.word import Word
def main():
guesses = 8
hangman, word = Hangman(guesses), Word(guesses)
secret_word, letters_guessed = hangman.secret_word, hangman.letters_guessed
print'Welcome to the game, Hangman!'
print'I am thinking of a word that is', len(s... |
4102158203edcd742ae91803696be85091766797 | Luke-TE/4-is-the-magic-number | /magic_number/__main__.py | 893 | 3.703125 | 4 | import sys
from num2words import num2words
def remove_punctuation(sentence):
new_name = sentence.replace(' ', '')
new_name = new_name.replace(',', '')
new_name = new_name.replace('-', '')
return new_name
def generate_sequence(curr):
seq = [curr]
while True:
new = get_num_from_len(cur... |
53480e718df73c84024dd5530ae7f1fbdbb03a1a | abhinavnarang/Human-Vs-Ai-Bot-Chess-Game | /modules/pieces.py | 8,371 | 3.96875 | 4 | import pygame
def capture_check(your_color, y, x, board):
"""
Checks if a square (y,x) can be captured by the color inputted
"""
piece = board.array[y][x]
if piece == None:
return False
else:
if piece.color != your_color:
return True
else:
return ... |
34b62b7b789c46ac790d76fec61de770f916b6a4 | rahulsingh237/python-practice | /mockvita 2 (tcs).py | 1,547 | 3.796875 | 4 | ''' Problem Description
Given N three-digit numbers, your task is to find bit score of all N numbers and then print the number of pairs possible based on these calculated bit score.
Rule for calculating bit score from three digit number:
From the 3-digit number,
extract largest digit and multiply by 11 then extract ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.