blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
78968f84d165aaace48acb20a87b525fc686a37b | GlaucoPhd/Python_Zero2Master | /OptionalBinComplex24.py | 744 | 4.1875 | 4 | #Complex number is created from real numbers. Python complex number can be created either using direct assignment statement or by using complex () function.
#Complex numbers which are mostly used where we are using two real numbers. For instance, an electric circuit which is defined by voltage(V) and current(C) are use... |
623cba7f5551a0cff2ba0278082af107fbdc123c | lsyleo/HelloPython | /Python/Ch_01/Turtle_02.py | 537 | 3.859375 | 4 | import turtle
run = 1
t = turtle.Turtle()
t.shape("arrow")
pen = 1
while run == 1:
command = input("")
d = t.degrees
if command == "w":
t.forward(10)
if command == "s":
t.backward(10)
if command == "d":
t.right(20)
if comm... |
577f9b8165f2c5b2fc84c20a71d81547d08b00f1 | hellochmi/google-coursera | /week4_divide_and_conquer/3_improving_quicksort/sorting.py | 1,470 | 3.90625 | 4 | # Uses python3
import sys
import random
#quicksort
"""
def partition3(a, l, r):
#write your code here
# all the elements to the right < x, all the elements to the left > x
# x is the pivot
mid = a[l]
i = 0
j = 0
k = r
while j < k:
if a[j] < mid:
a[i], a[j]... |
c771b5b838aa78ed77d0511b3fc41e34a7b398d1 | BarbaraAFernandes/python | /CodesComplete/Extras/anagram.py | 376 | 4.0625 | 4 | def is_anagram(first, second) -> bool:
counter_first = {x: first.count(x) for x in first}
counter_second = {x: second.count(x) for x in second}
for x in counter_first:
if counter_first[x] != counter_second[x]:
return False
return True
first_word = input()
second_word = input()
res... |
8d048bacfd3fc6143358f11ab7cf712c32840f5c | aprebyl1/DSC510Spring2020 | /Kuppuswami_DSC510/Assignment_2_1.py | 1,577 | 3.75 | 4 | #Algoritham to get Quote from Fiber Optics installation Organization
#Assignment Number 2.1
#Created by Rajkumar Kuppuswami
#Created on 03/21/2020
#Used tkinter package to deveop like a form
from tkinter import *
#Define Parameter
def calculatePayment():
# get the qty
amt = float(amount.get())
payment = (a... |
d0cc8d4bd6b2d95e12b97f8ca9b9608d101f4ec4 | AlexMan2000/ICS | /Lectures/Lecture 6/site-selection-student.py | 1,650 | 3.6875 | 4 | #def euclidean_distance(xy1,xy2):
# return ( (xy1[0]-xy2[0])**2 + (xy1[1]-xy2[1])**2 ) ** 0.5
def manhanttan_dist(xy1, xy2):
return abs(xy1[0]-xy2[0])+abs(xy1[1]-xy2[1])
def min_manhattan(coordinates):
print(coordinates)
import math
min_sum = math.inf
min_point = None
coordinates_x = [coord... |
8755c29eba7ef401926ab629e7f2f5685823d7e2 | ankushsharma0904/Infytq-assignment-solution | /Programming Fundamentals using Python/Day-2/Assgn-18.py | 913 | 3.921875 | 4 | #PF-Tryout
def convert_currency(amount_needed_inr,current_currency_name):
current_currency_amount=0
#write your logic here
if current_currency_name == 'Euro':
current_currency_amount = amount_needed_inr * 0.01417
elif current_currency_name == 'British Pound':
current_currency_am... |
2624ca762c245fae9a956ae2b7db8ad5b3916306 | Gagan-453/Python-Practicals | /GUI/Canvas/Creating Rectangle.py | 1,231 | 4.65625 | 5 | # Creating Oval using Canvas
from tkinter import *
#Create a root window
root = Tk()
# var c is Canvas class object
# root is the name of the parent window, bg is background colour, height is the height of the window and width is the breadth of window, cursor represents the shape of the cursor in the canvas
c = Canva... |
b42316c868ef20c2b42fa2e797293f2f31def995 | Harishmabanu/banuu | /positive.py | 127 | 4.125 | 4 | n=float(input("Enter a num: "):
if n > 0:
print("Positive num")
elif n==0:
print("Zero")
else:
print("Negative num")
|
486813cb76cc93a9361ffb4ff19cf5b0cb774552 | enrach21/example | /test/test_algs.py | 3,392 | 3.71875 | 4 | import numpy as np
import math
from example import algs
# Make arrays to be tested
Test1 = np.array([1,2,4,0,1])
Test_Empty = np.array([])
Test_Ordered = np.array([1,2,3,4,5,6,7,8])
Test_Reversed = np.array([8,7,6,5,4,3,2,1])
Test_Char = np.array(['cat','Dog','elephant','Snake','bird'])
def test_intertion_sort():
... |
2836153a771abfba67f50b6b422cdbc1d1530fe5 | akmadi/python | /TestPython/TestPackage/BinarySort.py | 839 | 3.578125 | 4 | '''
Created on Dec 26, 2017
@author: amadin001c
'''
'''class MyClass(object):
classdocs
'''
def main():
list = [1,3,6,4,5,2,4]
item=4
result = binarysort(list, item)
print('position is '+str(result))
def binarysort(list,item):
mi... |
dfd9b450168ae6caeb9fdb2ad32c835e0de735a6 | raffaellomarchetti/uri-python | /1257.py | 540 | 3.546875 | 4 | from string import ascii_uppercase
alfa_pos = {}
for letra in ascii_uppercase:
alfa_pos[letra] = ascii_uppercase.index(letra)
n = int(input())
while n >0:
l = int(input())
linha = []
while l > 0:
linha.append(input())
l=l-1
valor = 0
for index_linha in range(len(linha)):
... |
0fcac24e1728b2be332b04a8d6726863e868b9cf | damingus/CMPUT174 | /class_Example1.py | 2,887 | 3.921875 | 4 | class Rectangle: #capitalize the first letter of a class
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.top_left = (self.x, self.y)
self.bottom_right = (self.x + self.width, self.y + self.height)
de... |
04b1dedacd9d8da651d331587704e1517ca1a7da | pavitrawalia/CodeChef_Solutions | /https:/www.codechef.com/problems/HS08TEST.py | 159 | 3.515625 | 4 | # cook your dish here
inp=input().split(" ")
wid=float(inp[0])
bal=float(inp[1])
if wid>bal-0.5 or wid%5!=0:
print(bal)
else:
print(bal-wid-0.5)
|
97a10c847357af291b0f4f29188fe26841b9ae94 | pombredanne/wtahash | /random_data.py | 560 | 3.65625 | 4 | import numpy as np
class RandomDataGenerator:
"""Generates an array with random numbers using the input parameters
Attributes:
data (matrix of floats): contains classifiers models of n dimensions
"""
def __init__(self, classifiers_count, n, min_number, max_number):
random_coefficients = np.random.random_sampl... |
0fe25a979cdcebcd0f8706cf9d3e75d41b74581f | lresende/examples | /binder/getting-started/getting_started_python.py | 1,102 | 3.859375 | 4 | import io
import pandas as pd
import requests
def create_df_from_remote_csv(url):
"""
Loads url and creates a Pandas DataFrame if url identifies
an existing CSV file. If an error is encountered None is returned.
"""
if url is None:
return None
response = requests.get(url)
if respon... |
98287479db1fe98fdd9cccf2990027746f4e5970 | bobcaoge/my-code | /python/leetcode_bak/961_N-Repeated_Element_in_Size_2N_Array.py | 362 | 3.6875 | 4 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
class Solution(object):
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
s = set()
for num in A:
if num in s:
return num
s.add(num)
def main():
s = Solution(... |
8f1750e6c2393ee4fbcadc7c0b631b6a393f0d20 | ZzzwyPIN/python_work | /chapter9/Demo9_1.py | 1,322 | 3.96875 | 4 | # ~ class Dog():
# ~ """一次模拟小狗的简单尝试。"""
# ~ def __init__(self,name,age):
# ~ """初始化属性name和age"""
# ~ self.name = name
# ~ self.age = age
# ~ def sit(self):
# ~ print(self.name.title()+" is now sitting!")
# ~ def roll_over(self):
# ~ """模拟小狗被命令打滚"""
# ~ print(self.name.title()+" rolled over!")
#... |
839b33ab11a660be4ff454e8d2944732cf6213df | niysalomon/DSAA_SORTING | /main_sorting.py | 590 | 3.890625 | 4 | import sys
# import sort_data as sd
import sorting_data as document
ALL_THE_LIST = ['sequence', 'size', 'priority']
ORDERING = ['asc', 'desc']
Enter_choice = input('ENTER SORTING YOU WANT BETWEEN SEQUENCE,PRIORITY OR SIZE : ')
if Enter_choice not in ALL_THE_LIST:
print('Invalid Sort Choice!')
sys.exit(1)
E... |
514225e50fbb9b5d1f969540cf21f6746be25868 | python-practice-b02-927/andrei-levin | /lab2/8.py | 100 | 3.59375 | 4 | import turtle as t
t.shape('turtle')
for i in range(40):
t.forward(10 * (i+1))
t.right(90) |
a0c6bcb13689b67d6af8ea516ef17f29989cc5b7 | code-lgtm/Problem-Solving | /python/misc/max_sum_contiguous_subarray.py | 626 | 3.671875 | 4 | # https://www.interviewbit.com/problems/max-sum-contiguous-subarray/
#
# Main Idea : Keep on adding terms starting from index 0 till the time cumulative sum is positive.
# As long sum is positve it has something to contribute to the overall sum
def maxSubArray(A):
maxsum = float("-inf")
currsum = 0
... |
64c661e9105fed278a63c73a7785540718858db5 | mbsabath/popmodel | /PopModel.py | 2,886 | 3.703125 | 4 | __author__ = 'Ben Sabath'
"""
A module to allow for evolutionary game theory to be easily modeled.
includes an object representing an individual population.
"""
class OutcomeMatrix(object):
""" a class allowing for creation of a matrix representing the outcome of an
encounter within a population
"""
... |
354ea80aad45ba4309ea07d5a7f1eb3553be474a | colinyuran/pythonplay | /LearnDict.py | 774 | 3.90625 | 4 | phoneBook = {'cat':'2341','dog':'0123','duck':'2334'}
print phoneBook
print phoneBook['dog']
items = [('name','guuy'), ('age',23)]
d = dict(items)
print d
d = dict(name='cat',age=42,weight=100)
print d
x = {}
x[42] = 'foo'
print x[42]
people = {
'Alice': {
'phone': '1234',
'age': 42
},
'Beth' : {
'phone'... |
2e90fe7918b71e5252d2417c4cd21a701baa0fe1 | Pennylele/Algorithms-fun-daily | /258.py | 631 | 3.890625 | 4 | # ///////////////////The solution with loops///////////////////
class Solution:
def addDigits(self, num: int) -> int:
digital_root = 0
while num:
digital_root += num % 10
num //= 10
if num == 0 and digital_root > 9:
num = digital_root
... |
c73b6234910a622b38207ab6141f06018dd1422c | Team-bleu/CS361 | /lab04/test_init.py | 1,567 | 3.734375 | 4 | import unittest
from Rational import Rational
rational1 = Rational(2,1)
rational2 = Rational(3,1)
rational3 = Rational(4,1)
rational4 = Rational(1,3)
rational5 = Rational(2,3)
rational6 = Rational(3,9)
class testInit(unittest.TestCase):
def test_init(self):
self.assertEqual(rational3, 4 / 1)
self... |
aba86dfa7f9e8b843c34e973bd9e946fd4ae3618 | iykat/LintCode-Ladder | /1. Hack the Algorithm Interview/8-rotate-string.py | 622 | 3.953125 | 4 | class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, str, offset):
# write your code here
if not str:
return ''
l = len(str)
offset %= l
self.reverse(str, ... |
4cbf3b1347fbc88f53a4b95e26b98e314590169c | Athulya-Unnikrishnan/DjangoProjectBasics | /LaanguageFundamentals/kwargsFunction/args.py | 511 | 4.15625 | 4 | #args will accept n number of arguments
def add(*args):
sum = 0
print(args)#stores values in tuple format
for a in args:
#print(a)
sum+=a
print(sum)
add(10,20,30,40)
#"*args" cannot accept the values as key value pair so to remove the drawback of *args we use **args and it will accept t... |
b5372276a70814d1d11b629f5eae1c429ec4fe5f | abeloscher/advent-of-code-2019 | /day1/part2.py | 567 | 3.671875 | 4 | """ Solutions for Day 1 """
import sys
def calc_til_0(mass: int):
r_sum = 0
while (mass//3)-2 > 0:
mass = mass//3-2
r_sum += mass
return r_sum
def calc_til_0_recurse_step(mass: int):
if mass <= 0:
return 0
return mass + calc_til_0_recurse_step((mass//3)-2)
def calc_ti... |
2cd3b2171fc561d2ccb36f5ef6c38577e1ee5cd2 | gortyy/leetcode-solutions | /1.-two-sum/solution.py | 1,374 | 3.59375 | 4 | from typing import List
from testcase import testcase
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
return self.single_pass_hash_map(nums, target)
def brute_force(self, nums: List[int], target: int) -> List[int]:
for i, n in enumerate(nums):
for j, m... |
d396f1cd96d0577011c580ae9203d17c94904af0 | artemenm/pb-homework | /pack_4/n2.py | 1,093 | 3.84375 | 4 | def derivative(f):
der = ''
def split_to_monomials(f):
l = f.split('+')
k = []
for m in l:
k.append(m.split('-'))
monomials = []
for a in k:
for i in range(len(a)):
if i > 0:
monomials.append('-' + a[i])
... |
c9ee80e933ec7b85bde6b45de936585dc748da4c | PhamKhoa96/leetcode | /easy/test.py | 132 | 3.78125 | 4 | current_index = 0
while(current_index < 3):
for j in range(5):
current_index = current_index + 1
print(current_index)
|
b4478222b80b9c17d9bbc7493d53c091c6d06c8a | zhyErick/fengkuang_python | /05/5.1.multi_return.py | 435 | 3.90625 | 4 | def sum_and_avg(list):
sum = 0
count = 0
for e in list:
# 如果元素e是数值
if isinstance(e, int) or isinstance(e, float):
count += 1
sum += e
return sum, sum / count
my_list = [20, 15, 2.8, 'a', 35, 5.9, -1.8]
# 获取sum_and_avg函数返回的多个值,多个返回值被封装成元组
tp = sum_and_avg(my_list)
... |
f5688fe765506cdc79e11fa7cd335abbd638c999 | gHuwk/University | /First course/1st semester/Textredactor.py | 7,704 | 3.609375 | 4 | # abc - согласные буквы, text - текст(вау),choice - выбор действия,
# rech -выбор выравнивания, остальные переменные - рабочие
# Иванов ИУ7-11Б
abc=['б','в','г','д','ж','з','й','к','л','м','н','п','р',
'с','т','ф','х','ц','ч','ш','щ']
text=['Пусть мама','услыши... |
0dfc989de25f416b9b4d347444a4569b3ac39c4d | HalfMoonFatty/Interview-Questions | /386. Lexicographical Numbers.py | 657 | 3.53125 | 4 | '''
Problem:
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
'''
class Solution(object):
def lexicalOrder(self, n):
... |
4517c6dd606e4be2b5721b0a7866f66414e9ef9e | soobinkiki/code-challenges | /is_prime.py | 191 | 3.75 | 4 | def is_prime(num):
#edge cases
if num <= 1:
return False
if num == 2:
return True
for i in range(3, num):
if (num % i) == 0:
return False
|
f12983a5d287674b89d572fa001e2bf1c04caea6 | Frankiee/leetcode | /array/2_pointers_sliding_window/340._longest_substring_with_at_most_k_distinct_characters.py | 1,220 | 3.828125 | 4 | # [2-Pointers-Sliding-Window]
# https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
# 340. Longest Substring with At Most K Distinct Characters
# History:
# Facebook
# 1.
# Mar 28, 2020
# 2.
# May 4, 2020
# Given a string, find the length of the longest substring T that contains at mos... |
e4becd1b8ab4434b86cc1acac6d6d3fb2f0e664a | JuajXavier/python_studies | /currencyConverter.py | 1,835 | 3.65625 | 4 | import requests
import json
# import sys
class Currency:
def get_quotation(self, income, outcome):
self.income = income
self.outcome = outcome
quotationUrl = 'https://api.exchangeratesapi.io/latest?'
quotationPayload = {
'symbols': self.outcome,
'base': self.income
}
response = r... |
44c796ebf37c973e00b94b5db32d245c204086d6 | TorridGlacier/Intro-to-Computer-Science-2015 | /Lab 11/Strategy.py | 2,521 | 3.578125 | 4 | import random
def rock_paper_scissors_rounds(hand_1, hand_2):
levels = ['rock', 'paper', 'scissors', 'rock']
a = False
while a == False:
if levels[levels.index(hand_2)] == levels[levels.index(hand_1) + 1]:
a = 1
return a
elif levels[levels.index(hand_2)] == levels[l... |
ae79d40c7c3b5d5158b35c31955aeb0cea900d53 | Leonardo-KF/Python3 | /ex035.py | 318 | 4.03125 | 4 | t1 = float(input('Digite o tamanho da primeira reta: '))
t2 = float(input('Digite o tamanho da segunda reta: '))
t3 = float(input('Digite o tamanho da terceira reta: '))
v = (t1 - t2) < t3 < (t1 + t2)
if v:
print('Elas podem formar um triângulo!')
else:
print('Elas não podem formar um triângulo!')
|
b5446af7d1cfef9ff91f0ceafbe83849d7b9669d | DougBaldwin/CrystalGraphics | /Utilities/VectorOps.py | 4,337 | 4.28125 | 4 | # A collection of utility functions for performing vector arithmetic useful in graphics.
# The vectors that these functions work with are of fixed length, either 3 or 4 elements,
# represented as Python lists. 3-element vectors are generally vectors in 3-space, which
# may also represent points, while 4-element lists a... |
1bcee2dc9ea78e1d6d6a6d3f695511136dbdffdd | dafu2020/Mini-Python-Projects | /lab10/regular_expressions.py | 2,628 | 3.890625 | 4 | import doctest
import re
def is_email(address: str) -> bool:
"""Validate whether a string is an email address
:param address: a string
:precondition: address must be a string
:postcondition: validate if a string is an email address
:return: a boolean result, if a string is an email address return... |
10f8d9dc49bbe609bfd87e8b0a772e8e83ac0c98 | kamit17/Python | /py4e/Chp3/ex3.py | 591 | 4.15625 | 4 | """Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message.
If the score is between 0.0 and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
"""
prompt = "Enter the score ach... |
123fd86068cbe2d8b9e911dc76278a60a2e2b432 | nicolasfcpazos/Python-Basic-Exercises | /Aula20_Ex099.py | 816 | 3.953125 | 4 | # Faça um programa que tenha uma função chamada maior() , que receba vários
# parâmetros com valores inteiros.
# Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
from time import sleep
def maior(* num): # Usa-se o * para decompor os numeros (para variar a qtd)
cont = maior = 0
... |
e9caf3c48a88eaff2531e4152126bd847a44e9a5 | adwanAK/adwan_python_core | /think_python_solutions/chapter-16/exercise-16.2.py | 1,189 | 4.09375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
exercise-16.2.py
Created by Terry Bates on 2014-07-05.
Copyright (c) 2014 http://the-awesome-python-blog.posterous.com. All rights reserved.
"""
import sys
import os
class Time(object):
"""Represents the time of day.
attributes: hour, minute, second
"""
... |
6e5379c65e392d1c9e5009c671096ea32a6d5e02 | yoonsjeong/CodeKata | /coding-assessments/html_format.py | 2,061 | 3.53125 | 4 |
"""
helper('hello', ['b']) -> '<b>hello</b>'
helper('hello', ['b', 's']) -> '<s><b>hello</b></s>'
"""
def helper(text, fmt):
out = text
for i in fmt:
out = "<{1}>{0}</{1}>".format(out, i)
return out
def start(fmt):
return "<{}>".format(fmt)
def end(fmt):
return "</{}>".format(fmt)
""... |
5f241775792987d41cda409b63a38a36cf5981b7 | KevinMFinch/Python-Samples | /productCommercial.py | 591 | 4.125 | 4 | print("Hello! I am going to ask you questions about your device to create a commercial.")
yourObject = input("What is your object? ")
yourData = input("What data does it take? ")
how = input("How will you record the "+yourData+" from your "+yourObject+"?")
where = input("Where will the "+how+" be located? ")
cost = inp... |
43e152eb5c57c3953fcf58b2a7b1168aef2c463d | sd37/random-code | /leetcode/ReverseWordsInString/revword.py | 637 | 3.84375 | 4 | #https://oj.leetcode.com/problems/reverse-words-in-a-string/
#status = AC
import sys
class Solution(object):
# @param s, a string
# @return a string
def reverseWords(self,s):
# reverse entire string
s = s[::-1]
ls = s.split()
new_ls = []
# reverse indivi... |
84149276e8b679fd7a910966fa34bb2bcd026de8 | burhan221b/Python-Tax-Calculator | /tax cal experiment.py | 3,313 | 3.828125 | 4 | #tax calculator
from tkinter import *
class Calculator:
def __init__(self):
window = Tk()
window.title("Tax Calculator: Set fields to 0")
####before tax
self.beforetaxlabel = Label(window, text = "Before Tax: ", font = "Helvectica 12")
self.orgbtlVar = StringVar()
self.... |
c4781c5d01bdc679bcffe5fcc0ad6aa8b0b31999 | Sravanthi-Gogadi/PythonDeeplearningCourse | /PythonProgramming/ICP5/kmeans.py | 1,155 | 3.875 | 4 | # import matplotlib for plotting the clusters
import matplotlib.pyplot as plt
# import numpy library
import numpy as np
# from sklearn import kmeans
from sklearn.cluster import KMeans
# import random package to take random input dynamically
import random
# set the seed value to any int to get the same random values
ran... |
b5a0e2a6a10ffacabfce2e98284cb79846a4f0b3 | sabyers1/PyCode | /blackjack.py | 1,507 | 4.1875 | 4 | #blackjack tutorial
sample = ['A', 'A', '9']
sample2 = ['A','A','9','3']
def total_hand(hand):
total = 0
aces = 0
for card in hand:
if card.isdigit():
total += int(card)
elif card == 'A':
total += 1
aces += 1
else:
total += 10
wh... |
f5ceddcfe3581c618f7007734b4cc6bebe0ed336 | RadwaRamadan/Rock-Paper-Scissors | /first_trial.py | 1,705 | 4.46875 | 4 | '''
Basic idea :
1-Store the three cases in a dictionary
2-Get the input from the user
3-Generate a random integer representing the computer choice
4-Compare the the user choice and the computer choice as follow :
4.1-computer chooses the same as the user
4.... |
9736360d9b409ae3cde5ba388993338477e9964a | edward-tes/pydemo | /face.py | 1,367 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# face_detect.py
# Face Detection using OpenCV. Based on sample code from:
# http://www.pythontab.com
# Usage: python face_detect.py
import sys, os
#引入opencv库中的相应组件
from cv2.cv import *
#引入PIL库
from PIL import Image, ImageDraw
from math import sqrt
def detectObje... |
c9448f430c3480a10d9ca41f38c7eaf65f7ab32b | vanadgir/Misc | /armygame.py | 9,078 | 3.84375 | 4 | # IMPORT
import os
import time
from random import *
# TITLE
os.system('clear')
print("|--------------------------------|")
print("|--------BARN'S ARMY GAME--------|")
print("|--------------------------------|")
# DEFINE BATTLE RULES
def custom_battle():
# INTRODUCTION
os.system('clear')
input("Please sta... |
91bef526d298831e6fc1772c1e842cc87550385e | christopheradriankusuma/Little-Pygame | /Tower of Hanoi/tower-of-hanoi.py | 5,430 | 3.5625 | 4 | # from pygame import *
import pygame
pygame.init()
WIDTH = 800
HEIGHT = 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tower of Hanoi")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
... |
7cba9f4a73a009ebe4d28bb587643ab2b27e519d | caiobonamin/hello-world | /metodo_strip_split.py | 488 | 3.796875 | 4 | # -*- coding: utf-8 -*-
texto = "Caio Allan Bonamin Caio Allan Bonamin"
#imprime o valores na ordem conforme incrementando o i com + 1
#adicionando a função .strip() remove o "\n" que pula uma linha ou ate mesmo um espaço do final da variável
print(texto.strip())
#com a função .split() transforma uma va... |
ddd4792629b53bc798f90a868491189284414f8e | marydCodes/jba_textgenerator | /Topics/Exception handling/Implementing logic/main.py | 284 | 3.75 | 4 | try:
name, surname = input().split()
print("Welcome to our party,", name, surname)
except ValueError:
print("You need to enter exactly 2 words. Try again!")
# ValueError: not enough values to unpack (expected 2, got 1)
# ValueError: too many values to unpack (expected 2) |
9f905e237b15846c45ed0daec7b50781aba3d2ec | lcarbonaro/python | /session20170117/myclass1b.py | 234 | 3.78125 | 4 | class Animal:
def about(self):
desc = 'I am an animal'
print(desc)
an1 = Animal()
an1.about()
an1.species = 'dog'
an1.food = 'meat'
an2 = Animal()
an2.about()
an2.species = 'horse'
an2.food = 'hay' |
d977453ac61a771d8e5d5bf60f057f14eb77fa25 | tinglesby87/PythonBlackjack | /Blackjack.py | 6,712 | 3.859375 | 4 | import random
# def start_game()
# Game()
# def start(self):
# Game = play_game()
# unfinished
def start__game():
answer = input("Do you want to start a game of Blackjack? Y/n")
if answer != "n":
make_deck()
# play_game() suits= ["H", "D", "C", "S"]
values = [2, 3, 4, 5, 6, 7, 8, 9, 10, ... |
856e776f00410eedb1ded20fd1e1ef929d0732bc | kitbitsks/alg_sol | /getNthFib.py | 608 | 3.671875 | 4 | # Space : O(n), Time : O(2^n)
def getNthFib(n):
if n == 1:
return 0
if n == 2:
return 1
return (getNthFib(n-1) + getNthFib(n-2))
# Space: O(n), Time : O(n)
def getNthFib(n, cache = {1:0,2:1}):
if n in cache:
return cache[n]
else:
cache[n] = getNthFib(n-1,cache) + getNthFib(n-2,cache)
return cache[n]
... |
3ddf5f2c1abe2974a23de025bd9a350b545ddb9d | ChangxingJiang/LeetCode | /LCCI_程序员面试金典/面试08.07/面试08.07_Python_3.py | 554 | 3.625 | 4 | from typing import List
class Solution:
def permutation(self, S: str) -> List[str]:
if len(S) == 2:
return [S, S[::-1]]
else:
ans = []
for i in range(len(S)):
ch = S[i]
for other in self.permutation(S[:i] + S[i + 1:]):
... |
6b002c2289800286e23e715774fba9e9a1a10cd8 | cutewindy/Leetcode | /Set_Matrix_Zeroes.py | 2,253 | 4 | 4 | # Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
# click to show follow up.
# Follow up:
# Did you use extra space?
# A straight forward solution using O(mn) space is probably a bad idea.
# A simple improvement uses O(m + n) space, but still not the best solution.
# Coul... |
386b2bac177248dde1552fc710bce1eff685ec8d | 6112/project-euler | /problems/037.py | 1,259 | 3.84375 | 4 | # encoding=utf-8
## SOLVED 2013/12/25
## 748317
# The number 3797 has an interesting property. Being prime itself, it is
# possible to continuously remove digits from left to right, and remain prime at
# each stage: 3797, 797, 97, and 7. Similarly we can work from right to left:
# 3797, 379, 37, and 3.
# Find the sum... |
627505c135b05a2fc2ef6e9edc19bb74120eb189 | ViniciusBrag/Exercicios-Python | /Mundo - 2/Desafio044.py | 986 | 3.796875 | 4 | print('=' * 4, 'Desafio ', '=' * 4)
print('Olá Bem vindo')
nome = str(input('Digite seu nome: ')).title()
valor = float(input('Digite o preço do produto:R$ '))
print('Opção:\n{} ( 1 ) Á Vista \n ( 2 ) Cartão Á Vista \n ( 3 ) 2x no Cartão \n (4) 3x ou mais{}'.format('\033[34m)', '\033[m'))
cond = int(input('Digite a op... |
a65b5ff8cc9f556dcfad4bce1864f3e807579fa5 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/Mid Exercise/13.py | 173 | 4.0625 | 4 | '''
13. Write a Python program to sum all the items in a list.
'''
my_list=[1,2,3,4,5,6,7]
sum=0
for i in range((len)(my_list)):
sum=sum+my_list[i]
print(sum) |
6e35fc68f5487a551eb014705f2df7e558ffc422 | cha606/FindDocumentContainingWord | /LookUp.py | 1,586 | 3.640625 | 4 | import os
import docx
look = input("Enter the keyword: ")
look=str(look)
#print(os.listdir(r"C:\Users\Richard\Desktop\LookupTest"))
Results=[]
def searchThroughFileDocx(filename):
doc=docx.Document(filename)
FullText=""
for z in range(len(doc.paragraphs)):
FullText+= " " + doc.paragr... |
7be602ea3e4feae11b7aa099256f0d5e522acc51 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise09_29.py | 2,926 | 3.671875 | 4 | from tkinter import * # Import tkinter
from random import randint
import math
width = 300
height = 200
radius = 2
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Is point (x, y) close to this point
def isNearBy(self, x, y):
return distance(self.x, self.y... |
deecee792de7039182510abd5ec19e468b2a9160 | kaka-go/Programming | /python/lintcode/443-unionset.py | 2,240 | 4 | 4 | import pprint
class UnionSet:
def __init__(self):
self.root = {}
def count(self):
# pprint.pprint(self.root)
s = set()
for key in self.root:
r = self.findRoot(key)
s.add(r)
# print(s)
return len(s)
def makeSet(self, node):
... |
92668a346e5b9e29e6201894ddd0b668e37036b7 | EdwardJTL/CSC180 | /Pycharm/Lab 3/4_DataStructures.py | 1,820 | 3.6875 | 4 | import random
import string
def isPrime(x):
r = True
for i in range(2,x):
if (x%i==0):
r = False
break
return r
def genPrime(min,max):
while True:
x=random.randint(min,max)
if isPrime(x):
break
return x
n = 0
accum = []
while (n<10):
... |
cdb23e6d146c652a00db0d76fa4f5bfa18f1be4f | sling1678/python | /hacker_rank/src/day_4_prob_geom_distr.py | 1,255 | 4.1875 | 4 | # Objective In this challenge, we learn about geometric distributions. Check out the Tutorial tab for learning
# materials!
#
# Task
# The probability that a machine produces a defective product is . What is the probability that the defect is found during the inspection?
#
# Input Format
#
# The first line contains t... |
66a24c9bbf2aed44f3d2a5e62bb7764314036b0a | alex1431999/APOA-Common | /common/mongo/data_types/user.py | 1,390 | 3.671875 | 4 | """
MongoDb data type
"""
from passlib.hash import pbkdf2_sha512
class User:
"""
This class carries a user result from the mongodb database
"""
def __init__(self, _id, username, password, created_at):
"""
Set attributes
:param ObjectId _id: The id of the database object
... |
d3fc38e81517a8e4a411a44596e08baf20a27c80 | dTenebrae/Python | /lesson3/lesson3_6.py | 1,025 | 3.75 | 4 | # Реализовать функцию int_func(), принимающую слово из маленьких латинских
# букв и возвращающую его же, но с прописной первой буквой. Например,
# print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов,
# разделенных пробелом. Каждое слово состоит из латинских букв... |
643413167f280e531131964aafb8e6bfad39ee26 | eareyan/emd-adx | /strategies/WE.py | 4,440 | 3.796875 | 4 | import itertools
from typing import Dict, List
import pulp
from game.structures import Market, Allocation, Good, Bid, Sorting
def greedy_allocation(m: Market) -> Allocation:
"""
Given a market, returns a greedy allocation.
:param m: a market
:return: an Allocation
"""
# Sort a shallow copy o... |
55e226e6a706624418c97df93df7f202b0aded4e | JiahongHe/Data-Structures-and-Algorithms | /Data Structures/Assignment3/hash_substring.py | 764 | 3.828125 | 4 | # python3
def read_input():
return (input().rstrip(), input().rstrip())
def print_occurrences(output):
print(' '.join(map(str, output)))
def hash_func(s):
_multiplier = 263
_prime = 1000000007
ans = 0
for c in reversed(s):
ans = (ans * _multiplier + ord(c)) % _prime
... |
c85799c0967cf745068800b559a0343fd3aed781 | dwjkate/Python-Study | /Jump02-Q2.py | 193 | 4.15625 | 4 | #자연수 13이 홀수인지 짝수인지 판별할 수 있는 방법에 대해 말해 보자
num1 = 13
if num1%2 == 1 :
print('This is odd number')
else:
print('This is even number') |
0d90065d254cf85703c3b54b1b2a1d207836c3d8 | nikhil-pandey/corobots-melodic | /corobot_follower/scripts/point.py | 995 | 3.9375 | 4 | from fractions import Fraction
class Point:
"""
The point class.
"""
def __init__(self, x, y, segment=None):
"""
(x, y) points. Uses fraction to prevent round-off error.
:param x: The x-coordinate.
:param y: The y-coordinate.
:param segment: The segment point b... |
9cf3358999a736c09a41a974a40a1fa2e0caf9a3 | codeBueno/Python-FileRenamer | /FileRenamer.py | 801 | 3.96875 | 4 | import os
def rename_files():
#get file names from folder
file_list = os.listdir(r"{replace with path of files to change}")
#if you want to make sure you've got the right path, unhash next line
#print(file_list)
saved_path = os.getcwd()
print("current working directory is " +saved_path)
os.c... |
cbbea21b90b3dc028b2fc30cf631eb1287d6563b | Maxington20/Python-Udemy-Course | /BasicLessons/Tkinter-self-adjusting-widgets.py | 266 | 4.28125 | 4 | from tkinter import *
root = Tk()
label1 = Label(root, text="First Name", bg="Red", fg="White")
label1.pack(fill=X) # fill this label to the width of the window
label2 = Label(root, text="Second", bg="Blue", fg="Green")
label2.pack(side=LEFT, fill=Y)
root.mainloop() |
d5603e7ca6f48fd5876b2a948c2804d9eee0aced | tb659/python | /demo/基本.py | 3,935 | 3.625 | 4 | '''
Author: tb659
Date: 2021-08-14 12:17:34
LastEditors: tb659
LastEditTime: 2021-08-14 15:13:33
Description:
FilePath: \python\基本.py
'''
# coding=utf-8
import datetime
import random
import math
import time
import calendar
a = 1
b = 2
print(a + b)
print('你好')
list = ["a", "b", "c"]
print(list)
for item in list:
... |
06322ae49ac57c2e0fd858f52ff1ee82ef8ebc42 | jhanse9522/Feet-Wet-Python2 | /score.py | 431 | 4.09375 | 4 | prompt = ("Enter score: \n")
try:
grade = input(prompt)
if .9 <=float(grade) <= 1:
print("A")
if .8 <= float(grade) < .9:
print("B")
if .7 <=float(grade) < .8:
print("C")
if .6 <=float(grade) < .7:
print("D")
if float(grade) < .6:
print("F")
except:
print("Bad score!")
def computegrade(score)
... |
2ebc0ffc92374603625a7f537981a7fcd42dcd17 | aryamanchoudhary123/Morse_converter | /morse_code.py | 1,851 | 3.703125 | 4 | code={
"a":".- ", "b":"-... ", "c":"-.-. ", "d":"-.. ", "e":". ", "f":"..-. ",
"g":"--. ", "h":".... ", "i":".. ", "j":".--- ", "k":"-.- ", "l":".-.. ",
"m":"-- ", "n":"-. ", "o":"--- ", "p":".--. ", "q":"--.- ", "r":".-. ",
"s":"... ", "t":"- ", "u":"..- ", "v":"...- ", ... |
1c4feae51df1c33620b688f1137f6d7fa39a019a | ccamargo8/Mi-primer-repositorio | /Funciones.py | 2,626 | 4.125 | 4 | #Funciones
def imprimir ():
""" Esta funcion se utiliza para imprimir. Triplecomillas se llaman DOCSTRING """
print("Función para imprimir")
print("Otro Letrero")
imprimir()
help(imprimir) #Permite imprimir lo que se ponga entre triple comillas
def imprimir_2(letrero):
print(letrero)
imprimir_... |
875f0277e8f0a1d890f62156d1ff2f9287f22dc2 | habeebahmed/challenges | /bin_to_dec_oct_hex.py | 2,906 | 3.875 | 4 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
# print("Hello World")
# b_num = list(input("Input a binary number: "))
# value = 0
# for i in range(len(b_num)):
# di... |
beb350331e2c47ae3d78c726377f40db50189e67 | sidlim/BIMM-181 | /3. assembly/29. k universal circular binary string.py | 2,602 | 3.5 | 4 | import sys
import random
# Given an integer k, construct a string that, when
# circularized, contains every k-mer on the alphabet [0, 1]
# run `python main.py filepath` where the file's first line is k.
def main():
file = open(sys.argv[1], "r")
k = int(file.readline().strip())
kmers = all_kmers(k - 1, ["0... |
73b55deb5b6a3fab056e91cf45378e03bb4c6292 | kmesfun/UCB_projects | /3-game-Arcade/diceroll.py | 260 | 4.0625 | 4 | import random
min=1
max=6
roll_again="yes"
while roll_again == "yes" or roll_again =="y":
print"Rolling the dices.."
print "Values are..."
print random.randint(min,max)
print random.randint(min,max)
roll_again=raw_input("Roll dices again?")
|
e071e978df5eccfa0c22879fc4b32dfa7bc0d8bf | x-jeff/Algorithm_Code | /python/Sort/MergeSort.py | 652 | 4.09375 | 4 | import math
def mergeSort(arr):
if (len(arr) < 2):
return arr
middle = math.floor(len(arr) / 2)
left, right = arr[0:middle], arr[middle:]
return merge(mergeSort(left), mergeSort(right))
def merge(left, right):
result = []
while left and right:
if left[0] <= right[0]:
... |
cc889dceb7f2820944db6f8f505fb5e923404c9b | MohamedHedeiwy/Learning-Python | /Learning_Python.py | 1,167 | 4.34375 | 4 | print(10 / 3)
print(10 // 3) # Using // prints the number in an integer form instead of a float
multiline = """
This
is
a
multi
line
string
"""
print(multiline)
print('{0} {2} {0}'.format(0,1,2)) # the number inside the {} represents the index of what is inside the format function
# The Back slash tells python to ... |
289f94dd6a3628970db258ca37a2ecca9b776f36 | JCarlos831/cs50 | /week6/mario3.py | 270 | 4.1875 | 4 | # Prints a positive number of question marks, as specified by user
from cs50 import get_int
# Prompt user for a positive number
while True:
n = get_int("Positive number: ")
if n > 0:
break
# Print out that many bricks
for i in range(n):
print("#") |
de94608a24be509d4bc2d1dd693959a860d35b1a | zamirzulpuhar/zamir- | /2 неделя/какое число больше.py | 128 | 3.8125 | 4 | a = int(input())
b = int(input())
if a - b > 0:
print(1)
elif b - a > 0:
print(2)
elif a - b == 0:
print(0)
|
e267f23926eb3359684f35361dd9bebf79bd8c3d | akylly/futuredemand | /test_anagram.py | 808 | 3.765625 | 4 | # Run 'python3 test_anagram.py' to run tests
import unittest
from anagram import is_anagram
class AnagramTest(unittest.TestCase):
def test_empty_strings_should_return_true(self):
self.assertTrue(is_anagram('', ''))
def test_small_strings_should_return_true(self):
self.assertTrue(is_anagram(... |
7a1189bd588f1adf97e566da2b08699e4d05e391 | jfdousdu/pythonProject | /jianzhioffer/jiaonan/JZ29.py | 1,686 | 3.703125 | 4 | '''
最小的K个数
输入n个整数,找出其中最小的K个数。
例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
'''
#本事使用sort排序速度很快但感觉面试不能用sort
# class Solution:
# def GetLeastNumbers_Solution(self, tinput, k):
# if k == 0 or tinput == None or k > len(tinput):
# return []
# tinput.sort()
# print(tinput)
# use... |
6e10a065e1e2c1f148a1513dbe504589bdfcd119 | sohye-lee/algorithm_study | /strings/11654.py | 319 | 3.71875 | 4 | import string
letter = str(input())
# upper = list(string.ascii_uppercase)
# lower = list(string.ascii_lowercase)
# if letter in upper:
# print(upper.index(letter)+65)
# elif letter in lower:
# print(lower.index(letter)+97)
# elif int(letter) in range(0,10):
# print(int(letter) + 48)
print(ord(letter)) |
b77278f19e1f2d7aec184189be719a46a5503e46 | sahilg50/Python_DSA | /others/prime.py | 305 | 4.15625 | 4 | num = int(input("Enter the number to be checked: "))
def Check_Prime(num):
if num < 2:
print("The number is not prime! ")
else:
for i in range(2, num):
if(num % i == 0):
return print("prime")
return print("Non Prime")
Check_Prime(num)
|
58645eb74bfb29b2be43b69963cf0b4d1b5e06f3 | walkccc/LeetCode | /solutions/0677. Map Sum Pairs/0677.py | 702 | 3.578125 | 4 | class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode)
self.sum = 0
class MapSum:
def __init__(self):
self.root = TrieNode()
self.keyToVal = {}
def insert(self, key: str, val: int) -> None:
diff = val - self.keyToVal.get(key, 0)
node: ... |
91fc44950a05a9ae9b36847af16342c83b9bbd29 | henrique-af/cursoemvideo-python | /Desafio59.py | 2,454 | 4.03125 | 4 | print('====== DESAFIO 59 ======')
print('~~~ CALCULADORA ~~~')
n1 = float(input('Digite o 1º número: '))
n2 = float(input('Digite o 2º número: '))
print('1 - Somar\n'
'2 - Multiplicar\n'
'3 - Maior\n'
'4 - Novos números\n'
'5 - Sair do programa')
menu = int(input('Qual sua opção? '))
while menu ... |
9cad5cd2d369f241a34c39aa02c12ead79548259 | mutdmour/projecteuler | /projecteuler-2015/p46.py | 676 | 3.625 | 4 | def checkprime(x):
if x == 1:
return False
for i in range(2,int(x**(1/2)+1)):
if x % i == 0:
return False
return True
def main():
z = True
i = 1
prime = []
while z == True:
i = i + 2
if checkprime(i) == True:
prime.append(i)
e... |
89bb160c9692f168aba0891a422e4525db66a5b2 | AmandaBoatswain/Tutorial-IntroToPythonProgramming | /instrumentation_python_intro.py | 6,291 | 4.625 | 5 |
# coding: utf-8
# ** Mac Robotics Club Tutorial 5: An Introduction to Coding in Python **
# Tuesday November 7, 2017
# Created by Amanda Boatswain Jacques
# In[3]:
## Printing to the screen
print('Hello')
print('World!')
# In[4]:
## Simple numerical operations
# (*) Means multiply, (/) means divide, (+) means to... |
aa1e51faa7455449d9ccef94c2854cbec9818bd2 | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Tkinter GUI/10.Check_Box.py | 1,309 | 3.984375 | 4 | #Name: Jake Lorah
#Date: 12/5/2018
#Program Number: 10.Check_box
#Program Description: This program adds a check box.
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.title("Welcome To Computer Science 4")
window.geometry('350x200')
var = IntVar()
def sel():
selection =... |
f49f050b159de87fe80f5d9d2b01f8d09326a5a3 | sayeed007/PythonProgramming | /MySQL/5_Python MySQL Select From.py | 637 | 3.625 | 4 | import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="123456",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
#Selecting Columns
mycursor.execute("SELECT name,... |
e6390324909b46a304f390133663d48cc35edcc6 | kiran-kotresh/Python-code | /freq_seq.py | 163 | 3.796875 | 4 |
def freq_seq(s, sep):
result = ''
for i in s:
result += str(s.count(i)) + sep
return(result.strip(sep))
print(freq_seq('hello world', '-'))
|
ae04ad0e7b199026667ddf2ebb37d41d109638c9 | SATYAM9717069261/python | /Exp4_c.py | 400 | 3.578125 | 4 | class class1:
def data1(sel):
sel.a=10;
class class2(class1):
def data2(sel):
sel.data1();
sel.b = 20 + sel.a;
class multi_inher(class2):
def data3(sel):
sel.data1();
sel.data2();
sel.result=20+sel.b
def out(sel):
print "Result => " + str(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.