blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bde1a653d76316d23b9a8fdc8f85f082159136ee | Meshugah/EPI | /src/C0/_81_.py | 870 | 3.828125 | 4 | # stacks and queues baybeee
# queues are fifo
# stack are first in last out like pancakes
import collections
def print_linked_list_in_reverse(head):
nodes = []
while head:
nodes.append(head.data)
head = head.next
while nodes:
print(nodes.pop())
# implement a stack with max API
cl... |
8ac81494f4e68f6ccc9d08180c475bd9c5c8c00c | earl-grey-cucumber/Algorithm | /99-Recover-Binary-Search-Tree/solution.py | 777 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
p, q, pre = None, None, None
def recoverTree(self, root):
global p, q, pre
p, q, pre = None, None, No... |
a48ef00d5671b7b09f1ac306800abbb07632730c | senorpatricio/python-exercizes | /exercise3.py | 990 | 4.1875 | 4 |
# exercise 3
def isFloat(string):
try:
float(string)
return True
except ValueError:
return False
def check():
mph = raw_input("Enter a speed in miles per hour: ")
if mph.isdigit() and mph is not "0":
return mph
elif isFloat(mph) and mph is not "0":
return mph
... |
ef3dba4c4c3c06bed77a06379821a8460f18620c | supriya1610190086/python_Logical_Question | /conversion time.py | 696 | 3.65625 | 4 | # def convert(str1):
# if str1[:-2] == "AM" and str1[:2]== "12":
# return str1[:-2]
# elif str1[:-2] == "PM" and str1[:2]=="24":
# return str1[:-2]
# else:
# return str(int(str1[:2]) + 12) + str1 [2:11]
# print(convert(input("")))
# def convert_time(s):
# list1=["01","02",... |
c8870163b3223a209937cd98f41126154701a1c8 | mnocenti/aoc20 | /day7.py | 43,236 | 3.625 | 4 | #/usr/bin/python
import itertools
def search_bag(outermost, target, seen):
for _,bag_type in input[outermost]:
if bag_type == target:
return True
if not bag_type in seen:
seen.add(bag_type)
found = search_bag(bag_type, target, seen)
if found:
... |
de3487e2ddca771954c49f2b6c27e9b9ba846275 | linbeta/Day-18_Hirst-painting | /color_extract.py | 325 | 3.578125 | 4 | # =====This part is using colorgram to extract colors from the image. ====#
import colorgram
colors = colorgram.extract("brighter_dots.jpg", 60)
color_list = []
for color in colors:
new_color = color.rgb
r = new_color[0]
g = new_color[1]
b = new_color[2]
color_list.append((r, g, b))
print(color_l... |
cbb6879b1460c1acaad976391148d545c1bfd69b | 425776024/Learn | /pyoop/3/2.py | 783 | 3.625 | 4 | class Fjs(object):
def __init__(self, name):
self.name = name
def hello(self):
print("said by : ", self.name)
def __getattr__(self, item):
print("访问了特性1:" + item)
return None
raise AttributeError
def __setattr__(self, key, value):
print("访问... |
ffaef098cafd8b66bfc98b8f647d8be0b7ee8c74 | ari10000krat/checkio | /Home/Between Markers.py | 1,898 | 3.625 | 4 | def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
start_index = 0 if text.rfind(begin) == -1 else text.find(begin) + len(begin) # End of the first sepatrator
end_index = len(text) if text.find(end) == -1 else text.find(end) # Begin... |
7759642ea2e197004bb0ce8585b3d654771f45ac | Vitoria0/Notepad | /Observações-05.py | 2,146 | 4.3125 | 4 | # Interactive Help
#Ele explica como funciona e os valores de determinada função
help(print)
print('\n')
#Outra maneira seria
print(input.__doc__)
print('\n')
###
#Docstrings
def contador(i, f, p):
"""
-> Faz uma contagem e mostra na tela
:param i: Inicio da contagem
:param f: Fim da contagem
:p... |
14e538c13f09a95da8ff8324f72396e423e11342 | Gameatron/python-things | /CS1/Conditionals/human_age_v2_robertst.py | 612 | 4.21875 | 4 | def human_age(age):
if age < 1:
term = 'baby'
if age < 3:
term = 'toddler'
elif age < 5:
term = 'preschooler'
elif age < 9:
term = 'child'
elif age < 13:
term = 'preteen'
elif age < 19:
term = 'teen'
elif age < 40:
term = ... |
7c9c1b02e24cd85fad64c3e55601d6cb1555a8fc | theusouza0/Python | /while.py | 698 | 4.15625 | 4 | #3. Crie um programa que solicite o código do produto e a quantidade, calcule e exiba o total do item, então solicite novamente código e quantidade até que o usuário digite 0 (zero). Então exiba o total da compra.
#Entrada
valor = 0
soma = 0
print("Mercado!")
#Processamento e saída
while True:
code = int... |
7a1ddf7761be3ca035dc1964de2c1a3ca8d3dd2c | kudoyoshihiro10xx/09_dict_practice | /fruits.py | 505 | 3.859375 | 4 | # 辞書を定義
fruits_dict= {"りんご":"Apple",
"ぶどう":"Grape",
"みかん":"Orange"}
# print(fruits["りんご"])
# print(fruits["ぶどう"])
# print(fruits["みかん"])
# Keyだけforループ
for jp_name in fruits_dict.keys():
print(jp_name)
# Valueだけforループ
for en_name in fruits_dict.values():
print(en_name)
# KeyとValue... |
7a3bdc49947b11dc4b79cb7367284e0fd6c428d4 | thanhtuan18/anthanhtuan-fundametal-c4e15 | /Session2/change_color.py | 359 | 3.546875 | 4 | # from turtle import *
#
# speed (0)
#
# color ("green")
# forward (100)
# color ("red")
# forward (100)
#
# mainloop ()
from turtle import *
speed (0)
width (5)
for i in range (3):
color ("red")
forward (20)
penup ()
forward (20)
pendown ()
color ("blue")
forward (20)
penup ()
fo... |
9c789ae02a7e203f95cd9219ceaaf91816083d10 | sethmnielsen/optimization-techniques | /lectures/prob.py | 1,485 | 3.53125 | 4 | """
The provided function takes in a vector x of length 3
and returns a scalar objective f to be minimized,
a vector of constraints c to be enforced as c <= 0,
a vector gf containing the gradients of f,
and a matrix gc containing the gradients of the constraints
\[gc[i, j] = partial c_i / partial x_j].
In... |
2656dd060642d9d95ab86a4c5f0ca63cb0bc0d16 | joswha/interviewpreparation | /coding-interview-university/DataStructures/Array/array.py | 1,921 | 4.125 | 4 | # Implement a vector (mutable array with automatic resizing):
# Practice coding using arrays and pointers, and pointer math to jump to an index instead of using indexing.
# New raw data array with allocated memory
# can allocate int array under the hood, just not use its features
# start with 16... |
ec5808be9b9cc327035a1baaa03319308fbccbd3 | AhmedRaja1/Python-Beginner-s-Starter-Kit | /Code only/4- Functions/Debugging.py | 147 | 3.90625 | 4 | def product(*numbers):
total = 1
for number in numbers:
total *= number
return total
result = product(1, 2, 3)
print(result)
|
6faad19f1a12ad65e79c213424e7604134ddd257 | mehulchopradev/bryan-python | /evennos.py | 308 | 3.78125 | 4 | n = int(input('Enter n : '))
i = 0
# while loop
'''while i <= n:
if not i % 2:
print(i)
i = i + 1'''
# for loop
'''
for v in <<sequence of elements>>:
I1
I2
I3
'''
# 0 to n
# range(0, n + 1)
'''for v in range(n+1):
if not v % 2:
print(v)'''
for v in range(0, n + 1, 2):
print(v) |
6156adfa7c2427998aa29d4a5cc83171c75f43a5 | ghostrider77/improve_coding_skills | /Python/algorithmic_toolbox/12_maximizing_revenue.py | 561 | 3.578125 | 4 | import sys
def convert_to_intlist(line):
return [int(elem) for elem in line.split()]
def calc_maximal_revenue(profit_per_click, average_click):
revenue = 0
for p, a in zip(sorted(profit_per_click), sorted(average_click)):
revenue += p * a
return revenue
def main():
data = sys.stdin.rea... |
64e2f03d28cf9cc7700a693a7509b0c726baf9e9 | J-AugustoManzano/livro_Python | /ExerciciosAprendizagem/Cap08/c08ex03.py | 626 | 3.984375 | 4 | a = []
s = 0
print("Somatório de valores informados")
# Entrada de dados
i = 0
resp = 'S';
while (resp.upper() == 'S'):
a.append(float(input("\nEntre o {0:3}o. valor: ".format(i + 1))))
s += a[i]
i += 1
print()
print("Deseja continuar? ")
resp = input("Tecle [S] para SIM / qua... |
c411105b1bc50f85ea3862065b8b70636d5823e3 | Kalia3/Scrapping-py | /assingment 13(b) (scraping data on web page).py | 979 | 3.703125 | 4 | ''' Scraping in (http://py4e-data.dr-chuck.net/comments_1003519.html) this
URL and find the sum of no. in this web page. '''
import urllib.request, urllib.parse, urllib.error #imported for getting on web(socket or connection)
from bs4 import BeautifulSoup #for reading html on web page
y = 0
url = input("Ente... |
56166119c4f1819612aab742eac338301422a34b | sethhardik/language-model-machine-learning | /code.py | 2,940 | 3.875 | 4 | import numpy as np
from keras.models import Sequential
from keras.layers import Dense,LSTM,Embedding
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
data = """ Jack and Jill went up the hill\n
To fetch a pail of water\n
Jack fell down and broke his crown\n
A... |
cc2a4a7fde59ac9f34faba40c40ac4bd08d5a71c | MD-AZMAL/python-programs-catalog | /Data-Structures/graphs/kruskal.py | 3,556 | 3.5 | 4 | """ Author - Sidharth Satapathy """
""" This code is in python 3 """
class Vertex(object):
def __init__(self,name):
self.name = name
self.node = None
class Node(object):
def __init__(self,height,nodeId,parentNode):
self.height = height
self.nodeId = nodeId
self.parentNo... |
1e503308a39bf605ae491406f4e66c67a562a5b8 | joseck12/blog | /tests/test_user.py | 701 | 3.578125 | 4 | import unittest
from app.models import User
from app import db
#the setup method creates an instances of our user
class UserModelTest(unittest.TestCase):
def setUp(self):
self.new_user = User(username = 'joseck',password = 'qwerty', email = 'jogachi4@gmail.com')
def save_user(self):
db.sessi... |
162b66a26d08323ad2b6d856e3c8bb1735d293a7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/schdan037/question4.py | 1,008 | 3.953125 | 4 | """Daniel Schwartz
question 4
april 2014"""
# used for math functions inout by user
import math
def main():
"""main,
receives input and prints out graph of function"""
f = input("Enter a function f(x):\n")
#nest for loop generates x, y values in ranges of graph
for y in range(-10, ... |
befc36c5dfef12a8840347ebe5d8aca666bdef55 | Jimmyopot/JimmyLeetcodeDev | /data_structures/binary_trees.py | 6,804 | 4 | 4 | '''
- Tree represents the nodes connected by edges.
- It is a non-linear data structure.
- It has the following properties.
# One node is marked as Root node.
# Every node other than the root is associated with one parent node.
# Each node can have an arbiatry number of chid node.
- Search for a value... |
2e5547151fa0f906a303a163257ebda103d5dddd | wttttt-wang/leetcode_withTopics | /Backtracking/gray-code*.py | 529 | 3.671875 | 4 | """
Gray Code
@ Backtracking: Get results[n = 3] from results[n = 2] : [00, 01, 11, 10] --> [000, 001, 011, 010, 110, 111, 101, 100]
@ Also see: 'math/gray-code'
"""
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n < 0:
... |
7ba3d15de5c18eb40f5772c186962e9bb7ffca4c | Shandris1/QAC-work-Python | /Python/AddingClasses.py | 305 | 3.625 | 4 | class Replicate():
"""docstring for Replicate"""
def __init__(self, A=0, B=0, C=0):
self.a = A
self.b = B
self.c = C
def __add__(self, other):
print("2+2")
return self.a * other.a
china = Replicate(5)
japan = Replicate(7)
print(china + japan)
6 + 4
|
d89f58d25346278cf9d153f29a82bae8b6c2e39a | ThiagoCComelli/URI-Online-Judge | /URI-py/1154.py | 176 | 3.515625 | 4 | # -*- coding: utf-8 -*-
qtde = 0
soma = 0
while True:
n = int(input())
if n >= 0:
soma += n
qtde += 1
else:
break
print("%.2f"%(soma/qtde))
|
4bcc1ededfc4a0f4221fb8bea994cc418fb5ae65 | HarunErenMutlu/reflexiveTransitiveClosureAlgorithm | /reflexiveTransitiveClosureAlgorithm.py | 3,717 | 3.609375 | 4 | import itertools
def createSet(sampleSet):
newSet = set()
for i in sampleSet:
newSet.add(i)
return newSet
def make_it_reflexive(alphabet,relation):
newSet = createSet(relation)
for i in alphabet:
newSet.add((i,i))
return newSet
def findAllTuplesOfIndex(index, alphabet)... |
5506ac587b3f24393a0a2f35164aa152ea2336e4 | Nagajothikp/Nagajothi | /s31.py | 210 | 3.65625 | 4 | x=input("Enter a braces:")
count1=0
count2=0
for i in x:
if i =='(':
count1=count1 +1
else:
count2=count2 +1
if(count1==count2):
print("yes")
else:
print("no")
|
67f4979670771b1e292848ea3894af32426132cb | golubitsky/exercism-solutions | /python/rna-transcription/rna_transcription.py | 306 | 3.5625 | 4 | def to_rna(dna_strand):
convert = {
'G':'C',
'C':'G',
'T':'A',
'A':'U'
}
if any(char not in convert for char in dna_strand):
raise ValueError(f"Can only convert {convert.keys()}")
return "".join(list(map(lambda char:convert[char], dna_strand))) |
3927c9ed10e0326144c6d41144159b7009f2eb96 | SamCadet/PythonScratchWork | /my_car.py | 371 | 3.96875 | 4 | ''' p. 175 The import statement at u tells Python to open the car module and
import the class Car. Now we can use the Car class as if it were defined in
this file. The output is the same as we saw earlier: '''
from car import Car
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_ca... |
3d7bc8eb1802fd5231730b89782f80047bcde73f | sergio-ruano27/201612203-Cortos980 | /Corto1/collatz.py | 273 | 3.953125 | 4 | #SERGIO ESTUARDO RUANO NAJARRO
#201612203
def collatz(num):
while(num != 1):
if(num %2> 0):
num = 3*num +1
yield num
else:
num = num/2
yield num
n=203
for i in range(2,n):
print(list(collatz(i)))
|
93c3aacf8a59fea767925f247a09490c75b58c2b | Jeffery-Zhou/URLeapMotion | /threadstu.py | 397 | 3.578125 | 4 | # -*- coding: UTF-8 -*-
import threading, time
def fun1():
while True:
time.sleep(2)
print("fun1")
def fun2():
while True:
time.sleep(6)
print("fun2")
threads = []
threads.append(threading.Thread(target=fun1))
threads.append(threading.Thread(target=fun2))
print(threads)
if __n... |
37221df1c2b2d185b0cffc2ad58baaf8f80ec45d | sarthak77/practice | /word/line_and_page_break.py | 569 | 3.65625 | 4 | """
To add a line break (rather than starting a whole new paragraph), you
can call the add_break() method on the Run object you want to have
the break appear after. If you want to add a page break instead, you
need to pass the value docx.text.WD_BREAK.PAGE as a lone argument to
add_break(), as is done in the middle of ... |
8dcbf055ce4dc5e5561df8075c16c2f7e8c337aa | patpalmerston/Data-Structures | /binary_search_tree/binary_search_tree.py | 10,142 | 3.921875 | 4 | import sys
sys.path.append('../doubly_linked_list')
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this node could already
have ... |
db22219e3bb6c829bf741eb3652e823d37572718 | sanghunjlee/bisection-method-calculator | /itercalc.py | 2,913 | 4 | 4 | """This module contains iteration method(s) that is used to find the zero.
BisectionMethod will calculate the zero by using the bisection method -- the next subdivision is found using an average of the previous subdivision's endpoints.
"""
import logging
from random import uniform
from mathform import MathFormula
MA... |
024724213be0c5faa732e02090b3e66576af302b | shadowfelldown/AdventureGame | /Player.py | 2,724 | 4 | 4 | import random
import map
__author__ = 'Daniel'
def options(choices):
while True:
try:
userchoice = str(raw_input('What do you do? '))
if 'stuck' in userchoice.lower():
return 'STUCK'
if 'hint' in userchoice.lower():
return 'HINT'
... |
1d91f3d249f2902cf47953bb1f59ae3ede5026aa | hashtagallison/Python | /Practice_STP/Challenge_Questions/Ch8 - Challenges/Ch8_Challenge1.py | 951 | 3.765625 | 4 | # https://www.theselftaughtprogrammer.io
# Cory Althoff - The Self-taught Programmer
# Chapter 8 pg 121 - Challenges
# hashtagallison - Practice 2019-04-11
#-------------------------------------------
#-------------------------------------------
# CHAPTER 8: CHALLENGES
# - Official Answer Key: http... |
e131178d3481ed8a542fe91d1cda9edf52082f39 | iamparkerm/pythonRPG | /main.py | 4,169 | 3.671875 | 4 | # updated for python3
import sys
import time
from scripts.classes import *
p = Player()
#Main() is the first function the game runs
def main():
intro()
# Loop that begins game
while p.knowledge < 16:
line = input("What would you like to do? > ")
args = line.split()
if len(args) > 0:... |
92858ce1ba67fcf35d235e22637099c1180fbf39 | 17390089054/Python | /matplotlib/scatter_squares.py | 506 | 3.5 | 4 | import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,
edgecolor='none',s=40)
#设置图表标题并加上标签
plt.title("Square Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of Values",fontsize=14)... |
72f2ad8a38748b9c6626aff8db7c992e24f78169 | qmaurmann/pytris | /tetris.py | 12,650 | 3.59375 | 4 | """This is the main file for the Pytris project. The three concrete classes
defined herein are
Board: generally controls the flow of the game, e.g. interacting with the
classes defined in tetris_pieces.py to determine whether and how pieces
get moved around the board. Also responsible for displaying the state ... |
5877578ec81d77cb87ef32daba202c016a2f31d6 | IngridFCosta/Exercicios-de-Python-Curso-em-video | /condicoesAninhadas/ex036_emprestimoBank.py | 786 | 4.09375 | 4 | """"036- Escreva um programa para aprovar o emprestimo bancario
para a compra de uma casa. O programa vai perguntar o valor da casa,
o sálario do comprador e em quantos anos ele vai pagar.
-Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário
ou então o empréstimo será negado.
"""
valorC... |
4d8409fd75964b3a6e18956f9e1a2704c27b7d2f | taeheechoi/data-structure-algorithms-python | /20-80-questions/BST.py | 1,356 | 4.3125 | 4 | #https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-binary-search-tree-exercise-3.php
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_BST(root):
stack = []
prev = None
while root or stack:
... |
77d8a09fceccdb9ac3bf9ed74816b8a5eeceee92 | hernandez232/FP_Laboratorio_06_00075919 | /Ejercicio2.py | 137 | 4.03125 | 4 | n = int (input ("Inserte un numero: "))
for f in range (1, n+1):
for c in range (1, f+1):
print (f, end=" ")
print (" ") |
8b26a2111a223859a2fed703c3ef8b8bda57e5e1 | Xitram/Batter-Up | /ExcelFinal/BudgetOrganizer.py | 6,915 | 3.671875 | 4 | import openpyxl #the needed imports for this script
from sys import argv
script, filename = argv #sets the script name and filename as necessary args to run
#IMPROVEMENT: set the filename as a rawinput to pass
data = open(filename, "r") #gives a variable for the opened file
everything... |
915966359141544979197250f4ae1155616ad58d | ZhouPao/work | /RedisQueue.py | 1,677 | 3.546875 | 4 | import redis
class RedisQueue(object):
"""
Simple Queue with Redis Backend
"""
def __init__(self, name, namespace='queue', **redis_kwargs):
"""
The default connection parameters are: host='localhost', port=6379, db=0
"""
self.__db= redis.Redis(**redis_kwargs)
sel... |
f02610dfd0a58c6e1cd27d270a4461164a073575 | maxmyth01/unit5 | /longestWord.py | 393 | 4.0625 | 4 | #Max Low
#11-13-17
#middleWord.py -- finds middle if even print both
words = input('Enter some words: ').split()
lettercount=0
maxletters = 0
maxword=0
for w in words:
for ch in w:
lettercount += 1
if lettercount > maxletters:
maxletters = lettercount
maxword = w
lettercoun... |
54ee354b7d8839dcf03f09606db554bd650fc6fd | tchia007/Simplilearn | /Deep_Learning/tensorFlowTutorial_p2.py | 3,956 | 3.984375 | 4 | '''
This code has been copied from the simplilearn tensorflow tutorial
https://www.youtube.com/watch?v=E8n_k6HNAgs&index=24&list=PLEiEAq2VkUULYYgj13YHUWmRePqiu8Ddy
'''
#--------------1. Read the census_data.csv using pandas library
import pandas as pandas
census = pd.read_csv("census_data.csv")
#--------------2. D... |
7d57f1a59084ebe2edba2c5ca3d0e46cc1a64087 | mjgrace/python-mit-open-courseware | /PythonHW1/src/rps.py | 721 | 4 | 4 | player1 = raw_input("Enter player 1 selection: ")
if (player1 != "rock" and player1 != "paper" and player1 != "scissors"):
print "Invalid selection"
player2 = raw_input("Enter player 2 selection: ")
if (player2 != "rock" and player2 != "paper" and player2 != "scissors"):
print "Invalid selection"
if ((playe... |
68cbc4dab7374c03abbfacdb8e30d1ae87e5b084 | fatecoder/Python-practices | /battleship.py | 1,490 | 3.703125 | 4 | #!/bin/python
import random
tablero = []
vista = []
tam = random.randrange(2, 6)
def gene_tablero():
for i in range(tam):
tablero.append([])
for j in range(tam):
tablero[i].append("O")
#ship
tablero[random.randrange(0,tam)][random.randrange(0,tam)] = "S"
def test_view_tablero... |
a84226a010f0b63854b0e0e3f6c4c2f194724e02 | maxianren/algorithm_python | /recusion_base_conversion.py | 1,782 | 3.96875 | 4 | '''
Base conversion
Given a number in base M, please convert it to base N
Input format:
Two lines, the first line has two digits, which are M and N in decimal notation, separated by spaces; where M and N satisfy 2 ≤ M and N ≤ 36
The second line has the number to be converted, the part of each digits exceeding 9 is rep... |
99aa19fc583a9d79de276c6266b1918a33e36eeb | bivanalhar/rec_problem | /separate_file.py | 2,661 | 3.53125 | 4 | """
This file is intended to split the csv file of the QFactory Statistics
into several csv files, each is unique based on semester identity
"""
import csv
appended_row_h1s1 = []
appended_row_h1s2 = []
appended_row_hcal = []
appended_row_hsta = []
appended_row_hsu1 = []
appended_row_hsu2 = []
appended_row_m1s1 = []
... |
8a67db12307a1bc931d3fbbffbb699885b5f3928 | Jav10/Python | /C-digosPython/estructurasControl.py | 1,300 | 4.3125 | 4 | #Estructuras de Control
#Autor: Javier Arturo Hernández Sosa
#Fecha: 1/Sep/2017
#Descripcion: Curso Python FES Acatlán
#sentencia IF,ELSE y ELIF
edad = 10
if(edad<18):
print("Eres un niño todavía")
elif(edad>=18 and edad<40):
print("Eres un adulto")
elif(edad>=40 and edad<70):
print("Ya estas viejo")
e... |
a63b118187b8131a385603eca1551f98b5a74009 | rafaelperazzo/programacao-web | /moodledata/vpl_data/13/usersdata/109/4753/submittedfiles/flipper.py | 300 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CÓDIGO AQUI
P=input('Digite a posição de P:')
R=input('Digite a posição de R:')
if P==1 and R==0:
print('B')
if P==1 and R==1:
print('A')
if P==0 and R==0:
print('C')
if P==0 and R==1:
print('c')
|
068239d4e6776599bad54ccf91d05e18b9952b02 | jpaulopd/IFB | /202001/lp2/codigos/adivinhacaoPart.py | 1,516 | 3.96875 | 4 | print("*********************************")
print("Bem vindo ao jogo de adivinhação!")
print("*********************************")
#numero_secreto = random.randrange(1, 101) # 0.0 1.0
#pontos = 1000
#print("Qual o nível de dificuldade?")
#print("(1) Fácil ")
#print("(2) Médio ")
#print("(3) Difícil ")
#nivel = int(in... |
d4617ea452a253fc454b2b7781e032df1bc67f79 | jlassi1/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 400 | 4.25 | 4 | #!/usr/bin/python3
"""module"""
def write_file(filename="", text=""):
"""function that writes a string to a text file (UTF8)
and returns the number of characters written"""
with open(filename, mode="w", encoding="UTF8") as myfile:
myfile.write(text)
num_char = 0
for word in text:
... |
fbe4f078636bed0a0070a3e192a279a8cce776e4 | manelbonilla/hackerrank | /Artificial_Intelligence/Tic tac toe Random.py | 665 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
from random import shuffle
import re
import sys
def print_board(board):
for r in board:
for c in r:
print(c, end='')
print("")
def nextMove(player, board):
available = []
for i1 in range(3):
for i2 in range(3):
cell = board[i1][i2]
if cell != 'X' ... |
8289efd5c2efb55c9b4a2a627d79d3536fa7ce16 | Abbath90/python_epam | /homework9/task1/merge_sorted.py | 570 | 4 | 4 | """
Write a function that merges integer from sorted files and returns an iterator
file1.txt:
1
3
5
file2.txt:
2
4
6
#>>> list(merge_sorted_files(["file1.txt", "file2.txt"]))
[1, 2, 3, 4, 5, 6]
"""
from pathlib import Path
from typing import Iterator, List, Union
def merge_sorted_files(file_list: List[Union[Path, str... |
c87262ffcb67a750c9fd4870568d268cbb9349f8 | baxievski/exercism | /python/matching-brackets/matching_brackets.py | 642 | 3.890625 | 4 | import re
def is_paired(input_string):
cleaned_string = re.sub(r"[^\[\]\(\)\{\}]", "", input_string)
stack = []
opening_braces = "({["
closing_braces = ")}]"
for current_brace in cleaned_string:
if current_brace in opening_braces:
stack.append(current_brace)
continu... |
34215b22a77ca423d121f8cc710eefad327f0c21 | hexinyu1900/PythonPractice | /GuessNumber.py | 472 | 3.84375 | 4 | import random
guess = []
answer = []
number = 0
for i in range(3):
A = random.randint(1, 3)
B = random.randint(1, 3)
guess.append(A)
answer.append(B)
if A == B:
number += 1
continue
print("guess =", guess, ", answer =", answer)
print(number)
if number == 0:
print("小A一次都没猜对")
eli... |
0a26588eea2ed870164149d8a22106961e2a02a8 | BettyAtt/myWork | /week07/lecture/followAlong.py | 759 | 4.25 | 4 | # This program is to demonstrate files
# follow along to the lecture
# Author Betty Attwood
# Credit Andrew Beatty's code
with open(".\lecture1.txt", "w") as f:
print ("create a file")
# mode r won't work, as won't r+
# 'a' append mode will work,
# x wont work as file exists
with open("textData.txt",... |
df1aa8e782cecb338e5467912ebb965d8b9de8ab | patkub/userscripts | /scripts/zoom.us logger/chatlogger.sh | 1,007 | 3.8125 | 4 | #!/usr/bin/env python3
import argparse, json, textwrap
# python chatlogger.py chat.json
# python chatlogger.py chat.json --output chat.txt
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
Usage Examples:
Display chat from file:
... |
b8ad68ca372a4e45e09306f0d869fa420bacf25a | ajrinanw/Python-Projects-Protek | /Chapter 05/Praktikum 2/Latihan 05.py | 601 | 3.78125 | 4 | #CHAP.05 PRAK.02 LATIHAN 05
from random import randint
bil = randint(0,100)
print("Hi.. Nama saya Mr.Lappie, saya telah memilih sebuah bilangan bulat secara acak antara 1 sampai dengan 100. Silahkan tebak ya..!!")
tebakan = int(input("Tebakan Kamu :"))
while True:
if (tebakan > bil):
print ("Yahhh teba... |
662023d77d0b173a8f99386279032b958513237d | RockutSaben/Codechef_Solutions | /DSA_Learning_Series/Easy_Problems_to_Get_Started/1__Buy_Please.py | 1,353 | 3.703125 | 4 | #Question
'''Chef went to a shop and buys 'a' pens and 'b' pencils. Each pen costs 'x' units and
each pencil costs 'y' units. Now find what is the total amount Chef will spend to buy
'a' pens and 'b' pencils.
INPUT:
First-line will contain 4 space separated integers a, b, x and y respectively.
Output:
Print the answ... |
7c8f97151a1212f568fb6a30217ea69617d3da4b | xiaoyueli/MOOC | /DatastructureAndAlgorithm/DataStructure-ZhejiangU(20160229-20160603)/week9_InsertionOrHeapSort.py | 2,293 | 3.796875 | 4 | def check(lst1, lst2):
for idx in range(len(lst1)):
if lst1[idx] != lst2[idx]:
return False
return True
def printOut(lst):
result = ""
for idx in range(len(lst)):
result += str(lst[idx])
if idx != len(lst) - 1:
result += " "
print(result)
def insert... |
3f2b5572d68041e137d22ccc8e09a8ea68917915 | jenamico/Markov-Chains | /markov.py | 1,485 | 3.859375 | 4 | #!/usr/bin/env python
from sys import argv
def make_chains(corpus):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
markov_dictionary = {}
filename = open(corpus, 'r')
read_file = filename.read()
words = read_file.split()
for word_index in range(0, len(word... |
870e997d7d5f2c2309bf873381c1af7274101019 | amalmhn/PythonDjangoProjects | /flow_controls/looping_statements/for_loop/nested_forloop2.py | 156 | 3.546875 | 4 | # *
# **
# ***
# ****
#4 coloumn and row
for row in range(1,5): #row=1
for coloumn in range(0,row): #col(0,2)
print("*", end=" ")
print()
|
707ae372b77d660e8ff670ac5c3339e9f5bf6ea9 | chunche95/ProgramacionModernaPython | /IntroductionToPythonAndProgrammingBasic-Cisco-master/contents/programs/3.1.6.6Operators on lists-in and not in.py | 91 | 3.65625 | 4 | myList = [0, 3, 12, 8, 2]
print(5 in myList)
print(5 not in myList)
print(12 in myList) |
4d417102aa34855ad57372c209adee03a905569b | NikoTaga/Python-algorithms-and-data-structures | /lesson_3/task_3.py | 746 | 4.21875 | 4 | '''
В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
разбор не смотрел
'''
import random
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
min_elem = MAX_ITEM
min_index = 0
max_elem = 0
max_index = 0
for i, item... |
712eabb773bb1a1b997b1f745110570bf8ea7d95 | thuspatrick/PYTHON-EXERCICES | /exercices/morefizzbuzz.py | 933 | 3.96875 | 4 | # Nettoyer la console avant le demarrage du programme #
import os
os.system('clear')
#######################################################
##################
# counting FIZZBUZZ #
#################
num = 1
fizzes = 0
buzzes = 0
fizzbuzzes = 0
fizval = []
buzval = []
fizbuzval = []
while num <= 1000:
if ((num % 3)... |
7a5d27ee02dfe26b5477bab87e21ae06a63f4639 | ajoyoommen/aichallenge-ants | /bots/MyBot.py | 5,263 | 3.78125 | 4 | #!/usr/bin/env python
# define a class with a do_turn method
# the Ants.run method will parse and update bot input
# it will also run the do_turn method for us
import random
from ants import Ants
class MyBot:
def __init__(self):
obstacles = []
def distance(self, ants, loc1, loc2):
'calculat... |
07e1aea139b7ce45146ecfd7306e16fa1ced6060 | macmiles/tic-tac-toe-player-vs-ai | /app.py | 9,967 | 4.125 | 4 | # PYTHON BASED TIC-TAC-TOE GAME WITH A WORKING AI
# AUTHOR: SELIM CAM
# DATE: 09.22.2017
# X | O | X
# --- --- ---
# O | X | O
# --- --- ---
# X | O | X
import random
# set value to 1 to better understand how the AI algorithm makes decisions
debug_mode = 0
# default user symbols
player = "X"
ai = 'O'
# default ... |
ac9e021f5b559422c8e5e412b0063f5374ccf08d | niketanrane/CodingDecoding | /Codeforces/141A.py | 222 | 3.5 | 4 | if __name__ == "__main__":
guest = input()
host = input()
total = sorted(input())
guest += host
guest = sorted(guest)
if guest == total:
print("YES")
else:
print("NO") |
5992e0e3fa55a4124524315a6b1e93b7773a7b4d | snguy3nn/data_structures | /linkedlist.py | 556 | 3.828125 | 4 | from node import Node
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_node(self, data):
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
return
else:
self.tail.... |
970ebbabab0ea06d80bf04fc99704fad50a0f351 | samprasgit/leetcodebook | /python/34_FindFirstandLastPositionofElementinSortedArray.py | 910 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/28 4:54 PM
# @Author : huxiaoman
# @File : 34_FindFirstandLastPositionofElementinSortedArray.py
# @Package : LeetCode
# @E-mail : charlotte77_hu@sina.com
class Solution:
def searchRange(self, nums, target):
left_idx = self.extreme_ins... |
8e70258ed9e546cd440c0b0cfbbfdd440cb7f845 | catoostrophe/MP1---Morpion | /Morpion vs AI.py | 4,687 | 3.75 | 4 | import random,time
#Liste des valeurs_tableau possibles du robot
liste_robot=[]
#Liste des valeurs du tableau:
valeurs_tableau = []
#Les listes prennent les valeurs de 0 à 8 (qui représentent alors les cases du tableau et les valeurs_tableau possibles du robot et du joueur).
for x in range (0, 9):
valeurs_tabl... |
ef63eab8f64d95054655dfe9ec440289d28dc67b | nhenninger/CrackingTheCodingInterview6e | /ch04_Trees_and_Graphs/q04_09_bst_sequences.py | 1,443 | 3.609375 | 4 | from nodes import BinaryTreeNode as BTNode
# 4.9 BST Sequences
def bst_sequences(root: BTNode) -> list:
"""
Prints all possible arrays that could produce the given binary search tree
Assumes tree contains distinct elements.
Not thread safe.
Runtime: O(2^n)
Memory: O(2^n)
"""
arrays... |
3cfe0d970c94d4db59887493089401ca1686a8f9 | SRchary/Python | /PYTHON_BASICS/text_to_speech.py | 760 | 3.578125 | 4 | import pyttsx
engine = pyttsx.init()
engine.say('HELLO ammulu')
engine.setProperty('rate', 100)
engine.say('Python supports a concept called "list comprehensions". It can be used to construct lists in a very natural, easy way, like a mathematician is used to do.The following are common ways to describe lists (or sets,... |
8e72fb71eeaec9570b6721e89afeb3c783af2aac | GiovanniCassani/discriminative_learning | /nonwords/neighbors.py | 6,763 | 3.515625 | 4 | __author__ = 'GCassani'
import helpers as help
from collections import defaultdict, Counter
def map_neighbours_to_pos(neighbours_file, wordform2pos, ids2words):
"""
:param neighbours_file: the file with the neighbours retrieved for each test item: each item is on a different
colu... |
8657eaabfec2e73566deb7cff77349ae0912b4b5 | boopalanjayaraman/DataStructures_Algorithms | /Big O Analysis - Project 01/Task1.py | 910 | 4.0625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
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 1:
How many different telephone nu... |
10fc63f6608a45c2a6f4ad9341597205f9446d78 | thapaliya123/Python-Practise-Questions | /data_types/problem_26.py | 463 | 4.34375 | 4 | """
26. Write a Python program to insert a given string at the beginning of all items in
a list.
"""
def insert_string_to_list_at_begining(sample_list, insert_string):
string_to_list = [insert_string+str(item) for item in sample_list]
return string_to_list
sample_list = [1, 2, 3, 4]
insert_string = "emp"
print... |
fc6adbaa7407f22b77f62822854978ebc4943187 | thelmuth/cs-101-spring-2021 | /Class32/nyt_satellite_image_manip.py | 4,312 | 3.890625 | 4 | """
Replicates some of the work of this NYT article.
https://www.nytimes.com/interactive/2020/09/02/upshot/america-political-spectrum.html
In particular, we can take an image, sort its pixels by luminance, and make the
new image.
"""
from PIL import Image
import matplotlib.pyplot as plt
def main():
### This is a... |
aced0d712e9d6aeac84f1e7ea57f438d8cf67d20 | DivyamSingh18/Note_Taker | /main.py | 1,637 | 4.28125 | 4 | print("#################### Welcome to Note_Taker ####################")
print("\n To write a note, enter keyword 'write' ")
print(" To read a note, enter keyword 'read' ")
print(" To append to a note, enter keyword 'append' ")
cmd = input("\n\nWhat operation do you want t... |
b8b591909cf25d30d9f984b12b898ec1f54330f7 | mare-astrorum/leetcode-practice | /191009 Watering Plants.py | 3,743 | 3.75 | 4 | """
https://leetcode.com/discuss/interview-question/394347/google-oa-2019-watering-flowers-20
"""
plants = [2, 4, 1, 5, 6, 100]
capacity1 = 5
capacity2 = 7
watering_plants(plants, capacity1, capacity2)
sum(plants)
def watering_plants(plants, capacity1, capacity2):
import copy
... |
ce8a6daa9183bd168f5e29fa3ffadb43c54c2ea3 | Franklin-Wu/project-euler | /p002.py | 630 | 3.96875 | 4 | # Even Fibonacci numbers
#
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the su... |
d3c049b91302779f6b13530c6b7ddd53d605ea0a | V2xray1024/pyHack | /replaceTools.py | 682 | 3.515625 | 4 | '''
Description: 命令格式如 python script.py old_str new_str filename
对指定文件内容进行全局替换,并且替换完后打印替换了多少处内容
Author: yrwang
Date: 2021-09-01 18:03:12
LastEditTime: 2021-09-02 21:39:50
LastEditors: yrwang
'''
import sys
# print(sys.argv)
old_str = sys.argv[1]
new_str = sys.argv[2]
filename = sys.argv[3]
# 1 读取文件
f = ... |
ff7488264a00c95c79d309a7e98b0ec2e203e848 | Himanshu091190/IIT_Madras_Python | /yuio.py | 429 | 3.921875 | 4 | ##try:
## print(x)
##except TypeError:
## print("Variable x is not defined")
##except NameError:
## print("Variable x)( is not defined")
##except:
## print("Something else went wrong")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
print(x)
e... |
515b3270c9d23082486d984a889b5988f9e39ad0 | wherby/hackerrank | /Algorithms/Oracle/test3.py | 632 | 3.703125 | 4 | #// array, 'a', 'b', 'c'
#// unsorted
#// input -> ['b', 'a', 'b', 'a', 'c', 'a']
#// output ->
def sortls(ls):
pa,pb,pc = 0,0,0
n =len(ls)
for i in range(n):
t= ls[i]
if t == 'a':
pa = pa +1
if t =='b':
pb = pb +1
if t == 'c':
pc = pc +1... |
36ac13bf8bcc2809615491f0f4dd20ae2afd64cc | lee7py/Python-Programming | /Ch03/3-4-2.py | 246 | 3.953125 | 4 | ## Display population from 2014 to 2018.
pop = 300000
print("{0:10} {1}".format("Year", "Population"))
for year in range(2014, 2019):
print("{0:<10d} {1:,d}".format(year, round(pop)))
pop += 0.03 * pop # Increase pop by 3 percent.
|
ab8ac5509b5c801486646cd92a12d021d15d7b52 | xexugarcia95/LearningPython | /CodigoJesus/ProgramacionFuncional/Ejercicio5.py | 299 | 3.859375 | 4 | """Escribir una función que reciba una frase y devuelva un diccionario
con las palabras que contiene y su longitud."""
def apply_func(frase):
lista = frase.split(' ')
diccionario = map(len, lista)
return dict(zip(lista, diccionario))
print(apply_func("hola amigo que tal estas"))
|
c340913ece85820276dcc52273cb0dee7fa46455 | stepus3000/sphinx-msiit | /Sphinx-Project/code_sources/Holmes/doyl.py | 789 | 3.90625 | 4 | import random
error = ["Я не понимаю, введи цифрой.", "Не смешно, давай нормально.", "Очень смешно", "Так трудно ввести пару цифр?", "Неправильный ответ, давай еще раз."]
while True:
year = input("Сколько тебе лет? ")
try:
answer = int(year)
if 0 <= answer <= 140:
print("Крутяк!")
... |
9219fec726d71c657c0f6203e38fcf3c1902bc67 | Adarsh0047/Object-Oritented-Programming | /Oops/user_defined_exception.py | 106 | 3.765625 | 4 | y=input("Please enter a positive number: \n")
if int(y) <=0:
raise ValueError("Negative Number")
|
b29bf1f2be9f8dbe6a928826b3a42ae858bcaab3 | Brandilyar/PythonOzon | /Banch/Banch.py | 574 | 3.921875 | 4 | count = 0
def degree_recursion(degree,result_list=[]):
global count
count = count + 1
number = 5
if degree == 0 or degree == 1:
return 1
else:
result = number * degree_recursion(degree-1,result_list)
result_list.append(result)
'''if degree == count:
return... |
69b54fde762b51332aa992ba6e969c5d7038c2a0 | junedsaleh/Python-Programs | /Programs/BinarySearch.py | 326 | 3.59375 | 4 | lst = [6,8,9,23,45,56]
lst.sort()
high = len(lst)-1
low = 0
flag = 0
print(high)
print(low)
n = input("Enter Number")
n = int(n)
while(low <= high):
mid = (low + high)/2
if(mid == n)
flag = 0
elif(lst[mid]>n):
flag = 0
else
flag=0
if(flag==1):
print("Value not Found... |
9bc94edfebbfadfb5d90bf3e7dc119967dc27943 | krishna-rawat-hp/PythonProgramming | /codes/stringformat.py | 717 | 4.5 | 4 | # String format method in python
# Example-1 format with {}
str1 = "java"
str2 = "python"
str = "{} and {} are good languages".format(str1,str2)
print(str)
# Example-2 format with {index}
strin = "{1} is easy compare to {0}.".format(str1,str2)
print(strin)
# Example-3 format with number system
val = 10
print("Decima... |
b0cf52ca9cd3c12f84813012e8cc0d6dbbed9c4a | iSkylake/Algorithms | /Tree/KthLargeBST.py | 1,975 | 3.828125 | 4 | # Create a function that returns the Kth largest value in a Binary Search Tree
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
self.size = 0
# def insert(self, val):
# new_node = Node(val)
# if self.size < 1:
# ... |
cd11542b28904b0865526267ec5db987183b714d | Yu4n/Algorithms | /CLRS/bubblesort.py | 647 | 4.25 | 4 | # In bubble sort algorithm, after each iteration of the loop
# largest element of the array is always placed at right most position.
# Therefore, the loop invariant condition is that at the end of i iteration
# right most i elements are sorted and in place.
def bubbleSort(ls):
for i in range(len(ls) - 1):
... |
020faa764f096d361c801b962c965525db19182c | sol0703/programacion-1 | /examenes/quiz3.py | 4,171 | 3.765625 | 4 | # Trabajamos Miguel Zuleta
# punto 1
# a
print('Punto a')
class ElementosDigitales ():
def __init__ (self, nombre, creador, fechadepublicacion):
self.nombre = nombre
self.creador = creador
self.fechadepublicacion = fechadepublicacion
def mostrarAtributos (self,):
print (f''' Los ... |
a9b65d20a521f9e16a9e65e2745f663217cab1e7 | gktgaurav/python-coding-basics | /pract.py | 416 | 3.96875 | 4 | # # # print('gfgfgffhgfhgfhg')
# # x=[2,4,6,8,10]
# # x1=[]
# # for i in x:
# # x1.append(i*2)
# # print(x)
# # print(x1)
# odd_list=[1,3,5,7,9]
# unordered_list={11,12,13,14,15,16,17,18,19,20}
# for n in unordered_list:
# if not n%2==0:
# odd_list.append(n)
# print(odd_list)
my_list = [34, 82.6, "Dar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.