blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3e19de9b0a180355d97f72f0ffe3658eec7e4eb9 | filipi86/Studies-Python-Bases | /World_2/Exercises/ex038.py | 239 | 3.953125 | 4 | n1 = int(input('O primeiro numero eh: '))
n2 = int(input('O segundo numero eh: '))
if n1 > n2:
print('O PRIMEIRO valor eh maior!!')
elif n2 > n1:
print('O SEGUNDO valor eh maior!!')
else:
print('Os dois valors sao IGUAIS')
|
ad5e29cbf1e77de706249aac2ffe280c98cd3f67 | dpBhalala26/007_DevangBhalala | /Lab1/Practice/Lab1_0_prac_pandas_matplotlib.py | 854 | 3.59375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# from google.colab import drive
# drive.mount('/content/drive')
data=pd.read_csv('mtcars.csv')
d=pd.crosstab(index=data['cyl'],columns="count",dropna=True)
print(d)
print(data.info())
#Count Total Null values in each column
print("Total Null Da... |
a02836893370fa2e0b809624a3bf06e2d9e0f4da | DragonKoc/python_ru | /level00/lecture08/task0107.py | 863 | 4.0625 | 4 | # /*
# Комментарии излишни
# Раскомментируй одну строчку, чтобы программа вывела на экран числа 12 и 2 (сначала 12, а затем 2).
#
# Требования:
# • Программа должна выводить на экран числа 12 и 2.
# • Нельзя изменять строки с объявлением переменных.
# • Программа должна содержать только две переменные типа int.
# • Нел... |
a8ef7b470dce77c84bdec997d9e483d253399fa1 | hasabnistejas/Python-Projects | /Hangman Game/hangman.py | 3,165 | 3.9375 | 4 | import random
def hangman():
WORD = random.choice(["pencil","pen","superman","glasses","mobile","calculator","laptop","book","person","animal"])
# print(WORD)
alphabets = "abcdefghijklmnopqrstuvwxyz"
chance = 10
guess_made = ""
while len(WORD) > 0:
main = ""
for letter in WORD:... |
8994723fed879b9869ae17c8bad360f0765007a9 | xenron/sandbox-github-clone | /wizcabbit/leetcode.python/035.Valid.Sudoku.py | 1,727 | 4.03125 | 4 | # *********************************************
# Source : https://oj.leetcode.com/problems/valid-sudoku/
# Author : wizcabbit
# Date : 2014-11-01
# Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
# The Sudoku board could be partially filled, where empty cells are filled with the character ... |
f69a7b03622e10f0b00cb728bb0be5128a4e4b83 | astilleman/MI | /test3.py | 4,590 | 3.65625 | 4 | '''
from list_helpers import *
l = [1, 2, 3, 2, 4, 3, 5]
remove_duplicates(l)
print(l)
import list_helpers
l = [1, 2, 3, 2, 4, 3, 5]
list_helpers.remove_duplicates(l)
print(l)
def dummy_method(value):
print("")
value = 10
dummy_method(20)
print(value)
##
# Simulates the rolling of 5 dice and draws the face of ... |
eb3abc03d105a904c9447c3e5c23af6830389d3b | subho2107/Hacker-Rank | /Data Structures/Stack/Game of Two Stacks.py | 1,225 | 3.828125 | 4 | """
PROBLEM LINK :https://www.hackerrank.com/challenges/game-of-two-stacks/problem
"""
#!/bin/python3
import os
import sys
#
# Complete the twoStacks function below.
#
def twoStacks(x, a, b):
#
# Write your code here.
#
sum_ = 0
posOfStack1 = 0
posOfStack2= 0
m = len(a)
n = len(b)
... |
706cab2fc8b3af8fa0854ca4a22d509bae93768a | squashmeister99/PythonProjects | /primeNumbers/primeNumbers_fast.py | 954 | 3.53125 | 4 | import argparse
from time import perf_counter
def main():
parser = argparse.ArgumentParser()
parser.add_argument('n', type=int, default=15,
help="find all primes upto specified number")
args = parser.parse_args()
upperLimit = args.n
myset = set([x for x in range(2, upperLim... |
70b2a7b216a3ed5325665e4e68e5f77f73dfe0c4 | hello-wangjj/Introduction-to-Programming-Using-Python | /chapter2/2.2.py | 170 | 3.984375 | 4 | import math
r,l=eval(input('Entet the radius and length of a cylinder:'))
area=r*r*math.pi
volumn=area*l
print('the area is: %06.2f'%area)
print ('the volume is:',volumn) |
601153e85c2a4c32ef5929e1c456fd7012403c8e | Kirink212/TrabalhodeIA_BinPacking | /main.py | 18,064 | 3.65625 | 4 | ########################################
############# LIBRARIES ################
########################################
from time import time #Library to calculate algorithm running time
from random import shuffle, randint
from re import finditer
from operator import itemgetter
####################################... |
68c89e6015581c3eaff562164a69075b0cf54832 | socc-io/algostudy | /ProblemPool/recursive_hanoi/becxer.py | 126 | 4 | 4 |
def hanoi(n,f,z,t):
if n > 0 :
hanoi(n-1,f,t,z)
print str(f) + " -> " + str(t)
hanoi(n-1,z,f,t)
print hanoi(3,1,2,3)
|
40a37e639f227a35e45a2b90d89736ef181659cb | ThomyRa/MisionTic2022 | /semana3/taller1/calculadora_aritmetica.py | 1,551 | 4.0625 | 4 | """ Modulo calculadora artimética #
Realiza las 4 operaciones (+,-,* /)
Oscar Franco-Bedoya
Mayo 3-2021 """
# Definición de Funciones
def sumar_numeros(numero_uno, numero_dos):
"""
Parameters
----------
numero_uno:float
operando uno para la suma
numero_dos:float
operand... |
67c2841fad24db45fa6e61b27cfe1580d611c94f | PaulaOlivan/1-Evaluacion | /Contador numero primos.py | 598 | 3.75 | 4 | #este programa se encarga de contar y decir cuales de los numeros dados son primos y cuales no
def contador_primos():
print "Este programa se encarga de contar los numeros primos"
print "Para ello necesita conocer el numero mas alto deseado"
n= input ("Cual sera el numero mas alto?")
primo =True
... |
c1f00162dd6bbc22ee4620df60697f9fdae399a9 | omerorkn/GlobalAIHubPythonHomework | /Project.py | 4,052 | 3.984375 | 4 | #__author__ = omerorkn
import os,time
#All attributes and methods(OOP Logic)
class StudentSystem():
def __init__(self,sysname):
self.sysname = sysname
self.names = []
self.courses = []
self.grades = {"midterm":38,"final":66,"project":89}
self.score = (self.grades["midterm"]*0.3) + (self.grad... |
593c69bcd3c7edc74a9b0b5c03b7338f58740107 | ourway/simple-cnn | /feedforward.py | 1,656 | 4.59375 | 5 | #! /usr/bin/env python3
'''
A neuron is a simple function, it get's two inputs,
sum them with some weight and bias and finally pass it
through an activation function.
We'll use a sigmoid function as activation func.
'''
import numpy as np
def sigmoid(x):
'''
>>> raw = sigmoid(7)
>>> round(raw, 4... |
264b242fcc902ba2758101fcb4eb3d518715a32e | theHuston/akcovid | /modules/soup.py | 803 | 3.75 | 4 | # import libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup
# specify the url
quote_page = 'http://dhss.alaska.gov/dph/Epi/id/Pages/COVID-19/monitoring.aspx'
# query the website and return the html to the variable ‘page’
page = urlopen(quote_page)
# parse the html using beautiful soup and sto... |
63fe7c0e7c861f7d18764953af1790a6a3f5613a | zosob/binaryTree | /nodeDel.py | 1,307 | 3.90625 | 4 | #Deleting a node in BST
#Creating tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def deleteNode(root, key):
#if root doesn't exist
if not root:
return root
# If smaller, then left subtree
if root.val>key:
... |
a15d86bd39ce3eea3c9c7af2ef3f7171b7b92685 | Vitalton/python_labs | /HistoryPerson.py | 1,342 | 4.0625 | 4 | import random
class HistoryPerson():
'''СПЕЦИАЛЬНЫЕ МЕТОДЫ'''
def __init__(self, surname, industry):
self.__surname = surname # АТРИБУТ "Только для чтения"
self.industry = industry
self.year_birth = random.randint(1580, 1630)
self.year_death = random.randint(1630, 1680)
i... |
3206a1db76a4c8da9af9c2125a6c51b46fc65627 | manjunatha-kasireddy/python | /lists/loop_list2.py | 340 | 3.84375 | 4 | thislist2 = ["c-lang", "java", "python", "html", "css", "javascript"]
for x in thislist2:
print(x)
thislist = ["c-lang", "java", "python"]
for i in range(len(thislist)):
print(thislist[i])
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
thislist2 = ["c-lang", "java", "python", "html", "... |
0f6ffda1250d4b1d809b1fd6a48e3b25e2a7c068 | lynstanford/math_adventures_with_python | /default_property.py | 223 | 3.78125 | 4 | from turtle import *
# The sidelength property can be re-called each time it's used
def square(sidelength=100):
for i in range(4):
forward(sidelength)
right(90)
square(50)
square(30)
square()
|
cabd16fd09fd935a5d90ff677ce201339f09fc31 | ghahremanielham/python | /1/elham ghahremani4-3.py | 144 | 3.5 | 4 | #salam elham ghahremani hastam
#hal tamrin 3 jalase 4
List=("Benz","BMW","porsce")
List=list(List)
List[1]="Ford"
List=tuple(List)
print(type(List))
print(List)
|
38f41e768da9e8fe34b58f8230fe50a14d2c4b77 | daniel-reich/turbo-robot | /FwCZpyTZDH3QExXE2_7.py | 1,044 | 4.03125 | 4 | """
Create a function that returns the amount of Fibonacci numbers strictly
smaller than the given integer. In mathematics, the Fibonacci numbers commonly
denoted Fn, form a sequence, called the Fibonacci sequence, such that each
number is the sum of the two preceding ones, starting from 0 and 1. Thus:
F0=0 and... |
1201e877a80aa7cc2f52abca3490a59b164b8d1e | Ricardoengithub/URI | /1009.py | 116 | 3.625 | 4 | name = input()
salary = float(input())
sold = float(input())
print("TOTAL = R$ {:.2f}".format(salary + (sold*.15)))
|
2b7878798244dd87be26cdc3a95f1aaf7ed4c064 | karar-vir/python | /pop().py | 161 | 3.890625 | 4 | #pop() method is dicionary{}
diction={'name':'karan','c':'B-Tech'}
print(diction)
print(diction.pop('c',None))
print(diction.pop('c',None))
print(diction)
|
936d77aa8da1ed70d56eff6e7f572dbcba2f99b5 | danieldfc/trainling-python | /Atividades/Yuri/lista4/exerc02.py | 161 | 3.953125 | 4 | numero = int(input('Informe um número -> '))
lista = []
while numero != 0:
lista.append(numero)
numero = int(input('Informe um número -> '))
print(lista) |
12bacdc6c46f090d4e0fc916d2361b22cb7aca39 | pansettykarthik/DES-RSA-encryption | /RSA_encryption.py | 1,024 | 3.859375 | 4 | import random
import math
def is_prime(p):
if p==2:
#print("Prime")
return True
elif p%2 and p>2:
#print("Not Prime")
return False
for i in range(3,int(math.sqrt(p)),2): # as all the even numbers other than 2 are not prime
if p%i==0:
#pri... |
41ae8afa625434d2bbbc0c2a218f8162356c148a | manohartn/codePractice | /1008_ECLIPSE_codePractice/All_K_subsets/all_k_subsets.py | 804 | 3.75 | 4 | import sys
_subsets = list()
def get_subsets(input_list, n, k, index, subset, i):
global _subsets
if index == k:
_subsets.append(list(subset))
return;
if (i>=n):
return
else :
#print "index ", index
replace_or_insert(subset, index, input_list[i])
#... |
a1fd1ad0ea9deed730092bfd5b436fdd7db58786 | JoelEager/Functional-Python | /code/generators.py | 1,101 | 4.375 | 4 | """
Iterator creation using Python generator syntax.
Docs:
https://docs.python.org/3/howto/functional.html#generators
https://docs.python.org/3/tutorial/classes.html#generator-expressions
"""
from random import randint
def random_gen(max_int=100, min_int=0, num_entries=None):
"""
A generator-based t... |
5dfeb203ca2e5c7e87e66de88a59fc785f22f574 | wondershow/CodingTraining | /Python/LC116_PopulateNextRightNode.py | 692 | 3.921875 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
d... |
e1cf2c58609a17ab32d640e162e1274405bd2050 | vishwa8545/first | /first.py | 709 | 3.640625 | 4 | '''d = {1:'vishwa',2:'mohan',3:'raj',4:'bhuvan',6:{1:2343,2:'fdbhhd',3:323443}}
print(d)
print(d.keys())
print(d.values())
d[3]= 'shashi'
print(d[6][3])
s={1,2,2,3,4,5,5,5}
len(s)
print(s'''
class House:
def __init__(self,key,owner,flatno,no_of_members):
self.key = key
self.owner = owner
se... |
576ce058e6fbead92a39289e16edef982b5ae9eb | NabeelahY/leetcode_april_challenge | /week03/18-min-path-sum.py | 1,019 | 4.0625 | 4 | # Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
# Note: You can only move either down or right at any point in time.
# Example:
# Input:
# [
# [1,3,1],
# [1,5,1],
# [4,2,1]
# ]
# Output: 7
# Explanation: Bec... |
ce9c672dec52afdb4e45e4047d14d394e62219c0 | SeanNeilTalbot/The-Start-of-my-Python-Journey | /2.2.ForLoops.py | 376 | 4.28125 | 4 | #ForLoops
#We take a look at for loops and we use the turtle module
#Turtle draws lines on the screen and helps us learn and practice in a entertaining way.
import turtle
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.color('green')
turtle.forward(50)
turtle.color('red')
for steps in ra... |
ed78c0cf287f20a2760d7c1f574a2c654e0fe0c0 | n8mob/py | /month_bug.py | 453 | 4.125 | 4 | #Printing out a interger correlated with a month
def main():
#First receiving input from user
n = eval(input("Please provide a number 1 to 12 for the month we are in: "))
pos = n - 1
#Have the input from user display the correlating month with number
months = ["January", "February", "March", "April"... |
3e8db90b2f12868459fe972f19dd6d2450f77397 | spacemuggle/Python-ML-Class-2020 | /HWs/HW4_test_import.py | 186 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
def tell_age(age):
"""This is where you should describe what the function does"""
print('You are ' + str(age) + ' years old.')
|
dacabb367a607f0dea6a2e0dff1d1fe193d3991d | RHARO-DATA/DataStructure--Algorithms | /Number of 1 bits.py | 222 | 3.984375 | 4 | """
Given an Integer, find the number of 1 bits it has
"""
def one_bits(num):
count = 0
while num > 0:
if num & 1 ==1 :
count +=1
num = num >> 1
return count
print(one_bits(23))
|
8e9d9cdbca34d909e314f02688f7957c414074c4 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise04_37.py | 875 | 4.21875 | 4 | import turtle
width = 100
height = 50
x, y = eval(input("Enter a point with two coordinates x, y: "))
turtle.penup() # Pull the pen up
turtle.goto(50, 25)
turtle.pendown() # Pull the pen down
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(width)
turtle.right(90)
turtle.forward(height)
turtle.... |
684113ce3c2410e68610d10c5f42b3b8a46c090d | JaydevVadachhak/Python-Basics | /2_Variables_DataTypes/StringDataTypes/String_Processing.py | 347 | 3.6875 | 4 | a="jaydev"
print(a.capitalize())
print(a.upper())
print(a.islower())
b = "JAY"
print(b.lower())
print(b.isupper())
c = "hi welcome"
print(c.title())
print(c.find("wel"))
print(c.index("c"))
d = "In hi in welocme in a in"
print(d.count("In"))
print(d.count("in"))
print(d.isalpha())
f = "100"
print(f.isdigit())
e = ... |
03d1104dfff77ddcb3653cd216d0676149fb47d3 | mohzys23/Algorithm5 | /unit8.py | 519 | 3.75 | 4 | #file = open('new.txt', 'r')
#try:
# print(file.write('new.txt'))
#except:
# print('Something went wrong')
import ast
from unit7LJ import invert_dict
file = open('new.txt', 'r')
make = file.read()
convert = ast.literal_eval(make) #converts string item to dictioary
file.close()
print(convert)
invert =... |
f0ff7dc057265d01ec0ddff19b02dcfc1a642b98 | lavanya2710/python-all-programs | /trial.py | 5,288 | 3.671875 | 4 | """for i in range(0,5):
for j in range(0,i):
print("*",end=" ")
print("\n")
i=i+1
rows = 6
for num in range(rows):
for i in range(num):
print(num, end=" ")
class a:
def __init__(self):
print("hello")
def b(self):
print("world")
obj=a()
obj.b()
class... |
e9652f54dbb548f70a4647290f94d572a0b6dea2 | saurin94/Cracking-the-Coding-Interview | /Linked List/PartitionAroundElement.py | 639 | 3.65625 | 4 | ### O(n) ###
class Node:
def __init__(self, val):
self.next = None
self.val = val
head = Node(1)
p = head
l = [9, 5, 3, 6, 5, 4, 7, 5, 8, 2]
for i in l:
p.next = Node(i)
p = p.next
x = 5
def sort(head, x):
p = head
if not head:
return None
while p.next:
if ... |
9abc2d0e3b511b47255e9ee2c6f3c67df564687c | teddy-boy/python_crash_course_exercises | /basics/ch04_working_with_list/ex_4_7.py | 110 | 4.09375 | 4 | numbers = []
for number in range(3, 31):
numbers.append(number*3)
for value in numbers:
print(value)
|
a8efb3ae864cf50e3a0430ae5f0ef6789babcfae | udaynarwal72/pythontutorial | /practice/finding file.py | 226 | 3.984375 | 4 | a = input("Enter the name of the file: ")
def function(b):
"""
This is a function for taking input from the file
"""
f = open(b)
content = f.read()
f.close()
return content
c = function(a)
print(c)
|
94e973d580b7d92cfb73644a0d1e2a0885aa3971 | Luolingwei/LeetCode | /String/Q1087_Brace Expansion.py | 648 | 3.609375 | 4 |
# 思路: 用一个flag标识是否位于{}内
# 如果在其中, 存储遇到的char,结束时进行expand, 否则直接expand
class Solution:
def expand(self, S):
res,stack,flag=[""],[],0
for c in S:
if c==',': continue
if c=='{':
flag=1
elif c=='}':
flag=0
res=[s+c for s i... |
5e476d44bdaff9950ea9dda98dcbd8a734a031ad | mitraparthib3/phython-learning | /health-potion-project.py | 439 | 3.59375 | 4 | # build a health potion for video game
# it will have differrernt difficulty levels
# uses varible, random module, print
import random;
initialHealth = 50;
highestLimit = 50;
lowerLimit = 25;
difficulty = 3; #1 easy and 3 hard
potionHealth = int(random.randint(lowerLimit, highestLimit) / difficulty); #force casting t... |
2c247d26215167f1fce4beccda3c9686cdbf6f8b | emilepennes/polynome_second_degre | /Polynome_second_degre_resolution.py | 1,787 | 4.03125 | 4 | # coding:utf-8
""" Le but de l'exercice est de définir un programme qui pour toute équation
aX^2 + bX + c = 0, a,b,c étant réels, nous donne les solutions réelles."""
from math import sqrt
print("Le but de cet exercice est de définir un programme qui",
" pour toute équation aX^2 + bX + c = 0 nous donne les solu... |
07323828723df0274a14cf8e85f26328272d3cb4 | Ankit-debug777/Reference | /Python/prime2.py | 236 | 4.15625 | 4 | upper = int(input('Upto what number?'))
def isprime(upper):
for num in range(2, upper+1):
for i in range(2, num//2+1):
if (num % i) == 0:
break
else:
print(num)
isprime(upper)
|
28bb2f9ef24b110ae33a2bb13503dc5a5dc06408 | SergeyHodak/my-tasks-for-python | /tasks-0083.py | 1,236 | 4.28125 | 4 | def replace_last(line: list) -> list:
"""
В данном списке последний элемент должен стать первым.
Пустой список или список только с одним элементом должны оставаться неизменными.
"""
if len(line) < 2: # список из одного элемента или вообще пустой
return line # вернуть как есть
else: # ... |
454b1a702c44ec6012efbf2474e35fb249d11c86 | Aldunate5/Diego_Aldunate | /Deporte/bienvenida.py | 821 | 3.5 | 4 | import os,sys
#from abdominales import*
print(os.getcwd())
#sys.path.append("C:\Users\Diego\Desktop\python")
def greetings():
print("Que quiere hacer?")
print("1. Abdominales")
print("2.Informacion")
print("3.Agregar Ejercicio")
print("4. Salir:")
greet=input()#separar, recursion
count=le... |
d142f2ac6cf20fa972547b28bbce433db532dbaa | DanielVisca/Python-Projects | /Shopify/MVP/MVP/OrderFromExcelSheet.py | 1,634 | 3.65625 | 4 | import xlrd
import os
class Excel_order:
"""
Take in an Excel sheet, for every line create an order request.
Every order request will be added to a Queue.
extra additions to keep in mind:
-give an approx. wait time
"""
def __init__(self, excelFile, queue):
"""
initialize E... |
a0df79c6c08f3350c81e221f9466b9e5eb38cf9f | annabanana99/bmipage | /trash.py | 112 | 3.828125 | 4 | list = list(range(0,5))
print(list)
print(str(len(list)))
for i in range(1,7):
print(str(i))
print("Hello")
|
b0a8667c8ef464522f6a309ec351167a4952ba49 | Taoge123/OptimizedLeetcode | /LeetcodeNew/DFS/LC_133_Clone_Graph.py | 1,233 | 3.734375 | 4 | """
Given a reference of a node in a connected undirected graph,
return a deep copy (clone) of the graph.
Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
Example:
Input:
{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"... |
18cb9cb9a694caa613d322fe2dc60ce63aee9d32 | StylishSdp/ProgrammingTask | /Task1/Linked list/创建双向链表.py | 2,728 | 3.828125 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
self.pre = None
class DoubleLinkedList:
def __init__(self, node=None):
self.__head = node
def isEmpty(self):
return self.__head is None
def length(self):
current = self.__head
... |
a5134161b640be6f917f4165eb471c6bc0be8c24 | LeeeLiu/workDiary | /old/绘图.py | 674 | 3.546875 | 4 |
P 238
14. Here is the code to plot the loss and accuracies using Matplotlib:
# Plot loss over time
plt.plot(eval_indices, train_loss, 'k-')
plt.title('Softmax Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('Softmax Loss')
plt.show()
def plot_loss(d_loss, g_loss, train_options):
eval_indices = range(0,... |
b51deab9f0efc51890242e675c5075f8783657fb | momentum-team-3/examples | /python/sequences-files/sequence_examples.py | 33,825 | 4.09375 | 4 | import sys
def lineref():
"""Helper for printing line numbers (students, ignore this)."""
return f"(see line {sys._getframe(1).f_lineno})"
# A collection is a structured group of data. Intuitively, you can think of a collection as
# "anything that can be used with a for loop".
#
# A sequence is an *ordered* ... |
1003ee33cda0f39c37865f6e96101513db50c780 | agusmp97-uab/ES-2020-431-04 | /src/main/Destiny.py | 2,026 | 3.84375 | 4 | from . import Hotel
from . import Flight
from . import Car
from src.main.Cars import *
""" Class containing the information of one destiny in a journey"""
class Destiny:
def __init__(self, flight, n_passengers, n_days):
#outbound flight
self.flight = flight
self.name = flight.get_destiny() ... |
53db8e022d1b65e0c44142845f117f266fb2f471 | xiangnanyue/Algorithm1 | /UnionFind/SurroundedRegion.py | 2,235 | 3.8125 | 4 | # -- coding: utf-8 --
"""
Percolation Problem
给出二维矩阵:
X X X X
X O O X
X X O X
X O X X
把被 'X' 围绕的区域填充之后变为:
X X X X
X X X X
X X X X
X O X X
"""
class Solution:
"""
@param: board: board a 2D board containing 'X' and 'O'
@return: nothing
"""
def surroundedRegions(self, board):
# write your c... |
5c394b6b8c25785da9edeb24c350aff9b644e04f | babiswas/Multiprocessing | /test5.py | 795 | 3.625 | 4 | from threading import Thread
from queue import Queue
from time import sleep
import random
def task(*args):
print(args)
sum=0
for i in args:
sum+=i
return sum
queue=Queue()
class Producer(Thread):
def run(self):
while True:
queue.put((task,(random.choice([1,2,3]... |
b9e322479349cef0d9eabf6b1f12cc49a9ac00a0 | kaush4l/Euler | /20/5kk.py | 459 | 3.84375 | 4 | # GCD of first 20 numbers
# This answer was solved on paper
# Should write method to find the GCD of given numbers
def isPrime(n):
primes = [1, 2, 3, 5, 7, 11, 13, 17, 19]
if n in primes:
return True
else:
return False
# Either have list of primes and iteratively reduce list whe... |
d3a9904f7fbb058b992e671b3d5be6b7e6646d35 | edu-athensoft/stem1401python_student | /py210628e_python1b/day08_210726/homework/quiz9_2.py | 1,887 | 4.03125 | 4 | """
find max and min from 10 given numbers
1. find max
2. find min
1. find max
fetch each number one by one and compare it with the current max
when all numbers have been finished scanning,
the current max number is the result.
pseudo-code
given a0 to a9 as List
(hard code)
set a0 as current max
scan and compare... |
461be45c88893996de22f393f21ac7db8c5d02e1 | mahamudulhasanmeem/district_in_game | /main.py | 1,144 | 3.65625 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("BD District Map Location")
image = "PngItem_5237914.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("location.csv")
all_district = data.district.to_list()
guessed_district = []
while len(guessed_district) < 64:
answer_user_... |
9753c8a0fa8503a3a763f53cbfeeec10cb10d04f | rajubapi/NN-Notes | /Blog/Perceptron/Perceptron-1/figures/figure1.py | 2,811 | 3.890625 | 4 | import matplotlib.pyplot as plt
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class Perceptron():
"""Implements a single general perceptron"""
def __init__(self, input_dimensions, Weights=np.array([]),
w_=False, learning_rate=1, epochs=500, fn='binary'):
if no... |
eca5d4561bd2a6dfc45e546f40bd8752183d8b8a | Edith-panda/Sort_Search_algorithm | /insertion_sort.py | 300 | 3.96875 | 4 | def insertion_sort(num_list):
for num in range(1,len(num_list)):
cur_val = num_list[num]
pos = num
while pos > 0 and num_list[pos-1] > cur_val :
num_list[pos] = num_list[pos-1]
pos = pos -1
num_list[pos]= cur_val
return num_list
print insertion_sort([54,26,93,17,77,31,44,55,20])
|
6f074567a62365e88f778d9c8c82cfe7f017bee6 | danielamtz/Cuatrimestres | /cuatrimestre 2/programacion/programacion orientada a objetos parte 2/pycharm projects/practicas/myAlumno.py | 658 | 3.859375 | 4 | from alumno import alumno
num= input("Cuantos Alumnos va a capturar? ")
for x in xrange (num):
nombre= raw_input("Ingresa el nombre del alumno: ")
carrera= raw_input("Ingresa la carrera del alumno: ")
nivel= raw_input("Ingresa el nivel del alumno: ")
myAlumno=alumno(nombre,carrera,nivel)
i=0
con... |
93b7eda53e49af1fac3e2c94fa96779b61356ed5 | addriango/curso-python | /sintaxis-basica/13.range.py | 224 | 3.984375 | 4 | for i in range(5):
print(f"valor de la variable {i}")
print("")
for i in range(5,10):
print(f"valor de la variable {i}")
print("")
for i in range(10,20,2):
print(f"valor de la variable {i}") |
714a15cbb72b7b5686744d071ab30c8a7550d753 | zerghua/leetcode-python | /N1304_FindNUniqueIntegersSumuptoZero.py | 833 | 3.828125 | 4 | #
# Create by Hua on 4/16/22.
#
"""
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
Input: n = 3
Output: [-1,0,1]
Example 3:
Input: ... |
c9002e5aabe2fa69baa792ff7520cc7700d60b65 | CS196Illinois/lecture-activities-sp19 | /Big O demo/bigO.py | 1,371 | 4.3125 | 4 |
"""
Calculate the nth fibonacci number in O(n) time
note that the formula for the nth fibonacci number is fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
The base case: Fibonacci(n) = 1 if n <= 2
"""
def fibonacci(n):
pass
"""
Determine the frequency of each element in the list.
Return a dictionary wh... |
05f370307c28420aa36057fc30a7013d7efe4d79 | Parkyes90/algo | /leetcode/501~600/557. Reverse Words in a String III.py | 375 | 3.859375 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
words = s.split(" ")
for i in range(len(words)):
word = words[i]
words[i] = word[::-1]
return " ".join(words)
if __name__ == "__main__":
s = Solution()
answer = s.reverseWords("Let's take LeetCode contes... |
322a82c897921612629e4d65a1538ba88f41966d | Yue-Du/Leetcode | /125.py | 366 | 3.8125 | 4 | class Solution:
def isPalindrome(self, s: str) -> bool:
new = ''
for i in s:
if i.isalpha() or i.isdigit():
new += i
new = new.lower()
b = new[::-1]
if new == b:
return True
else:
return False
New = Solution()
New.... |
c819371220e1b0b7dcc79f852f8c4cf5f4b19c95 | djohnmustard/Intermediate-Python-Assignments | /midtermtest.py | 4,328 | 3.890625 | 4 | import random
number_of_decks = 4
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,]
def cards_define_function():
cards = deck * number_of_decks
return cards
cards = cards_define_function()
def remove_card(string):
return cards.remove(string)
def dealer_cards():
dealer_card_one = random.choice(cards)
r... |
f3cc01ad1ca997cd905360a3f5ed2cb7196ca7d6 | larissarmp/Judge | /funcoes/lista28.py | 316 | 3.640625 | 4 | lista = []
for i in range(1, 11):
numeroLista = lista.append(int(input(f"digite o {i} número")))
print(lista)
listaPar = [list(filter(lambda x: x % 2 == 0, lista))]
print("os números pares", listaPar)
listaImpar = [list(filter(lambda x: (x % 2 == 1), lista))]
print("os números ímpares", listaImpar)
|
0564cebd0dc15ba1065fc1788c803fda21675c3e | masci/playground | /cstutoring/022.py | 745 | 3.578125 | 4 | """
In math, a midpoint is a point lying between two (x, y) coordinates on a graph.
As an example, say we have the points:
(2, 5)
(4, 10)
The midpoint is found by adding the two x coordinates, the two y coordinates
and dividing by 2. The result is another (x, y) pair:
((2+4)/2 , (5+10)/2)
The answer is: (3, 7.5)
... |
e6a9c31e0a1771a2062151373ada3864d2867149 | NicholasWM-zz/Cursos | /Python/AULAS/cursoemvideo/PythonExercicios/ex045.py | 1,838 | 3.5625 | 4 | print('{:=^40}'.format(' DESAFIO 44 '))
from time import sleep
from random import randint
print('\033[30m-=-\033[m' * 20)
print('\033[7;30mBEM VINDO AO NOSSO JOGO DE JOKENPO\033[m')
print('\033[30m-=-\033[m' * 20)
print('Digite sua escolha:')
print('(1)PEDRA (2)PAPEL (3)TESOURA')
player = int(input('Qual é ... |
73e5dca5c6dff225d0f2022e1fb56b797e50b70f | Joao-Godoi/Python_The_Huxley | /Códigos/Descontos.py | 202 | 3.515625 | 4 | ent = float(input("Preço do produto: R$"))
desc = float(input("De qunato é o desconto: "))
desconto = (ent * desc) / 100
pfinal = ent - desconto
print("\nO preço final é de %.2f reais" %(pfinal))
|
e460f508e81e02bed05092b2f1b6a731785f9f48 | sptechguru/python-Core-Interview | /Datastructure/Bubble_sort.py | 339 | 3.953125 | 4 |
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
mylist = [85,56,3,20,7,6,2,1,0,1000]
alist = ['s','a','n','t','o','s','h']
print(bubble_sort(mylist))
print(bubb... |
2ff5447bf29b965ef3cb4154e7e5aadd3bcd7a07 | aditirajnish/scholarship_web_scraper | /main.py | 4,730 | 3.734375 | 4 |
import requests
from bs4 import BeautifulSoup
from verify import verify_university, verify_year
def write_file(information, university, year):
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Writes information to a text file. Title contains the
university's name and the year (both are ... |
e703daa6e78037cde39720548c87d52fa6dc069d | polukhinArtyom/Dictionaries | /dictionaries.py | 627 | 3.609375 | 4 | print("***********************Использование словаря****************")
powers = {"The Pigeon": "flight", "Brainzar": "mind reader", "Cyborg": "controls machines"}
print(powers["The Pigeon"])
print("*********Добавление элемента в словарь******************")
powers["Laser Girl"] = "shoot laser"
print(powers)
print("******... |
354bdf829f63d4ad05ca4aaac3b1f6889e7be0ff | rioscesar/Python | /Algos and Data Structures/Search.py | 789 | 3.953125 | 4 | def linear_binary_search(l, item):
mid = -1
while mid != 0:
mid = len(l)//2
if l[mid] == item:
return True
elif l[mid] > item:
l = l[:mid]
elif l[mid] < item:
l = l[mid:]
return False
def recursive_binary_search(l, item):
mid ... |
a42086da7cd0ee1bbb8bb02c3f9922802855d25c | naldridge/pokemon_python_version | /trainer_class.py | 426 | 3.734375 | 4 | class Trainer:
def __init__(self, name, pokemon_party):
self.name = name
self.pokemon_party = pokemon_party
#Function that prints out name of pokemon within your party
def num_pokemon(self):
for pokemon in self.pokemon_party:
print(pokemon.name)
class Enemy:
de... |
39c55d0489fcc6dd4bde4c067801b1fdf1d25a22 | kxhsing/data-structures-algorithms | /recursion/print_recursively.py | 184 | 4.15625 | 4 | def print_recursively(lst):
"""Print items in the list, using recursion."""
if len(lst) == 0:
return
last = lst[0]
print last
print_recursively(lst[1:])
|
a8f7e743447be4b3fd2671aacc8ef2732cf472ed | shehryarbajwa/Algorithms--Datastructures | /binary_search/first_and_last.py | 1,259 | 3.859375 | 4 | def first_and_last(array, target):
output = []
def find_first(array, target, output):
left = 0
right = len(array) - 1
while left + 1 < right:
mid = (left + right) // 2
if array[mid] == target:
right = mid
elif array[mid] < target:... |
15c7449661fadfba298c2915868c8818172d4bf0 | jon-moreno/learn-python | /ex20sd.py | 982 | 4.09375 | 4 | from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
#f.seek(offset, from_what)
def print_a_line(f):
print f.readline(),
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of li... |
87cc680e244aad7660ea7f2744d5cbcba25d1008 | HoustonRossouw/Projects | /Tier 1/Lists, Functions and String handling/SickleCellDisease.py | 1,706 | 3.75 | 4 | dna = str(raw_input("Please enter a DNA string:"))
def translate(dna):
dna_list = []
output_list = []
while dna:
dna_list.append(dna[:3])
dna = dna[3:]
for dna_if in dna_list:
#print dna_if
if dna_if == "ATT" or dna_if == "ACT" or dna_if == "ATA":
output_list... |
89a84a8077a6116c9e2a122880b15f278b5ca40f | linolastella/CSC148H1---F2015 | /A2/word_ladder_puzzle.py | 5,968 | 4.0625 | 4 | # Assignment 2 - Puzzle Game
#
# CSC148 Fall 2015, University of Toronto
# Instructor: David Liu
# ---------------------------------------------
"""Word ladder module.
Rules of Word Ladder
--------------------
1. You are given a start word and a target word (all words in this puzzle
are lowercase).
2. Your goal is ... |
6598cf6d5e16439c6547f3b983cc143650b1e2e0 | lchojnacki/python_design_patterns | /observer.py | 1,911 | 3.625 | 4 | class Observer:
def __init__(self):
pass
def update(self):
pass
class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
if isinstance(observer, Observer):
self.observers.append(observer)
def detach(self, observer):
i... |
9a4530246f5d82c198bf37d85be4fe77565d5594 | pelegm/randomwalk | /graph.py | 1,505 | 3.90625 | 4 | """
.. graph.py
The graph class.
"""
class Hypergraph(object):
""" A :class:`Graph` is a tuple of a vertex set, which is always the set of
integers from 1 to n for some n>0, and an edge set, which is partial to the
set of subsets 2 of the vertex set. """
def __init__(self, n, edges):
self.n = ... |
03a8de30c7c5306ad393fb9d92c6416f8a8ddc4d | reniass/ProjectEuler | /problem6.py | 300 | 3.765625 | 4 | def sumSquares(n):
sum = 0
for number in range(1, n+1):
sum += number ** 2
return sum
def squareSum(n):
sum = 0
for number in range(1, n+1):
sum += number
return sum ** 2
print(sumSquares(100))
print(squareSum(100))
print(squareSum(100) - sumSquares(100)) |
89dad2fd5a19c08e1a62a03eeee34644972347d4 | minhnguyen2610/C4T-BO4 | /Session7/minihack2.2.py | 87 | 3.671875 | 4 | n = int(input("nhap so vao day de tao day so: "))
for i in range(0, n+1):
print(i)
|
071c2d353a28d384e87654a305dcb2523e44d604 | v1ktos/Python_RTU_08_20 | /Lists/list_2.py | 381 | 3.546875 | 4 | my_list = []
my_list
my_list += list(range(5, 1, -1))
my_list
my_list[-1]
result = my_list.pop() # in place means modifies list!!\
result
my_list
del my_list[1]
my_list
my_list += list(range(10))
my_list
del my_list[4:6]
my_list
my_list.remove(5)
my_list
my_list.remove(5)
my_list
sum(my_list)
min(my_list), max(my_list... |
8bec17d44f594fb565ba7ad184c16a26436f983d | daviguetta/POOcomPython | /Conceitos chaves.py | 828 | 4.21875 | 4 |
#CLASSE EM PYTHON
class Carro():
# __init__ CONSTRUTOR DO PYTHON - METODO PARA A ATRIBUIÇÃO DE ATRIBUTOS PARA UMA INSTÂNCIA
# "def" define um metodo dentro da classe
def __init__(self,arg,arg2):
self.Atributo1 = arg
self.Atributo2 = arg2
def getAtributo1():
return self.Atributo1
# HE... |
5e0aae75eaea10a2adc958e5f5586ecf5baf2c26 | vqpv/stepik-course-58852 | /7 Циклы for и while/7.4 Цикл while/2.py | 108 | 3.859375 | 4 | word = input()
while (word != "КОНЕЦ") and (word != "конец"):
print(word)
word = input()
|
d527694b8640490c19d4fe51e32643b234b9c427 | fernandeson/27-states-br | /main.py | 1,253 | 3.953125 | 4 | import turtle
import pandas as pd
screen = turtle.Screen()
screen.title("BR States Game")
# Add background image:
image = "mapa-brasil.gif"
screen.addshape(image)
turtle.shape(image)
guessed_states = []
df = pd.read_csv("27_states_br.csv")
state_names = df["name"].to_list()
while len(guessed_states) < ... |
bdb3b8afa71c8bfef4a7dc87b0a1f1b122ed2099 | kevinmel2000/computer-vision-raspberrypi | /012-tflite-object-detection/altusi/logger.py | 2,272 | 3.5 | 4 | """
Logger class
============
Wrapper of built-in `logging` Python module
that supports logging task to both console and files
"""
"""
Revision
--------
2019, Sep 24: first version
"""
import os
import logging
# format for logging message
LOG_FILE_FORMAT = '%(asctime)s %(name)12s [%(levelname)s] %(message)s... |
bcbd899cdd69b533e46b86d74e627926a779df58 | H-Shen/Collection_of_my_coding_practice | /Hackerrank/Python/Nested_Lists.py3 | 610 | 3.65625 | 4 | Name = list()
Grades = list()
N = int(input())
for i in range(N):
nameInput = input()
gradeInput = float(input())
Name.append(nameInput)
Grades.append(gradeInput)
result = list(zip(Name, Grades))
for x in range(N):
result[x] = list(result[x])
minimum = min(Grades)
maximum = max(Grades)
for j in ... |
57057aa45cbb5a24479da954f8bd3bd91376c886 | ShihabAhmed09/HackerRank-Solutions-Python | /Mathematics/Algebra/SteppingStonesGame.py | 567 | 3.703125 | 4 | import math
def solve(n):
result = (-1 + math.sqrt(1 + 8 * n)) / 2
if result == int(result):
return "Go On Bob " + str(int(result))
else:
return "Better Luck Next Time"
# def solve(n):
# result = int((-1 + math.sqrt(1 + 8 * n)) / 2)
# if n == (result * (result + 1)) // 2:
# ... |
5559c0b123db9f0a1d7b170df4217c87613871f8 | tmoertel/practice | /EPI/15/soln_15_011_levenshtein_distances.py | 6,889 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Tom Moertel <tom@moertel.com>
# 2013-11-08
"""Solution to "Levenshtein Distances" problem, EPI 15.11.
This is problem 15.11 in the book Elements of Programming Interviews.
Problem: Given two strings A and B, compute the Levenshtein distance
between them.
... |
e5acad8c71f294b05dcb8af16375c49f0a3f1265 | CodingDojoOnline-Nov2016/CandraDavis | /Python/basic_python/sumList.py | 726 | 4.34375 | 4 | # Create a program that prints the sum of all the values in the list:
a = [1, 2, 5, 10, 255, 3]
sum(i in i for a)
# this works because the sum function adds the numbers progressively as the for loop travels through the list.
#
# def sumList(list):
# for i in range(6, 0, -1):
# add1 = a[len(a)-1]
# ... |
d26c16c4ef2153c79bf9e0f39b3edf75a6571bca | sotheaYouk/bootCamp | /youksakmonysothea17/week01/ex/20_decode.py | 605 | 4.21875 | 4 | message = input("Enter your encrypted message: ")
message_temp = ""
if message == "":
print("Nothing to decode.")
else:
for char_temp in message:
# check special symbols and numbers
if not (65 <= ord(char_temp) <= 90 or 97 <= ord(char_temp) <= 122):
message_temp += char_temp
... |
67382e437393cdf104681c9e528d66b23d521486 | suraj184/LetsUpgrade-python-essentials | /Day 4/substring occurence.py | 332 | 4.0625 | 4 | str1 = ("what we think we became; we are python programmer")
print("*Given string is --- 'what we think we became; we are python programmer'")
b=input("Enter letter to check occurence ")
a=-1
c=[]
for each in str1:
a=a+1
if str1.index(each)==str1.index(b):
c.append(a)
print("indices of occurence of ", b... |
e4aaf9a6a79b35a498487b07fdbc48d7051c94c9 | mpyrek/ASD | /lab 6/Huffmans_code_2.py | 1,691 | 3.578125 | 4 | from queue import PriorityQueue
S = ["a", "b", "c" ,"d", "e", "f" ]
F = [10 , 11 , 7 , 13, 1 , 20 ]
T=[0]*len(S)
suma=0
class Tree:
def __init__(self,prob,char,idx=None):
self.prob=prob
self.char=char
self.code=None
self.right=None
self.left=None
self.idx=idx
def __gt_... |
1751f9de488bd1f61808badc82bced4cd25ecdcf | zenvisuals/DesignPatterns | /ObserverPattern.py | 3,579 | 4.0625 | 4 | """
Observer Pattern - Defines a one-to-many relationships where there is a Subject
and many Observers. Like the name suggests, the Observers observe the Subject,
receive notifications from the Subject when something has changed. This concept
is similar to Followers and Following in Twitter.
Example - I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.