blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3714290166d95b048beff2b2ba2950f70678485c | hajdaini/tomo | /src/database.py | 2,259 | 3.75 | 4 | #!/usr/bin/python3.6
#coding:utf-8
import sqlite3
import sys
"""
Classe Database
- Sauvegarde les données du jeu
"""
class Database:
__instance = None
def __init__(self, filename : str):
self.filename = filename
self.connection = None
self.cursor = None
if Database.__instance is None:
Database.__instanc... |
b10bcbbac711fd39ce1cb97a7b34f67618e8c36b | dnbadibanga/Python-Scripts | /calc_area.py | 181 | 4.3125 | 4 | #Calculate the area of a circle
from math import *
radius = input('Enter the radius of a circle: ')
radius = int(radius)
area = pi * (radius ** 2)
print('The area is ', area)
|
a9aff10aa9a634abf0fafa793872b7c206cbaa39 | praneesh12/python_review | /Collections_module/hackerank_OrderedDict.py | 370 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 6 14:28:06 2019
@author: praneeshkhanna
"""
from collections import OrderedDict
n = int(input())
d = OrderedDict()
for i in range(n):
item, price = (input().rsplit(None, 1))
if item not in d.keys():
d[item] = int(price)
else:
d[item]... |
3a19f15d99ea37d76839c5e8e3c15ff28dbff029 | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 10 Tuples/Code/Lab 10.2 Tuples are NOT immutable.py | 444 | 3.640625 | 4 | __author__ = 'Kevin'
# 08/04/2015
# Tuples are NOT immutable
# Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string
x = [9, 4, 7]
print x # [9, 4, 7]
x[2] = 6
print x # [9, 4, 6]
# cannot convert string variable
# y = 'ABC'
# y[2] = 'D' # Traceback:'str' object doe... |
2d4f8b57199e02c2e5e61b398bad6915612689e5 | kodeskolen/tekna_h19 | /trondheim/dag2/funksjoner2.py | 356 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 16:55:49 2019
@author: Marie
"""
def legg_sammen(ledd1, ledd2):
return ledd1 + ledd2
def maks(a, b):
# Ta inn to tall, returner det største av dem
if a > b:
størst = a
else:
størst = b
return størst
print(legg_sa... |
60eedb5211db6dad67bf52deec72877d86170771 | MonsieurPengu/ENGR-102 | /Apps and Progs/Lab3Act2.py | 818 | 3.9375 | 4 | name1 = str(input("First name "))
day1 = int(input("First day "))
month1 = int(input("First month "))
year1 = int(input("First year "))
name2 = str(input("Second name "))
day2 = int(input("Second day "))
month2 = int(input("Second month "))
year2 = int(input("Second year "))
name3 = str(input("Third name "))
d... |
b8cf0ac6ff9726649088f5f4dcdbb436aa5993ec | breathfisheva/Algorithm | /Greedy Algorithm/GiveChange.py | 1,883 | 3.75 | 4 | '''
钱币找零问题
这个问题在我们的日常生活中就更加普遍了。假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。现在要用这些钱来支付K元,至少要用多少张纸币?
用贪心算法的思想,很显然,每一步尽可能用面值大的纸币即可。在日常生活中我们自然而然也是这么做的。在程序中已经事先将Value按照从小到大的顺序排好。
分解问题:
当还需要找N'钱的时候,选择一个纸币用来找零,这个纸币要小于还需要找的钱的值,而且这个纸币还有>0张
选择最优策略:
策略1:选择面值最大的纸币
'''
class Money(object):
def __init__(sel... |
9ab9f49feb09e8ff5930514b3f664fcd583a74d9 | shadowlaw/data_struct | /BinaryHeap.py | 2,715 | 4.09375 | 4 | class Node:
def __init__(self, value):
self.value = value
self.is_min = True
self.left = None
self.right = None
self.parent = None
class Heap:
class Queue:
def __init__(self):
self.__queue = []
def empty(self):
return self.__queu... |
7ff552b80486bc00059ee089ab4b2cd847fa9df5 | noamrubin22/dataprocessing | /homework/week_1/scraper/tvscraper.py | 4,282 | 3.609375 | 4 | #!/usr/bin/env python
# Name: Noam Rubin
# Student number: 10800565
"""
This script scrapes IMDB and outputs a CSV file with highest rated tv series.
"""
import csv
import re
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
TARGET_U... |
6d744cb1c88d063a3265cce976134928a2a03a99 | kojino/nlp100 | /ch1/p5.py | 551 | 3.6875 | 4 | # 5
def ngram(n,s,unit):
if unit == "char":
chars = s
return ngram_char(n,s)
elif unit == "word":
words = s.replace(',','').split( )
return ngram_word(n,words)
else:
raise ValueError('unit must be char or word')
def ngram_char(n,s):
result = []
for i in range(len(s)-n+1):
result.appe... |
9eba57c0586d9a6e8fe03db61e977ec3c60cbd9c | red23495/random_util | /Python/Algebra/binary_exponentiation.py | 671 | 3.90625 | 4 | def mod_pow(base, power, mod=None):
"""
Implements divide and conquere binary exponetiation algorithm
Complexity: O(log power)
source: https://cp-algorithms.com/algebra/binary-exp.html
Params:
@base: base number which needs to be multiplied
@power: power to which base should be raised
@... |
7502b23ccae00d7afa3e787308781251b8632930 | JanaRasras/CNN | /P01.py | 1,109 | 3.765625 | 4 | '''
@ Jana Rasras
Train CNN to classify images with Pytorch
'''
# Import libraries
import numpy as np
from matplotlib import pyplot as plt
from torch import nn # torch for nn and torchvision for datasets
from torchvision import datasets, transoforms #datasets for mnist # transforms for preprocessing
#... |
a6651bca2e1d83bb7c1bba1ea7f7211300f0eeef | tiagopalomares/covid-19-program | /covid-19-program.py | 1,052 | 4.125 | 4 | # new-program
print('COVID-19 ')
import time
# introdução
time.sleep(2)
print('Esse Programa foi desenvolvido por Tiago Palomares')
time.sleep(2)
print('Iniciando Programa . . . ')
time.sleep(2)
nome = (input('Qual o seu nome? '))
time.sleep(1)
print('Bem vindo {}'.format(nome))
time.sleep(1)
idade = int(input('Qual a... |
ecebb551e0dc0f5e8123e4d6f04678cd47086b81 | Iamsdt/Problem-Solving | /problems/hacker_earth/basic_input_output/ali_helping_innocent_people.py | 378 | 3.5625 | 4 | code = input() #"12X345-67"
# take first two
first = int(code[0]) + int(code[1]) % 2
# now check later
vowels = ["A","E","I","O","U","Y"]
# now check
second = int(code[3]) + int(code[4]) % 2
third = int(code[4]) + int(code[5]) % 2
fourth = int(code[7]) + int(code[8]) % 2
if first+second+ third+ fourth == 0 and code[2... |
09f5c8bf9c92f7990757dbdf04ddcef967851205 | daniel-reich/ubiquitous-fiesta | /xA8FJW2cwjAnJ2ptt_3.py | 122 | 3.640625 | 4 |
import re
def bomb(txt):
return "There is no bomb, relax." if re.search("bomb", txt.lower()) == None else "Duck!!!"
|
0fa132a77a3d3fe74a7c4f268aa3bd12f02d53fb | kobyyoshida/Project-Euler-Problems | /prob14.py | 1,022 | 4.03125 | 4 | import operator
highest = 0
memory = {}
def even(num):
return num/2
def odd(num):
return (3*num)+1
def process_num(num,chain):
#print("CHAIN CHECK: ",chain)
if num == 1:
#print("DONE")
return int(chain)
elif num % 2 == 0:
if num in memory:
return chain+memory[... |
71b26523d2cfa7f747799778bce39e612710cc3a | fis-jogos/2016-2 | /python-101/03 while.py | 866 | 4.25 | 4 | # O while executa um comando enquanto o argumento possuir um valor de verdade
# igual à True.
#
# No loop abaixo, enquanto x for menor que 5, o valor de verdade da expressão
# "x > 5" será verdadeiro. Neste caso, imprimimos os números de 1 a 5
x = 0
while x < 5:
x += 1
print('x = %s' % x)
# Note que essas fo... |
edb63793a549bf6bf0e4de33f86a7cefb1718b57 | onionmccabbage/python_april2021 | /using_logic.py | 355 | 4.28125 | 4 | # determine if a number is larger or smaller than another number
a = int(float(input('first number? ')))
b = int(float(input('secomd number? ')))
# using 'if' logic
if a<b: # the colon begins a code block
print('first is less than second')
elif a>b:
print('second is less than first')
else:
pr... |
c45ebbaa7cca26fe8972c43b51ae727dd8ee35b2 | marcdloz/cosc4377-Computer-Networks | /practice2_3.py | 793 | 3.96875 | 4 |
# range starts inclusive, exclusive, then step
def main():
for i in range(2):
print("Go, Cats, Go!")
print("Go, Dogs, Go!")
print("BEAR DOWN!")
for i in range(3):
print("Who's house?! COUGS HOUSE")
for i in range(5):
print(i)
for num in range(2, 11, 2):
p... |
92cc15e32cb659ed74d9fab6f79a11d05591bd72 | gabriellaec/desoft-analise-exercicios | /backup/user_087/ch19_2019_03_12_03_14_04_642132.py | 228 | 3.515625 | 4 | import math
θ = float(input())
θ= math.radians(θ)
def calcula_distancia_do_projetil(v, θ, y0):
d = ((v**2)/(2 * 9.8))*(1 + math.sqrt(1 + (2 * 9.8 * y0)/(v*math.sin(θ))**2))*math.sin(2*θ)
return d |
89aa3909cf0b4328ddc516261238123fee97c1ff | TylerJGabb/MoshPython | /foundational/classes/data_classes.py | 576 | 4.1875 | 4 | from collections import namedtuple
"""
sometimes we don't really need a class if all we are doing is storing data, so in this case
we can use the data class "named tuple" that allows us to create objects in a way that is
expliciy and everything is name
In this case, checking equality will only validate that data fie... |
35ac102cfebb2f1948aef10f5ffd981f9ef64b6a | BITMystery/leetcode-journey | /21. Merge Two Sorted Lists.py | 591 | 3.546875 | 4 | class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur = ListNode(0)
while cur:
if not l1:
cur.next = l2
break
if not l2:
... |
422b37bcac901a23e2af37809c89b17d83c7b1ff | adamrosenberg/LearnPython | /ex35.py | 1,521 | 3.953125 | 4 | from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next=raw_input("> ")
how_much = int(next)
if how_much < 50:
print "Nice, you aren't that greedy. You win!"
exit(0)
else:
dead("GREEDY! YOU LOSE!")
def bear_room():
print "There is a bear here"
print "The be... |
83ae840c22634cbfbc4b6d19721356779dad68b9 | HellHuang/group_training | /base_exercise.py | 655 | 3.796875 | 4 | __author__ = 'fen'
#coding=utf-8
import random
list=[]
for i in range(5):
list.append(int(random.random()*100))
print "fist list",list
print "top 3",list[:3]
for i in range(10):
list.append((random.random()*50))
print "append list",list
list.sort()
print "soar list",list
list.sort(reverse=True)
print "decent li... |
683186491e97e944cbe0d665d937265fda1a316b | aloklenka666/python101 | /ex3.py | 334 | 3.5 | 4 | # + -> addition operation
# - -> substraction operation
# / -> division operation
# * -> multiplication operation
# % -> modules operation ( reminder)
# < -> less than
# > -> greater than
# <= -> less than equal
# >= -> greater than equal
print(5+6*4/2-5)
print(10%2)
print(5>6)
print(3<5)
print(5<=3)
print(7>=4)
print... |
d1f0010c2db6a36517ba6c5ec70b537fffa159d9 | TheSlientnight/Algorithms-and-Data-Structures | /Graph/KnightTour.py | 2,141 | 3.53125 | 4 | from KnightGraph import knight_graph
def knight_tour(depth, path, vertex, limit):
vertex.set_color('gray')
path.append(vertex)
if depth < limit:
neighbors = order_by_available_moves(vertex)
i = 0
done = False
while i < len(neighbors) and not done:
if neighbors[i... |
d5ecb9639fa4dc7d29267fb3594f44c9f79e2ab4 | kirigaikabuto/Python19Lessons | /lesson11/6.py | 405 | 3.703125 | 4 | n = int(input())
arr = []
for i in range(n):
s = input() # yerassyl,22
name, age = s.split(",") # ["yerassyl","22"]
age = int(age)
arr.append([name, age])
maxiLen = 0
current = []
for i in arr:
if maxiLen < len(i[0]):
current = i
maxiLen = len(i[0])
print(current)
# #arr->[
# [... |
0011eb6310cc0a89ee3850b1c6642c4899401fae | acrodeon/coursera-algo1 | /algo1week2_programex2.py | 1,045 | 4 | 4 | ####################################################################
# Algo1 Week2 : 10,000 integers between 1 and 10,000 (inclusive) #
# in some order, with no integer repeated. #
####################################################################
import os
import sys
from algo1week2_quicks... |
c2a245b7663528d7301e46841b6e8c4ba7118b1c | Marcus893/algos-collection | /stack&queue/matching_bracket.py | 1,100 | 4.21875 | 4 | A string of brackets is correctly matched if you can pair every opening bracket
up with a later closing bracket, and vice versa. For example, "(()())" is correctly
matched, and "(()" and ")(" are not. Implement a function which takes a string of
brackets and returns the minimum number of brackets you'd have to add to t... |
470fcaa1347c7d68424e2eeb7f26eba657e1f89f | addyp1911/Python-week-1-2-3 | /python/Algorithms/MergeSort/MergeSort.py | 873 | 4.375 | 4 | #Merge Sort - Write a program with Static Functions to do Merge Sort of list of Strings.
#a. Logic -> To Merge Sort an array, we divide it into two halves, sort the two halves independently,
# and then merge the results to sort the full array. To sort a[lo, hi), we use the following recursive strategy:
#b. Base ca... |
abf5917af6585be1e5d3df218a426bd5e7196c97 | dm-fedorov/epixx | /lesson_8/linear_search3.py | 464 | 3.984375 | 4 | # linear_search3.py
def linear_search(lst, value):
'''
Реализация алгоритма линейного поиска. Версия 3
'''
lst.append(value)
i=0
while lst[i] != value:
i += 1
lst.pop()
if i == len(lst):
return -1
else:
return i
if __name__ == '__main__':
print(linear_... |
d0c292c63ea78d5105864b808f7a83002d4cd0cf | ValentynaGorbachenko/BasicLanguagesInfo | /py/other/classNode.py | 2,473 | 3.96875 | 4 | class Queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
# len(self.items) == 0
# print "inside the isEmpty method returns ", self.items == []
return self.items == []
# return len(self.items) == 0
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
... |
ef3e4c9be9e43f01ab719b7ec958bc565d5b5cfc | leomonu/CarPython | /Car.py | 608 | 3.53125 | 4 | class Car(object):
def __init__ (self,speedLimit,company,color,model):
self.speedLimit = speedLimit
self.company = company
self.color = color
self.model = model
def start(self):
print('Started')
def stop(self):
print('Stopped')
def accelara... |
73c6e9de25d4746b9cf491efcb739c50e0671f5c | dgisolfi/cmpt120-labs | /RobotStore.py | 1,786 | 3.75 | 4 | #Into to programing
#Author: Daniel Gisolfi
#Date: 11/18/16
#RobotStore.py
class Products:
def __init__(self,name,price,stock):
self.name = name
self.price = price
self.stock = stock
def stockCount(self):
if (self.stock > count):
return false
return true
... |
c62c0150939d4f3ee003706dd93dbd1f2c77d0b7 | neelgandhi108/Python-Codes- | /Magic Square.py | 1,632 | 4.125 | 4 | def magic_square(n):
magicSquare=[] # defining a variable magic square
for rows in range(n):
list=[] # defining the list so that whenever loops initiated a new list created for each row
for cols in range(n):
list.append(0) # whenever cols loop will be passed rows will be appended by value... |
387dad0987c3775cf0eb42ed368ce4894307ebdb | noorulameenkm/DataStructuresAlgorithms | /LeetCode/30-day-challenge/December/December 1st - December 7th/increasingOrderSearchTree.py | 1,086 | 3.71875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def increasingBST(self, root):
results = []
self.constructIncreasingBST(root, results)
... |
91fbd39cc7384a91350d8ba98c1bd4abf8b736a5 | jschnab/budgies | /src/spark/sort_s3_folders.py | 1,347 | 3.5625 | 4 | # script which reads a text file containing folder names and another
# containing their size, then saves a text file with folder names sorted by size
import os
# get path of the file containing accessions (= folders) names
with open('config.txt', 'r') as config:
while True:
line = config.readline()
... |
1dd7675790f7deaae1d020847b08b3f77fe7ae1a | BottleH/Algorithm-Python | /BaekJoon_Practice/Mathematics/Q_2292.py | 771 | 3.578125 | 4 | """
위의 그림과 같이 육각형으로 이루어진 벌집이 있다. 그림에서 보는 바와 같이 중앙의 방 1부터 시작해서 이웃하는 방에 돌아가면서 1씩 증가하는 번호를 주소로 매길 수 있다.
숫자 N이 주어졌을 때, 벌집의 중앙 1에서 N번 방까지 최소 개수의 방을 지나서 갈 때 몇 개의 방을 지나가는지(시작과 끝을 포함하여)를 계산하는 프로그램을 작성하시오.
예를 들면, 13까지는 3개, 58까지는 5개를 지난다.
"""
# 방이 한개씩 늘어날 때마다 숫자는 6개씩 증가함.
n = int(input())
cnt = 1 # 기준값
num = 6 # 숫자의 갯수
resul... |
cce2a195c1929bf0bbeb68e87ff5a9bcf33edeba | Alistrandarious/FizzBuzz-and-Rock-Paper-Scissors | /While.py | 533 | 3.640625 | 4 | #x = 0
#while (x) < 10:
# print(x)
# x += 1 # x = x + 1
#while x <= 10:
# print(f"The number is currently {x}")
# x += 1 # x = x + 1
# if x == 4:
# print("bored now")
# break
counter = 0
ageNum = False
while ageNum == False:
counter += 1
age = input(f"Attempt {counter}: What is ... |
a018743caf298dd57455de239b55d02b11d6f7a5 | Bcoders/Searching_and_Sorting | /Sum_to_100_ShiftedUp.py | 693 | 3.671875 | 4 | def operation(str1, str2, set1):
str1 = str1+str2[0]
str2 = str2[1:]
sign = ['+','-','']
for item in sign:
str3 = str1+item
str4 = str3+str2
if str4[-1] == item:
break
add = eval(str4)
if add == 100:
... |
718e1f95452502cc941ad556cc7345f9fa1a360b | xxd59366/python | /pycharmContent/else/testmk03.py | 327 | 3.640625 | 4 | import random
import string
key_poll=string.ascii_letters+string.digits
def gen_pass(n=8):
"说明:生成密码"
result=''
for i in range(n):
result+=random.choice(key_poll)
return result
if __name__ == '__main__':
print(gen_pass())
print(gen_pass(4))
print(gen_pass(12)) |
3f19b16871dcd793ec0916a909f708dfb1a3e235 | nsiicm0/project_euler | /5/impl2.py | 1,366 | 3.796875 | 4 | '''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
n = 20
def get_test_numbers(n:int) -> int:
'''We will only test the largest multiples
for instan... |
81c484e0eb3971043f2a6abf4cf7470abb1db852 | percivalalb/Python | /Python 3/pacman/datacomplier.py | 4,210 | 3.75 | 4 |
class dataoutput():
def __init__(self):
self.data = bytearray()
def writeByte(self, byte):
assert(byte >= 0 and byte <= 255), 'Can\'t write a %d as a byte' % byte
self.data.append(byte)
def writeInteger(self, integer):
negative = integer < 0
integer = i... |
0b40c796e20ddeee67bd3df55f4e6fafc5e745e8 | Niemaly/python_tutorial_java_academy_and_w3 | /zad_11-20/zad15.py | 169 | 4.0625 | 4 | word = input("wprowadź słowo")
if word[-1] == "m" or word[-1] == "M":
print("ostatnia litera to M lub m")
else:
print("ostatnia litera jest inna niż m lub M") |
21553b42216d701b4d909e6f7f2aea8cd5c5cfd0 | Dilshan1997/Hacktoberfest-2021-Full_Python_Tutorial | /Beginner level/Arithemetic operator.py | 119 | 3.8125 | 4 | print(2+32)
print(2*5)
print(7/2)
print(2**5)
x=int(input('x:'))
y=x+3
print(y)
y+=3
print(y)
x+=7
print(x)
print(7//5) |
66df08e69ad0020e42a8a3f150931520b522e6fb | 810Teams/pre-programming-2018-solutions | /Onsite/1130-Matrix Multiplication 3x3.py | 678 | 4.03125 | 4 | """
Pre-Programming 61 Solution
By Teerapat Kraisrisirikul
"""
def main():
""" Main function """
matrix_a = [[int(input()) for _ in range(3)] for _ in range(3)]
matrix_b = [[int(input()) for _ in range(3)] for _ in range(3)]
matrix_r = [[multiply(matrix_a, matrix_b, i, j) for j in range(3)] for i in ra... |
79e1dd972927c161894a7a5337e8303e81de2aab | aasheeshtandon/Leetcode_Problems | /linkedList_implementation_of_stack.py | 1,539 | 3.953125 | 4 | from __future__ import print_function
class Node:
def __init__(self,value):
self.val = value
self.next = None
class Stack():
def __init__(self):
self.top = None
def isEmpty(self):
if self.top is None:
return True
else:
return False
de... |
61d4a00671ec6152f04b0cba9398c1e0dcb700e6 | damienlancry/.leetcode | /160.intersection-of-two-linked-lists.py | 894 | 3.59375 | 4 | #
# @lc app=leetcode id=160 lang=python3
#
# [160] Intersection of Two Linked Lists
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def getlen(head):
if not head:
return 0
else:
return 1 +... |
e5583d5fdf043520e106444e3f8b77e2ea048520 | mikepatel/NBA-Teams | /East/southeast.py | 338 | 3.71875 | 4 | """
Michael Patel
November 2019
"""
# Miami
class Miami:
def __init__(self):
self.roster = [
"Jimmy Butler",
"Tyler Herro",
"Kendrick Nunn",
"Goran Dragic",
"Justise Winslow"
]
# print team roster
def print_roster(self):
... |
66c68076ece4c3def8acfefdf5d5573a57c5b902 | jasokan/myplayground | /python-examples/jSumDigitsOddEven.py | 233 | 4 | 4 | #
# Created by Jagannathan Asokan dated 20/10/20
#
number = 145898
total = 0
while(number > 0):
digit = number % 10
total = total + digit
number = number // 10
print(total)
if total % 2 > 0:
print('ODD')
else:
print('EVEN') |
4154ad1ccfa646dadc108130592e3a866d61b106 | ahmedyoko/python-course-Elzero | /loop25while.py | 2,135 | 4.0625 | 4 | #-------------------
# loop => while
#-------------------
# while condition_is_true :
# code will run until condition become false
a = 0
while a < 10 :
print(a)
a += 1
else :
print("loop is Done") # true become false
print("#"*50)
myf = ['os','ah','aj','so','no','ju','on','ha','em','ya']
print(len(my... |
006d7da758407c4a24a1eb6e795201be978005f8 | MuhammetALAPAN/Python-Exercises | /Beginner/q24.py | 427 | 4.125 | 4 |
def my_pow(num):
"Calculates power 2 of a given number!"
return num ** 2
print(help(abs), "\n", help(int), "\n", help(len), "\n", help(my_pow))
print(abs.__doc__)
"""
print(abs.__doc__)
print(int.__doc__)
print(input.__doc__)
def square(num):
'''Return the square value of the input number.
... |
ed9689963d0f8750830e043bf37965a0829b1750 | Veldhuis94/LEGENDE-VAN-HABAM | /DigitaleComponent/Utilities/Button.py | 6,271 | 4.28125 | 4 | #Made by Audi van Gog
#Version 1.3.0
import copy
#This class is a clickable object (has an event) and can be drawn on screen.
class Button:
#Properties you can set with **args
#[Size]
w = 200 #width
h = 40 #height
#[Text]
txt = "text" #text that gets displayed on the button
txtSize = 3... |
79f8f1290a404311b5cd193f1140ac918100fd44 | kritikyadav/Practise_work_python | /pattern/pattern50.py | 178 | 3.78125 | 4 | n=int(input("enter rows= "))
for i in range(1,n+1):
for j in range(1,n-i+1):
print(end=' ')
for l in range(0,2*i-1):
print(l+1,end='')
print()
|
aed8e1ad6928f06243b97ad432853cefbc24bd0a | chinempc/CultureTags-Game | /Menu.py | 3,519 | 4.28125 | 4 | #Game requirements:
#Functions:
# - Menu(option)
# - Displays the user's choice to them
# - Lets the user choose between the following
# - 1: Instructions
# - 2: Play Game
# - 3: Add New Cards
# - instructions()
# - Prints out to the user the instructions to play the game.
# - In the later build this w... |
c7d3df516b1cee1dc43db89b07fc9b4eba41a674 | riven314/COMP7404_ComputationalIntelligence_MachineLearning | /nQueens_Problem/nQueens_BacktrackForward_AllSol.py | 914 | 3.953125 | 4 | """
Apply backtrack + forward checking to find all solutions of n-queens problem
Remarks:
1. for 8 queens, there are 92 unique solutions
"""
from util import *
def solve(nqns):
row_i = 0
qns = []; qns_sets = []
tmp = backtrack_all(nqns, row_i , qns, qns_sets)
if len(qns_sets) == 0:
print('No solution is found'... |
bc4106e296c40c5a10af25b2b20f85c97cc6a2e0 | BhatnagarKshitij/datamanager | /datamanager.py | 16,898 | 4.40625 | 4 | import sqlite3 as sql
from sqlite3 import Error
def createConnection(db_file_path):
""" create a database connection to a SQLite database, If file doesn`t exists then, SQLite automatically creates the new database for you.
:param db_file: database file
:return: Connection object or None
"""
... |
ef0833d03015dfc2a2a53781fe8ed8d42caee82b | JorgeLJunior/Exercicios-do-URI | /URI_1011.py | 121 | 4 | 4 | from math import pow
n = float(input())
pi = 3.14159
vol = 4 / 3.0 * pi * pow(n, 3)
print('VOLUME = {:.3f}'.format(vol)) |
5d620baa0b20d320b8e492c74f06afeb7100de12 | Palgun7/Python-Assignment | /Week 3/Q2.py | 132 | 3.609375 | 4 | str = input("Enter A String: ")
d1=dict()
for i in str:
if i in d1.keys():
d1[i]+=1
else:
d1[i]=1
print(d1) |
9595ee35f3107ded429592e17972964e95f6b06e | Abhishek-IOT/Data_Structures | /DATA_STRUCTURES/DSA Questions/Strings/wordbreak.py | 899 | 4.1875 | 4 | """
Word Break Problem | DP-32
Difficulty Level : Hard
Last Updated : 02 Sep, 2019
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
This is a famous Google interview question, als... |
a6ceaf8bcbf6ec2c89d530198ae997a0068f5d94 | tomoya7/python | /python_100days/day3.py | 225 | 3.890625 | 4 | import math
a,b,c=3,4,5
if a+b>c and a+c>b and b+c>a:
print("周长:%f"%(a+b+c))
p=(a+b+c)/2
area = math.sqrt(p * (p - a) * (p - b) * (p - c)) #海伦公式
print("面积:%f"%(area))
else:
print("不能构成三角形") |
3b5248c447594891ec99284e8c427fcc8f7fe18a | zjuzpz/Algorithms | /others/sort Stack In Place.py | 436 | 4.1875 | 4 | def sortStackInPlace(stack):
if stack:
temp = stack.pop()
sortStackInPlace(stack)
sortedInsert(stack, temp)
def sortedInsert(stack, num):
if not stack or num > stack[-1]:
stack.append(num)
else:
temp = stack.pop()
sortedInsert(stack, num)
stack.append... |
d16dfb0ebb2aa2657c9fabf5062615e9092665a0 | olesigilai/password_locker | /run.py | 6,121 | 4.28125 | 4 | from user import User,Credentials
def create_new_user(username,password):
'''
function that creates a user using a password and username
'''
new_user = User(username,password)
return new_user
def save_user(user):
'''
function that saves a new user
'''
user.save_user()
def display_... |
a2b5a79772c657c249e5dfe8d8bf77adc8467040 | asmitashrestha/Number-Guessing | /main.py | 387 | 3.921875 | 4 | actual_number = 55
counts = 0
while True:
counts+=1
guess=int(input("Guess the number"))
if guess<actual_number:
print("Your guess is too low")
elif guess>actual_number:
print("your guess is too high")
else:
print(f"You guessed the number in {counts} counts")
... |
6fcb7468cbb7dbd9508cbbf1aded2d54ae7ca685 | fuzzyblankets/Advent_2019 | /Day7_OBE/Part1_Amplifiers.py | 1,026 | 3.640625 | 4 | """
https://adventofcode.com/2019/day/7
"""
from itertools import permutations
import Part1_intcode
if __name__ == '__main__':
int_code =[]
puzzle_input_path = "//puzzle_input_test.txt"
with open(puzzle_input_path, 'r') as file:
puzzle_input = file.read().strip().split(",")
int_code = lis... |
69c2a33ff3f3f0cdd600eef2c566ba5cd5f9f39b | chahal18/Scrapy | /visualisation.py | 3,651 | 3.671875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import bokeh
data = pd.read_csv('Fin.csv', index_col=None)
# Loading the csv file
data.info()
# Plotting relationship between height and weight
# Importing the Bokeh package
from bokeh.io import output_notebook, show
from bokeh.plotting impor... |
5d28d14c1bbacc0b21f49804799c0c3b8520be1b | deepakgd/python-exercises | /multithreading2.py | 507 | 3.96875 | 4 | # multithreading - run two function parallely with some delay
# first hello then hi in this order five time
from threading import Thread
from time import sleep
# sleep is like settimeout
class Hello(Thread):
def run(self):
for i in range(5):
sleep(1)
print("Hello")
class Hi(Thread... |
6fcee2181070d38525e088ecbe511465315cb945 | iamtheluiz/curso_em_video_python | /Mundo 1/aula09/desafio026.py | 410 | 3.953125 | 4 | # imports
print("""
|*****************|
| Desafio26 |
|*****************|
""")
print("Analisador de Frase")
frase = input("Digite uma frase: ")
frase = frase.lower()
count = frase.count("a")
f_a = frase.find("a")
l_a = frase.rfind("a")
print("""
A frase '{}' possuí:
{} letra(s) 'A'
O primeiro 'A' está na {}ª ... |
f945cb638876010f5e2dbaaf5f3c09fd193c013d | zhangfengwe/python | /python/study/practice/python02/StrMultiply.py | 641 | 3.984375 | 4 | # 序列乘法运算示例
# 在屏幕中央且宽度适中的盒子中打印一个句子
# 要打印的句子
content = input('请输入要打印的句子: ')
# 屏幕宽度
screen_width = input('请输入屏幕宽度: ')
text_width = len(content)
box_width = text_width + int(screen_width) // 2
left_margin = (int(screen_width) - box_width) // 2
print()
print(' '* left_margin + '-' * box_width)
print(' '* left_margin + '|' ... |
c7f047d25a2fccd87ee9a2fec18070169a618a2f | R42H/AI-of-Pain | /Main.Py | 19,999 | 3.53125 | 4 | import os, sys, random, time#, #allGames
print 'trout'
#load the file with names/usernames of people who have used it
f = open("people.txt", "r")
prevUsers = [line.strip() for line in f]
f.close
print "When you want to leave, type 'exit', then y"
com = "hello."
def StartUp(com,name,mood,age,school,subject,hobbies,int... |
70acf83a49faa5643f115d5a74594519e3495efb | syed-ashraf123/deploy | /General Mini Programs and Competitive codes/Python/Filter.py | 116 | 3.53125 | 4 | def remove_negative(a):
return list(filter(lambda x:x<0,a))
a=[1,2,3,-1,-5,-6,4,-8]
print(remove_negative(a)) |
ad56f9040aa6434836a66885a35152bb4b044306 | Q10Viking/algoNotes | /code/src/sort/demo/practice_7.py | 629 | 4.09375 | 4 | KEY_NOT_FOUND = -1
# find the index of key in the arr list
def BinarySearch(arr,key,start,end):
while not end<start:
mid = (start+end+1)//2
if arr[mid]>key:
end = mid-1
elif arr[mid]<key:
start = mid+1
else:
return mid
return KEY_NOT_FOUND
if ... |
1148aacc3662098b1dbe90d72dc0b892263c7523 | SakuraSa/MyLeetcodeSubmissions | /Generate Parentheses/Accepted-6469749.py | 987 | 3.546875 | 4 | #Author : sakura_kyon@hotmail.com
#Question : Generate Parentheses
#Link : https://oj.leetcode.com/problems/generate-parentheses/
#Language : python
#Status : Accepted
#Run Time : 164 ms
#Description:
#Given n pairs of parentheses, write a function to generate all combinations of well-formed parent... |
7fa38b65157e9ab64d14fcadf861d17e3146081a | Mahnoor2809/Example-Code-3 | /sms.py | 916 | 3.765625 | 4 | students = []
for i in range(2):
student = {}
student['Name'] = input('Please enter student name: ')
student['Father Name'] = input('Please enter father name: ')
student['Cell number'] = input('Please enter Cell Number: ')
students.append(student)
print('Currently Enrolled Students: ', len(stude... |
c53c01d6156955a5524cf095f56202bfc463ab13 | hampgoodwin/automated-software-testing-with-python | /section2/if_statements.py | 411 | 3.984375 | 4 | known_friends = ['John', 'Anna', 'Mary']
people = input("Enter people you know.")
def who_do_you_know(people):
people_list = people.split(',')
known_people = list(set(people_list).intersection(set(known_friends)))
return known_people
known_people = who_do_you_know(people)
known_people_string = ', & '.join... |
5c989d9b2bbcc4442e1b7e7ef89182f6312e6c37 | jhaslema/PHYS202-S14 | /SciPy/Integrators.py | 790 | 3.515625 | 4 |
import numpy as np
def trapz(func,a,b,N):
"Performs the trapezoidal integral of func through a and b with a certain number of trapezoids(accuracy, higher the N the more accurate) N"
h = (b-a)/N
k = np.arange(1,N)
I = h*(0.5*func(a) + 0.5*func(b) + func(a+k*h).sum())
return I
def simps(func,a,b,N)... |
72e6af32ade5cc501da744a962f0b001c12faabd | sors5139/CTI110 | /P2T1_SorSerah.py | 331 | 3.703125 | 4 | #CTI-110
#P2T1_Sales Prediction
#Serah Sor
# Mar. 07, 2018
# Get the projected total sales.
total_sales = float (input( 'Enter the projected sales: ' ))
# Calculate the profit as 23 percent of total sales.
profit = total_sales * 0.23
# Display the profit.
print ( ' The profit is $', format (prof... |
d89225e2e452904db64dd8b2904a894462952098 | Ericzyr/pythonStudy | /14day_class5.py | 1,282 | 4.28125 | 4 | #!/usr/bin/env python3
# -*-coding:utf-8-*-
#方法重写
class Parent(object): # 定义父类
def __init__(self):
pass
def myMethod(self):
print('调用父类方法')
class Child(Parent): # 定义子类
def __init__(self):
pass
def myMethod(self):
print('调用子类方法')
p =Parent()
p.myMethod()
c = Chi... |
09e06c997091c201f3dd2a96174ab0770bd844a3 | rominecarl/hafb-intro-python | /words.py | 1,463 | 3.953125 | 4 | """
Get a file from the Web
http://icarus.cs.weber.edu/~hvalle/hafb/words.txt
"""
def fetch_words():
"""
Fetch the words a sorted word list with word counts from a prespecified URL
:return: None
:print: Word list
"""
from urllib.request import urlopen
file = "http://icarus.cs.weber.edu/... |
30cb2dd2889c496457028e18ffeac107a739f8c5 | samalty/file_io | /write.py | 446 | 3.921875 | 4 | # The script below enables us to make changes to a separate txt file
# 'a' stands for append, meaning every time we enter something into the write function, it will add it to the pre-existing content, rather than overwriting everything. '\n' ensures that new content features on its own line.
f = open('newfile.txt', 'a... |
0c2020b33f4e711bd2c9ba36e3d18c76403dcffc | fs302/LeetCode | /033-SearchRotated/search_rotated_sorted_array.py | 2,621 | 3.953125 | 4 | import json
class Solution(object):
"""
Find the pos where rotation happended at, aka original start
nums - arraylist
start - start position, include
end - end position, not included
"""
def find_split_pos(self, nums, start, end):
if start >= end:
return 0
mid = (... |
1c04e67857dce885198e69be3144b0cb744f5445 | mickey0524/leetcode | /724.Find-Pivot-Index.py | 530 | 3.546875 | 4 | # https://leetcode.com/problems/find-pivot-index/
#
# algorithms
# Easy (41.83%)
# Total Accepted: 83,546
# Total Submissions: 199,708
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
right_sum, left_sum = sum(nums), 0
... |
f089b9535be0267799e320715e4b0191b4a0a1b6 | arzzon/PythonLearning | /PythonInbuilts/Regex/regex.py | 2,289 | 4.375 | 4 | '''
Regex in python
'''
import re
'''
IMPORTANT:
Python offers two different primitive operations based on regular expressions:
re.match() checks for a match only at the beginning of the string, while re.search()
checks for a match anywhere in the string (this is what Perl does by default).
'''
# Find a pattern in t... |
633598a8ebfdca6434df8b829f6232c3623b6f24 | analuisadev/100-Days-Of-Code | /Day-49.py | 654 | 3.71875 | 4 | from random import randint
from time import sleep
lista = list()
jogos = list()
print ('{:=^40}'.format(' MEGA SENA '))
quantnum = int(input('Quantos números serão sorteados? '))
total = 1
while total <= quantnum:
contador = 0
while True:
num = randint (1, 60)
if num not in lista:
li... |
8c8e0edcce5805a6921719d029bead03e3babe03 | AgentRatz/VITAP-FRESHERS-CSE1002-AS1 | /#To find a generic root of a number using While loop.py | 926 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 20:27:26 2021
@author: 91798
"""
#VITAP assignment-1
#School: SCOPE
#Semester: Fall Sem 2021-22
#Subject: Problem Solving using Python
#Subject Code: CSE1012
#To find a generic root of a number using While loop
"""
genric root is the sum of the numb... |
82c151b262a7ffb682f24267aa5fa823e1b0f68e | MingduDing/A-plan | /acmcoder/约德尔测试.py | 892 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 2019/9/18 14:03
# @Author: Domi
# @File: 约德尔测试.py
# @Software: PyCharm
"""
输入
每组输入数据为两行,第一行为有关约德尔人历史的字符串,第二行是黑默丁格观测星空得到的字符串。
(两个字符串的长度相等,字符串长度不小于1且不超过1000。)
样例输入
@!%12dgsa
010111100
输出
输出一行,在这一行输出相似率。用百分数表示。(相似率为相同字符的个数/总个数,精确到百分号小数点后两位。print("%%");输出一... |
f9582bb9d86f66bdc06b4058fe8149e710895d2e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2528/60770/233861.py | 1,026 | 3.65625 | 4 | def solve():
nums = list(map(int, input()[1:-1].split(',')))
quicksort(nums,0,len(nums)-1)
print(nums)
def quicksort(a=[], left=0, right=0):
if left+2<=right:
pivot=median3(a,left,right)
i=left+1
j=right-2
while True:
while (a[i]<pivot):
i+=1
... |
42812996787d0c888cbb0d944b59b6c0f14b7b38 | Mishakaveli1994/Python_Fundamentals_May | /Excercise Lists Advanced/8_Feed_The_Animals.py | 1,919 | 3.640625 | 4 | animalList = []
animalInfo = []
zoneName = []
zoneInfo = []
while True:
command = input()
if command == 'Last Info':
break
else:
commandSplit = command.split(':')
subCom = commandSplit[0]
animalName = commandSplit[1]
animalFood = int(commandSplit[2])
animalAr... |
1849afeceb4070855ab82a01177bbbc96b8b18da | Susaposa/Homwork_game- | /activities/2_functions.py | 4,996 | 4.3125 | 4 | # REMINDER: Only do one challenge at a time! Save and test after every one.
# Challenge 0: Remember: Do the first thing for any Python activity.
print('Challenge 1 -------------')
# Challenge 1:
# Write the code to "invoke" the function named challenge_1
def challenge_1():
print('Hello Functional World!')
chall... |
1937b9517a2f625a91d792327466cf1ab8a82807 | nickbonne/code_wars_solutions | /factorial.py | 180 | 3.78125 | 4 |
# https://www.codewars.com/kata/factorial-1/train/python
def factorial(n):
nums = range(1, n + 1)
ans = 1
for num in nums:
ans = ans * num
return ans |
722878db0ec3d9db1f0c3944f9d4e4fc0102b416 | shankar01139/python_Basics | /tuple.py | 2,593 | 4.1875 | 4 | # python tuples
# 1.General tuple
tup = (100 ,111, 112, 113,114,115)
print(tup[1:])
print(tup[::-1])
print(tup[2:4])
tup=(False,20,30,True,50,20,60,'shankar',20 ,'ram')
print('Counting tuple elements with count() method : ',tup.count(20))
print('Identifying the index of an particular element with index(... |
e0c0ca3e0eb33d8ca4708d5a6786ab3c32396ec4 | FarnazO/Simplified-Black-Jack-Game | /python_code/main_package/play_game.py | 10,892 | 3.84375 | 4 | '''
This module contains the PlayGame class which contains the steps of the game.
And when the file is run on the command line, you can play the black jack game.
'''
from main_package.game import Game
from main_package.chips import Chips
from main_package.deck import Deck
from main_package.hand import Hand
class PlayG... |
2ab23bbcea7160b11635f20be5e66dcd27585172 | Lindisfarne-RB/GUI-L3-tutorial | /Lesson43.py | 2,391 | 4.125 | 4 | '''from tkinter import *
from tkinter import ttk
# Create a window
root = Tk()
root.title("Greetings App")
# Create a label and add it to the window using pack()
title = ttk.Label(root, text="Greetings! Enter your name: ")
title.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
#Create a StringVar() to store tex... |
b8f7b109345b3579184f20136ae102b5e0fb098d | ashwin4ever/Programming-Challenges | /Cracking the Coding Interview/google_str_encoding_decoding.py | 644 | 4.0625 | 4 | #String encoding decoding
def encode(arr , sep):
n = len(arr)
res = ''
'hello world'
for s in arr:
res += s + sep
res = res[0 : len(res) - 1]
return res
def decode(s , sep , res):
print(s)
if sep not in s:
res.... |
8dc1b48a41cc4592566ffa8635de2fb602c9bc0e | wallacesilva/liasis | /liasis/core/datastructures.py | 961 | 3.890625 | 4 | from dataclasses import dataclass
@dataclass
class DataStructure:
"""
Base dataclass to be used as representation of Entities or any data
crossing the domain boundary.
"""
pass
@dataclass
class Request(DataStructure):
"""
Request attributes are specific for each UseCase, so te base datac... |
591e87d967ea6bd4d682cf6c3c7e99a61b458f3a | jmfcc/IPC2_Proyecto1_201709020 | /main.py | 1,433 | 4 | 4 | import manejador
def main():
#Menu Principal
while True:
print(" _______________________________________________________________________________")
print(" _______________________________________________________________________________")
print()
print(" [1] - Cargar archivo")
... |
5d85679d7aef6aa74aa9a42ef452f99dc2547db3 | renatojobal/fp-utpl-18-evaluaciones | /eval-parcial-primer-bimestre/Ejercicio9.py | 1,589 | 4.375 | 4 | '''
Ejercicio 9.- Dos triángulos son congruentes si tienen la misma forma y tamaño, es decir, su ángulos y lados
correspondientes son iguales. Elaborar un algoritmo que lea los tres ángulos y tres lados de dos
triángulos e imprima si son congruentes, caso contrario que imprima que no son congruentes.
@author Renato
'''... |
3adbd1fed9306b3e06468fb4d17fb2e169ae8026 | eschwabe/interview-practice | /leetcode/permutations.py | 643 | 3.5625 | 4 | # Leetcode 46
# Permutations
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
from collections import deque
res = []
nums_copy = deque(nums)
self.permute_r(nums_copy, [], res)
return res
... |
4af8b60a6149c7e6c28cc7ea83a6467dbdbc2e07 | igor-si/shared | /recipies/python/strings_examples.py | 193 | 4.0625 | 4 | #Here we use Pyhon string formatting to replace { } with value from variable:
print 'The fruits are {0}, {2}, {1}!'.format('Apple', 'Banana', 'Kiwi')
>>>> The fruits are Apple, Kiwi, Banana!
|
8c74233598d134ea2c43276bf5d382e41ac08b45 | KiraLow/labs | /sem_1/lab3/python/lab3.py | 3,103 | 3.84375 | 4 | import math
import pylab
pi = 3.14
while (True):
run = input("Вычислим функцию? (yes/no)")
if run == "yes":
x1 = float(input("Введите первую границу для x: "))
x2 = float(input("Введите вторую границу для x: "))
a = float(input("Введите a: "))
step = float(input("Введите шаг: "))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.