blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5f522fb8221a2bdc5251290858bda16fcceca60e | murayama333/python2020 | /01_basic/tr/src/08/set_tr4.py | 133 | 3.796875 | 4 | names = set()
while True:
name = input("Name: ")
if name == "":
break
names.add(name)
print("Names:", names) |
516f66fb7ae9c1c08dd40d01cde39a00fd5dffe9 | soy-sauce/cs1134 | /lab9/q4b.py | 893 | 3.609375 | 4 | #change last and first
from DoublyLinkedList import*
def reverse_list_change_elements_order(lnk_lst):
while not lnk_lst == None:
first=lnk_lst.first_node()
last=lnk_lst.last_node()
first, last = lnk_lst.last_node(),lnk_lst.first_node()
lnk_lst.delete_first()
lnk_lst... |
e104f2b0289e8cfdcd672768efa680336a32afb1 | SSravanthi/Python-Deep-Learning | /ICP2/Source/wordcount.py | 767 | 3.84375 | 4 | FILE_NAME = 'task3.txt'
wordCounter = {}
with open(FILE_NAME,'r') as fh:
for line in fh:
# Replacing punctuation characters. Making the string to lower.
# The split will spit the line into a list.
word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
for word in word_list... |
762d67ca2fbe6dd4181c8b8a6028436424ea0f6e | nelvinpoulose999/Pythonfiles | /LanguageFundamentals/flowcontrols/looping/reversinganumber.py | 132 | 4.0625 | 4 | num=int(input("enter a number"))
result=" "
while num!=0:
digit=num%10
result+=str(digit)
num=num//10
print(result)
|
d6c7996905f0a35a122b26f703061f9e5cf11624 | tanmaymudholkar/project_euler | /1-49/twenty_seven.py | 807 | 3.78125 | 4 | #!/usr/bin/env python
from __future__ import division, print_function
from peModules.primality import is_prime
def quadratic_form(a,b,n):
return (n**2 + a*n + b)
def get_number_of_consecutive_primes(a,b):
n = 0
while (is_prime(quadratic_form(a,b,n))):
n += 1
return n
if __name__ == "__main_... |
d1689df87ee4b20b1e2e0331b47e93ec6c4ac71d | bahareh-farhadi/Python-Projects | /Robots/main.py | 2,015 | 4.34375 | 4 | #!/bin/python3
from turtle import *
from random import choice
screen = Screen()
screen.bgcolor('White')
turtle = Turtle()
turtle.penup()
turtle.hideturtle()
# opens the file, 'r' means 'read only'
file = open('cards.txt', 'r')
robots = {}
#read the file's lines separately
for i in file.read().splitlines():
#... |
cf46824dd7b067a02718419c4cbc4dec7c6c9f00 | kongli23/Seo_spider | /5 循环语句/loop_while.py | 563 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# 循环语句
sum = 1
while sum <= 10:
print('第{}遍'.format(sum))
sum +=1 # 等同于 sum = sum+1,每循环一次+1,不然会一直条件不满足死循环
# 使用 while 生成0-10的url
page = 0
while True:
if page >=10:
break
print(f'http://www.baidu.com/seo/{page}.html')
page +=1
# 使用while打印 99 乘法表,正序
x = 1
while x <... |
f7dafe1fb0816d92b685b36a8d357a66672a6a1f | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/domdivakaruni/Lesson03/slicing_lab.py | 1,438 | 4.375 | 4 | #!/usr/bin/env python3
# Dom Divakaruni
# Lesson03- slicing
def exchange_first_last(input):
#take in a string, touple or list and return one with the first and last items exchanged.
return input[-1:] + input[1:-1] + input[:1]
def every_other_item(input):
#with every other item removed.
return inpu... |
2c0872c5987842a3f9ae8aab74dc70ef7bd8189a | teksasha/ChemPython | /grams:moles.py | 252 | 3.84375 | 4 | print "Gram to Mole conversion"
print "-------------------------"
givenM=raw_input("Given mass: ")
atomicM=raw_input("Atomic/Molar mass: ")
wanted=float(givenM)*(1/float(atomicM))
print "-------------------------"
print "Result:"
print wanted
print " " |
5458b4ef88f8628054dd979f0fd66371e0723ced | sendurr/spring-grading | /submission - lab2/set2/DUSTIN S MULLINS_3737_assignsubmission_file_Lab 2/lab2/Lab 2.py | 505 | 3.515625 | 4 | #1
jimmhy = (98,35,56)
jones = (89,88,98)
lucy = (99,90,98)
print jones[2]
#2
M1 = [[1,1,1],[1,1,1],[1,1,9]]
M2 = [[2,2,2],[2,8,2],[2,2,2]]
M3 = [M1,M2]
print M3[0][2][2]
print M3[1][1][1]
#3
scores = {"physics":58,"math":98,"english":98}
for subject in scores:
print subject,scores[subject]
#4
cityT = {"columbia":... |
68e7f665a224b1018ca11c6b16446c638774a722 | kartikeya-shandilya/project-euler | /python/51_2.py | 716 | 3.625 | 4 |
from math import sqrt
def isPrime (n):
for i in xrange(2,int(sqrt(n))+1):
if not n%i:
return 0
return 1
"""
for i in xrange(10**5,2*10**5-1):
if isPrime(i):
prSum = 0
for j in xrange(10):
prSum += ... |
d328a004b80bceb77180e6f81923c64849f887e8 | bosontreinamentos/python-jogos | /Jogo - Interação Textual.py | 1,712 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 16:04:57 2021
@author: Fábio dos Reis
"""
import random
import time
def mostraIntro():
print('''Duas cavernas, uma à esquerda e uma à direita. Ambas
possuem tesouros guardados por duendes. Escolha uma caverna para explorar''')
print()
... |
c7685b365661d548b12290777489b6a4e1ee3315 | Niloy28/Python-programming-exercises | /Solutions/Q76.py | 292 | 3.96875 | 4 | # Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
import random
def generator(start=100, end=200):
for i in range(start, end+1):
if i % 2 == 0:
yield i
print(random.sample(list(generator()), k=5))
|
2f282295827d7a049c520db9a8b94cd484507843 | Leumash/UVaOnlineJudge | /113/113.py | 1,370 | 4.21875 | 4 | #!/usr/bin/python
'''
Power of Cryptography
Background
Current work in cryptography involves (among other things) large prime numbers and computing powers of numbers modulo functions of these primes. Work in this area has resulted in the practical use of results from number theory and other branches of mathemat... |
f46aa872c4b2e948466bd8706ce3543401a202e2 | dalaAM/month-01 | /day19_all/day19/exercise03.py | 528 | 3.78125 | 4 | """
使用装饰器,增加打印函数执行时间的功能.
"""
import time
def print_execute_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
stop_time = time.time()
print("执行时间是", stop_time - start_time)
return result
return wrapper
@print_execute... |
bd885cd21a02386f9b270fac365734d356b5e509 | anden3/Python | /dailyprogrammer/#198 - Words with Enemies.py | 317 | 3.796875 | 4 | def word_diff(a, b):
for c in a + b:
if c in a and c in b:
a.remove(c)
b.remove(c)
return "A: " + ''.join(a) + "\nB: " + ''.join(b) + '\n' + ("Tie!" if len(a) == len(b) else ("Left Wins!" if len(a) > len(b) else "Right Wins!"))
print(word_diff(list("hello"), list("below")))
|
54918ade2aa30ce88de8e067e12fe61634292528 | sumitpatra6/leetcode_daily_challenges | /august/decode_ways.py | 639 | 3.640625 | 4 | def numDecodings(s):
if not s or s == '0':
return 0
memory = {}
def util(string):
if not string:
return 1
if string[0] == '0':
return 0
if string in memory:
return memory[string]
left = util(string[1:])
right = 0... |
c69e73e5fa5c97d1b8175bae68f8385ea6ef826f | Monikabandal/My-Python-codes | /Find the minimum distance between two numbers.py | 604 | 3.90625 | 4 |
"""
set={3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}
"""
z=[]
def minimum_distance(z,x,y):
distance=999999
for i in range(0,len(z)):
if(z[i]==x or z[i]==y):
prev=i
break
for j in range(prev,len(z)):
if(z[j]== x or z[j]==y):
if(z[j]== z[prev])... |
ffff39f3b254d358a1a92f9c5cff6de4f0e9f840 | darkvoid32/CTF-writeups | /ångstromCTF 2020/Reasonably Strong Algorithm/rsa_qpe.py | 3,214 | 3.546875 | 4 | import fractions
from binascii import unhexlify
# https://www.alpertron.com.ar/ECM.HTM
def getModInverse(a, m):
if fractions.gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (
u1 - q * v1), (... |
35ac2d8ff8548ac5899910bda94f718af65c82fb | sreekarachanta/py-programs | /calc.py | 602 | 4.09375 | 4 | def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def divide(a,b):
return a/b
print("What operation do you want to Perform - \n"
"1. add\n" \
"2. sub\n" \
"3. multiply\n" \
"4. Divide\n")
select = input("Select operations from 1, 2, 3, 4 :")
num1 = int(input("Enter 1st numb... |
05b13efaa3731c3e675c4b8df6e89609fcf4f89a | t-walker-21/gameAI | /tic_tac_toe/game.py | 353 | 3.96875 | 4 | """
Script to play tic tac toe game
"""
import sys
from board import board
b = board.Board()
while True:
b.display_board()
move = int(raw_input("Enter your move\n"))
b.place_piece(move)
if b.check_win(1):
print "Player 0 won!"
b.display_board(True)
exit()
elif b.check_win(-1):
print "Player 1 won!"... |
b17dbb8a8126323fe53ca7738f6f19d93d0d7b23 | narsingojuhemanth/pythonlab | /largestof3.py | 302 | 4.21875 | 4 | # Write a python program to find largest of three numbers.
a=int(input("enter a="))
b=int(input("enter b="))
c=int(input("enter c="))
largest=0
if (a>b) and (a>c):
largest=a
elif (b>c) and (b>a):
largest=b
else:
largest=c
print("largest of ",a,b,"and",c,"=",largest) |
cf2a471fba237137ec68f03f446c05c1c7dab937 | taehoon95/python-study | /예외처리/trycatchelse.py | 642 | 3.78125 | 4 | try:
number_input_a = int(input("정수 입력"))
except:
print("정수를 입력 하지 않았습니다.")
else:
print("원의 반지름 : " ,number_input_a)
print("원의 둘레 : " , 2*3.14*number_input_a)
print("원의 넓이 : " ,3.14*number_input_a*number_input_a)
try:
number_input_a = int(input("정수 입력"))
print("원의 반지름 : ", number_input_... |
7dbf0c315399a19749fdcaf288b7da5fd6b0cc49 | SwiftPanda10/fib | /fib.py | 155 | 4.21875 | 4 | fib=int(input("Enter a number of the desired fibonacci: "))
a1=0
a2=1
print(a1)
print(a2)
for i in range(1,fib):
a3=a1+a2
print(a3)
a1,a2=a2,a3 |
32eb0904eaccd01b783944803b87fa3211ef4506 | Cprocc/Python-Study | /foundmently/foundmentlyKnow.py | 4,862 | 3.765625 | 4 | '''map function & for '''
def fib(n):
if n == 0 or n==1:
return 1
else:
return fib(n-1) + fib(n-2)
for i in map(fib, [2,6,4]):
print (i)
L1 = [1,4]
L2 = [2,3]
for i in map(min, L1,L2):
print (i)
'''lambda no-name function'''
L = []
for i in map (lambda x,y: x**y, [1,2,3,4], [3,2,1,0]):
L.append(i)
print (L)
... |
7d5db8b89c83154deef7c87278a50cbe8848360f | claudiodantas/labfmcc2 | /labfmcc2.py | 4,236 | 3.5 | 4 | import csv
#arquivo = open(r'C:\Python27\data\raw', 'r')
#linhas = csv.reader(arquivo)
#UFCG - Campina Grande
#Autor: Franciclaudio Dantas da Silva
#Matricula: 118210343
#Disciplina: Fundamentos Matematicos para Ciencia da Computacao II
#Professor: Thiago Emmanuel
#----------------SETUP-------------------
dict1 = {1... |
fc40272b31101efdbece1a66cc0d6048e0ecccac | dyutibhardwaj/Memory-Allocator | /compare.py | 2,034 | 3.53125 | 4 | '''
@anirudha
12:26:55 17-11-2020
'''
choose=input("Original [press 0] or New [press 1]?")
if(choose==1):
filename1 = input("input file: ")
filename2 = input("Output file: ")
else:
filename1 = "output2.txt"
filename2 = "out_A2_20.txt"
file1 = open(filename1).readlines()
file1_line = []
... |
1c10da1e772df6147613f3fd8edf63e5171078d4 | dhaipuleanurag/CourseWork | /BigData/hw2_solution/task2-e/reduce.py | 1,121 | 3.5 | 4 | #!/usr/bin/python
import sys
current_num_days = None
current_medallion = None
current_date = None
current_num_trips = 0
current_num_days = 0
#input comes from STDIN (stream data that goes to the program)
for line in sys.stdin:
medallion, date = line.strip().split("\t", 1)
if medallion == current_me... |
a5292ad1e0c43b9210ed79fb54523ca751555fbf | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/pllnev006/question4.py | 690 | 4.15625 | 4 | # Program to print out palindromic primes
# Nevarr Pillay - PLLNEV006
# 8 March 2014
def pal(num):
newnum = str(num)
reverse = newnum[::-1]
if(newnum == reverse):
return True
return False
def prime(num):
for i in range(2,num):
if (num%i==0):
return Fals... |
7af0a8a0c82fe9587b9278049e1a36700b039bda | hoonest/PythonStudy | /src/chap08/01_baseInheritance.py | 440 | 3.59375 | 4 | class Base:
def __init__(self):
print(self)
self.messge='Hello, World.'
def print_message(self):
print(self.messge)
class Derived(Base):
pass # Derived 클래스가 스스로 구현한 메서드는 없지만, Base로 부터 물려받은 print_messages()는 갖고 있음
if __name__ == '__main__':
base = Base()
... |
b2cfb1f6f99493738fa21cb57501942ef42357c8 | keithdowd/newsgroups-classifier | /train-classifier.py | 1,318 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Demonstrates how to use NewsGroupsClassifier to fit a model to
text data to classify newsgroup articles. This example comes
from an example provided in the [Scikit-Learn documentation](http://
scikit-learn.org/stable/auto_examples/model_selection/
grid_search_text_feature_extraction.html)... |
e0ce2ebd915f72d145306e71953b59a85ae4a1f3 | cybelewang/leetcode-python | /code137SingleNumberII.py | 1,010 | 3.5625 | 4 | """
137 Single Number II
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"""
# count bit at the same position, and mo... |
52b1d9178a2ef36dae25e9e30c39fbaab66f0aa6 | drubiom/python | /Otros Ejercicios/numero_magico.py | 967 | 3.84375 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: david.rubio
#
# Created: 10/01/2018
# Copyright: (c) david.rubio 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
i... |
58857b7bb7eaa63a364cf66d15450c409ed88369 | Jayesh97/programmming | /design/588_DesignInmemoryFs.py | 2,015 | 3.609375 | 4 | from collections import defaultdict
#my solution
class TrieNode():
def __init__(self):
self.children = defaultdict(TrieNode)
class FileSystem():
def __init__(self):
self.root = TrieNode()
self.fileinfo = defaultdict(str)
def ls(self, path):
cur = self.root
for t... |
fa396ab3d8496d509228265822fe6d674436cbe3 | RahulYamgar/Predict-whether-income-based-on-census-data-using-Python | /LogisticReggresstion_AdultDataset.py | 3,824 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 5 23:20:30 2018
@author: User
"""
# Importing Library
import pandas as pd
import numpy as np
# Reading the File
adult_df = pd.read_csv('adult_data.csv',header = None,
delimiter=' *, *',engine='python') # delimiter=Seperation
adult_df.... |
bee06b90dd29b1a1b0dc3b8f50be5832a07c545f | Darfunfun/Revisions | /2.4.4 - Anagrammes.py | 553 | 3.625 | 4 | ch1 = "items"
ch2 = "attention"
compteur = 0
for i, lettre in enumerate(ch1) :
# print(i, "-> ", end='')
# print(lettre, "-> ", end='')
for j, lettre2 in enumerate(ch2):
if lettre == lettre2:
# print("True")
compteur += 1
# print(f"Compteur = {compteur... |
b6682bc9360c3ee2622cf32ffb9e2c697df66ba3 | alejo8591/dmk-django | /lab2/lab2_1.py | 732 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Program: lab2_1.py
Author: Alejandro Romero
Calcuar la tasa de impuesto de un alimento
1. Declaracion de variables:
tax tasa de impuesto
tax_one tasa de impuesto adicional
2. Entradas:
valor del alimento
numero de alimentos
3. Computacion:
tasa de en... |
89ff89e5fc410acdc9dd06855169b421fdf5a3bc | PanamaP/pythonDump | /BikeRent.py | 1,443 | 3.59375 | 4 | # Elfar Snær Arnarson
# 27 Febrúar 2020
# Skilaverkefni 4
class BikeRent:
def __init__(self, inventory=15):
self.inventory = inventory
def displayinv(self):
with open("bike_inventory.txt", "r") as f:
fjoldi = f.read().replace('\n', '')
self.inventory = in... |
d4c5782aae6bbf877843a9f4ce52f7267ab3f486 | frclasso/turma1_Python_Modulo2_2019 | /Cap02_Classes/revisao.py | 987 | 4.03125 | 4 | #!/usr/bin/env python3
# revisao
# declaracao da classe
class Pessoa_Fisica:
idade = 40 # variaveis de classe
def __init__(self, nome, sobrenome, salario): # construtor de classe, inicializa as var
self.nome = nome
self.sobrenome = sobrenome
self.salario = salario
def nome_comp... |
71f2b14710792195eb42943def005504c8333713 | jeffyjkang/Algorithms | /making_change/making_change.py | 1,196 | 3.734375 | 4 | #!/usr/bin/python
# penies = 1 , nickles = 5 , dimes = 10 , quarters = 25 , half-dollars = 50
# input = amount of cents
# denominations = array of coin denominations
# total number of ways in which change can be made for input
# create denominations array
# start with largest denomination
# if largest denom is divisi... |
5fb1e37c271f9aa0bc2e08332b3dc08eecc823ef | ramaisgod/My-Python-Practice | /prog54_Raise_Errors.py | 673 | 4.25 | 4 | # Raise In Python
# search Built in exceptions
#----- Example-1 -------
# name = input("Enter Name : ")
# if name.isnumeric():
# raise Exception("Numbers not allowed")
# print(f"Welcome {name}")
#----- Example-2 -------
# a = int(input("Enter 1st Number: "))
# b = int(input("Enter 2nd Number: "))
... |
3969d5bb0f1944b5a0d35ee923d174798afa7071 | grimmessor/example | /main.py | 1,720 | 3.765625 | 4 | from deflist import read_file, balance, expenses
while True:
print('1 - Show current funds')
print('2 - Expenses per month')
print('3 - Exit')
print('')
a = input('Choose an option: ')
if a not in ['1', '2', '3']:
print('Ops, something went wrong, please try again')
else... |
0c63defa16af478b09c7059a9895aac271dfc1d5 | qeedquan/misc_utilities | /math/bernstein-polynomial.py | 757 | 3.828125 | 4 | """
https://en.wikipedia.org/wiki/Bernstein_polynomial
"""
from sympy import *
from sympy.abc import *
import sys
import os
def bernstein(v, n):
return expand(binomial(n, v) * x**v * (1-x)**(n-v))
def bernstein_derivative(v, n):
return n*(bernstein(v-1, n-1) - bernstein(v, n-1))
def bernstein_integral(v, ... |
2fd243a844a8cba06ab9941a6b3251ecbf420482 | LimaEchoAlpha/cluedetective_python_class_project | /clue_detective_module/detective.py | 12,857 | 4.15625 | 4 |
from board import *
class Note():
"""This is class represents the types of notes stored in a notebook.
Attributes:
- type = what type of information the note contains
Subclasses:
- Yes: marks the cards that are known to be in another player’s hand
- No: marks the cards that ar... |
85677d11942a377ef05aff3c880d4d919e60c5c2 | YvesHarrison/Python-programming-exercises-forked-from-zhiweihu | /53.py | 308 | 3.625 | 4 | class shape:
def __init__(self):
pass
def area(self):
return 0
class square(shape):
def __init__(self,l):
shape.__init__(self)
self.length=l
def cal(self):
return self.length**2
def Question53():
a=square(3)
print(a.cal())
Question53() |
23dd47cf6e5688e6bb07fba8ddae7d9f9466eedf | pradeepsinngh/A-Problem-A-Day | /random/022-kth_largest_element_array.py | 448 | 3.75 | 4 | # Prob: Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order,
# not the kth distinct element.
# Sol 1:
# ---------------------------------
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k:... |
8a6c015d009ba2fa86907d54fc822d3b16c2af18 | cpingor/leetcode | /654.最大二叉树.py | 677 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=654 lang=python3
#
# [654] 最大二叉树
#
# @lc code=start
# 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 constructMaximumBinaryTr... |
3b74abb365ba0d492987165616b4a72e8c38de9e | KoliosterNikolayIliev/Softuni_education | /Fundamentals2020/Final exam Prep/Battle Manager.py | 1,390 | 3.671875 | 4 | people = {}
while True:
command = input()
if command == "Results":
break
command = command.split(":")
cmd = command[0]
if cmd == "Add":
personName = command[1]
health = int(command[2])
energy = int(command[3])
if personName not in people.keys():
... |
21e9870cce1df1472bae46dde01096ea092c644a | tsaihuangsd/Data-Structures | /linked_list/linked_list.py | 1,563 | 3.765625 | 4 | """
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
retu... |
7d7bcc3ea22df74a71dd5bc953678f62058c8605 | chinitacode/Python_Learning | /Tencent_50/03_kth-largest-element-in-an-array.py | 1,807 | 3.65625 | 4 | # 215. Kth Largest Element in an Array
# Method 1: quick sort + random seed, O(n), the best solution
import random
def findKthLargest(self, nums, k):
x = random.randint(0, len(nums) - 1)
nums[0], nums[x] = nums[x], nums[0]
r = [num for num in nums[1:] if num > nums[0]]
if len(r) == k - 1: ret... |
d68ccd24394df9742be117ea664a0b3a0e7c36f1 | estraviz/codewars | /7_kyu/The Poet And The Pendulum/pendulum.py | 271 | 3.5625 | 4 | from collections import deque
def pendulum(values):
output = deque(maxlen=len(values))
for i, value in enumerate(sorted(values)):
if i % 2 == 0:
output.appendleft(value)
else:
output.append(value)
return list(output)
|
c2375e02dc89b88ffa4f3a75d79791bb1e583bc8 | ficklel/HankerRank-Algorithms | /8.py | 605 | 3.53125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
sumi=sum(arr)
mini=arr[0]
maxi=arr[0]
t=1
n=len(arr)
while t<n:
if arr[t]<=mini:
mini=arr[... |
4c6bd47164e8ec7febea991bf74db245d31b148a | dorjeedamdul/python-basics | /basics.py | 3,557 | 4.34375 | 4 | #### --- STRINGS IN PYTHON --- ####
# Strings can be indexed
word = 'Python'
word[0] # character in position 0 --> 'P'
word[5] # character in position 5--> 'n'
# Indices may also be negative numbers, to start counting from the right:
word[-1] # last character --> 'n'
word[-2] # second-last character -> 'o'
word... |
befaf447b804416f94809a4ea5aeefd135451f25 | buzycoderscamp/ML-Workshop-Samlpes-Day2- | /Visualization/Plot.py | 467 | 3.546875 | 4 | from matplotlib import pyplot
import math
def sine(xvals) :
y = []
for i in xvals :
y.append(math.sin(i * math.pi / 180))
pyplot.plot(xvals, y)
pyplot.show()
def plotLine(x, m, c) :
y = [(i*m) + c for i in x]
pyplot.xlabel("X axis")
pyplot.ylabel("Y axis, y = mx+c")
pyplot.xlim([... |
479af0cce4d2f110cad924e34862b214a775d328 | prajwal60/ListQuestions | /learning/BasicQuestions/Qsn8.py | 162 | 4.125 | 4 | # Write a Python program to display the first and last colors from the following list.
list1 = ["Red","Green","White" ,"Black"]
print(list1[0])
print(list1[-1]) |
b981529d1f6d5df5680f9b5a8284f5d7d75eb159 | panosadamop/pythonCourses | /scrap.py | 737 | 3.734375 | 4 | import copy
di1={1:[1,2,3], 2:{1:'A', 2:'B'}}
di2 = copy.copy(di1)
di2[2][1] = 'X'
di3 = copy.deepcopy(di1)
di3[1][0] = 'Y'
print(di1)
print(di3)
print("---------------------------------------------")
print("---------------------------------------------")
adict = {1:'A', 20:'B', 50:'C'}
print(sum([max(adict), min... |
a628f2937aba932584fef752a175ee98c207ca05 | RubinaSali/rock_paper_scissors | /game3.py | 1,364 | 4.28125 | 4 | import random
print("...rock...\n...paper...\n...scissors...")
player_wins = 0
computer_wins = 0
winning_score = 2
while player_wins < winning_score and computer_wins < winning_score:
print(f"player = {player_wins} computer = {computer_wins}")
rand_number= random.randint(0,2)
player=input("Make your mov... |
d44968811cb1d91e1bfab31910f85ec3de2f9916 | felipeonf/Exercises_Python | /exercícios_fixação/049.py | 383 | 3.9375 | 4 | ''' Crie um programa que leia 6 números inteiros e no final mostre quantos deles
são pares e quantos são ímpares.'''
par = 0
impar = 0
for num in range(1,7):
numero = int(input(f'{num}° numero: '))
if numero % 2 == 0:
par +=1
else:
impar += 1
print(f'A quantidade números pares digi... |
84411a0f519a6846b68195c011ea1edb044e8d6a | LoutreStarery/ift6759_project1 | /models/CNN2D.py | 1,927 | 3.703125 | 4 | """
Basic model example using a 2D CNN with images as inputs and metadata
"""
import tensorflow as tf
class CNN2D(tf.keras.Model):
"""
Simple 2D CNN
"""
def __init__(self):
"""
Define model layers
"""
super(CNN2D, self).__init__()
self.conv_1 = tf.keras.layers.C... |
2b438c288ce8569b0517a6c6e2a156f9ec4e46bc | jazzy1331/cseGradingScripts | /CSE2421/unzipSubmissions.py | 819 | 4.03125 | 4 | #Author: Thomas Sullivan
#unzips .zip files in current directory and puts content in a file named after the student and late status.
#places processed files in a folder named "unzipped"
#Expected file format: studentname_<late>_####_####.zip
#<late> is optional and ### are numbers
#usage: python unzipSubmissions.py &... |
15c5ea2d0e66890f39325a6b9bb7c93472371a21 | banana-galaxy/challenges | /challenge4(zipcode)/vaterz.py | 1,156 | 4.09375 | 4 | def validate(x):
"""
Validates a integer based zip code.
Requirements:
11xxx # two or more same digits in a row, not valid
1x1xx # two or more neighboring digits, not valid
1xx1x # no neighboring or next to each other digits, valid
Parameters:
x (int): the zipcode to validat... |
b6c50034f278ccbf64133f511cbc49a1dc364c66 | bdliyq/algorithm | /lintcode/word-ladder.py | 1,043 | 3.6875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# Question: http://www.lintcode.com/en/problem/word-ladder/
import string
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
# write your code... |
7d6efd78eab99429705058902f3c8a7a1a00f47d | Jessica8729/DeepLearningStartUp | /ex_dpl.py | 1,211 | 3.625 | 4 | # -*- coding:utf-8 -*-
# 该程序使用python 2,因此,一般用以下4,5,6三行代码解决中文编码错误问题,一劳永逸
# 但貌似因为Python2选择了 ASCII,而python 3默认Unicode,所以,有声音不建议这种用法。
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import re
from collections import Counter
from zhon.hanzi import punctuation
initial_input=open("happiness_seg.txt", "r").read().de... |
cb83fe4bf92aa21c219ff985af0e7b9cf6a9ca77 | kruthik23/Python | /assignment 1/q4.py | 215 | 4.46875 | 4 | my_str = input("Enter string : ")
str = ''
for i in my_str:
str = i + str
print("\nThe Original String is: ", my_str)
print("The Reversed String is: ", str)
print("Reverse of the string: "+my_str[::-1]) |
de052ee82161fff6946b7d43247713fa746949f7 | OuroborosD/estudospython | /12_validador_cpf.py | 4,058 | 3.90625 | 4 | #TODO cria v2 identificar numeros repetidos, e quantidade de caracteres.
def verifica_repetido(valor,resultado = 0):
"""verifica se só tem numeros repetidos no cpf.
modifiquei para uma igualdade, entre os valores multiplicados
de valor X ele mesmo e o resultado
pois pode dar um falso negativ... |
5c13b41c9ce3e5daf06af2946139119822e4e8e8 | mdinos/coding-problems | /codewars/python/kyu/4/catch_car_milage_numbers.py | 1,381 | 3.84375 | 4 | # https://www.codewars.com/kata/52c4dd683bfd3b434c000292
def is_interesting(number, awesome_phrases):
if number == 98 or number == 99:
return 1
elif number < 100:
return 0
next_three = [number, number + 1, number + 2]
xs = []
xs.append([check_followed_by_zeros... |
1b3133fa49a9489e93e2b38a40cea366646cb1b0 | BIGStrawberry/ALDS | /Week_4/4.1.py | 2,605 | 3.578125 | 4 | """
Student Naam: Wouter Dijkstra
Student Nr. : 1700101
Klas : ??
Docent : frits.dannenberg@hu.nl
"""
import random
class HashTable:
def __init__(self):
self.data = [None for _ in range(11)]
self.num_elements = 0
def __repr__(self):
s = ''
for i in range(l... |
c5e9ebc16d2bb7fb00e48198c888e8c501502f71 | Uttam1982/PythonTutorial | /08-Python-DataTypes/String-Format/07-formating-class.py | 177 | 4.21875 | 4 | # Example : Formatting class members using format()
#define a class
class Student:
name = 'Sara'
age = 21
print("Name = {s.name} and Age = {s.age}".format(s= Student()))
|
4b668844a8b443abbbb922624b94e06558664a41 | Avaddov/DevInstitute | /Week4/Day3 - Dictionaries/XP1.py | 2,448 | 4.21875 | 4 | ## Convert the two following lists, into dictionaries.
# keys = ['Ten', 'Twenty', 'Thirty']
# values = [10, 20, 30]
# # Hint: Use the zip method
# results = zip(keys, values)
# print(dict(results))
# Exercise 2 : Cinemax #2
# “Continuation of Exercise Cinemax of Week4Day2 XP”
# A movie theater charges different ticket... |
c1161d513e39679c51f2e4fcfc55cf8828302101 | mitchell-johnstone/PythonWork | /PE/P069.py | 2,021 | 3.765625 | 4 | # Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine
# the number of numbers less than n which are relatively prime to n.
# For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6.
#
# n Relatively Prime φ(n) n/φ(n)
# 2 1 1 2
# 3 1,2 2 1.5
... |
6151aa62eda1ba641d891d6a2d130f681bf892d8 | stuartses/AirBnB_clone | /models/amenity.py | 340 | 3.734375 | 4 | #!/usr/bin/python3
"""Module: amenity
This module define Amenity class
Atributes:
name (str): name of amenity
"""
from models.base_model import BaseModel
class Amenity(BaseModel):
"""Class Amenity
Inherits from BaseModel
create class Amenity
Atributes:
name (str): name of amenity
... |
dcff7c64de0769865aa4be9031857ae3864a87ea | Amarnath9962/Breakfast_Hotel_Bill- | /Tiffen_hotel_bill_Generation.py | 3,695 | 3.5 | 4 | from tkinter import *
root = Tk()
root.geometry('500x500')
root.title('Billing Table')
# Functions
def Calculate():
Cust_name = Name_1.get()
Idly_Qty = int(Idly_1.get())*5
Dosa_Qty = int(Dosa_1.get())*15
Upma_Qty = int(Upma_1.get())*25
Spl_Dosa_Qty = int(Spl_Dosa_1.get())*30
Tea_... |
013774f0fa13db3af7f995c1809eafa8d5ecb6b3 | ameyyadav09/ML-Assignments | /custom utils/cat_conv.py | 2,420 | 3.75 | 4 | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
"""
Given a Series object CountVectorizer is used to obtain a csr matrix
and then it is converted as a pandas DataFrame and returned
input:
ser:Pandas Series
output:
Pandas DataFrame obtained after vectorizing
"""
def _v... |
a3bebc702725a87b56f55474aea8809a8db1726e | uvkrishnasai/algorithms-datastructures-python | /interviewcake/BalancedBinaryTree.py | 2,095 | 4.125 | 4 | class BinaryTreeNode(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_left(self, value):
self.left = BinaryTreeNode(value)
return self.left
def insert_right(self, value):
self.right = BinaryTreeNode(value... |
88d6d52120fdeff0551067ccc0b5e72521b35137 | neilsjlee/AlarmSystem | /ControlHub/priority_queue.py | 1,600 | 3.875 | 4 | # Implementing Priority Queue using List data type
import threading
class MyPriorityQueue:
def __init__(self):
self.queue_list = []
self.queue_size = 0
self.lock = threading.Lock()
def put(self, task_type, priority, timestamp, address, data):
self.p()
i = 0
fo... |
032deea49c29c887b574f27763c8a70716657231 | sudbasnet/Leetcode-Practice | /splitArrayLargestSum.py | 2,472 | 3.640625 | 4 | class Solution:
def splitArray(self, nums: [int], m: int) -> int:
"""
One of the solutions that I can think of is by considering multiple options
but here, the branches could be too large. For example, I cant just consider
every possibility, that would be absurd.
ho... |
f960aade75f2731a957fd78bedbe9cf4f9e3b19d | kumarnalinaksh21/Python-Practice | /Arrays/Palindrome problem.py | 647 | 4.34375 | 4 | ################ Question ######################################
# "A palindrome is a string that reads the same forward and backward"
# For example: radar or madam
# Our task is to design an optimal algorithm for checking whether
# a given string is palindrome or not!
################################################... |
d14b9b174ae386ba9ff36e36b08410c22f2d95f7 | ErickBritoN/Aprendizados | /Python/Atividade1.py | 364 | 3.6875 | 4 | preco_pass = float(input("Preço da passagem: "))
num_pass = int(input("Numero de Passageiros: "))
especiais = int(input("NUmero de Passageiros especiais: "))
faturamento = float(preco_pass*num_pass)
faturamento_espec = float((preco_pass*especiais)/2)
faturamento_total = faturamento + faturamento_espec
print("O faturame... |
6134378797364b29d35b133d70edbb7f7f3af9ad | Oyagoddess/PDX-Code-Guild | /learnpyex/ex35.py | 4,241 | 4.28125 | 4 | from sys import exit # importing the exit feature from system
def gold_room(): # defines the function for the gold room
print "This room is full of gold. How much do you take?" # ask for user input
next = raw_input("> ") # collects user inputs
if "0" in next or "1" in next: # creates conditions for ... |
14fa85dc6110b79590cf0ebde52eb0660d29e63a | Quarant/pythong | /homework/lotto/lotto.py | 1,475 | 3.59375 | 4 | import random
def num_len(num_list):
if(len(num_list)<6):
raise Exception(1,"fall to reach limit")
elif(len(num_list)>6):
raise Exception(2,"list exceeded limit")
def dublicate_number(num_list):
for i in num_list:
if(num_list.count(i) > 1):
raise Exception(3,"dublicate ... |
f1811d48129a36d55f8442de3ad719184e720901 | nightwolfer1/NUMA01-Numerical-analysis-with-python | /Task_Lecture_10.py | 2,121 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 8 10:50:46 2020
@author: nightwolfer
"""
import numpy as np
import matplotlib.pyplot as plt
#Task 1
x_val=np.linspace(-10,10,100)
#make a list of resulting values of the polynomial x**3+x
y=list(map(lambda x:x**3+x , x_val))
#derivateive of pol 3x**2+1
... |
84ec03686f4c9ba9c54f5f92c3ef3ddb029a5294 | wsjung/2017Challenges | /challenge_3/python/wjung/src/challenge_3.py | 213 | 3.625 | 4 | array = [2,2,3,7,5,7,7,7,4,7,2,7,4,5,6,7,7,8,6,7,7,8,10,12,29,30,19,10,7,7,7,7,7,7,7,7,7]
def findMajority(array=[]):
for n in array:
if array.count(n) >= len(array)/2:
print n
break
findMajority(array) |
9049dcc8b9cb24fbe3a6feed1365701be17ff544 | grock2015/python | /separarTuplas.py | 447 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# Definindo as variaveis
minha_tupla = (1,0.3,"vasco")
# Funcao que checa o tipo do elemento e o adiciona a lista correta
# que é convertida em tupla ao final
def separarTuplas(tupla):
tupla_string = []
tupla_outros = []
for item in tupla:
if type(item) == str:
tupla_string.append(ite... |
22f180585c535a04ce138c3afddda52463479d28 | Rostyk1404/Codewars | /What time is it?.py | 1,188 | 4.21875 | 4 | """
Kata source :
https://www.codewars.com/kata/converting-12-hour-time-to-24-hour-time/train/python
Given a time in AM/PM format as a string, convert it to military (24-hour) time as a string.
Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-... |
e6feabccacae15ed66205deb0bf4724d79b0b10f | hytim/SegDL | /Viz/demo05.py | 459 | 3.671875 | 4 | #语义分割之图片和 mask 的可视化
#https://www.aiuai.cn/aifarm276.html
import cv2
import matplotlib.pyplot as plt
imgfile = 'image.jpg'
pngfile = 'mask.png'
img = cv2.imread(imgfile, 1)
mask = cv2.imread(pngfile, 0)
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,... |
0e15002cb2966234e7aecd129f6921f10c4742db | wilsonify/euler | /src/euler_python_package/euler_python/easiest/p035.py | 1,186 | 4.03125 | 4 | """
The number, 197, is called a circular prime because all rotations of the
digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37,
71, 73, 79, and 97.
How many circular primes are there below one million?
"""
from euler_python.utils i... |
095eacb0f416f38570e083badc5a2f8d257f252f | katelevshova/py-algos-datastruc | /Course1/p5_set_possible_telemarketers.py | 7,784 | 3.9375 | 4 | """
Read file into texts and calls.
"""
import csv
from enum import Enum
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 5:
The telephone company want to identify numbers that might be... |
99ca8f843e217582f1df12212a811272f59c7574 | emirot/algo-loco.blog | /algorithms/sorting/quick_sort.py | 434 | 4 | 4 |
def quick_sort(arr):
if len(arr) < 2:
return arr
z = (len(arr)-1) // 2
pivot = arr[z]
left = [i for i in arr if i < pivot]
right = [i for i in arr if i > pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
if __name__ == '__main__':
arr = [-4, 3, 2, 1, 10, 9]
... |
65343486561d6145d17de698787500a2749d7fb1 | RicardoAugusto-RCD/exercicios_python | /exercicios/ex004.py | 962 | 4.1875 | 4 |
# Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possiveis
# sobre ele.
print('-'*20)
leia = input('Escreva algo: ')
print('-'*20)
print('O tipo primitivo do valor {} é'.format(leia), type(leia))
print('-'*20)
print('{}, é um múmero?'.format(leia), leia.isn... |
78ef753e2d7a894eb3268bab611755d0c0df53a2 | RennanFelipe7/algoritmos20192 | /Lista 3/lista03ex08.py | 525 | 4.0625 | 4 | print("Digite dois numeros, lembrando que o primeiro numero tem que ser menor que o segundo, a diferença entre os dois numeros tem que ser maior que 1, e esses dois numeros também não pode ser iguais.")
MenorNumero = int(input("Qual o menor numero do intervalo? "))
MaiorNumero = int(input("Qual o maior numero do interv... |
aab1f0ec1331b59ed783eb966f28244945756d12 | kate2797/password-manager | /delete_by_website.py | 715 | 4.25 | 4 | import sqlite3
import os
def delete():
# connect to db
connect_to_db = sqlite3.connect('database.db')
c = connect_to_db.cursor()
user_input = input("Password for which website you want to delete? ")
print(">> WARNING <<")
confirm = input("Whole database entry will be deleted, not just the pa... |
e45d70bdf8936a3c80da80a653654581821883b0 | abbindustrigymnasium/Python-kompendium_Vicfag | /5_If_satser.py | 1,725 | 3.65625 | 4 | # print('Vilket kön har du?')
# kön=input()
# print('Vilken hårfärg har du?')
# hårfärg=input()
# print('Vilken ögonfärg har du?')
# ögonfärg=input()
# daniel_radcliff=['man','brun','brun','Daniel Radcliff']
# rupert_grint=['man','röd','blå','Rupert Grint']
# emma_watson=['kvinna','brun','brun','Emma Watson']
# selen... |
1db49111f14dc7429d1dabb12d233301f4042572 | Sbenaventebravo/AdhGestionFichas | /Clases/DTO.py | 21,875 | 3.59375 | 4 |
# -*- coding: cp1252 -*-
from datetime import datetime, date
import re
def formatoAtributoInforme(cadena,largo):
listaCandena= list(cadena)
for i in range(largo - len(cadena)):
listaCandena.append(" ")
return "".join(listaCandena)
class Caracteristica(object):
"Clase que representa una Ca... |
6053f8cc30a7377d6545da6da8bd3878b9cfeadc | cyberchaud/automateBoring | /vid16/vid16.py | 1,731 | 4.40625 | 4 | # Dictionaries are a collection of key value pairs
# Python gets the value by indexing the name of the dictionary with the key value in []
# key values in a dictionary are unordered
# the is no order to the keys - ie: no first and last value
myCat = {'size': 'fat',
'colour': 'grey',
'disposition': 'lou... |
710f58225a8f62da34b6e9efa4081e7b7151f1d4 | vishrutkmr7/DailyPracticeProblemsDIP | /2019/10 October/dp10082019.py | 3,332 | 3.796875 | 4 | # This problem was recently asked by Facebook:
# Two words can be 'chained' if the last character of the first word is the same as the first character of the second word.
# Given a list of words, determine if there is a way to 'chain' all the words in a circle.
# Input: ['eggs', 'karat', 'apple', 'snack', 'tuna']
# O... |
f356960886a2ce737f291544154888b22c1783b4 | ChidinmaKO/Chobe-Py-Challenges | /bites/bite140.py | 1,299 | 3.546875 | 4 | import pandas as pd
import collections
data = "https://bites-data.s3.us-east-2.amazonaws.com/summer.csv"
def athletes_most_medals(data=data):
# read data
pd_data = pd.read_csv(data, index_col=0)
# ==> one way
# male_most_medals = dict(pd_data[pd_data["Gender"] == "Men"]["Athlete"].value_counts()... |
7ac67028bb4174be1d7088e3854e4b0ef215f945 | MaxIakovliev/algorithms | /old/Session002/DepthFirstSearch/SearchinBinarySearchTree.py | 736 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
https://leetcode.com/problems/search-in-a-binary-search-tree/description/
"""
def searchBST(self, root, val):
"""... |
2830989eed91875e04f40aedf2459f1ef2aadb3a | conradylx/Python_Course | /24.03.2021/Excercise8/exc8.py | 886 | 3.65625 | 4 | # Utwórz generator dowolnego typu np. generator zdań, tweetów czy konferencji.
# Dane wejściowe pobierz z pliku csv (plik csv możesz traktować jako plik txt ze znanym znakiem podziału),
# który będzie przechowywał dane potrzebne do generowania.
import csv
import random
def read_file() -> dict:
reader_dict = dict(... |
9eb153d1270f0c8cd1a6835f6d8d522268850c3f | MEng-Alejandro-Nieto/Python-3-Udemy-Course | /6 Print formatting with strings.py | 1,285 | 4.4375 | 4 | # 1 METHOD --- .format()
print("his name is {}".format("Alejandro")) # It will print "his name is Alejandro"
print("the next 3 words are {} {} {}".format('fox','brown','quick')) # It will print "the next 3 words are fox brown quick"
print("the next 3 words are {2} {1} {0}".format('fox','brown','quick')) # It wil... |
a4ee6d78fba7e778d7ab1bf993c6df2406f5a0a4 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/tfbanks/Lesson03/List_Lab.py | 4,657 | 4.40625 | 4 | # List Lab Exercise by tfbanks
#!/usr/bin/env python3
# Series 1
fruits = ["Apples", "Pears", "Oranges", "Peaches"] # Original List of Fruits
# Welcome to series 1 and tells how many fruits are in the list
print("Welcome to Series 1\nThis list has the following", len(fruits), "fruits: ", fruits, "\n")
new_fruit = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.