blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
37e117c118c097f12b47c6cbaf6b4e000ec5eef0 | newagequanta/MITx_6.00.1x | /Week 2/minimum_payment_to_pay_off.py | 398 | 3.609375 | 4 | balance = 3926
annualInterestRate = 0.2
min_payment = 0
unpaid_balance = balance
while unpaid_balance > 0:
unpaid_balance = balance
min_payment += 10
for i in range(12):
unpaid_balance -= min_payment
unpaid_balance += (unpaid_balance * annualInterestRate/12)
print(min_payment, unpaid_ba... |
99cf7c6c97e849424c4aaf54aa5eaa75693913fb | fearlessfreap24/codingbatsolutions | /Warmup-2/string_times.py | 171 | 3.625 | 4 | def string_times(str, n):
return str*n
if __name__ == "__main__":
print(string_times('Hi', 2))
print(string_times('Hi', 3))
print(string_times('Hi', 1)) |
f976d93d92203105aa3fc0f1c02796dcd8a54217 | D12020/my-first-python-programs | /geometry.py | 947 | 4.21875 | 4 | # This program contains functions that evaluate formulas used in geometry.
#
# Saleem Alnawasreh
# August 31, 2017
import math
def triangle_area(b, h):
a = (1/2) * b * h
return a
def circle_area(r):
a = math.pi * r**2
return a
def parallegogram_area(b,h):
a = b * h
return a
... |
0b2f3cd53f5cf5422bd327ff6756ac396395d879 | jewells07/Python | /map_2.py | 434 | 3.921875 | 4 | def square(a):
return a*a
def cube(a):
return a*a*a
fun=[square,cube] #Having two functions square and cube::
for i in range(5):
val=list(map(lambda x:x(i),fun))
print(val)
#It will take fun variable map into lamba function that returns x(i)
#Explaination of val=list(map(lambda x:x(i),fun))
#lamba... |
bf209a3333e3bdf9b88cf6c8b20f5ee8860df673 | syo0e/Algorithm | /python/programmers/level1/이상한문자만들기.py | 361 | 3.5 | 4 | def solution(s):
arr = s.split(' ')
idx = 0
for x in arr:
answer = ''
for i in range(len(x)):
if i % 2 == 0:
answer += x[i].upper()
else:
answer += x[i].lower()
arr[idx] = answer
idx += 1
return ' '.join(map(str, ar... |
6807928c3f2f094749b735b2e9e696c86b1f80e6 | Poseidonst/Enigma | /Teije/Attempts after Holidays/TheRotorsNumbersAndClasses.py | 2,553 | 3.671875 | 4 | alphabet_list = [i for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
rotor_II_list = [i for i in "AJDKSIRUXBLHWTMCQGZNPYFVOE"]
alphabet_dict = {chr(65+i) : i for i in range(26)}
rotor_I_numbers = [alphabet_dict[i] for i in "EKMFLGDQVZNTOWYHXUSPAIBRCJ"]
rotor_II_numbers = [alphabet_dict[i] for i in "AJDKSIRUXBLHWTMCQGZNPYFVOE"]
ro... |
2da8102fa9f7e1acea137aa1fbf3a041b660d76a | mshekhar/random-algs | /epi_solutions/strings/trie/palindrome-pairs.py | 1,997 | 3.75 | 4 | class TrieNode(object):
def __init__(self):
self.word_idx = None
self.next_radix = [None] * 26
self.matching_suffix_indices = []
class TrieHelper(object):
@classmethod
def is_palindrome(cls, word, i, j):
while i < j:
if word[i] == word[j]:
i += 1... |
d7ca123fc54a787ade7a59488d45fe466fb852d9 | DreamITJob/Top-35-Medium-Level-Python-programs | /Program29.py | 276 | 4.125 | 4 | #Python program for moving zero at the end of an array.........
def MovingZero(array):
a = [0 for i in range(array.count(0))]
x = [ i for i in array if i != 0]
x.extend(a)
return(x)
print(MovingZero([0,2,3,4,6,7,10]))
print(MovingZero([10,0,11,12,0,14,17]))
|
eb906b96ca000bd9cb27c7cad4390dd11b3a3226 | haoccheng/pegasus | /coding_interview/subtree.py | 1,572 | 4.0625 | 4 | # Given two binary tree, check whether one is a substructure of the other.
# 8 8
# 8 7 -> 9 2 -> True.
#9 2
# 4 7
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = Node(left) if left is not None else None
self.right = Node(right) if ri... |
5a781f7ff01e839d7c689e10e1dcfb66d9913807 | robertpiazza/ProfessionalDevelopment | /Exploring Data Science/1-3-1 Single Value Decomposition.py | 4,426 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 8 10:03:48 2018
@author: 593787 Robert Piazza - Booz Allen Hamilton
"""
###Foundations-Singular Value Decomposition Section 1.3.1
#Learn about a technique called Principal Component Analysis (PCA) and a
#related, more scalable algorithm called Singular Value Decomposi... |
00c49eaa0a2be8f62bc119c7aa1377b2da40de5e | AswiniSankar/OB-Python-Training | /Assignments/Day-2/p15.py | 446 | 4.0625 | 4 | # program to remove duplicates in list with and without using set function
list = [12, 4, 90, 3, 12, 5, 6, 17, 3, 5, 9, 10, 6, 5, 90, 100]
s = set()
for i in list: # with using set
s.add(i)
print(s)
withoutduplicate = []
for i in list: # without using set
if i not in withoutduplicate:
withoutduplicate... |
eb49632fcaf5f96e40c57015a30fe5d4dce5e3a0 | surinder1/new-file | /area.py | 676 | 3.765625 | 4 | def a():
x=int(input("enter the radius"))
r=3.14*x*x
print(r)
a()
def perfect(num):
result=0
for x in range(1,num):
if num%x==0:
result=result+x
if result==num:
print("perfect number:",num)
for x in range(1,1001):
perfect(x)
def rectangle(x,y):
if y<=10:
t=x*y
print(t)
y+=1
rectangle(x,y... |
99d18e2b26afa9af9cce758c05a9be059f5de60c | SukeshReddySpaceX/Hackerrank-SI | /tower-of-hanoi-easy.py | 356 | 4.0625 | 4 | def towerOfHanoi(n,fr,to,aux):
if n==1:
print("Move 1"+" from "+str(fr)+" to "+str(to))
return
towerOfHanoi(n-1,fr,aux,to)
print("Move "+str(n)+" from "+str(fr)+" to "+str(to))
towerOfHanoi(n-1,aux,to,fr)
m=int(input())
for i in range(m):
n=int(input())
print(pow(2,n)-1... |
27717486449b6b5de93a5ac1f562fba1a9d099bd | n8sty/dowhy | /dowhy/utils/cit.py | 5,849 | 3.609375 | 4 | from collections import defaultdict
from math import exp, log
import numpy as np
import pandas as pd
from scipy.stats import norm, t
def compute_ci(r=None, nx=None, ny=None, confidence=0.95):
"""Compute Parametric confidence intervals around correlation coefficient.
See : https://online.stat.psu.edu/stat505/... |
48f2f1a1071c245187b5e6c32c04a012b02cd0a6 | thinkphp/computer-science-in-python | /foundations/greedy/salesman.py | 1,914 | 3.59375 | 4 | def Greedy(nodes, matrix):
BIG = 99999
cost = 0
node = 0
start = node
explored = [ 0 ] * (nodes+1)
explored[node] = 1
print(node+1, end = " ")
for i in range(1, nodes):
min = BIG
for vertice in range(0, nodes):
if matrix[node][vertice] != 0 and explored[... |
91c1f0df605fce36398b1ddef810aa860c431133 | eli-roberts/python-functions | /chickenmonkey.py | 284 | 3.921875 | 4 | def poultry_primate():
for x in range(1, 101):
if x % 7 == 0 and x % 5 == 0:
print("ChickenMonkey")
elif x % 5 == 0:
print("Chicken")
elif x % 7 == 0:
print("Monkey")
else:
print(x)
poultry_primate() |
8f5028a81cce2f1d9d1d03f2ef642d8dab51696d | NicolaiFinstadLarsen/Hackerrank | /1.Introduction/hacker rank oppgave 6(Write a function).py | 561 | 4.0625 | 4 | '''
def is_leap(year):
leap = False
leap = year
if (leap % 4) ==0:
return True
if (leap % 100) == 0:
return False
if (leap % 400) == 0:
return True
return False
is_leap(year = int(input("Write your year here:")))
'''
d... |
dbf888c7476650c16196e78c213690a0a74a8a6b | jmnmv12/IA | /Guiao_2/tree_search.py | 7,923 | 3.71875 | 4 |
# Modulo: tree_search
#
# Fornece um conjunto de classes para suporte a resolucao de
# problemas por pesquisa em arvore:
# SearchDomain - dominios de problemas
# SearchProblem - problemas concretos a resolver
# SearchNode - nos da arvore de pesquisa
# SearchTree - arvore de pesquisa, com ... |
8af3525bfe92ee6c4cff1a381fddd5e20383bb6d | leandroflima/Python | /fatorial.py | 215 | 4.1875 | 4 | numero = int(input("Digite um número inteiro:"))
fatorial = numero
if (numero == 0):
fatorial = 1
while(numero > 1):
fatorial = fatorial * (numero - 1)
numero = numero - 1
print(fatorial)
|
aa21723c177bf9dbb3171c0d2599035d23ad41df | jiluhu/dirtysalt.github.io | /codes/contest/leetcode/sum-of-root-to-leaf-binary-numbers.py | 692 | 3.8125 | 4 | #!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
def fx(root, pv):
... |
f3fa3b2f67ffe846bad750a450f5bd4ad6430316 | Lysogora29/Lesson_2_hw | /first.py | 414 | 3.953125 | 4 | # name = input ('what is your name? ')
# var_type = type(name)
# print(var_type)
# print(' Hello ' , name , '!' )
name = input ('What is your name ? ')
city = input ('Your city - ')
age = input ('How old are you ? ')
print(name, 'from' ,city, 'He is' ,age,)
number1 = input ('Set on number-1 = ')
number2 = input (... |
4d11a1ceb0df5eee0f4f9f8a15f4eef84bc3860b | Vitor-Carmo/Exercicios-Python-Curso-em-Video | /Guanabara/desafio56.py | 614 | 3.65625 | 4 | SomaIdade = 0
MaisVelho = 0
Quantidade_mulher = 0
for i in range(0,4):
nome = str(input("Digite o seu nome: "))
idade = int(input("Digite sua idade: "))
sexo = str(input("Digite seu sexo M/F: ")).upper()
SomaIdade += idade
if sexo == "M" and idade > MaisVelho:
MaisVelho = idade
... |
622172762ec846d3a36f572f28933d4b2089957c | MilosSimek/Python-Udemy-Masterclass | /120.py | 120 | 3.53125 | 4 | t = ("a", "b", "c")
print(t)
name = "Tim"
age = 10
print(name, age, "Python", 2020)
print((name, age, "Python", 2020)) |
c035d48508f660afe24d89525d3df4c9d2cbf2db | sompodsign/pytictactoe | /find_phone_email.py | 1,108 | 3.53125 | 4 | # python 3
# find_phone_email.py
import pyperclip, re
# Phone Regex
phoneRegex = re.compile(r'''
(\d{3}|\(\d{3}\)) #first three-digit
(\s|-|\.)? #separator or space
(\d{3}|\(\d{3}\)) #second three-digits
(\s|-|\.)? #separator or space
(\d{4}|\(\d{4}\))... |
39fceea70662b7d6f173e9dc10412269045b2fe4 | hzjken/leetcode-practice | /Python/46_permutations.py | 655 | 3.5625 | 4 | class Solution:
def permute(self, nums):
non_visited = set(nums)
queue = [([], non_visited)]
output = []
while queue != []:
perm, non_visited = queue.pop(0)
if len(non_visited) == 0:
output.append(perm)
else:
for i ... |
26af40cfa49d8b728b06d999c5d1adee5e10b917 | renuka28/hackerrank | /python/utils.py | 1,858 | 3.625 | 4 | def listify(filename: str, print: bool = False):
file_lines_as_list = [line.strip() for line in open(filename)]
if (print):
print(file_lines_as_list)
return file_lines_as_list
def readn(prompt: str = None):
""" prompts and reads an integer from stdin
returns:
n (int): read integer
... |
a34fac9901e1b8a06d67ca0d77a1758521f46d52 | MrSpadala/Probability-riddles | /2018-HW1-ex1-social_networks.py | 3,212 | 4.125 | 4 |
"""
<<<
Problem 1. We create a small-world graph G according to the following model. We start with a
directed cycle with n nodes. That is, we have nodes v1, v2, . . . vn and we have a directed edge from
each vi to vi+1 (vn is connected to v1). Each of these edges has length 1. In addition there exists
anothe... |
5930ff7fbd473cd207d77e61bd22b0e701594171 | blukitas/JugandoCodewars | /JugandoCodewars/ResueltosCodeWars/string-to-camel-case.py | 397 | 3.875 | 4 | def to_camel_case(cadena):
salida = ''
b = False
for c in range(0, len(cadena)):
n = ord(cadena[c])
if n == ord('-') or n == ord('_'):
b = True
c += 1
continue
if b:
salida += ''.join(cadena[c]).upper()
b = Fals... |
adcb81ba9be52411867cc6ff7fd9e488b75944c1 | srujana-patwari/python_codes | /project1.py | 1,071 | 4.03125 | 4 | gmae_list=[0,1,2]
def display_game(game_list):
print("Here is the current list: ")
print(game_list)
def position_choice():
choice="WRONG"
while choice not in ["0","1","2"]:
choice=input("pick position (0,1,2): ")
if choice not in ["0","1","2"]:
print("sorry inval... |
1cc63c67a437e4aba6ca09eeb6f87657b344c716 | madhurisharmabs410/1BM18CS410 | /3b.py | 161 | 3.796875 | 4 | import string
import random
str1=string.printable
print(str1)
len=int(input("enter the length of a password:"))
b = " ".join(random.sample(str1,len))
print(b)
|
8033fe605247c69f09bd499ad9d6ca2c11ea2cf7 | melquizedecm/pythonProjects | /ESTRUCTURA_DATOS/19B/recursividad.py | 317 | 3.578125 | 4 | def a(contador):
if contador>0:
contador=contador-1
print("funcion A",contador)
b(contador)
else:
return False
def b(contador):
if contador > 0:
contador = contador - 1
print("funcion B", contador)
a(contador)
else:
return False
a(10) |
42258a7c70a1a4c315021430c0074f961e8530e9 | leonhllai/challenge | /sortable.py | 2,060 | 4 | 4 | # A Solution to the Coding Challenge @Sortable
# By Hung-Liang (Leon) Lai
# March 20, 2015
#
import json
def extract(filename,key,JsonObjects,KeySets):
# Given a file and its target key
# extract the arrays of JSON objects and the corresponding key sets
#
# open the file in filename
# loop over each line of... |
afb09833d626ab1174c799c9c26f7501dd01de21 | AlbyAa03/Compiti_Vacanze | /sistemi/scrabbleScore.py | 468 | 3.640625 | 4 | VALORI = {"A":1,"B":3,"C":3,"D":2,"E":1,"F":4,"G":2,"H":4,"I":1,"J":8,"K":5,"L":1,"M":3,"N":1,"O":1,"P":3,"Q":10,"R":1,"S":1,"T":1,"U":1,"V":4,
"W":4,"X":8,"Y":4,"Z":10}
def scrabblleScore(parola):
parola = parola.upper()
if len(parola)>1:
return VALORI[parola[0]] + scrabblleScore(parola[1:])
... |
ca4c5ce2099d27d46542a1ac006b3f1973b4b3f6 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/572d7e63068b4b35a3758d6866916a8b.py | 247 | 3.90625 | 4 | '''
A leap-year occurs on every year that is evenly divisible by 4,
except every year that is evenly divisible by 100,
unless the year is also evenly divisible by 400.
'''
def is_leap_year(y):
return y%4 == 0 and (y%100 != 0 or y%400 == 0)
|
ce098d22739f37881ff423f14c72a13920e0ad10 | kyungtae92/python-basic | /day0930/Base03.py | 174 | 3.984375 | 4 | # number = input("Number IN: ")
# number = int(number)
number = int(input("Number IN: "))
if number >= 100:
print("100 over!!")
else:
print("100 under!!")
|
0658e1c5f4e5ad09c326a7ff76c00ab279ab76ac | Afriendarko/week4_codes | /code3_file_operarion/code3.py | 207 | 3.671875 | 4 | import pandas as pd
data = pd.read_csv("q2sample.csv")
max_salary = max(data['raisedAmt'])
min_salary = min(data['raisedAmt'])
print("Max Salary is {} and Min Salary is {}".format(max_salary, min_salary)) |
64c2d7fdea15b0a3541b7e95a5591f56cca57c29 | PMiskew/Year9DesignTeaching2020_PYTHON | /GUIDemo/GUIPackPractice.py | 332 | 3.625 | 4 | from tkinter import *
root = Tk()
a = Label(root, text="Red", bg="red", fg="white")
a.pack(side=LEFT)
b = Label(root, text="Green", bg="green", fg="black")
b.pack(side=LEFT)
c = Label(root, text="Blue", bg="blue", fg="white")
c.pack(side=LEFT)
d = Label(root, text="Blue", bg="blue", fg="white")
d.pack(side = BOTTOM)
... |
149b4b7336b06024aec2369b5528d32718086c92 | coach-wang/workwork | /腾讯07_字符移位.py | 1,099 | 3.53125 | 4 | '''
小Q最近遇到了一个难题:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。
你能帮帮小Q吗?
输入描述:
输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000.
输出描述:
对于每组数据,输出移位后的字符串。
输入例子1:
AkleBiCeilD
输出例子1:
kleieilABCD
'''
'''
思路:从后往前遍历,遇到大写字母往后交换位置
注意 大写字母的 ACSII码比小写字母小
'''
while True:
try:
string = list(input().strip())
if strin... |
0d2d5fe8601b347cf8608a17c20f53d87ea04620 | mordred9971/discordbot | /plugins/games.py | 2,686 | 3.765625 | 4 | import random
class Games:
"""This is a plugin for fun things you can use to play with [^_^].
!flip, !coin: Flips a coin
!trick: Does a super cool magic trick"""
legacy = True
def __init__(self, client):
self.client = client
async def flip(self, message):
... |
ab4c0ae2d18e3eedaf044e70e3ca80da1c273923 | lxd262/CoffeeMachine | /Coffee Machine/Problems/A mean of n/task.py | 115 | 3.9375 | 4 | total_num = int(input())
count = 0
for _ in range(total_num):
count += float(input())
print(count / total_num)
|
f8f16a138cd28f37ddf29b160ea6e7d9fe41fe59 | ViktorJJF/python-professional | /primer.py | 220 | 3.75 | 4 | def is_prime(number:int) -> bool:
counter=0
for i in range(1,number+1):
if number%i==0:
counter+=1
return counter<=2
def run():
print(is_prime(59))
if __name__=='__main__':
run() |
fce64c87ffaf1d465334450e809a74c15f37616d | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/nucleotide-count/12c2388f18db44aa81f1270eb36b450d.py | 374 | 3.796875 | 4 | def count(dna, nucleotide):
if nucleotide not in ['A', 'C', 'G', 'T']:
raise(ValueError, 'Nucleotide must be one of A, C, G or T')
dna = list(dna)
return len([a for a in dna if a == nucleotide])
def nucleotide_counts(dna):
counts = {}
for nucleotide in ['A', 'C', 'G', 'T']:
counts[n... |
f45872e38ca9bdf91727b976f5a9dfc7d282da21 | Deaddy0430/python_learning | /03_Object-Oriented Programming/10_classmethod.py | 334 | 3.578125 | 4 | class Car:
count = 0
@classmethod #the first elecment is cls
def getTotalCount(cls):
return cls.count
@classmethod
def increment(cls, num):
cls.count += num
print(Car.getTotalCount())
#Car.count +=1 # OOP不提倡直接操作里面的属性
c1=Car()
c1.increment(10)
print(c1.getTotalCount()) |
03d311ff97ffde996de1033a6067d696e92d4f66 | MalteMagnussen/PythonProjects | /week2/download_script.py | 1,084 | 3.9375 | 4 | # 1. Write a program `download_script.py`, which downloads a set of files from the internet.
# The files to download are given as arguments to your program on the command-line as illustrated in the following:
# ```bash
# $ python download_script.py http://www.gutenberg.org/files/2701/2701-0.txt http://www.g... |
481c25dd569991881ec6af62ed369d1367dfeb1a | Dennis-E/Project-Euler | /Euler 52 - sort list, multiples, same figures.py | 1,214 | 3.609375 | 4 | # Euler Problem #52
# Smallest integer number x that has the same numbers as its 2*, 3*, 4*, 5* and 6* multiple
i=0
while True:
i+=1
#numbers in i
elements=[]
elements2=[]
elements3=[]
elements4=[]
elements5=[]
elements6=[]
for number in str(i):
elements.appe... |
6ceb95532fb955a42cf780fb56e2b42379109d0d | TheMeapster/List-Project | /list3.py | 521 | 4.0625 | 4 | #List-3
#Dylan and Avi
#12/8/17
from random import *
def main():
print "This is will make a random list of number between 1 and 50 and it will see if 27 is in the list and it will then tell you the frequency of 27."
count = 0
nums = []
for i in range (50):
num = randint (1, 50)
nums.append... |
7d4a6d76a1a34888926c2f32b47f5b8121192a70 | FlowerFlowers/Leetcode | /src/Tree/110BalancedBinaryTree.py | 1,409 | 3.734375 | 4 | '''
leetcode题号:110
给定一棵二叉树,看看是不是平衡的
平衡的标准是,叶子节点的高度差不超过1
eg:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
思路:
递归的计算每个节... |
de52f2dcdbdaca5e525327c27ac88e3ac8e3146f | jisethpenarias/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 4,253 | 3.671875 | 4 | #!/usr/bin/python3
"""Base Class"""
import json
class Base:
""" This class will be the “base” of all other classes"""
__nb_objects = 0
def __init__(self, id=None):
"""The goal of this is to manage id attribute in all your future
classes and to avoid duplicating the same code"""
... |
a170b77f29c70264a7fbab0bd5b1df862a113db2 | spweps/Day-1-Python | /pre-camp/textcorrected.py | 3,179 | 4.125 | 4 | num1 = 42 # variable declaration, number initialized
num2 = 2.3 # variable declaration, decimal/float initialized
boolean = True # variable declaration, boolean initialized
string = 'Hello World' # variable declaration, string initialized
# variable declaration, list initialized
pizza_toppings = ['Pepperoni', 'Sausage... |
067af370bd95001a83f4692f7b82b96a84920f97 | Jomondi/MachineLearningProject | /MachineLearningProject.py | 995 | 3.640625 | 4 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Load csv file and display the columns
csv_file = pd.read_csv("chidata_for_assignment_5.csv")
print(csv_file.columns)
print()
# Convert the file into a dataframe and print the head/tail results
df = pd.DataFrame(csv_file)
print(df.head().to_ma... |
c8ce9347ea7c0ea79b1db742c82277d406d1fceb | MauroMaia/pwManager | /pwmanager/ext/persistence/json/domain/vault_user.py | 931 | 3.546875 | 4 | from datetime import datetime
class User:
def __init__(
self,
username: str,
password_hash: str,
last_update_at: datetime,
created_at: datetime,
read_only=True
):
""" TODO """
assert username is not None, 'username should... |
05a5748eba26bf3a3b77f52dbb188529af54237c | rutujab1498/blind_searches | /dfs.py | 905 | 3.640625 | 4 | def dfs(graph, start, visited, stack):
visited, stack = visited, stack
visited.append(start)
stack.append(start)
print(start)
for i in graph[start]:
if not i in visited:
dfs(graph, i, visited, stack)
s = int(input('Enter start node: '))
g=[]
v = int(in... |
acf75af322a75c30a1220661a34eeae30822014e | TorpidCoder/DataStructure | /HeadFirst/maximumofArrayProblem.py | 431 | 4.09375 | 4 | __author__ = "ResearchInMotion"
def maximumElement(arr):
max = arr[0]
for value in arr:
if (value >= max):
max = value
return max
if __name__ == '__main__':
arr = []
size = int(input("Please enter the size of the Array : "))
for numbers in range(0,size):
arr.appen... |
6a3e7117ddb3479dfa0a84763844885e4d7971cd | LingyeWU/unit3 | /Week28/q3.py | 412 | 4.375 | 4 | # This program accepts a comma separated sequence of words as input and prints the words
# in a comma-separated sequence after sorting them alphabetically.
print("enter a list of words separated by commas(no space):")
# splitting words along commas
a = input().split(',')
# alphabetically sorting words
b = sorte... |
824412a9fa8467fa62f10d0892a1749cd2c532a8 | lokivmsl98/python | /beg 44.py | 74 | 3.703125 | 4 | a=int(input())
if(1<=a and a<=10):
print("yes")
else:
print("no")
|
3443a8b47c3d2548ed29555264fe727112b3b21f | stevenjwheeler/uni-python-snippets | /simple_calc.py | 457 | 4.40625 | 4 | integer1 = int(input("Please enter the first integer: "))
integer2 = int(input("Please enter the second integer: "))
operator = input("Please enter an operator (+, -, /, *): ")
if operator == "+":
sum = integer1 + integer2
elif operator == "-":
sum = integer1 - integer2
elif operator == "/":
sum = intege... |
14111ee34978f569763a1d5d020e986deb0695da | Bobafeti1998/Pyton-feladatok | /celsius.py | 148 | 3.71875 | 4 | celsius = int(input("Adj meg egy számot!"))
farenheit = (((celsius*9)/5)+32)
print(str(celsius) + " celsius " + str(farenheit) + " farenheit!")
|
4df1de482971b6c1227a9143c75b0a2e5f3cbd51 | franciscoguemes/python3_examples | /basic/76_serialization_05.py | 3,315 | 4.1875 | 4 | #!/usr/bin/python3
# Following the previous examples, in this example I am building a primitive software for managing your collection
# of movies. The software is able to read the movies from a file (deserialize) and to save the movies to a file
# (serialize)
import pickle
class Movie:
def __init__(self, title... |
a9a4f9e454711353a969c827b8c3a6226ced3bf9 | newpheeraphat/banana | /Algorithms/List/T_ChangeValuesInList.py | 340 | 3.546875 | 4 | def check_score(s):
import itertools
# Transpose 2D to 1D
res = list(itertools.chain.from_iterable(s))
for key, i in enumerate(res):
if i == '#':
res[key] = 5
elif i == '!!!':
res[key] = -5
elif i == '!!':
res[key] = -3
elif i == '!':
res[key] = -1
elif i == 'O':
res[key] = 3
elif i == '... |
e1fc8191bcc553e185fe54a53f29e3e1540bbaa4 | tbahlo/checkio | /count-inversions.py | 617 | 3.953125 | 4 | def count_inversion(sequence):
n_conversions = 0
for iter in range(0,len(sequence)):
for comparitor in range(iter+1,len(sequence)):
if sequence[iter] > sequence[comparitor]:
n_conversions += 1
return n_conversions
if __name__ == '__main__':
#These "asserts" using onl... |
caa0a0c2213222fdd2869258490fe33e2e82c3a1 | vmohheng/NPRZC | /LinkedList.py | 1,299 | 3.65625 | 4 | import pygame, sys, math
from Node import *
class LinkedList:
head = None
def __init__(self):
self.head = None
def add(self, data):
newNode = Node(data, None, None)
# If list is empty, make new node the head
if self.head == None:
self.head... |
7e97734e32a7efe28d33dd0f7de054131c1f8b4d | kldznkv/tms | /Lessons/Lesson 5/Task_5_8.py | 645 | 3.6875 | 4 | pupils = [{'firstname': 'You_1', 'Group': 54, 'Physics': 8, 'Informatics': 9, 'history': 10},
{'firstname': 'You_2', 'Group': 52, 'Physics': 3, 'Informatics': 7, 'history': 6},
{'firstname': 'You_3', 'Group': 32, 'Physics': 4, 'Informatics': 8, 'history': 5}]
def calc_avg_score(users):
for user in users:
av... |
0f7d407a32928a1da3332b67728e9b9bf67c1bd6 | RobinFrancq/learn_python | /basicprograms/studentdetails.py | 228 | 3.71875 | 4 | studId = int(raw_input("Enter Student Id: "))
studName = raw_input("Enter Student Name: ")
studMarks = float(raw_input("Enter Student Marks: "))
print("ID: " +str(studId)+ ", Name: " +str(studName)+ ", Marks: " +str(studMarks)) |
ac3874c1f628834a3f4e06041e74aa97601efc92 | shannan1989/ShannanPython | /WordCloud/colored.py | 1,549 | 4.03125 | 4 | #!/usr/bin/env python
"""
Image-colored wordcloud
=======================
You can color a word-cloud by using an image-based coloring strategy
implemented in ImageColorGenerator. It uses the average color of the region
occupied by the word in a source image. You can combine this with masking -
pure-white will be interp... |
d25666dfb46a3b7677f6d6826b8af59f742f1f3b | wjosew1984/python | /clase3.py | 9,777 | 4.375 | 4 | Listas
Es un contenedor que se usa para almacenar conjuntos de elementos relacionados del mismo o distinto tipo. Son colecciones ordenadas de objetos. A cada elemento se le asigna un índice (posición) comenzando con el cero.
Creacion
Ej mismo tipo de dato:
>>> numeros_positivos = [ 1, 6, 8, 12]
>>> nombres =... |
bffdc66091ac5b01df9f5c2bc64ca68f64f36c3e | jeffsilverm/kart.io.challenges | /kart.io.challenge.py | 3,286 | 3.765625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Imagine we have an image where every pixel is white or black. We’ll represent
# this image as a simple 2D array (0 = black, 1 = white). The image you get is
# known to have a single black rectangle on a white background. Find this rectangle
# and return its coordinate... |
2342a60a9a7a7218745abe64f0ffd65a1de96864 | greedyx/Algo_questions | /Merge sort --- Count inversions.py | 1,530 | 3.96875 | 4 | '''
[1, 20, 6, 4, 5]
(20,6) ,(20,4),(6,4) and so on, in total 5 inverse number pairs
use merge sort O(n*logn)
no calculations during "divide" process
during "merge" process, observe how many numbers behind the medium value and calculate
使用分治算法,递归将数组进行二分(low ~ middle 和 middle+1 ~ high),直至为仅剩1个元素。此时逆序对数量为0。
再将数组(low ... |
35406dd7f841bb9d301ab13f56ede8be0df018c4 | Hannibal404/data-structure-and-algorithms | /searching/Linear_Search.py | 566 | 4.03125 | 4 | def LinearSearch(a, size, key):
for i in range(size):
if a[i] == key :
return i
return -1
if __name__ == "__main__":
a = []
n = int(input("Enter the number of elements in array :"))
print("Enter the elements in array :")
for i in range(n):
a.append(int(input()))
... |
2581ddcbcece578c21358ff72b7451c04933c91c | Ellie1994/python_quick_and_dirty | /stand_loopover_list.py | 120 | 4.0625 | 4 | nums = [1, 2, 3, 4, 5]
my_list = []
for n in nums:
my_list.append(n) #adds n to the end of the list
print(my_list)
|
446da80ee25605ea88f1b901c75f5c809d2e9abb | Javierfs94/Modulo-Programacion | /Python/poo/ficheros/Ejercicio6.py | 977 | 3.796875 | 4 | '''
* <p>
* Realiza un programa que diga cuántas ocurrencias de una palabra hay en un
* fichero. Tanto el nombre del fichero como la palabra se deben pasar como
* argumentos en la línea de comandos.
* </p>
@author: Francisco Javier Frías Serrano
'''
contador = 0
nombreFichero = input("Introduzca el nombre del f... |
fbba0b23b00ca394c5cbd7bae3ff66088fa2819a | thiagobarbosafirst/curso-python | /verificandoOrdenacao.py | 283 | 4.15625 | 4 | # -*- coding: utf-8 -*-
num1 = int(input("Digite um número inteiro: " ))
num2 = int(input("Digite um número inteiro: " ))
num3 = int(input("Digite um número inteiro: " ))
if num1 < num2 and num2 < num3:
print("crescente")
else:
print("não está em ordem decrescente")
|
1de8a73ef7b5fc738b421581cadf5bf7bef752a7 | sherin11/python-programming | /beginner/find number is + or - or 0.py | 104 | 3.71875 | 4 | a=int(input("m="))
if(a==o):
print("zero")
if(a>o):
print("positive")
else:
print("negative")
|
98153b5ec87a986fb689ec541d6491b8072812be | sanupanji/python | /first/range_even_number.py | 159 | 4.03125 | 4 | for i in range(0, 10):
if i % 2 == 0:
print(i)
#list conprehension #
print([i for i in range(0, 10) if i % 2 == 0])
print(list(range(0, 10, 2)))
|
660ab69d805594a41946a16150f3345a8b697091 | yiruiduan/2018-07 | /2018-06/rabbitmq_redis_mysql/mysql_connect.py | 543 | 3.671875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import pymysql
data=[("N4",55,"1963-04-03",10),
("N5", 56, "1963-04-04", 11),
("N6", 57, "1963-04-05", 12)]
#创建连接
mysql_connect=pymysql.connect(host="192.168.1.115",port=3306,user="yiruiduan",passwd="yiruiduan",db="oldboy")
#创建游标
cursor=mysql_connect.cursor()
# cu... |
1b36efbd9374057c25334fb8ff5110ad51c54bb6 | Jacken-Wu/CQU-python-2021 | /CQU-python-题库题参考答案/题库练习:字符串/编程题/2.py | 216 | 3.9375 | 4 | string = input()
s = ''
for c in string:
num = ord(c)
if 65 <= num <= 90:
s += chr(155 - num)
elif 97 <= num <= 122:
s += chr(219 - num)
else:
s += c
print(string)
print(s)
|
9d461cda682c060b98845bbac7ea5def2d1c3e50 | jaxball/justcodeit | /online_problems/longestPalindrome.py | 205 | 3.6875 | 4 | """ Given a string, i.e. "zaabbaacaz" which may contain more than one palindrome substrings, find its longest palindromic substring. """
def longPalindrome(instr):
print longPalindrome("geeksforgeeks") |
df05216f687732538bf9f81437e0633efb05f79f | SR-Sunny-Raj/Hacktoberfest2021-DSA | /24. Cryptography/Additive_Cipher.py | 808 | 4.15625 | 4 | ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SPECIAL_CHARS = " ,.-;:_?!="
def decrypt(cipher_text, key=None):
texts = []
for key in range(0,26):
plain_text = ""
for letter in cipher_text:
#Skipping special characters (incomplete solution)
if letter in SPECIAL_CHARS:
... |
0f37a1a42b324eba9521cb56bda859857c815dac | abdullahmujahidali/probable-system-Game-Python | /code.py | 1,401 | 4 | 4 | import random
# 2d list with words and their corresponding descritpors
words = [['greeting','python','table','create','script','stethoscope','hedgehog','accelerate','xylophone','circle'],
['some act of communication','a digital snake','has a flat top','to design from scratch','a kind of blueprint',
'doctors like it','s... |
095b6a12fde01b798916845bbfeafa27b7e7d9cf | prathiksha-naik/python | /python7.py | 325 | 4.09375 | 4 | #armstrong number
num=int(input("Enter the number: "))
temp=num
order=len(str(num))
sum=0
while num>0:
c=num%10
sum+=c**order
num=num//10
if temp==sum:
print("The entered number {} is amstrong number: ".format(temp))
else:
print("The entered number {} is not amstrong number: ".format(tem... |
7dfed4a7868cb60b936c4ee7b0cdb1f8a138e64d | limisen/Programmering-1 | /16/e16-02.py | 325 | 3.578125 | 4 | pannkaka = {
'vetemjöl': '2 1/2 dl',
'salt': '1/2 tsk',
'mjölk': '6 dl',
'ägg': '3'
}
for values in pannkaka:
print(values)
print("----------------")
for keys in pannkaka:
print(keys)
print("----------------")
for keys, values in pannkaka.items():
print(keys, values, sep=": ")... |
a20e12cfc25617b2a8f0259b5a6259710ff87bae | Ayala075/Ejercicios-de-tipos-de-datos-simples | /Ejercicios de Tipos de Datos Simples/Ejercicio9.py | 409 | 4 | 4 | # Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de años, y muestre por pantalla el capital obtenido en la inversión.
inversion = input("Ingrese una cantidad a invertir: ")
interes_anual = input("Cual es el interes anual? ")
anios = input("De cuantos anios estamo... |
db4b5f492e5e338beb8ac04849f6f3ceedb036e2 | Leonidis2411/Python | /2 Задание Python/14 Четное и нечетное.py | 156 | 3.65625 | 4 | a = int(input())
b = int(input())
c = int(input())
a1 = a % 2
b1 = b % 2
c1 = c % 2
s1 = a1 + b1 + c1
if 3 > s1 > 0:
print('YES')
else:
print('NO')
|
daac4843cf2bb753bcdeebc50fc31bbf29fca9c9 | HowFunSong/Algo | /dijkstra.py | 1,747 | 4.03125 | 4 | #實作Dijkstra 主要要有三部分
#1.建立紀錄圖形的Hash table
#裡面包括節點連接的各個節點(Node),以及邊(edge)的長度
graph = {}
graph["Start"] = {}
graph["Start"]["a"] = 6
graph["Start"]["b"] = 2
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] =5
graph["fin"] = {}
print(graph)
#2.建立每個節點"成本" 的... |
1695d1cebc488f9cc66213e6cf1b373fc8213cfd | brunoleej/study_git | /Mathematics/Data science/Python/week2_python1_super.py | 715 | 3.90625 | 4 | # super : 부모 클래스에서 사용된 함수의 코드를 가져다가 자식 클래스 함수에서 재사용할때 사용
'''
class A:
def plus(self):
code1
class B(A):
def minus(self):
code1 # super().plus()
code2
'''
class Marine:
def __init__(self):
self.health = 40
self.attack_pow = 5
def attack(self,unit):
unit.... |
974caa831c430eb55aaf5eccd441c9829c545a2e | chati757/python-learning-space | /extra/speed_tip_coding/avoid_if_in_count_dict.py | 474 | 3.5 | 4 | #Avoid IF
#--------
import time
mydict = {'p':1, 'y':1, 't':1, 'h':1, 'o':1, 'n':1}
word = 'pythonisveryfast'
start = time.time()
for w in word:
if w not in mydict:
mydict[w] = 0
mydict[w] += 1
print(mydict)
print("Time elapsed for IF case is:", time.time() - start)
start = time.time()
for w in word... |
7701e23553ef46831b41be67ae5d1693e31e0003 | bozhikovstanislav/Python-Fundamentals | /Class-HomeWork/06.Animal.py | 3,156 | 3.65625 | 4 | class Animal:
def __init__(self, name, age, number_l="", iq="", cruelty=""):
self.__name = self.set_name(name)
self.__age = self.set_age(age)
self.__number_l = self.set_number_of_legs(number_l)
self.__iq = self.set_IQ(iq)
self.cruelty = self.set_cruelty(cruelty)
def set_... |
f7955a7d90c49280143e3af7e264903570e2f034 | shevapato2008/HadoopMapReduce_Python | /2. Friends By Age/FriendsByAge.py | 727 | 3.59375 | 4 | from mrjob.job import MRJob
class MRFriendsByAge(MRJob):
def mapper(self, _, line):
(ID, name, age, numFriends) = line.split(',')
yield age, float(numFriends) # Cast numFriends as a float.
# This tells python we can do arithmetic operations on it.
def... |
37666f7c59bca095f89665af11d31da52f8bbea3 | 8BitJustin/2020-Python-Crash-Course | /Chapter 9 - Classes/user_module.py | 1,416 | 3.734375 | 4 | class Users():
def __init__(self, first_name, last_name):
self.fname = first_name
self.lname = last_name
self.login_attempts = 1
def increment_login_attempts(self):
self.login_attempts += 1
return self.login_attempts
def reset_login_attempts(self):
self.logi... |
d24de936798903cf377181f39df508072ce68777 | jacqueline-homan/Python3inDebian8Linux | /simpleOOP2.py | 1,474 | 3.75 | 4 | #!/usr/bin/python3
#--View --
class AnimalActions:
def quack(self): return self._doAction('quack')
def feathers(self): return self._doAction('feathers')
def bark(self): return self._doAction('bark')
def fur(self): return self._doAction('fur')
def _doAction(self, action):
if action in self.strings:
return s... |
62fa4c229e67d96a748f9483d7ccbf852d919bb0 | Lewis-Lu/LeetCode | /CodeList/Sorts/Sorts.py | 1,648 | 3.609375 | 4 | '''
Sort ALGOs implemented in python
'''
class Sorting:
def __init__(self, data):
self.data = data
self.length = len(data)
self.Quick(0, self.length-1)
# print(self.data, end='\n')
def Bubble(self):
for i in range(self.length):
for j in range(self.length-1)... |
21e02592a2a092ac642ae7e9b07556fd06f66a9e | kylerbrown/spikedetekt | /spikedetekt/graphs.py | 1,805 | 3.5625 | 4 | '''
Various simple routines for working with graph structures, used in defining the
spatial structure of the probes.
'''
def contig_segs(inds, padding=1):
""" input: a list of indices. output: a list of slices representing contiguous blocks of indices,
where padding is the distance that they can touch each ot... |
f0b95e79b3886de3eba09a717049a660009da73e | nagask/leetcode-1 | /100 Same Tree/sol.py | 537 | 3.8125 | 4 | """
Simple recursive solution: 2 trees are the same if:
roots are the same, subtrees are the same.
O(N) time, O(h) space
"""
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not p or not q:
return False
is_root... |
1f684fec996e1cb2950ca2d3a527fe7034ea7360 | rmbennett/ProjectEuler | /1001stPrime.py | 638 | 3.8125 | 4 | import math
from time import time
def primeChecker(value):
for divisor in range(2, int(math.floor(math.sqrt(value))+1)):
if value % divisor == 0:
return False
return True
def nthPrime(nthValue):
prime = 0
currentValue = 0
for value in range(1, 9999999):
if primeChecker(value):
prime = value
currentV... |
a42028da7f58d212c60f4b4f21312ea2340ee71e | keerthisreedeep/LuminarPythonNOV | /Language_Fundamentals/swapping.py | 333 | 4.21875 | 4 | #swapping using 3 variables
num1=input("enter value for num1")
num2=input("enter value for num2")
temp=num1
num1=num2
num2=temp
print(num1)
print(num2)
#swapping using 2 variables
num1=int(input("enter value for num1"))
num2=int(input("enter value for num2"))
num1=num1+num2
num2=num1-num2
num1=num1-num2
print(num1)... |
a80a571cacc1a0150442dae0334d5ecd8936219c | ivan-yosifov88/python_basics | /For Loop - Lab/10. Odd even Sum.py | 365 | 4.09375 | 4 | numbers = int(input())
sum_even = 0
sum_odd = 0
for numbers in range(1, numbers + 1):
number = int(input())
if numbers % 2 == 0:
sum_even += number
else:
sum_odd += number
difference = abs(sum_odd - sum_even)
if sum_odd == sum_even:
print("Yes")
print(f"Sum = {sum_odd}")
else:
pr... |
0cbeaa5319d193a80d69810a23171079c45153cc | Valim10/Uri | /1020.py | 385 | 3.59375 | 4 | entrada = input()
anos =0
meses =0
dias = 0
while entrada > 0 :
if entrada/ 365:
anos =+ int(entrada/365)
entrada = entrada % 365
elif entrada/ 30:
meses =+ int(entrada/30)
entrada = entrada % 30
else :
dias = int(entrada)
entrada = 0
print (str(anos)... |
d8e0144e10003b53b401f45adb41e006145ac516 | danieldfc/trainling-python | /Atividades/Yuri/Aula/segundo_maior.py | 424 | 3.96875 | 4 | numero = int(input('Informe um número -> '))
maior = 0
segundo_maior = 0
opcao = True
while opcao:
if numero > maior:
segundo_maior = maior
maior = numero
elif numero > segundo_maior:
segundo_maior = numero
opcaoUser = str.upper(input('Você deseja continuar? S (Sim) / N(não) ->'))
if opcaoUser != '... |
5dca03c706051823e9bd4fd6370510fcdca16164 | erjan/coding_exercises | /count_hills_and_valleys_in_array.py | 1,589 | 3.84375 | 4 | '''
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill o... |
1d3bda6a96dd47128045bc0ddb86f9607b2a057e | harshal9876/AI5002 | /Assignment_3/Codes/Asssignment_3.py | 2,558 | 3.703125 | 4 | #Prob 2.6
#Including Libraries
import numpy as np
import random
import matplotlib.pyplot as plt
#Defining functions
#Function to generate random set of product values for A/B/C marked as Normal or Defective
def production_set(percentage,size,true_value,false_value):
value=[]
i=0
for i in range(size):
if(i... |
a14fabfa619e804eb9d8a0d3e93bb80f18d330d9 | daniel-reich/ubiquitous-fiesta | /pihNcNQXiYHSRW8Cv_24.py | 137 | 3.6875 | 4 |
def sort_by_length(lst):
main=sorted([len(x) for x in lst])
main2=[b for a in main for b in lst if a==len(b)]
return main2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.