blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
296e89f93f80b101088a1e3e89b2d889eb50fa05 | vinceajcs/all-things-python | /algorithms/graph/bfs/valid_tree.py | 1,342 | 4.15625 | 4 | """Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false
A... | true |
8e6229c7685cf84d2f59e09cdb26349846aadbf9 | cvhs-cs-2017/sem2-exam1-thomasw19 | /Turtle.py | 582 | 4.125 | 4 | """Create a Turtle Program that will draw a 3-dimensional cube"""
import turtle
thomas = turtle.Turtle()
for i in range (4):
thomas.forward(300)
thomas.right(90)
thomas.left(135)
thomas.forward(200)
thomas.right(135)
thomas.forward(300)
thomas.right(45)
thomas.forward(200)
thomas.right(135)
thomas.forward(300)
thom... | false |
ebf403e6382bcfe27c154498c227798f4fb8fe26 | KodeKunstner/grundat | /weeks/week38/oversaet.py | 907 | 4.1875 | 4 | def translate(string):
"""Make a direct translation, by replacing english words with danish words"""
# set of words used in the translation
dict = {
"a": "en",
"another": "endnu",
"hello": "hej",
"is": "er",
"is": "er",
"next": "naeste",
"now": "nu",
... | true |
1d329f78ff1a5cd779a87864d6c959685ae59d28 | youssef-abbih/python_projects | /turtle_race/main.py | 1,106 | 4.125 | 4 | import turtle
from turtle import *
from random import choice
colors =['red', 'blue', 'green', 'black']
y_position = [50, -50 ,-100, 100]
speed = list(range(0,10))
turtles = []
#******Screen****************************
screen = Screen()
screen.setup(width = 500, height = 400)
screen.bgpic("race_road.png")
#******cr... | true |
fb7c57de673ac7102b7c7e5927acef368d3d11d1 | IzzyBrand/cs1951c_demos | /pi_basics/blink.py | 834 | 4.40625 | 4 | '''
Demonstrates how to blink an LED using the RPi.GPIO library.
See this tutorial for more details
https://learn.sparkfun.com/tutorials/raspberry-gpio/python-rpigpio-api
Example code for csci1951c Designing Humanity Centered Robots
Brown University
Izzy Brand (2018)
'''
import RPi.GPIO as GPIO # this library enabl... | true |
82699003d5d51bf9a8d53f5d101078b64ff24acc | MissNaibei/PythonBasics | /Classes_and_Objects.py | 1,600 | 4.25 | 4 | name = "Naibei"
age = 16
# print(type)
# print(type(name))
# print(type(age))
class Person:
#class attribute - shared by all instances
species = "Homo sapien"
#METHOD - Is a function defined inside a class. Self is a default parameter
def walk(self):
print("is walking.")
def sleep(self):
... | false |
28cfe665d7b3bcb53c1bb765e69715dad904eb43 | hellowitsme/python | /string_manipulation/main.py | 1,166 | 4.40625 | 4 | # フォーマット
# -------------------------------------
# titleメソッド
# 頭文字を大文字に
print("the walking dead".title())
# formatメソッド
who = input("誰が:")
where = input("どこで:")
what = input("何を:")
do = input("した:")
print("{}が、{}で、{}を、{}したw".format(who, where, what, do))
# splitメソッド
# 引数に渡した文字で分割
print("splitメソッドでは、文章を分割できます。".split(... | false |
9e3e2ccc89bc10f802eda677a0d12bbd09cc546a | IvetteAb/PythonProjects | /Plotting graphs in Python.py | 2,894 | 4.75 | 5 | # Plotting graphs in Python
# import the relevant modules
import matplotlib.pyplot as plt # named the package plt
# create a very basic plot - we'll want something better
# create a random list
x = [1, 3, 5, 10] # this is what we're plotting
plt.plot(x) # this won't work because you need to say --> ... | true |
c5a103a78ecb069d9364ca58103927ec2489a2fd | daviddumas/mcs260fall2020 | /samplecode/redemo_2pm.py | 1,561 | 4.53125 | 5 | """Regular expression demonstrations
MCS 260 Fall 2020 Lecture 28
"""
import re
import sys
def demo1():
"""Minimal example of a regex"""
s = "Avocado is usually considered a vegetable."
print(re.sub("vegetable","fruit",s))
def demo2():
"""dot and repetition controls"""
s = "Do not f... | false |
dd34ca54274370c73b5d75147d9b3cd86de3aaea | daviddumas/mcs260fall2020 | /samplecode/sumprod.py | 228 | 4.28125 | 4 | # Read two floats and print their sum and product
# MCS 260 Fall 2020 Lecture 3 - David Dumas
x = float(input("First number: "))
y = float(input("Second number: "))
print("Sum: ",x,"+",y,"=",x+y)
print("Product:",x,"*",y,"=",x*y)
| true |
1ee852b510d92527c5651e5ef3959030608e0f94 | h4r3/PythonFunctions | /[functions] Time_related.py | 665 | 4.25 | 4 | #Time-related functions 2020/12/22
"""Get elapsed time"""#[関数] プログラムの計測時間の表示
def time_elapsed():
import time
print(__doc__)
start = time.time()
print('== Replace the program you want to time here ==') and time.sleep(1)
end = time.time()
_time=end-start
hour,min,sec=_time//3600,_... | true |
a043f06288cbc30dda8650601447de6ed6284faf | mirmire/beginner_python_project | /factors.py | 311 | 4.40625 | 4 | #!/usr/bin/python3
# A program to find given number's factors
num = int(input("The number to calculate the factors of: "))
factors = []
def calculate_factors(num):
for i in range(1, num+1):
if num % i == 0:
factors.append(i)
i += 1
calculate_factors(num)
print(factors)
| true |
89329b040f0e579f82588413ebbb5a7dfdd93080 | LuuanOliveira/Snake | /087.py | 1,200 | 4.125 | 4 | matriz = [[0,0,0], [0,0,0], [0,0,0,]] #Uma lista com 3 listas
soma_par = soma_coluna = soma_linha = 0
#Laço para adicionar os valores na matriz
for linha in range(0, 3):
for coluna in range(0, 3):
matriz[linha][coluna] = int(input(f'Digite um valor para [{linha}, {coluna}]: '))
#Adicionando valores... | false |
960044ee52fc67bb256254724b090f1471a271ac | AlexArango/PythonExercises | /ex19.py | 2,029 | 4.34375 | 4 | # Function that prints out the two number parameters passed in to it
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket. \n"
# A call to the fun... | true |
320d2883c5a1fecf87c691878fd82f7716ea5755 | DsDravos-Lnx/DesignPatterns_Strategy | /Exercise_5/invoice.py | 1,399 | 4.125 | 4 | from abc import ABC, abstractmethod
#implementando o metodo abstrado na classe de estrategia
class Strategy(ABC):
@abstractmethod
def tax_calculation(self, number):
pass
#implementando a classe da nota fiscal
class Invoice():
#construtor recebendo uma estrategia inicial do tipo Strategy
de... | false |
5268e6da877b0063a8d6e3d690861698e21e180e | gubenkoved/daily-coding-problem | /python/dcp_324_mices_and_holes.py | 1,142 | 4.375 | 4 | # This problem was asked by Amazon.
# Consider the following scenario: there are N mice and N holes placed at integer points
# along a line. Given this, find a method that maps mice to holes such that the largest
# number of steps any mouse takes is minimized.
# Each move consists of moving one mouse one unit to the ... | true |
5456219e7caf057c020757f70aa1e7f6bdccee2a | gubenkoved/daily-coding-problem | /python/dcp_401_permutation.py | 992 | 4.125 | 4 | # This problem was asked by Twitter.
#
# A permutation can be specified by an array P, where P[i] represents the location
# of the element at i in the permutation. For example, [2, 1, 0] represents the
# permutation where elements at the index 0 and 2 are swapped.
#
# Given an array and a permutation, apply the permuta... | true |
b66cabc4ca81819d90ad2eed53001187ebad091e | gubenkoved/daily-coding-problem | /python/dcp_377_moving_median.py | 1,565 | 4.125 | 4 | # This problem was asked by Microsoft.
#
# Given an array of numbers arr and a window of size k, print out the median of each
# window of size k starting from the left and moving right by one position each time.
#
# For example, given the following array and k = 3:
#
# [-1, 5, 13, 8, 2, 3, 3, 1]
# Your function should ... | true |
18b6747cbd7c12f8909f015cccb3e83dac083cdb | gubenkoved/daily-coding-problem | /python/dcp_337_shuffle_linked_list.py | 2,535 | 4.15625 | 4 | # This problem was asked by Apple.
# Given a linked list, uniformly shuffle the nodes. What if we want to prioritize space over time?
import itertools
from random import randint
class Node(object):
def __init__(self, val, next=None) -> None:
self.value = val
self.next = next
def insert(root: No... | true |
139d3b1da44b0e53666cfac9d23c106abc204a98 | gubenkoved/daily-coding-problem | /python/dcp_315_toeplitz_matrix.py | 1,643 | 4.3125 | 4 | # This problem was asked by Google.
# In linear algebra, a Toeplitz matrix is one in which the
# elements on any given diagonal from top left to bottom right are identical.
# Here is an example:
# 1 2 3 4 8
# 5 1 2 3 4
# 4 5 1 2 3
# 7 4 5 1 2
# Write a program to determine whether a given input is a Toeplitz matrix... | true |
2acf399ff7534ef83aad7f5a4ad5aa9d771d04e0 | gokou00/python_programming_challenges | /coderbyte/Camel_Case.py | 487 | 4.15625 | 4 | def CamelCase(string):
finalStr = ""
toCap = False
if string[0].isalpha():
finalStr += string[0].lower()
for x in string[1:]:
if x.isalpha() == False:
toCap = True
continue
if toCap:
toCap = False
finalStr += x.upper()
... | true |
2b5234a2677b8fdfdc5f87fb48b50d4ed1adf21e | chars32/edx_python | /Weeks/Week7/Dictionaries/Excercise6.py | 719 | 4.375 | 4 | #Write a function that takes a string as input argument and returns a dictionary of vowel counts i.e. the keys of this dictionary
#should be individual vowels and the values should be the total count of those vowels. You should ignore white spaces and they
#should not be counted as a character. Also note that a small... | true |
dac5f35f618cf20a6197c1883ee608349e857fca | chars32/edx_python | /Weeks/Week7/Dictionaries/Excercise8.py | 768 | 4.125 | 4 | #Write a function that takes an integer as input argument and returns the integer using words.
#For example if the input is 4721 then the function should return the string "four seven two one".
#Note that there should be only one space between the words and they should be all lowercased in the string that you return.... | true |
5ffc5e02425c991b076a58483c583ff0a7ed52f8 | chars32/edx_python | /Weeks/Week9/5. Nested.py | 516 | 4.21875 | 4 | #Write a function named nested_list_sum that receives a nested list of integers as parameter and calculates
#and returns the total sum of the integers in the list using recursion. Keep in mind that the inner elements
#may be integers or other nested lists themselves.
def nested_list_sum(list_nested):
sum = 0
for ... | true |
969bf5055bb8e265bdc829f6464782244f6acd16 | chars32/edx_python | /Quizes/Quiz5/one_to_2D.py | 1,198 | 4.125 | 4 | #Write a function named one_to_2D which receives an input list and two integers r and c as parameters and returns a
#new two-dimensional list having r rows and c columns.
#Note that if the number of elements in the input list is larger than r*c then ignore the extra elements.
#If the number of elements in the input ... | true |
4ab97b49e6ff1ea031aaf66ba7da59681ae158ff | chars32/edx_python | /Weeks/Week6/string_practices9.py | 549 | 4.25 | 4 | #Write a function that accepts a string of words separated by spaces consisting of alphabetic characters and returns a string such that each
#word in the input string is reversed while the order of the words in the input string is preserved.
def preserve_and_reverse(line):
line_split = line.split()
final = ""
c... | true |
9009a923d906e59077eafaa7004a088570231fbd | msberi/coding_practice | /rock_paper_scissor.py | 2,935 | 4.15625 | 4 | import random
class Computer(object):
def choose(self):
return random.randrange(1,3)
class Player(object):
def __init__(self, name):
self.name = name;
def choose(self):
print """Enter:
- 1 FOR ROCK;
- 2 FOR PAPER;
- 3 FOR SCISSOR."""
Choice = int(raw_input('>'))
while(Choice<1 or Choice>3)... | true |
52f49102910b46f6f9371c485e8aa484a6df67cc | nochemargarita/coding-challenges | /recursion.py | 1,075 | 4.125 | 4 | def count_recursively(lst):
"""Return number of items in a list, using recursion."""
if lst:
return 1 + count_recursively(lst[1:])
return 0
# print count_recursively([])
# print count_recursively([5, 6, 7])
def print_recursively(lst):
"""Print items in the list, using recursion."""
if l... | true |
b2a49c31909ab49962d507e95188e28bbd089ef0 | nochemargarita/coding-challenges | /Hackerrank/30-Day-Challenge-Hackerrank/day16_exceptions.py | 518 | 4.40625 | 4 | """Task
Read a string, S, and print its integer value; if S cannot be converted to an
integer, print Bad String.
Note:
You must use the String-to-Integer and exception handling constructs built into
your submission language. If you attempt to use loops/conditional statements,
you will get a 0 score.
Input Format
A s... | true |
60f77bc714f7bf3acdb1396306396b564eca8daf | nochemargarita/coding-challenges | /Technical-Challenge/strobogrammatic.py | 2,644 | 4.5625 | 5 | '''
-------------------
Long-form question
-------------------
A "Strobogrammatic Number" is a number that looks the same
when rotated 180 degrees (upside down) on an LED screen.
E.g.
11 -> 11, Strobogrammatic
252 -> 252, Strobogrammatic
37 -> LE, Not!
Write a function to determin... | true |
077122e2903858f716b3d384730d9450405d3d0e | nochemargarita/coding-challenges | /Hackerrank/30-Day-Challenge-Hackerrank/day20_sorting.py | 1,822 | 4.21875 | 4 | """Task:
Given an array, a, of size n distinct elements, sort the array in ascending
order using the Bubble Sort algorithm above. Once sorted, print the following 3
lines:
Array is sorted in numSwaps swaps.
where numSwaps is the number of swaps that took place.
First Element: firstElement
where firstElement is the fi... | true |
7416ca6c9c0f44ba0b9712c8a6b28de0ef307b04 | dmitry-izmerov/Udacity-Intro-to-computer-science | /Lesson04/Converting Seconds.py | 1,662 | 4.3125 | 4 | __author__ = 'demi'
# Write a procedure, convert_seconds, which takes as input a non-negative
# number of seconds and returns a string of the form
# '<integer> hours, <integer> minutes, <number> seconds' but
# where if <integer> is 1 for the number of hours or minutes,
# then it should be hour/minute. Further, <numbe... | true |
922bfd0a81850b411ffcb0ebe8397add059b9924 | maolasirzul/COMP1819ADS | /Lab_01/02_while loop with checking condition.py | 549 | 4.34375 | 4 | def staircase(data):
current = 0
if data > 0 and data <= 20:
while current <= data: # While the 'current' counter variable is less or equal to the input value 'data' the loop will continue to execute
print('#' * current) # This line will print the hash symbol by the current value of ... | true |
44ccabdc35767928022e0400ffc6799bf7aee320 | samwilliamsjebaraj/networkautomation | /PythonCode/function_operations.py | 707 | 4.15625 | 4 | """
File:function_operations.py
Mapping, Filtering & Reducing
map(),filter(),reduce()
"""
def check_even(x):
return x%2==0
def check_odd(x):
return x%2!=0
def add_numbers(x1,x2):
"""
add's the numbers and returns the value
"""
return x1+x2
def product(x1,x2):
'''
returns the product of t... | true |
5e561e78ee3b8adfb2e2002bfb9db0e851f467cb | kssim/efp | /making_decisions/python/multistate_sales_tax_calculator.py | 2,107 | 4.125 | 4 | # Pratice 20. Multistate sales tax calculator
# Output:
# What is the order amount? 10
# What state do you live in? Wisconsin
# What county do you live in? Eau Claire
# The state tax is $0.55.
# The county tax is $0.05.
# The total tax is $0.60.
# The total is $10.60.
# Or
# What is the order amount? ... | true |
aad75d82beb1ad4241514e8b5acf4c776912d531 | kssim/efp | /working_with_files/python/parsing_a_data_file.py | 2,045 | 4.15625 | 4 | # Pratice 41. Parsing a Data File
# Input:
# File name : parsing_a_data_file_input
# Output:
# Last First Salary
# ------------------------
# Ling Mai 55900
# Johnson Jim 56500
# Jones Aaron 46000
# Jones Chris 34500
# Swift Geoffrey 14200
# Xiong Fong 65000... | true |
db430d632e618f25d79d588df2538cd0e72fe1dc | kssim/efp | /making_decisions/python/legal_driving_age.py | 949 | 4.25 | 4 | # Pratice 16. Legal driving age
# Output:
# What is your age? 13
# You are not old enough to legally drive.
# Or
# What is your age? 25
# You are old enough to legally drive.
# Standard:
# 20 years old.
# Constraint:
# - Use a single output statement.
# - Use a ternary operator to write this program.
# ... | true |
0fa7b929eaadf462dbf8d0d106f4e0e91af01e30 | Sofista23/Aula1_Python | /Aulas/Exercícios-Mundo1/Aula010/Ex033.py | 879 | 4.1875 | 4 | n1=int(input("Digite um número:"))
n2=int(input("Digite outro um número:"))
n3=int(input("Digite mais um número:"))
if n1>n2 and n1>n3 and n2>n3:
print("{0} é o maior número.".format(n1))
print("{0} é o menor número.".format(n3))
if n1>n2 and n1>n3 and n2<n3:
print("{0} é o maior número.".format(n1))
pr... | false |
4c1939145029d1d52e5fefc5a13f26fd7b6640a3 | Coders222/Shared | /Comp Sci Gr 10/Selection/Bonus Question.py | 646 | 4.40625 | 4 | # this program takes in the year of input and tells you when is easter
year = input("What is the year? ")
year = int(year[-2:]) # takes last 2 digits of the year and parses into integer
x = year // 19
y = year // 4
r = (19 * year - x) % 30
s = (6 * year - y - r) % 7
# formulas ^^^^
# conditions to ch... | false |
b51bc6f916c8c16aeb2aa0a780aee969769fd087 | Dave0512/py_oop | /dir_Database/database.py | 2,913 | 4.125 | 4 |
## VORLAGE DATENBANK KLASSE
import pyodbc
class Database:
"""
Class to connect, and interact with several types of relational dbms
like ms sql server, mySQL, PostgreSQL, SQLite
Documentation:
Database Handler Class
1) Open Database (Using "with" to easy handle db_connection)
... | true |
5bc79659163519e172cfed17f106ae1e9af8fa9b | Shashank001122/Linked-List-2 | /ReorderList.py | 1,448 | 4.1875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
mid=self... | true |
46d985ce758d64b9743b1baab9eac5c27b3b95ea | jdaeira/Udemy-Python | /Data-Types/strings.py | 630 | 4.15625 | 4 |
x = "Hello World!"
print(x.lower())
print(x.upper())
print(x.split())
my_name = "John"
my_age = 50
print("Hello " + my_name)
text = "Hello {}, you are {} years old!".format(my_name, my_age)
print(text)
print("The {2} {1} {0}!".format("fox", "brown", "quick"))
# You can choose which index you want to use
print("The... | true |
7ea90ab04f978ae19d4294fa14dcefa94cc7c801 | jdaeira/Udemy-Python | /Python-Statements/comprehensions.py | 654 | 4.1875 | 4 |
mystring = "hello"
mylist = []
for letter in mystring:
mylist.append(letter)
print(mylist)
mylist = [letter for letter in mystring] # this creates a list of the letters in mystring (list comprehensions)
print(mylist)
mylist = [char for char in "word"]
print(mylist)
mylist = [num for num in range(0,11)]
pri... | false |
e082b4185da9587d3d7e5c9f1a078241708b8b72 | jdaeira/Udemy-Python | /Python-Statements/ifelse.py | 336 | 4.1875 | 4 |
number = 11
if number > 12:
print("Your number is greater than 12")
else:
print("Your number is less than 12")
loc = "Bank"
if loc == "Auto Shop":
print("I love Cars!")
elif loc == "Bank":
print("I'm at the Bank!")
elif loc == "Store":
print("Welcome to the Store!")
else:
print("I don't know... | true |
00b65c069fef5460d4fa9364383d397bcfd045af | marciorela/python-cursos | /luizotavio/aula020/aula032 - desafios.py | 1,174 | 4.28125 | 4 | """
1 - Crie uma função que exibe uma saudação com os parâmetros saudacao e nome.
"""
def saudacao(saud, nome):
print(f"{saud}, {nome}")
saudacao("Olá", "Joaquim")
"""
2 - Crie uma função que recebe 3 números como parâmetros e exiba a soma entre
eles.
"""
def soma(n1, n2, n3):
print(n1 + n2 + n3)
soma(10, 2... | false |
98e168e73f9559d81e17c23bfc0b2ef75194d7d6 | fatemebaghi/into_python | /ex2/prog2.py | 592 | 4.28125 | 4 | def prog2(a,b):
""" (int,int)-> list
You can use this function to find even numbers between two numbers.
In this function, it does not matter which a or b is bigger .
>>> prog1(12,26)
[14, 16, 18, 20, 22, 24]
>>> prog1(26,12)
[14, 16, 18, 20, 22, 24]
"""
if b>a :
num=[]
for m in range(a,b):
... | true |
746094a4a00af0117ebbbf02761fb10409a58a0b | Edwinl777/contest-questions | /ProjectEuler/Project Euler #1 Multiples of 3 and 5.py | 271 | 4.15625 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
s = 0
for i in range(3, 1000):
if not i % 3 or not i % 5: s += i
print(s)
| true |
8755fdee63904f0de6c757f8153fbee065a57ee7 | Temp-Nerd/All-d-Porgrams-in-d-wurld | /palindrome.py | 247 | 4.125 | 4 | def reverse(a):
rev=''
for i in range (len(a)-1,-1,-1) :
rev+=a[i]
return(rev)
a=(input('enter :'))
b=reverse(a)
if b==a :
fill=''
else :
fill='not '
print(f'The string is {fill}a palindrome')
| true |
31e5750e79937eefd9f9b803dcb5843546380866 | bishop527/MIT_OCW-6.00 | /ProblemSets/PS1/PS1b.py | 1,414 | 4.28125 | 4 | # MIT OpenCourseWare Introduction to 6.00
# Problem Set 1
# 10 March 2014
#Problem 2
min_monthly_payment = 0.0
cur_balance = 0.0
month = 0
total_interest = 0.0
total_paid = 0.0
success = False
start_balance = float(raw_input("What is the starting balance? "))
cur_balance = start_balance
annual_interest_rate = float(r... | true |
19bf2f59ee20094e7b2fe0ddfb570f810450c2e6 | itzketan/7th-day | /7th day.py | 1,712 | 4.21875 | 4 | """
1. Create a function getting two integer inputs from user. & print the following:
Addition of two numbers is +value
Subtraction of two numbers is +value
Division of two numbers is +value
Multiplication of two numbers is +value
"""
def add(a, b) :
return a + b
def sub(a, b) :
return a - b... | true |
91e029f13f5797575827b33620826c9bb2cd52fa | mwflickner/code-library | /merge-sort/python/merge_sort.py | 1,040 | 4.28125 | 4 | def merge_sort(the_list):
if len(the_list) < 2:
return the_list
left_side, right_side = split_list(the_list)
left_side = merge_sort(left_side)
right_side = merge_sort(right_side)
return merge(left_side, right_side)
def merge(left, right):
left_index = right_index = 0
sorted_list = [... | true |
4f1b61e589e878bdfe4088fc50e7202ba601c325 | jinkyukim-me/Learn-Python-Programming | /exercises/ex44d.py | 1,441 | 4.1875 | 4 | class Parent(object):
"""A simple example class""" # 클래스 정의 시작부분에 """...""" 도큐먼트 스트링
def __init__(self): # 컨스트럭터 (생성자)
self.name = "Kim"
def override(self): # override() 메소드
print("PARENT override()")
def implicit(self): ... | false |
559b5681b0c301958f4e6ecc2c0618cc5a1171c3 | jinkyukim-me/Learn-Python-Programming | /exercises/ex6.py | 861 | 4.28125 | 4 | # Exercise 6. Strings and Text
types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke... | false |
cc324b58ba872cd52137c1898bb9fef8b96e8dd8 | uolter/SortingAndSearch | /python/bubblesort.py | 1,458 | 4.34375 | 4 | #!/usr/bin/env
# -*- coding: utf-8 -*-
import unittest
def bubble_sort( seq ):
"""
Time Complexity of Solution:
Best O(n^2); Average O(n^2); Worst O(n^2).
Approach:
Bubblesort is an elementary sorting algorithm. The idea is to
imagine bubbling the smallest elements of a (vertical) ar... | true |
6c11c446f1ad859cf4c1c4e531633ced03bdc6a1 | cort-robinson/holbertonschool-web_back_end | /0x04-pagination/0-simple_helper_function.py | 591 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Write a function named index_range that takes two integer arguments: page and
page_size.
The function should return a tuple of size two containing a start index and an
end index corresponding to the range of indexes to return in a list for those
particular pagination parameters.
Page number... | true |
68eb5ec8fccafd6c2bd4abb94818b3a3a4ba38af | dastagg/bitesofpy | /68/clean.py | 298 | 4.34375 | 4 | import string
def remove_punctuation(input_string):
"""Return a str with punctuation chars stripped out"""
new_string = ""
for letter in input_string:
if letter in string.punctuation:
continue
else:
new_string += letter
return new_string
| true |
36820a394332863c004e35683353c86d581fab55 | faizalazman/UTArlingtonX--CSE1309x-Introduction-to-Programming-Using-Python | /Final Exam/Final Exam Part 3 (N letter dictionary).py | 2,657 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 1 13:33:45 2018
@author: Parmenides
"""
# =============================================================================
# Final Exam, Part 3 (N letter dictionary)
# 20.0/20.0 points (graded)
# Write a function named n_letter_dictionary that receives a string (words sep... | true |
070e48f8fcfb0722069f6c56c6fc1baaef4a079e | rwatsh/python | /codeacademy_proj/codeacademy/list_comprehension.py | 509 | 4.25 | 4 | __author__ = 'rushil'
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]
print doubles_by_3
# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,11) if x % 2 == 0]
print even_squares
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50
... | true |
2ccd980f63f90ec665ba214438aa90db57c736d6 | dayanandghelaro/practice_for_arbisoft | /basicPython.py | 2,453 | 4.40625 | 4 | """
VARIABLES:
variableName = value
"""
integer = 123
decimal = 12.3
string = "string"
boolean = True
# assignment
variableName = 12
# assignment with expression
variableName = otherVariableName operator someValue
"""
OPERATORS:
Addition: +
Subtraction: -
Multiplication: *
... | true |
aba7804090bdaa8d017dd1cf8592885eb86aa15e | helenle/Python | /fibonacci.py | 382 | 4.21875 | 4 | import math
# fibonacci
def fibonacci(n):
if not isinstance(n, int):
print "fibonacci is only defined for integers."
return -1
elif n < 0:
print "fibonacci is only defined for positive integers."
return -1
elif 0 <= n <= 1: # or if n == 0 or n == 1:
return 1
else:
return fibonacci(n -... | false |
3138940ce195de5ef13bfe7b7f6a297a117051fd | SarahLizDettloff/Mathematics | /Physics/bigfour.py | 2,590 | 4.34375 | 4 | def displacement_with_acceleration():
initial_velocity = float(raw_input("Enter the inital velocity of the object in m/s: \n"))
time = float(raw_input("Enter the time in seconds: \n"))
acceleration = float(raw_input("Enter the acceleration in m/s^2:\n"))
result = (float(initial_velocity) * float(time) +... | true |
3c6640ad9baad02e2a098269a9cb0fd2f0abc2dd | dpancho/leetcode_stuffs | /LeetcodeChallenges/easy/palindrome_num.py | 713 | 4.15625 | 4 | # To check if number inputed is the same forwards as it is backwards AKA palindrome
# x = 121
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# similar to reverse an int, just compare at the end.
# take x and store into separate ... | true |
7a59269681a3dd7d314575e7da273ff75e0218c6 | vish35/algorithms | /Level-3/cycle_in_graph.py | 1,780 | 4.28125 | 4 | #!/usr/bin/python
# Date: 2017-12-29
#
# Description:
# Program to check if there exists a cycle in a graph or not.
#
# Approach:
# - Graph has cycle if it contains a back edge(there is some other path which
# reaches to the same vertex from a source vertex).
# - This uses DFS approach to find back edge.
# - This is... | true |
a60b914cda1997cb8e7d1e7a015d3dc60d19b993 | Joes-BitGit/Leetcode | /leetcode/valid_paren.py | 1,519 | 4.25 | 4 | # DESCRIPTION
# Given a string containing only three types of characters: '(', ')' and '*',
# write a function to check whether this string is valid.
# We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must ... | true |
f31d566f815b4a3f79d4b00ee2a42f077b477756 | Joes-BitGit/Leetcode | /leetcode/longest_common_subseq.py | 1,613 | 4.15625 | 4 | # DESCRIPTION
# Given two strings text1 and text2, return the length of their longest common subsequence.
# A subsequence of a string is a new string generated from the original string
# with some characters(can be none) deleted without changing the relative order of the remaining characters.
# (eg, "ace" is a subseque... | true |
00db7034e92382db740054511b875d31a4b20869 | Anton-K-NN/Python-prakticum-Stepic | /ceasar crypt for dif alphabet.py | 1,780 | 4.1875 | 4 | '''
Реализуйте функцию caesar(text, key), возвращающую зашифрованный текст, работающую только с латинским алфавитом.
text - исходных текст, который надо зашифровать (или расшифровать)
key - ключ (сдвиг)
Ключ может быть отрицательным или больше 26
Из преобразуемого текста удаляются все пробелы и знаки препинани... | false |
5354f3c09a7ea0dc4815745bdbfa77975843dcd0 | Anton-K-NN/Python-prakticum-Stepic | /Practicum Numpy/Геометрическая прогр - вектор чисел.py | 570 | 4.21875 | 4 | '''
На вход подаются 3 числа (каждое с новой строки):
start
stop
n
Составьте список из n точек на отрезке [start, stop] в геометрической прогрессии, включая start и stop.
Округлите значения точек до 3 знака после запятой.
Результат сохраните в переменную Z.
'''
import numpy as np
start=int(input())
s... | false |
eb401e973c5fd01437ce19511b48dda51ed195de | anjaandric/Midterm-Exam | /task2.py | 970 | 4.3125 | 4 | """
=================== TASK 2 ====================
* Name: Product Of Digits
*
* Write a script that will take an input from user
* as integer number and display product of digits
* for a given number. Consider that user will always
* provide integer number.
*
* Note: Please describe in details possible cases
* in... | true |
b379d7433da0d408c5e56a8bd2c9051cee61fe2b | Sunno/interviewcake | /bracket_validator.py | 1,891 | 4.21875 | 4 | # Bracket Validator
# Just a bracket validator, this is the link https://www.interviewcake.com/question/python3/bracket-validator
import unittest
def is_valid(code):
# Determine if the input code is valid
# We'll use a list as a stack, it's the simpler way
stack = []
# Here we have our open... | true |
c392a5acbdc590ed92e4b9ae022b5b775ef152e3 | jodebane/PythonCode | /BostonTripPlanner | 2,557 | 4.25 | 4 | #!/usr/bin/python
print("You will be asked to rate your desire to see various tourist sights, by ranking types of sights on a scale of 1 to 4, 4 being the type of sight you most want to see, 4 being the type of sight you least want to see. You will also be asked how many days you are staying in this city")
artlist=["... | true |
865f5bfc1a9660ea8de54d2a0a9c37c0a97f2693 | aifulislam/Python_Demo_Third_Part | /lesson5.py | 1,627 | 4.1875 | 4 | #05/11/2020-------
#Function----------
def add(n1,n2):
return n1 + n2
n = 10
m = 20
result = add(n,m)
print(result)
#Function----------
x = 30
y = 40
result = add(x,y)
print(result)
print(add(2.50,6.50))
#Function----------
def sub(s1,s2):
return s1 - s2
x = 100
y = 50
sum = s... | false |
053e5e0d77941ea0d13a7f12fcd9d9ddfe307a32 | armasog/Project_Euler_Solutions | /1.py | 524 | 4.1875 | 4 | import unittest
'''
Challenge:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
class testSuite(unittest.TestCase):
def test_solution(self):
assert solution(10) == ... | true |
c8e905f7778a713f88da949f0af1a9d39471e01f | RafaelPerezMatos/VotingSystem | /Madlibs.py | 704 | 4.40625 | 4 | #string Connection (aka how to put strings toguether)
#suppose we want to create a string that says "subscribe to ____"
#youtuber = "Kylie Ying" #some string variable
# a few ways to do this
#print("subscribe to " + youtuber)
#print("subscribe to {}".format(youtuber))
#print(f"subscribe to {youtuber}")
"""------------... | true |
ee06139ffcd88f79b7c9a0bc7126088f61b3f1af | abhiiitcse/HackerRank | /Python/Functional/mapandlambda.py | 403 | 4.125 | 4 | cube = lambda x: x**3
def fibonacci(n):
ret_list = list()
if n>0:
ret_list.append(0)
if n>1:
ret_list.append(1)
if n >= 3:
a = 0
b = 1
for i in range(2,n):
ret_list.append(a+b)
temp = a + b
a = b
b = temp
return ... | false |
c8661b2aa80b2ac32cee09aa0c30bc5e327006a5 | munnamn/01-IntroductionToPython | /src/m6_your_turtles.py | 1,935 | 4.5 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Nihaar Munnamgi.
"""
########################################################################
# DONE:
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your... | false |
2c465c4d4f5c7e04806bef753dff033d12c208ff | hubrigant/python_exercises | /ex4/ex4.py | 266 | 4.3125 | 4 | #!/usr/bin/env python3
"""
W3Schools Python Exercises
Exercise 4
24 July 2020
Jon Williams
"""
from math import pi
r = float(input("Input the radius of the circle: "))
print("The area of the circle with radius {} is {}".format(str(r), str(pi * r**2)))
| true |
323a510fa8e250cbd3f7fbe753938c8d1478dd0d | Susanna501/Homework | /Homework28.py | 898 | 4.4375 | 4 | '''1. Create a python function factorial and import this
file in another file and print factorial.'''
from Susik import factorial2 as f
print(f(7))
'''2. Write a Python function tocalculate surface volume and area of
a cylinder(Գլան). V=πr^2h and A=2πrh+2πr^2 :'''
from Susik import cylinder_volume_and_area as cyl ... | true |
06ba5bb820f895d67b0370b59846f1ca1436f34f | szostiPL/kolo | /draw_methods.py | 538 | 4.3125 | 4 | def create_line(x, y):
"""
Returns list of tuples which are coordinates
of a line created in cartesian coordinate system
"""
return [(1,1),(2,2),(3,3)(4,4)]
def create_square():
"""
Returns list of tuples which are coordinates
of a square created in cartesian coordinate system
"""
... | true |
b51fdc7a0edab37a8b720a9b3a8e192ab569a23c | jlaufmann/python-fundamentals | /01_python_fundamentals/01_01_run_it.py | 1,139 | 4.59375 | 5 | '''
1 - Write and execute a script that prints "hello world" to the console.
2 - Using the interpreter, print "hello world!" to the console.
3 - Explore the interpreter.
- Execute lines with syntax error and see what the response is.
* What happens if you leave out a quotation or parentheses?
* How h... | true |
d6ee384ea6541eee98b5fcfef8772c504f9c13a6 | jlaufmann/python-fundamentals | /04_conditionals_loops/04_07_search.py | 1,137 | 4.25 | 4 | '''
Receive a number between 0 and 1,000,000,000 from the user.
Use while loop to find the number - when the number is found exit the loop and print the number to the console.
'''
magic_no = int(input("Enter an integer number between 0 and 1,000,000,000: "))
method = 'simple'
# method = 'fast'
guess_low = 0
guess_... | true |
34b9eb3a422d22dec6e0f585195aa47ca0e0b3f6 | jlaufmann/python-fundamentals | /03_more_datatypes/2_lists/03_10_unique.py | 1,284 | 4.34375 | 4 | '''
Write a script that creates a list of all unique values in a list. For example:
list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]
unique_list = [55, 'hi', 4, 13]
'''
# Example list:
list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]
'''
All this stuff is commented out because it is just too difficult to get a string from u... | true |
3e6059d11c6e02ce24cdfbeb5e6753f07d8917dd | jlaufmann/python-fundamentals | /03_more_datatypes/4_dictionaries/03_18_occurrence.py | 1,002 | 4.15625 | 4 | '''
Write a script that takes a string from the user and creates a dictionary of letter that exist
in the string and the number of times they occur. For example:
user_input = "hello"
result = {"h": 1, "e": 1, "l": 2, "o": 1}
'''
string_in = input("Enter your string: ")
# so that A and a are the same, convert string ... | true |
5998c9696b4ad3dd93cdae238e8f6516e55f4ad8 | jlaufmann/python-fundamentals | /02_basic_datatypes/1_numbers/02_04_temp.py | 447 | 4.4375 | 4 | '''
Fahrenheit to Celsius:
Write the necessary code to read a degree in Fahrenheit from the console
then convert it to Celsius and print it to the console.
C = (F - 32) * (5 / 9)
Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius"
'''
deg_F = float(input("Please enter temperature in de... | true |
f3b7818632d13f3ab51f9a1020ccf2382a82e9c5 | ivo-douglas/OlaMundo | /URI Programas/Age in Days.py | 807 | 4.4375 | 4 | # coding: utf-8
"""
Read an integer value corresponding to a person's age (in days) and print it in years, months and days,
followed by its respective message “ano(s)”, “mes(es)”, “dia(s)”.
Note: only to facilitate the calculation, consider the whole year with 365 days and 30 days every month.
In the cases of test th... | true |
675e2203367e209bdebc621a313cbc46e67f8a69 | bigorangedad/hogwarts | /main.py | 1,907 | 4.375 | 4 | """
list.append(x): 在列表的末尾添加一个元素。相当于a[len(a):] = [x]。
list.insert(i,x):在给定的位置插入一个元素。第一个参数是要插入的元素的索引,以a.insert(0,x)插入列表头部,a.insert(len(a),x)等同于a.append
list.remove(x):移除列表中第一个值为x的元素。如果没有这样的元素,则抛出ValueError 异常。
list.pop([i]):删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop()将会删除并返回列表中的最后一个元素。
list.sort(key=None,reverse=False):对列表中的元素进行排序... | false |
fc776359ce8fd44b0e2bdd58dab97a1603f5703a | sachinlohith/leetcode | /String/strobogrammaticNumber.py | 848 | 4.125 | 4 | """
https://leetcode.com/problems/strobogrammatic-number/description/
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", a... | true |
5fa2cea6a51c8a631c135040734d6b8fc1abd07a | vignesan-siva/python-project | /day5-time convertion problem.py | 1,755 | 4.21875 | 4 | #only enter valid number otherwise not properly respond
#hours to second
print("==========1) hours to second==========")
hr=int(input("enter no of hours:"))
def convert(hr):
hour=hr*60
return hour
print("second:",convert(hr))
#minutes to hour
print("=============2) minutes to hour==================")
... | true |
39e5ac0aaf7d255b7fad05047377e5aeae703108 | Shahidayatar/PythonLearn | /Constructors___15.py | 1,412 | 4.375 | 4 | #https://www.youtube.com/watch?v=ic6wdPxcHc0&list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3&index=55
class computer : # if you want to keep the class empty then use 'pass'
def __init__(self):
self.name= 'shahid' # we are making variables
self.age= 19
print(self.name, self.age)
... | true |
bdf8e6c6532ba8a06fc556c3a2fcb6048d55e67f | enterpriseih/Python100days | /day01_15/day09/triangle.py | 839 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 实例方法和类方法的应用
# @Date : 2019-07-13 22:41:54
# @Author : yaolh (yaolihui129@sina.com)
# @Link : https://github.com/yaolihui129
# @Version : 0.1
from math import sqrt
class Triangle(object):
"""docstring for Triangle"""
def __init__(self, a,b,c):
self._a = a
se... | false |
681fb2c333226985bcaa14db397687e6e12351a9 | izzyevermore/test-average-calculator | /main2.py | 796 | 4.15625 | 4 | # task 2
# Calculate a learners average mark
student_name = input("Please enter your name: ")
student_surname = input("Please enter your surname: ")
test1 = float(input("Please your mark for the first test: "))
test2 = float(input("Please enter your mark for the second test: "))
test3 = float(input("Please enter your... | true |
e1f5c724c7c5faa4c01d3ead8029a89191f3ce67 | Rammurthy5/random-topic-learnings | /composite_method.py | 1,399 | 4.375 | 4 | """
To understand & demonstrate composition. its an alternate approach to inheritance. to use only one or two methods
from a class, we can avoid inheritance, and go with composition
..date.. march 25 2020
..additional .. Understand the importance of total_ordering from functools module
"""
class A:
persis... | true |
d110080b0a3bb72270852dbd6092e641864d8b22 | Rammurthy5/random-topic-learnings | /duck_typing.py | 1,771 | 4.46875 | 4 | """
Duck Typing is helpful in returning some value nonetheless the type / class of the object. Objective is to get something
work based on behaviour rather having dependency on type of the object.
..date.. March 25 2020
..real-time eg.. we have a len() method in Python, which can return length of string, dict, l... | true |
5632e4f6a793e5660a1ca666530c033777686e16 | felipemaion/studying_python | /MaiQuete20220417.py | 1,613 | 4.125 | 4 | # Escreva um programa que calcule o preço a pagar pelo fornecimento
# de energia elétrica. Pergunte a quantidade de kWh consumida e o tipo de insta-
# lação: R para residências, I para indústrias e C para comércios. Calcule o preço a
# pagar de acordo com a tabela a seguir.
# Preço por tipo e faixa de consumo
# Tip... | false |
5819146d616965a9e209615769bd33f7755d6c05 | tnakagaw22/Introduction-to-Computer-Science | /factorial.py | 491 | 4.125 | 4 | number = 5
def factorial(number):
if number == 1:
return 1
else:
return number * factorial(number -1)
result = factorial(5)
print(result)
def iterPower(base, exp):
result = 0
while exp > 0:
if result == 0:
result = base * base
else:
result = re... | true |
09823770fe971ca2c6505750ca422201c5110a20 | jswoodburn/Ex14 | /rps_functions.py | 1,361 | 4.28125 | 4 | import random
# get user input
def get_user_choice(question_string="\nEnter your choice (r, p, or s): ", acceptable_answer=['R', 'P', 'S']):
while True: # fails after 3 attempts?
user_choice = input(question_string)
if user_choice.upper() in acceptable_answer:
return user_choice.upper... | true |
9205e997af7767698016b14cfcd9fdd949f439a3 | manuel-garcia-yuste/ICS3UR-Assignmentb-Python | /assigment2b.py | 393 | 4.4375 | 4 | #!/usr/bin/env python3
# Created by: Manuel Garcia
# Created on: September 2019
# This program calculates the surface area of the cube
def main():
length = int(input("Enter the length of the cube: "))
# process
surface_area = 6*length**2
# output
print("")
print("The surface area of the cub... | true |
35dd6500c70a59c8b655acbfe2e2d8667fb51700 | ashar-sarwar/python-works | /python_practice/filing2.py | 720 | 4.125 | 4 | filename='pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi=''
for line in lines:
pi+=line.rstrip()
print(pi)
print(len(pi))
filename='pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi=''
for line in lines:
pi+=line.strip()
print(pi)
print(l... | true |
a1bb86465b14c847ce05c7e22eb87f123bed4d74 | youngminpark2559/prac_ml | /flearning/003_001_numpy_array.py | 2,739 | 4.25 | 4 | # 003_001_numpy_array
# ======================================================================
# Numpy manages data as array and performs operations in array
# At this moment, array can be considered as vector or matrix mathematically
# ======================================================================
import num... | true |
1120102a7bd5bb2239193623ec7d0cbf2a06decd | andysain/_Project-Euler | /Problems/Problem019.py | 1,544 | 4.1875 | 4 | """You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs o... | true |
3dfb5ef5513de1172b741a69b154fde21d2ab84a | Aivrie/ping-pong | /pong.py | 2,893 | 4.1875 | 4 | # Procedural version of my ping pong game
'''
Ping Pong - A simple ping pong game built with procedural oriented programming coding style
'''
# Game 1 - Pong Game
import turtle
win = turtle.Screen()
win.title("Pong Game by Ivory")
win.bgcolor("white")
win.setup(width=800, height=600)
win.tracer(0)
# Score
score_... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.