blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7deb2d43fbf45c07b5e2186c320e77bdad927c18 | iAmAdamReid/Algorithms | /recipe_batches/recipe_batches.py | 1,487 | 4.125 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients, count=0):
# we need to globally track how many batches we've made, and pass recursively
# TODO: find how to do this w/o global variables
global batches
batches = count
can_cook = []
# if we do not have any necessary ingredient, return ... | true |
32cd09efb118604e0d5c2e521046e64e8ad1c33f | solcra/pythonEstudio | /cadenas.py | 524 | 4.15625 | 4 | texto = "Prueba dos dos"
print("Upper")
print(texto.upper())
print("Lower")
print(texto.lower())
print("Capitalize")
print(texto.capitalize())
print("Count")
#print(texto.count())
print("Fing")
#print(texto.fing())
print("Isdigit")
print(texto.isdigit())
print("Isalnum")
print(texto.isalnum ())
print("Isalpha")
print(t... | false |
9d6c5130c61b682b0de8397aee721303d56f4685 | noahhenry/python_for_beginners | /notes/built-in_module_random.py | 322 | 4.15625 | 4 | import random
for i in range(3):
print(random.random())
# what if you want to limit the range of random numbers returned?
# use random.randint() and pass in the range...
for i in range(3):
print(random.randint(10, 20))
members = ["John", "Marry", "Bob", "Mosh", "Noah"]
leader = random.choice(members)
print(leade... | false |
1f0d340225be278ee074362f280207a60be9ed63 | Ardra/Python-Practice-Solutions | /chapter3/pbm11.py | 332 | 4.125 | 4 | '''Problem 11: Write a python program zip.py to create a zip file. The program should take name of zip file as first argument and files to add as rest of the arguments.'''
import sys
import zipfile
directory = sys.argv[1]
z = zipfile.zipfile(directory,'w')
length = len(sys.argv)
for i in range(2,length):
z.write(s... | true |
09c3839dbbe5c8cfc50eff2e5bd07fa5851695c0 | Ardra/Python-Practice-Solutions | /chapter6/pbm1.py | 203 | 4.21875 | 4 | '''Problem 1: Implement a function product to multiply 2 numbers recursively using + and - operators only.'''
def mul(x,y):
if y==0:
return 0
elif y>0:
return x+mul(x,y-1)
| true |
c19f67d6f4a5d2448fb4af73f1e3f12d3786bd1c | Ardra/Python-Practice-Solutions | /chapter3/pbm2.py | 742 | 4.21875 | 4 | '''Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.'''
def listfiles(dir_name):
import os
list = os.listdir(dir_name)
return list
d... | true |
29d5d901fc4ea681b9c2caa9f2dddf954174da4d | Ardra/Python-Practice-Solutions | /chapter2/pbm38.py | 399 | 4.15625 | 4 | '''Problem 38: Write a function invertdict to interchange keys and values in a dictionary. For simplicity, assume that all values are unique.
>>> invertdict({'x': 1, 'y': 2, 'z': 3})
{1: 'x', 2: 'y', 3: 'z'}'''
def invertdict(dictionary):
new_dict = {}
for key, value in a.items():
#print key, value
... | true |
874438d788e903d45edc24cc029f3265091130b1 | IDCE-MSGIS/sample-lab | /mycode_2.py | 572 | 4.25 | 4 | """
Name: Banana McClane
Date created: 24-Jan-2020
Version of Python: 3.4
This script is for randomly selecting restaurants! It takes a list as an input and randomly selects one item from the list, which is output in human readable form on-screen.
"""
import random # importing 'random' allows us to pick a random elemen... | true |
f8f811d817cea9bc27e663e2299a43e189e75a51 | camilobmoreira/Fatec | /1_Sem/Algoritmos/Lista_04_Capitulo_04_-_Entrega_ 23_03/406_calc_preco_viagem.py | 494 | 4.15625 | 4 | #4.6) Escreva um programa que pergunte a distância que um passageiro deseja percorrer em km. Calcule o preço da passagem, cobrando R$0,50 por km para viagens de até 200km e R$0,45 para viagens mais longas.
dist = -5
while(dist < 0):
dist = float(input("Informe a distância da viagem (km): "))
if(dist < 0):
print("I... | false |
605f7cc9bfe67751cb89fa883285f051aa33626f | PolinaVasilevichh/Udemy | /сomparison_operators1.py | 495 | 4.375 | 4 | """Создайте 2 переменных, содержащие числовые значения.
Сравните их при помощи всех операторов сравнения и выведите результат на экран
"""
first_value = 5
second_value = 8
print(first_value > second_value)
print(first_value < second_value)
print(first_value >= second_value)
print(first_value <= second_value)
print(fi... | false |
b59250f494354805444856c585f6ce7019405f21 | cristhoseby/RegularExpressions | /phone_number.py | 1,689 | 4.34375 | 4 | #phone number validtor
import re
pattern = """\(0 #open bracket followed by a zero
#then either:
(
1 #1
#followed by either:
(
\d{3} ... | false |
c5a84486c9e216b5507fb076f1c9c64257804232 | DaveG-P/Python | /BookCodes/DICTIONARIES.py | 2,745 | 4.59375 | 5 | # Chapter 6
# A simple dictionary
person = {'name': 'david', 'eyes': 'brown', 'age': 28}
print(person['name'])
print(person['eyes'])
# Accessing values in a dictionary
print(person['name'])
# If there is a number in value use str()
print(person['age'])
# Adding new key-valu pairs
person['dominate side'] = 'left'
pers... | true |
9773d6abe3781c5c2bc7c083a267a3b84bc30983 | proTao/leetcode | /21. Queue/622.py | 1,931 | 4.1875 | 4 | class MyCircularQueue:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
self.data = [None] * k
self.head = 0
self.tail = 0
self.capacity = k
self.size = 0
def enQueue(self, value... | true |
be7f5249e86caa685f932b2cbd962d11fb9596a5 | purusottam234/Python-Class | /Day 17/exercise.py | 722 | 4.125 | 4 | # Create a list called numbers containing 1 through 15, then perform
# the following tasks:
# a. Use the built in function filter with lambda to select only numbers even elements function.
# Create a new list containing the result
# b.Use the built in function map with a lambda to square the values of numbers' eleme... | true |
03b3e29c726f1422f5fa7f6ec200af74bad7b678 | purusottam234/Python-Class | /Day 17/generatorexperessions.py | 530 | 4.1875 | 4 | from typing import Iterable
# Generator Expression is similar to list comprehension but creates an Iterable
# generator object that produce on demand,also known as lazy evaluation
# importance : reduce memory consumption and improve performance
# use parenthesis inplace of square bracket
# This method doesnot crea... | true |
c212f377fd1f1bf1b8644a068bbf0a4d48a86fb0 | purusottam234/Python-Class | /Day 5/ifelif.py | 524 | 4.28125 | 4 | # pseudo code
# if student'grade is greater than or equal to 90
# display "A"
# else if student'grade is greater than or equal to 80
# display "B"
# else if student'grade is greater than or equal to 70
# display "C"
# else if student'grade is greater than or equal to 60
# display "D"
# else
# display "E"
# Python impl... | true |
415a3f4dd9be70d5f66accb8b25db24791996c0b | purusottam234/Python-Class | /Day 14/conc.py | 224 | 4.125 | 4 |
# + operator is used to Concatenate lists
list1 = [10, 20, 30]
list2 = [40, 50]
concatenated_list = list2 + list1
print(concatenated_list)
for i in range(len(concatenated_list)):
print(f'{i}:{concatenated_list[i]}')
| false |
dd012da4f847a1ac2d8ee942adcad572104fa345 | pianowow/projecteuler | /173/173.py | 967 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: CHRISTOPHER_IRWIN
#
# Created: 05/09/2012
##We shall define a square lamina to be a square outline with a square "hole" so
##that the shape possesses vertical and horizontal ... | true |
9ecc61f4d52f236379f2c9ada813efd364e651c0 | liradal/Python-520 | /aula2/lacos.py | 1,641 | 4.125 | 4 | #!/usr/bin/python3
######
## laços de Repetição
######
######
## Laço Whiloe
######
# Este laço executa enquanto uma condição for verdadeira
# i = 0
# while(i < 10): # enquanto i for menor que 10
# print(i) # mostra valor de i
# i += 1 # i = i + 1
# repete
# Como fazer controle de um loop while
# whi... | false |
66b4199a8bf357c92e78a65c637d07d79627b657 | liradal/Python-520 | /aula2/manipulacao_arq.py | 1,021 | 4.375 | 4 | #!/usr/bin/python3
#########
## Manipulando arquivos com python
#########
# ### Abrir um arquivo para modificação
# #### Método não recomendado ####
# ponteiro = open('nomedoarquivo.txt','a') # abre um ponteiro para
# # escrita de arquivos, modo utilizado é o read plus (r+) que serve para
# # leitura e escrita.Possu... | false |
d28564c2c36afa5fe4e96ce763d90bd07b6f2bcd | alok162/Geek_Mission-Python | /count-pair-sum-in-array.py | 901 | 4.125 | 4 | #A algorithm to count pairs with given sum
from collections import defaultdict
#function to calculate number of paris in an array
def countPairSum(d, arr, sum):
count = 0
#storing every array element in dictionary and
#parallely checking every element of array is previously
#seen in dictionary or not
... | true |
0700f44ab1b11b60d28cd635aeaf20df5b90959d | jaolivero/MIT-Introduction-to-Python | /Ps1/ProblemSet1.py | 779 | 4.125 | 4 |
r = 0.04
portion_down_payment = 0.25
current_savings = 0.0
annual_salary = float(input( "What is your annual salary: "))
portion_saved = float(input("what percentage of your salary would you like to save? write as a decimal: "))
total_cost = float(input("what is the cost of your deam home: "))
monthly_sav... | true |
04acb5cf7f7f70354415001e67ba64b6062e97aa | isiddey/GoogleStockPrediction | /main.py | 2,377 | 4.25 | 4 | #Basic Linear Regression Tutorial for Machine Learning Beginner
#Created By Siddhant Mishra
#We will try to create a model to predict stock price of
#Google in next 3 days
import numpy as np
import pandas as pd
import quandl as qd
import math
from sklearn import preprocessing, cross_validation
from sklearn.linear_mod... | true |
6545045e6e520f70af769078d008a3e72492c4fe | saifazmi/learn | /languages/python/sentdex/basics/48-53_matplotlib/51_legendsAndGrids.py | 728 | 4.15625 | 4 | # Matplotlib labels and grid lines
from matplotlib import pyplot as plt
x = [5,6,7,8]
y = [7,3,8,3]
x2 = [5,6,7,8]
y2 = [6,7,2,6]
plt.plot(x,y, 'g', linewidth=5, label = "Line One") # assigning labels
plt.plot(x2,y2, 'c', linewidth=10, label = "Line Two")
plt.title("Epic Chart")
plt.ylabel("Y axis")
plt.xlabel("X ... | true |
b6a0bc120206cbb24f780c8b35065925c9ae038a | saifazmi/learn | /languages/python/sentdex/intermediate/6_timeitModule.py | 1,765 | 4.1875 | 4 | # Timeit module
'''
' Measures the amount of time it takes for a snippet of code to run
' Why do we use timeit over something like start = time.time()
' total = time.time() - start
'
' The above is not very precise as a background process can disrupt the snippet
' of code to make it look like it ran for longer than it... | true |
dcc08fb3c7b4ef7eeee50d79bd1751b537083339 | saifazmi/learn | /languages/python/sentdex/basics/8_ifStatement.py | 302 | 4.46875 | 4 | # IF statement and assignment operators
x = 5
y = 8
z = 5
a = 3
# Simple
if x < y:
print("x is less than y")
# This is getting noisy and clutered
if z < y > x > a:
print("y is greater than z and greather than x which is greater than a")
if z <= x:
print("z is less than or equal to x")
| true |
f9d01749e966f4402c3591173a145b65380d2102 | saifazmi/learn | /languages/python/sentdex/basics/62_eval.py | 900 | 4.6875 | 5 | # Using Eval()
'''
' eval is short for evaluate and is a built-in function
' It evaluates any expression passed through it in form of a string and will
' return the value.
' Keep in mind, just like the pickle module we talked about, eval has
' no security against malicious attacks. Don't use eval if you cannot
' trust... | true |
27634a1801bd0a5cbe1ca00e31052065a8e4ce9b | saifazmi/learn | /languages/python/sentdex/basics/64-68_sqlite/66_readDB.py | 852 | 4.40625 | 4 | # SQLite reading from DB
import sqlite3
conn = sqlite3.connect("tutorial.db")
c = conn.cursor()
def read_from_db():
c.execute("SELECT * FROM stuffToPlot") # this is just a selection
data = c.fetchall() # gets the data
print(data)
# Generally we iterate through the data
for row in data:
pr... | true |
95443c1973cf14c5467b2fb8c4e24fda942bdfa9 | saifazmi/learn | /languages/python/sentdex/intermediate/7_enumerate.py | 830 | 4.40625 | 4 | # Enumerate
'''
' Enumerate takes an iterable as parameter and returns a tuple containing
' the count of item and the item itself
' by default the count starts from index 0 but we can define start=num as param
' to change the starting point of count
'''
example = ["left", "right", "up", "down"]
# NOT the right way o... | true |
8bbb0737979d0709d1edca705a4966f369a110de | saifazmi/learn | /languages/python/sentdex/intermediate/2_strConcatAndFormat.py | 1,161 | 4.21875 | 4 | # String concatenation and formatting
## Concatenation
names = ["Jeff", "Gary", "Jill", "Samantha"]
for name in names:
print("Hello there,", name) # auto space
print("Hello there, " + name) # much more readable, but makes another copy
print(' '.join(["Hello there,", name])) # better for performance, no co... | true |
04652bd04e648972fd819c39d288b8f52577eb14 | saifazmi/learn | /languages/python/sentdex/basics/43_tkMenuBar.py | 1,464 | 4.25 | 4 | # Tkinter Menu Bar
'''
' Menus are defined with a bottom-up approach
' the menu items are appended to the menu, appended to menu bar,
' appended to main window, appended to root frame
'''
from tkinter import *
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
... | true |
2f6bb6a1d83586fe2504c1ceb787392891bd011d | lucky1506/PyProject | /Item8_is_all_digit_Lucky.py | 311 | 4.15625 | 4 | # Item 8
def is_all_digit(user_input):
"""
This function validates user entry.
It checks entry is only digits from
0 to 9, and no other characters.
"""
numbers = "0123456789"
for character in user_input:
if character not in numbers:
return False
return True
| true |
086101d275de833242f8fcfd2acddbfd6af62919 | gelfandbein/lessons | /fibonacci.py | 1,176 | 4.625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 4 18:50:32 2020
@author: boris
"""
"""Write a program that asks the user how many Fibonnaci numbers to
generate and then generates them. Take this opportunity to think
about how you can use functions. Make sure to ask the user to enter
... | true |
b0d34741b9de03eafe535eac8f30c8f977fa6518 | gordonramsayjr/Procedural-Programming | /fizzbuzz.py | 239 | 4.1875 | 4 | import math
for x in range(100):
if x % 5 == 0 and x % 3 == 0:
print("Bingo!")
elif x % 3 == 0:
print(x,"Is divisible by 3!")
elif x % 5 == 0:
print(x,"Is divisible by 5!")
print(x) | false |
eabbc8071925c42d579fe00f9736c7319f5b2a65 | somvud9843/leetcode | /Spiral Matrix.py | 1,422 | 4.1875 | 4 | '''
Spiral Matrix I
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
Spiral Matrix II
Given an integer n, generate a square matrix filled... | false |
7d7d6e70123576f89a5c8d318fc7339ec7c1a771 | shreyan-naskar/Python-DSA-Course | /Strings/Max frequency/prog.py | 532 | 4.3125 | 4 | '''
Given a string s of latin characters, your task is to output the character which has
maximum frequency.
Approach:-
Maintain frequency of elements in a separate array and iterate over the array and
find the maximum frequency character.
'''
s = input("Enter the string : ")
D = {}
Freq_char = ''
Freq = 0
for i in s... | true |
306f07a2159c83f1213a2d5d58b9b83a8a2778e5 | shreyan-naskar/Python-DSA-Course | /Patterns/floyd triangle/prog.py | 229 | 4.25 | 4 | #Generating the Floyd Triangle
n = int(input("Enter the number of rows : "))
v = 1
print('The Floyd Triangle would look like :\n')
for i in range(1,n+1) :
for j in range(1,i+1) :
print(v , end = ' ')
v = v + 1
print('\n') | false |
591e06efb766c4fd99986c756192b68d91ea2fd3 | shreyan-naskar/Python-DSA-Course | /Functions in Python/find primes in range/primes.py | 429 | 4.15625 | 4 | #Finding all primes in a given range.
def isPrime( n ) :
count = 0
for i in range(2,n) :
if n%i == 0 :
count = 0
break
else :
count = 1
if count == 1 :
return True
else :
return False
n = int(input('Enter the upper limit of Range : '))
List_of_Primes = []
for i in range(1,n+1) :
if isPrime(i) ... | true |
2dbeef63ca251b9d9ab446b8776ea376ac3b0451 | akshajbhandari28/guess-the-number-game | /main.py | 1,584 | 4.1875 | 4 | import random
print("welcome to guess the number game! ")
name = input("pls lets us know ur name: ")
print("hello, ", name, "there are some things you need tp know before we begin..")
print("1) you have to guess a number so the number u think type only that number and nothing else")
print("2) you will get three chance... | true |
3829020674ee0e08dd307a6e89606752f27f810b | Meowsers25/py4e | /chapt7/tests.py | 2,099 | 4.125 | 4 | # handle allows you to get to the file;
# it is not the file itself, and it it not the data in file
# fhand = open('mbox.txt')
# print(fhand)
# stuff = 'hello\nWorld'
# print(stuff)
# stuff = 'X\nY'
# print(stuff)
# # \n is a character
# print(len(stuff)) # 3 character string
# a file is a sequence of lines with \n... | true |
e1c7a8b10f8fdb183ec52927bf7b2fde52116971 | Meowsers25/py4e | /chapt5/counting.py | 1,245 | 4.15625 | 4 | # counting
# zork = 0
# print("Before: ", zork)
# for thing in [9, 41, 12, 3, 74, 15]:
# zork += 1
# print(zork, thing)
# print("After: ", zork)
#
# # summing
# zork = 0
# print("Before:", zork)
# for thing in [9, 41, 12, 3, 74, 15]:
# zork = zork + thing
# print(zork, thing)
# print("After:", zork)
#
#... | false |
4071598da7f76b0c61a03325b989b3a58f2e91fd | wwwser11/train_task_massive | /task5.py | 921 | 4.1875 | 4 | # 5. В массиве найти максимальный отрицательный элемент.
# Вывести на экран его значение и позицию в массиве.
# Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный».
# Это два абсолютно разных значения.
import random
print('vvedite diapazon massiiva')
char1 = int(input('min massiva:... | false |
fe5e4243e64ebedaa1b31718b2be256e24cd52a3 | bipulhstu/Data-Structures-and-Algorithms-Through-Python-in-Depth | /1. Single Linked List/8. Linked List Calculating Length.py | 1,401 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.ne... | true |
05caa2fd68e08437ee71919e6bc044168d4b69fc | emsipop/PythonPractice | /pig_latin.py | 680 | 4.28125 | 4 | def pig_latin():
string = input("Please enter a string you would like translating: ").lower() #Changes case of all characters to lower
words = string.split(" ") # Splitting the user's input into an array, each item corresponding to each word in the sentence
translation = [] # An empty array which each tr... | true |
4a1333b1c3da67ad28f85a9094066b52c6ad51b6 | gaurav9112in/FST-M1 | /Python/Activities/Activity8.py | 238 | 4.125 | 4 | numList = list(input("Enter the sequence of comma seperated values : ").split(","))
print("Given list is ", numList)
# Check if first and last element are equal
if (numList[0] == numList[-1]):
print("True")
else:
print("False")
| true |
020e801e0be13679a66e113af0945c191d54e2e9 | aniruddha2000/dsa | /Recursion/reverseStringRecursion.py | 210 | 4.15625 | 4 | def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
if __name__ == "__main__":
result = reverse("aniruddha basak")
print(result)
| false |
0071df21d8caf1ecaaf36ee25857ec85b9aae83d | davidjoliver86/advent-of-code-2019 | /aoc2019/day3.py | 2,344 | 4.1875 | 4 | """
Day 3: Crossed Wires
"""
import pathlib
import functools
from typing import List, Tuple, Set
def _trace_path(path: str) -> List[Tuple]:
steps = path.split(",")
path = []
x = 0
y = 0
for step in steps:
direction, distance = step[0], int(step[1:])
if direction == "U":
... | false |
0e8240844666542eeb745b0e53c5471e9a7d55a9 | sergiuvidican86/MyRepo | /exerc4 - conditions 2.py | 327 | 4.1875 | 4 | name = "John"
age = 24
if name == "John" and age == 24:
print("Your name is John, and you are also 23 years old.")
if name == "test"
pass
if name == "John"or name == "Rick":
print("Your name is either John or Rick.")
if name in ["John", "Rick"]:
print("Your name is either John or ... | true |
63c29133e42fb808aa8e42954534eef33508e22b | oscarwu100/Basic-Python | /HW4/test_avg_grade_wu1563.py | 1,145 | 4.125 | 4 | ################################################################################
# Author: BO-YANG WU
# Date: 02/20/2020
# This program predicts the approximate size of a population of organisms.
################################################################################
def get_valid_score():#re print the ... | true |
d9134fcdc5012a0529bd7a77131fa7c80c4a9085 | oscarwu100/Basic-Python | /HW2/roulette_wheel_wu1563.py | 952 | 4.125 | 4 | ################################################################################
# Author: BO-YANG WU
# Date: 02/05/2020
# This program calculate the pocket number color
################################################################################
num= int(input('Please enter a pocket number:'))
if num< ... | false |
6dd26ecb710eec1d072c7971044b29362b244b10 | AMRobert/Simple-Calculator | /Simple_Calculator.py | 1,846 | 4.15625 | 4 | #SIMPLE CALCULATOR
#Function for addition
def addition(num1,num2):
return num1 + num2
#Function for subtraction
def subtraction(num1,num2):
return num1 - num2
#Function for multiplication
def multiplication(num1,num2):
return num1 * num2
#Function for division
def division(num1,num2):
return num1 / ... | true |
e8af57b1a0b5d1d6ec8e8c7fa2899c2ddc8f2135 | lnogueir/interview-prep | /problems/stringRotation.py | 1,174 | 4.40625 | 4 | '''
Prompt:
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1.
(e.g., "waterbottle" is a rotation of "erbottlewat").
Follow up:
What if you could use one call of a helper method isSubstring?
'''
# Time: O(n), Space: O(n)
def isStringRotation(s1, s2):
if len(s1) != len(s2):
return False... | true |
e931d6c45ba4181ee92a5df69d3de859f3e2926d | ShreyaKaran14/Python | /program7.py | 632 | 4.15625 | 4 | def birthday(x):
if x == 'apurva':
print(x,'Birthday is on',data['apurva'])
if x== 'ankita':
print(x,"Birthday is on",data['ankita'])
if x=='madhu':
print(x, "Birthday is on",data['madhu'])
if x == 'kavita':
print(x, "Birthday is on",data['kavita'])
name = ['apurva','anki... | false |
713020b5e737e835ddb818a5faaacd037a2e4d16 | RaymondLloyd/Election_Analysis | /Python_practice.py | 976 | 4.15625 | 4 | counties = ["Arapahoe", "Denver","Jefferson"]
if counties[1] == 'Denver':
print(counties[1])
if "ElPaso" in counties:
print("El Paso is in the list of counties.")
else:
print("El Paso is not in the list of counties.")
if "Arapahoe" in counties and "El Paso" in counties:
print("Arapahoe and El Paso are i... | false |
334d1b51189b1492bb754f0db69a2357cc8e0f15 | abideen305/devCamp-task | /Bonus_Task_2.py | 1,845 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
# program to replace a consonant with its next concosnant
#Starting by definig what is vowel and what is not. Vowel are just: a,e,i,o,u
#defining a function with the name vowel and its argument v
def vowel(v):
#if statement to taste if the word containing any of the... | true |
f7330413f555d1dfa3164c3a3229e18cac863415 | mmarcosmath/learning_python | /PythonOO/inputs.py | 311 | 4.25 | 4 | nome = input("Digite seu nome: ")
print(nome)
print(nome.upper())
print(nome.capitalize())
print("O nome digitado foi "+nome)
print("O nome digitado foi {}".format(nome))
print("{} foi o nome digitado".format(nome))
sobre = input("Digite seu sobrenome: ")
print("{} {} é o nome completo".format(nome,sobre))
| false |
97433547ac2da4227d9c64499727b46c5b05c3f7 | Mayank2134/100daysofDSA | /Stacks/stacksUsingCollection.py | 490 | 4.21875 | 4 | #implementing stack using
#collections.deque
from collections import deque
stack = deque()
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack:')
print(stack)
# pop() function to pop element from stack i... | true |
3f81995adbbbc6c32e77ca7aaa05c91f5dd25d99 | Lexielist/immersive---test | /Prime.py | 204 | 4.15625 | 4 | A = input("Please input a number: ")
print ("1 is not a prime number")
for number in range (2,A):
if num%A == 0:
print (num," is a prime number)
else: print (num,"is not a prime number) | true |
a585ac1434cfc382a3d1f1f30850b36b4a0c3e35 | Millennial-Polymath/alx-higher_level_programming | /0x06-python-classes/5-square.py | 1,435 | 4.375 | 4 | #!/usr/bin/python3
""" Module 5 contains: class square """
class Square:
"""
Square: defines a square
Attributes:
size: size of the square.
Method:
__init__: initialialises size attribute in each of class instances
"""
def __init__(self, size=0):
self.__siz... | true |
f9411b270aea54e2d36cfabed30a18f3278a8b1e | eszkatya/test | /boolean.py | 387 | 4.28125 | 4 | #Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.
def bool_to_word(boolean):
if boolean == True:
return 'Yes'
else:
return 'No'
"""ezt is lehetett vna egy sorba, ami még érdekes:
def bool_to_word(bool):
return ['No',... | false |
c7e9613d1af0ec7359dc8a175bbd99059b05c66b | iomkarsurve/basicpython | /conditional statements/calculator.py | 309 | 4.25 | 4 | num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
op = input("Enter operator")
if(op=="+"):
print(num1+num2)
elif(op=="-"):
print(num1-num2)
elif(op=="*"):
print(num1*num2)
elif(op=="/"):
print(num1/num2)
else:
print("invalid operator") | false |
944d8d7851bb5f27d6fc1e6d5b4043cacbb4e16a | beyzend/learn-sympy | /chapter3.py | 329 | 4.34375 | 4 | days = ["sunday", "monday", "tuesday", "wednesday", "thursday",
"friday", "saturday"]
startDay = 0
whichDay = 0
startDay = int(input("What day is the start of your trip?\n"))
totalDays = int(input("How many days is you trip?\n"))
whichDay = startDay + totalDays
print("The day is: {}".format(days[whichDay % len(... | true |
714981cda6519db2aefa69f575c1d87c454d1c77 | ivan295/Curso-Python-Rafael | /tarea unidad 3/tarea3_ejercicio6.py | 917 | 4.40625 | 4 | """
Utilizando la función range() y la conversión a listas genera las siguientes
listas dinámicamente:
Todos los números del 0 al 10 [0, 1, 2, ..., 10]
Todos los números del -10 al 0 [-10, -9, -8, ..., 0]
Todos los números pares del 0 al 20 [0, 2, 4, ..., 20]
Todos los números impares entre -20... | false |
8bd9bbdabd8a962c794c3fa01b2de6437a0268ce | nenusoulgithub/LearnPython | /求知学堂/day8_09-类属性和实例属性.py | 892 | 4.1875 | 4 | # 类属性和实例属性
class Student:
school = "东北师范大学" # 类属性
def __init__(self, name):
self.name = name # 实例属性
def __str__(self):
return "学生%s就读于%s" % (self.name, Student.school)
xiaoming = Student("小明")
print(xiaoming)
print("类属性的地址是%d,内容是%s。" % (id(xiaoming.school), xiaoming.school))
xiaoming.s... | false |
a8bc4dee358f97fe97efbb01cb8c1aa3fdba6078 | nenusoulgithub/LearnPython | /求知学堂/day3_02-字符串操作.py | 2,509 | 4.5625 | 5 | # Python的序列 字符串 列表 元组
# 优点:通过下标访问元素
# 共同点:支持切片
python = "Python"
print("字符串的第一个字符%s" % python[0])
print("字符串的第二个字符%s" % python[1])
for c in python:
print(c, end=" ")
print("\n--------------------------------------")
# 大小写转换
python = "python"
print("将单词的首字母变为大写%s" % python.capitalize())
print("将单词所有字母变为大写%s" % p... | false |
b50df42287c5962d04b762d0c32feb4a81b72ac6 | nenusoulgithub/LearnPython | /求知学堂/day1_07-逻辑运算符.py | 436 | 4.125 | 4 | # 条件运算符 and or not
a, b, c, d = 5, 8, 2, 9
print("---------------and---------------")
print(a < b and c < d)
print(b > c and d < a)
print("---------------or---------------")
print(a < b or c < d)
print(b > c or d < a)
print(b < c or d < a)
print("---------------not---------------")
print(not a < b)
# 逻辑运算符... | false |
2f05c959814934372cf786623921c26f788d0d30 | ed1rac/AulasEstruturasDados | /2019/## Python/Ordenacao e Busca/insertion_sort-v1.py | 805 | 4.1875 | 4 | """
A estrategia do insertion sort é:
1 - iterar usando i de vetor[1] até tamanho do vetor (laço externo) - vetor[i] é o atual
2 - fazer um laço (usando j) de i-1 até 0 e: (laço interno)
3 - se o valor de atual < vetor[j], afasta vetor[j] para direita
4 - quando vetor[j] encontrar um valor menor ou 0, então insere o at... | false |
eb61ba46bf967a9e79600eb9905dfe652a4d0ca6 | ed1rac/AulasEstruturasDados | /2019/## Python/Basico-MacBook-Ed/SlicesString.py | 581 | 4.1875 | 4 | s = 'Edkallenn'
print("Fatias de strings:\n=============")
print(s[2:]) #a partir da segunda posição, começando de zero, para frente - 'kallenn'
print(s[1:]) #a partir da primeira posição, começando de zero, para frente - 'dkallenn'
print(s[-1:]) #slice com a Última posição - 'n'
print(s[-2:]) #slice com as duas última... | false |
53d1afc8ba2931f4f6a4c4df9baaa017b3ebf3b9 | ed1rac/AulasEstruturasDados | /UNP/ref/Python/TADs e Classes/Fila.py | 1,120 | 4.1875 | 4 | class Fila(object):
'uma classe de fila clássica'
def __init__(self):
'instancia uma lista vazia'
self.items = []
def esta_vazia(self):
'retorna True se a lista está vazia, False caso contrário'
return (len(self.items)==0) #se o tamanho for zero
def enfileira(self, item): #enqueue
'ins... | false |
d975784b292282e44aab27e86b07d0a0a175230d | ed1rac/AulasEstruturasDados | /2019/## Python/TADs e Classes/TAD_ponto.py | 936 | 4.28125 | 4 |
class Ponto(object):
def __init__(self, x, y): #método construtor (cria ponto)
self.x = x
self.y = y
def exibe_ponto(self):
print('Coordenadas -> x: ', self.x, ', y: ', self.y)
def set_x(self, x):
self.x = x
def set_y(self, y):
self.y = y
def get_x... | false |
e1730b223bc66de92afdb0f2f857a1b617a43df9 | vivekdubeyvkd/python-utilities | /writeToFile.py | 462 | 4.40625 | 4 |
# create a new empty file named abc.txt
f = open("abc.txt", "x")
# Open the file "abc.txt" and append the content to file, "a" will also create "abc.txt" file if this file does not exist
f = open("abc.txt", "a")
f.write("Now the file has one more line!")
# Open the file "abc.txt" and overwrite the content of entire... | true |
9a4374b3e3d6ef7651fdfbcd279af9c0d7cb2556 | ducang/python | /session5/validate_input.py | 749 | 4.1875 | 4 | '''check ten ko co so'''
# while True :
# name = input("enter your name:")
# if name.isalpha() :
# break
# else:
# print("error, please enter a valid name.")
'''check pass co chua so'''
# while True:
# pas= input("enter password:")
# if pas.isalpha():
# print("password must... | false |
191ce4a91dde400ff43493eea3a1b1a4f9ea08c9 | HaminKo/MIS3640 | /OOP/OOP3/Time1.py | 1,646 | 4.375 | 4 | class Time:
"""
Represents the time of day.
attributes: hour, minute, second
"""
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def print_time(self):
print('{:02d}:{:02d}:{:02d}'.format(self.hour, self... | true |
04c359f3e674466994f258820239885690299c21 | HaminKo/MIS3640 | /session10/binary_search.py | 1,143 | 4.1875 | 4 | import math
def binary_search(my_list, x):
'''
this function adopts bisection/binary search to find the index of a given
number in an ordered list
my_list: an ordered list of numbers from smallest to largest
x: a number
returns the index of x if x is in my_list, None if not.
'''
pass
... | true |
47b9e54b2b400bf8981920e4924a38c8091392ac | AhmedKhalil777/courses | /data_structures_and_algorithms/Thebes-1st-2018-2019/Lectures/Lecture-06/run.py | 1,163 | 4.3125 | 4 | # بسم الله الرحمن الرحيم
from Set import Set
mahmoud = Set()
mahmoud.add("CSCI-112")
mahmoud.add("MATH-121")
mahmoud.add("HIST-340")
mahmoud.add("ECON-101")
Eslam = Set()
Eslam.add("POL-101")
Eslam.add("ANTH-230")
Eslam.add("CSCI-112")
Eslam.add("ECON-101")
# Determine if two students are taking:
common_courses... | false |
0757693b76c6ccf62eb380198ab10365d6a2c016 | Titowisk/estudo_python | /meus_programas/04-desafio1.py | 457 | 4.15625 | 4 | # coding: utf-8
#desafio 1
#nome = input("Digite seu nome: ")
#print("Bem-vindo", nome)
#desafio 2
#dia = input("Digite o dia do seu nascimento: ")
#mes = input("Digite o mês do seu nascimento: ")
#ano = input("Digite o ano de seu nascimento: ")
#
#print("Você nasceu em", dia,"/",mes,"/",ano)
#desafio 3
a = float(i... | false |
fb16eda74a1e4ab4b412c9b206273839e3c8049c | jdogg6ms/project_euler | /p009/p9.py | 885 | 4.1875 | 4 | #!/usr/bin/env python
# Project Euler Problem #9
"""
A Pythagorean triplet is a set of three natural numbers.
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
from math import sqrt
def test_triplet(a,b,c):
re... | true |
0f8bc6d325c0e7af4cae255b3815e10be59148cb | utk09/open-appacademy-io | /1_IntroToProgramming/6_Advanced_Problems/10_prime_factors.py | 1,096 | 4.1875 | 4 | """
Write a method prime_factors that takes in a number and returns an array containing all of the prime factors of the given number.
"""
def prime_factors(number):
final_list = []
prime_list_2 = pick_primes(number)
for each_value in prime_list_2:
if number % each_value == 0:
final_lis... | true |
6ea5413956361c5ce26f70079caefca87f352112 | utk09/open-appacademy-io | /1_IntroToProgramming/6_Advanced_Problems/14_sequence.py | 1,120 | 4.46875 | 4 | """
A number's summation is the sum of all positive numbers less than or equal to the number. For example: the summation of 3 is 6 because 1 + 2 + 3 = 6, the summation of 6 is 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21. Write a method summation_sequence that takes in a two numbers: start and length. The method should return... | true |
88f52244e93514f9bab7cbfb527c1505f298925b | utk09/open-appacademy-io | /1_IntroToProgramming/2_Arrays/2_yell.py | 481 | 4.28125 | 4 | # Write a method yell(words) that takes in an array of words and returns a new array where every word from the original array has an exclamation point after it.
def yell(words):
add_exclam = []
for i in range(len(words)):
old_word = words[i]
new_word = old_word + "!"
add_exclam.append(... | true |
f737fe1edc1d4837154537fd3e8a55da0ada12c7 | utk09/open-appacademy-io | /1_IntroToProgramming/6_Advanced_Problems/1_map_by_name.py | 895 | 4.125 | 4 | """
Write a method map_by_name that takes in an array of dictionary and returns a new array containing the names of each dictionary key.
"""
def map_by_name(arr):
map_list = []
for each_dict in range(len(arr)):
map_dict = arr[each_dict]
for key, value in map_dict.items():
if key =... | false |
ac6ddb7a5ff88871ed728cc8c90c54852658ce30 | utk09/open-appacademy-io | /1_IntroToProgramming/2_Arrays/12_sum_elements.py | 586 | 4.15625 | 4 | """
Write a method sum_elements(arr1, arr2) that takes in two arrays. The method should return a new array containing the results of adding together corresponding elements of the original arrays. You can assume the arrays have the same length.
"""
def sum_elements(arr1, arr2):
new_array = []
i = 0
while i... | true |
086ed855f74612d9ef8e28b2978ae7ffe5bf62f4 | Mzomuhle-git/CapstoneProjects | /FinanceCalculators/finance_calculators.py | 2,602 | 4.25 | 4 | # This program is financial calculator for calculating an investment and home loan repayment amount
# r - is the interest rate
# P - is the amount that the user deposits / current value of the house
# t - is the number of years that the money is being invested for.
# A - is the total amount once the interest has been a... | true |
4cbc8fddcb32ba425cbcbb2ff96f580384c8ddbb | rushabhshah341/Algos | /leetcode38.py | 1,397 | 4.21875 | 4 | '''The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the co... | true |
ca9c82e87d639e70de2ce6b214706617fb8f6a71 | JeterG/Post-Programming-Practice | /CodingBat/Python/String_2/end_other.py | 458 | 4.125 | 4 | #Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string
def end_other(a, b):
lA=len(a)
lB=len(b)
if ... | true |
f8b9bd890548a5d2b5fd2b60e23f68053b282097 | duongtran734/Python_OOP_Practice_Projects | /ReverseString.py | 625 | 4.5625 | 5 | # Class that has method that can reverse a string
class ReverseString:
# take in a string
def __init__(self, str=""):
self._str = str
# return a reverse string
def reverse(self):
reverse_str = ""
for i in range(len(self._str) - 1, -1, -1):
reverse_str += self._str[i... | true |
bd12113e4ca9a48b588c74d151d21373cdc9cfa1 | pwittchen/learn-python-the-hard-way | /exercises/exercise45.py | 875 | 4.25 | 4 | # Exercise 45: You Make A Game
'''
It's a very simple example of a "text-based game",
where you can go to one room or another.
It uses classes, inheritance and composition.
Of course, it can be improved or extended in the future.
'''
class Game(object):
def __init__(self):
self.kitchen = Kitchen()
self.livi... | true |
7b979b62e0828aae93811ff6b9c39fd5bca83ec5 | sushmithasuresh/Python-basic-codes | /p9.py | 228 | 4.28125 | 4 | n1=input("enter num1")
n2=input("enter num2")
n3=input("enter num3")
if(n1>=n2 and n1>=n3):
print str(n1)+" is greater"
elif(n2>=n1 and n2>=n3):
print str(n2)+" is greater"
else:
print str(n3)+" is greater"
| false |
4186b70a8f55396abe0bbd533fe61b7e8819f14e | mprior19xx/prior_mike_rps_game | /functions.py | 919 | 4.34375 | 4 | # EXPLORING FUNCTIONS AND WHAT THE DO / HOW THEY WORK
#
# EVERY DEFINITION NEEDS 2 BLANK LINES BEFORE AND AFTER
#
def greeting():
# say hello
print("hello from your first function!")
# this is how you call / invoke a function
greeting()
def greetings(msg="hello player", num1=0):
# creating another func... | true |
53fcbf43171cfb5a3c38e05ee1c1d77d6b89a171 | jhmalpern/AdventOfCode | /Puzzles/Day5/Day5Solution.py | 2,238 | 4.1875 | 4 | # Imports
import time
from re import search
# From https://www.geeksforgeeks.org/python-count-display-vowels-string/
# Counts and returns number of vowels in a string
##### Part 1 functions #####
def Check_Vow(string, vowels):
final = [each for each in string if each in vowels]
return(len(final))
def Check_r... | true |
2bbc62def0409391e8d077114b6d001c95acd12b | xqhl/python | /04.function/03.function_return.py | 802 | 4.1875 | 4 | # 函数返回值
string = 'hello world'
string = string.replace('o', '0')
print(string)
# 具备返回值的函数
def add(a=0, b=0):
c = a + b
return c
def odd(c=1, d=1):
e = c * d
return e
# result_add = add(2, 3)
# result_odd = odd(c=result_add, d=6)
# print(result_odd)
result = odd(c=add(2, 3), d=6)
print(result)
# yie... | false |
e7f9f4f92b756426ec8dfd9aa75eda62ef6f25f8 | ngthnam/Python | /Python Basics/18_MultiDimensional_List.py | 761 | 4.53125 | 5 | x = [2,3,4,6,73,6,87,7] # one dimensional list
print(x[4]) # single [] bracket to refer the index
x = [2,3,[1,2,3,4],6,73,6,87,7] # two dimensional list
print(x[2][1]) # using double [] to refer the index of list
x = [[2,3,[8,7,6,5,4,3,2,1]],[1,2,3,4],6,73,6,87,7] # three dimensional list
print(x[0][2][2]) # using t... | true |
73c8e86223f7de441517c9206ae526ef5365c664 | JonathanFrederick/what-to-watch | /movie_rec.py | 2,223 | 4.28125 | 4 | """This is a program to recommend movies based on user preference"""
from movie_lib import *
import sys
def get_int(low, high, prompt):
"""Prompts the player for an integer within a range"""
while True:
try:
integer = int(input(prompt))
if integer < low or integer > high:
... | true |
eced2979f93a7fe022bab64f1520480b7882bf10 | bishnu12345/python-basic | /simpleCalcualtor.py | 1,770 | 4.3125 | 4 | # def displayMenu():
# print('0.Quit')
# print('1.Add two numbers')
# print('2.Subtract two numbers')
# print('3.Multiply two numbers')
# print('4.Divide two numbers')
def calculate(num1,num2,operator):
result = 0
if operator=='+':
result = num1 + num2
if operator ... | true |
789ca9376e8a07fc228c109b4dddaaf796b55173 | skishorekanna/PracticePython | /longest_common_string.py | 1,093 | 4.15625 | 4 | """
Implement a function to determine the longest common string between
two given strings str1 and str2
"""
def check_common_longest(str1, str2):
# Make the small string as str1
if not len(str1)< len(str2):
str1, str2 = str2, str1
left_index=0
right_index=0
match_list = []
while ( left_... | true |
8b8471130787bf0c603dd98b79ac77848d72eda4 | Andrew-Lindsay42/Week1Day1HW | /precourse_recap.py | 277 | 4.15625 | 4 | user_weather = input("Whats the weather going to do tomorrow? ")
weather = user_weather.lower()
if weather == "rain":
print("You are right! It is Scotland after all.")
elif weather == "snow":
print("Could well happen.")
else:
print("It's actually going to rain.") | true |
7a03a57714a7e1e7c4be0d714266f119ffbe2667 | pankaj-raturi/python-practice | /chapter3.py | 1,086 | 4.34375 | 4 | #!/usr/bin/env python3
separatorLength = 40
lname = 'Raturi'
name = 'Pankaj ' + lname
# Get length of the string
length = len(name)
# String Function
lower = name.lower()
print (lower)
# * is repetation operator for string
print ( '-' * separatorLength)
# Integer Object
age = 30
# Convert Integers to string obj... | true |
8a3ad8eac1b92fcd869d220e1d41e19c65bf44d3 | MegaOktavian/praxis-academy | /novice/01-05/latihan/unpickling-1.py | 758 | 4.1875 | 4 | import pickle
class Animal:
def __init__(self, number_of_paws, color):
self.number_of_paws = number_of_paws
self.color = color
class Sheep(Animal):
def __init__(self, color):
Animal.__init__(self, 4, color)
# Step 1: Let's create the sheep Mary
mary = Sheep("white")
# Step 2:... | true |
ab88ff7a1b5ebad88c6934741a0582603b9313ea | bmschick/DemoProject | /Unit_1.2/1.2.1/Temp_1.2.1.py | 1,482 | 4.15625 | 4 | '''1.2.1 Catch-A-Turtle'''
'''Abstracting with Modules & Functions'''
# 0.1 How does the college board create a “function”?
# 0.2 What is “return”
# 1
# Quiz:
'''Events'''
#
#
'''Click a Turtle'''
# 2 through 14 (Make sure you comment the code!!):
# 14 Did you have any bugs throughout this section of cod... | true |
77244a8edec8f482e61cfe7cb2da857d989206cb | jesse10930/Similarities | /mario.py | 830 | 4.3125 | 4 | #allows us to use user input
from cs50 import get_int
#main function for the code
def main():
#assigns the user input into the letter n
while True:
n = get_int("Enter an integer between 1 and 23: ")
if n == 0:
return
elif n >= 1 and n <= 23:
break
#iterates ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.