blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c8a1104eaafbc5d6d5684d863470643a57da0b25 | cattiza/thinkpython2 | /Optional_Parameter.py | 1,045 | 4.125 | 4 | class Dog():
"""A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes. """
self.name = name
self.age = age
def sit(self):
print(self.name.title()+ " is now sitting")
def roll_over(self):
pr... | false |
6d0c94be6a853bb27bc1fa316a1248294bfa5599 | ArturRejment/snake | /scoreboard.py | 725 | 4.15625 | 4 | from turtle import Turtle
""" A class to display current score and game over message """
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.score = -1
self.color("white")
self.hideturtle()
self.goto(0, 250)
self.write_score()
# Update and w... | true |
e0ee6cd8443b7cb52ad85246fccc8c5a4420f4f4 | Axaxaxas-Mlo/Python101 | /Lists.py | 1,332 | 4.375 | 4 | Lista1 = ['Elemento 1',2]
print(Lista1)
print(type(Lista1[0]))
cuadrados = [1,4,9,16,25]
print(cuadrados)
slice = cuadrados[:-1] # No entiendo bien como funciona, si es una clase porque se define asi?
print(slice) # Slice realmente es una lista, que onda con esto?
cuadrados[2] = 'dos'
print(cuadrados)
... | false |
c75efc7afdbd281bd93863f9f9d67194db9a1046 | Axaxaxas-Mlo/Python101 | /elseifLoop.py | 1,200 | 4.3125 | 4 | x = -2
if x < 0:
print ('x < 0') # checa si es menor a cero
elif x == 0:
print ('x is zero') # si no es verdadero que x < 0, checa si x = 0
elif x == 1:
print ('x is one') # si no es igual a cero, checa si es uno
else:
print ('Ninguno de los anteriores es verdadero') # cuando ningun valor es correcto
... | false |
61ebe352704ce9bbbf643534cacb3287214725e7 | dnieafeeq/mysejahtera_clone | /Day2/chapter32.py | 705 | 4.46875 | 4 | theCount = [1, 2, 3, 4, 5]
fruits = ['banana', 'grape', 'mango', 'durian']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in theCount:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# am... | true |
2580f8a9daee003faf559e5e880ecc12c7170e83 | Rantpel/Batch-Four | /leap year.py | 272 | 4.375 | 4 | #Purpose of the program
print("Program to Determine is a given year is a leap year")
year=int(input("Enter yearto be Checked."))
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year")
else:
print("The year isn't a leap year!")
| true |
5cb76103b8e0c3142b9530c0d8f4c3498ba3f439 | Rantpel/Batch-Four | /simple int.py | 573 | 4.3125 | 4 | #The purpose of the Program
print("this is a program to find Simple Interest")
#Ask the user to input the principal amount
print("Input the principal amount")
principal=int(input("the value of principal:"))
#Ask the user to input the rate
print("Input the principal amount")
rate=float(input("the value of rate:")... | true |
bdf46483e177e6e935750d552f5448f10a7d5bf2 | YXMforfun/_checkio-solution | /home/median.py | 1,251 | 4.15625 | 4 | """
A median is a numerical value separating the upper half of a sorted array of numbers from the lower half.
In a list where there are an odd number of entities, the median is the number found in the middle of the array.
If the array contains an even number of entities, then there is no single middle value, in... | true |
a109be86b2888df9b07f5a4a8b3cd254f7f99626 | sek550c/leetcode | /py/121BestTimeBuyAndSell.py | 901 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [... | true |
1805e80b2a72b2bec016f4a3180cdd649c3ecde6 | sek550c/leetcode | /py/27RemoveElement.py | 772 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave b... | true |
70979eb5db49ade6b309de53f1ca5eba96bca979 | sek550c/leetcode | /py/118PascalTriangle.py | 954 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
import time
def getNum(row, col):
if row == col or col == 1: return 1
else: return getNum(ro... | true |
b0d56744efd572d799a2a3d43924166ce2de0af0 | sek550c/leetcode | /py/283MoveZeros.py | 1,024 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do th... | true |
cebbe4aaacb3da2130490bb808a877c9272f2eee | sek550c/leetcode | /py/350IntersectionOfTwoArray.py | 2,526 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
... | true |
9a17391792811cb4a9ec80bb949315b09340b224 | Sharmaraunak/python | /wk215.py | 363 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 8 14:24:17 2018
@author: raunak
"""
##print("enter the base: ")
#base = eval(input())
#print("enter the exponential power: ")
#exp = int(input())
def iterPower(base,exp):
result =1
while exp > 0:
result = result*base
print(r... | true |
08a24f5866f3f3b9c14edfcdf459134bc530df3b | deepanshurana/Python-Codes | /ErrorsAndExceptions.py | 987 | 4.1875 | 4 | """
There are two kinds of errors: SyntaxError and Exceptions.
Even if the statement or expression is syntactically correct,it may cause
an error when an attempt is made to execute it.
It is possible to handle selected exceptions. (using try and except)
firstly, the try clause is executed. If no exceptions, then excep... | true |
07323696d37d37669753cca7eea3a943bf1adf78 | deepanshurana/Python-Codes | /max difference in an array.py | 500 | 4.125 | 4 | print('--'* 50)
list = [] #initialising list
size_of_array = int(input('ENTER THE TOTAL ELEMENTS IN AN ARRAY: ')) #for the total size of an array
for i in range(0,size_of_array):
value = int(input('Enter the %d element: ' % (i+1)))
list.append(value) #appending the list
print('The list is :' , lis... | true |
3f62423a1233a8009f15e13e29e05c8c9fa5453f | wrilka/python-beginner-projects | /A simple calculator/final calculator.py | 866 | 4.3125 | 4 | def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
def exponent(n1, n2):
return n1 ** n2
operation = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
"**": exponent,
}
def calculator():
n1 = int(input("Input t... | false |
13a4a85fe117384d118cd3fe2f3a56d88d5747b0 | nikgun1984/Data-Structures-in-Python | /Queues and Stacks/Stack.py | 1,159 | 4.15625 | 4 | # Stack implementation using LinkedList
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def push(self, value):
new_node = Node(value)
if ... | true |
15369703773202192231181b1c5940dfb8488fca | patrick-du/Notes | /Courses & Books/Grokking Algorithms/breadth_first_search.py | 2,680 | 4.25 | 4 | # Breadth-first search (BFS): a graph algorithm to find the shortest path b/w 2 nodes
# Breath-first search answers 2 questions:
# - Is there a path from node A to node B?
# - What is the shortest path from node A to node B?
# Example Use Case
# - Checkers AI to calculate fewest moves to victory
# - Spell chc... | true |
df90b293ace1bab8e500c6ab24d6a008170b2666 | mlama007/4RockPaperScissors | /4ROCK_PAPER_SCISSORS.py | 1,193 | 4.15625 | 4 | """This is a simple game of rock, paper, scissors"""
from random import randint
from time import sleep
options = ["R", "P", "S"]
LOSE = "You lost!"
WIN = "You won!"
def decide_winner(user_choice, computer_choice):
print "Your choice: %s" % user_choice
print "Computer selecting..."
sleep(1)
print "Com... | true |
a960c05cf9b1f541bc638170cf8ecb616c00cf6d | Sandhya788/Basics | /python/password5.py | 394 | 4.15625 | 4 | incorrectPassword= True
while incorrectPassword:
password = input("type in your password")
if len(password < 8):
print("your password must be 8 characters long")
elif noNum(password == False):
print("you need a number in your password")
elif noCap(password == False):
print("you n... | true |
3563aad76f85735b0d143c2fa6d3319e47e179bf | wurainren/leaningPython | /com/wurainren/base/dataType.py | 1,274 | 4.46875 | 4 | # -*- coding:utf-8 -*-
#Python内置的一种数据类型是列表:list。
# list是一种有序的集合,可以随时添加和删除其中的元素。
classmates = ['Michael', 'Bob', 'Tracy']
# query 通过下标;切片
print(classmates[0])
print(classmates[-1])
print(classmates[:1]) #===》这里切出来的结果,还是一个list
# count 通过len()函数 获取list元素的个数
print(len(classmates))
# add 通过append()函数,追加元素到末尾;insert()函数... | false |
0ba02a9253e23eb402cbb15f8b317256283bc025 | xen0bia/college | /csce160/book_source_code/Chapter 10/exercise1/exercise1.py | 1,785 | 4.65625 | 5 | # 1. Pet Class
# Write a class named Pet , which should have the following data attributes:
# • _ _ name (for the name of a pet)
# • _ _ animal_type (for the type of animal that a pet is. Example values are ‘Dog’, ‘Cat’,
# and ‘Bird’)
# • _ _ age (for the pet’s age)
# The Pet class should have an _ _ ... | true |
bbb14262a5f93148882b0a0c0b91cb224e769682 | xen0bia/college | /csce160/lab5/payroll.py | 876 | 4.15625 | 4 | '''
Zynab Ali
'''
REG_HRS = 40.0 # Hours at regular pay before overtime starts
OVERTIME_RATE = 1.5 # Overtime payrate multiplier
def main():
hours_worked = float(input('\nEnter the number of hours worked this week: '))
hourly_rate = float(input('Enter the hourly pay rate: '))
if hou... | true |
989d12e0d08597a26cb87d17c91b37671a213a2f | githubcj79/nisum_test | /answers.py | 1,755 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Ejercicio 1
# Write a Python program to square and cube every number in a given list of integers using Lambda.
# Original list of integers:
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square every number of the said list:
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Cube every num... | true |
909de2fb5af980a531f87002206b5b0a8972b2a7 | Zuiveraar/Proyectos-y-trabajos-Codecademy- | /Standalones/fibonacci.py | 1,340 | 4.21875 | 4 | def fibonacci(n):
if n is 1:
return 1
if n is 0:
return 0
fibValue = fibonacci(n-1) + fibonacci(n-2)
if fibValue not in alreadySeen:
alreadySeen.append(fibValue)
return fibValue
while True:
alreadySeen = []
choice = input("Do you want to generate fibonacci numbe... | false |
729b4259757b68b51fd036229495ec6b9108d7e1 | tal21-meet/meet2019y1lab2 | /MEETinTurtle.py | 1,412 | 4.15625 | 4 | import turtle
# Everything that comes after the # is a
# comment.
# It is a note to the person reading the code.
# The computer ignores it.
# Write your code below here...
turtle.penup() #Pick up the pen so it doesn’t
#draw
turtle.goto(-200,-100) #Move the turtle to the
#position (-200, -100)
#on... | false |
7c68b401fcd371aae138cbf0e3ebd2472985e591 | im-swapnilb/python | /app3-part11.py | 2,935 | 4.34375 | 4 | """
Problem statement :
Ask the user how many floating point numbers with 5 integer digits and two decimal digits the program should accept.
That means you need to check if the number entered by the user has 5 digits and two decimal digits to be accepted.
Your program should accept five of them. Add the numbers and dis... | true |
799b0d3dfc32ffbf001cda74455b22230e7ae94b | im-swapnilb/python | /pythonTest1/create_dictionary.py | 1,046 | 4.3125 | 4 | """
Create dictionary with different key-values and print it
@Author Swapnil_Bandgar, Student_id : 500186962
"""
# creating dictionary with different approach and datatype
def create_dict():
# creating empty dictionary
dict4 = {}
# dictionary with multiple data types
dict1 = {"Name": "Swapnil", "Cour... | true |
5dc54c2f2a1a94ef286021646bb4639060b17356 | im-swapnilb/python | /pythonTest1/operations.py | 420 | 4.3125 | 4 | # Python program for practical application of sqrt() function
# import math module
import testMathFunc
# function to check if prime or not
def check(n):
if n == 1:
return False
# from 1 to sqrt(n)
for x in range(2, (int)(testMathFunc.sqrt(n)) + 1):
if n % x == 0:
return False... | true |
9188e2bac20ff5ffc20a18924629faac35eccd6b | Nethermaker/school-projects | /intro/dictionary_assignment.py | 2,734 | 4.28125 | 4 | # 1. Create a dictionary that connects the numbers 1-12 with each
# number's corresponding month. 1 --> January, for example.
months = {1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:... | true |
63f9d76cd6887ae1e04bb01c9c1e7f5ad2d91270 | Nethermaker/school-projects | /adv/crash_course.py | 1,904 | 4.125 | 4 | print 'Welcome to Advanced Programming'
#Math
print 3 + 4
print 3 - 4
print 3 * 4
print 3 / 4
name = 'Handelman'
number = 27
number2 = 15
print 'My name is {}.'.format(name)
#your_name = raw_input('What is your name? ')
#print 'Hello there, {}!'.format(your_name)
def average_of_three(x,y,z):
... | true |
2822851327677da64c8304bc70604beb3f2c46eb | Nethermaker/school-projects | /intro/warmup_day4.py | 870 | 4.3125 | 4 | # The following program is supposed to ask a user how much the meal
# cost, how many people ate, and what percentage they are tipping, and
# should return the amount each person should pay.
# Unfortunately, there are several errors in the program. Can you find
# them all? Here is what the program should look like ... | true |
05babfc47f24daf65034ad088d157e909125f077 | acalzadaa/python_bootcamp | /week03 input and coditionals/friday.py | 1,316 | 4.34375 | 4 | # end of week project
# making a calculator!
# 1. Ask the user for the calculation they would like to perform.
# 2. Ask the user for the numbers they would like to run the operation on.
# 3. Set up try/except clause for mathematical operation.
# a. Convert numbers input to floats.
# b. Perform operation and prin... | true |
e7c0d6a1deed8429577c1ecf9100226f75445668 | acalzadaa/python_bootcamp | /week08 Efficiency/tuesday.py | 1,575 | 4.71875 | 5 | # Lambda functions, otherwise known as anonymous functions,
# are one-line functions within
# >>> lambda arguments : expression
# >>> lambda arguments : value_to_return if condition else value_to_return
# Using a Lambda
# using a lambda to square a number
print( ( lambda x : x**2) (4) )
# Passing Multiple Argument... | true |
909c816c70dc94e74ad37588623cca19493a0a46 | acalzadaa/python_bootcamp | /week06 data collections and files/tuesday.py | 1,912 | 4.46875 | 4 | # Tuesday: Working with Dictionaries
#Adding New Information
# adding new key/value pairs to a dictionary
car = {"year" : 2018}
car["color"] = "Blue"
print(f'year {car["year"]} , color {car["color"]}')
#Changing Information
# updating a value for a key/value pair that already exists
car["color"] = "Red"
print(f'yea... | true |
4b5e34a4a0f10ff3034e4d82e7c61811636bfdfe | acalzadaa/python_bootcamp | /week08 Efficiency/week_challenge.py | 704 | 4.25 | 4 | # For this week’s challenge, I’d like you to create a program that asks a user to input a number
# and tells that user if the number they entered is a prime number or not.
# Remember that prime numbers are only divisible by one and itself and must be above the number 2.
# Create a function called “isPrime” that you ... | true |
a2e299f33ca165eb421f24d80ef8b9996348fc54 | acalzadaa/python_bootcamp | /week04 lists and loops/tuesday.py | 1,551 | 4.28125 | 4 | # writing your first for loop using range,
# COUNTS UP TO... BUT NOT INCLUDING
print("1st Exercise ---------------------")
for num in range(5):
print(f"Value: {num}")
# providing the start, stop, and step for the range function
print("2nd Exercise ---------------------")
for num in range(2, 10, 2):
print(f"Va... | true |
d802058971fb6d6805caf1bf4a08f9ddd8c31dcb | ksambaiah/Programming | /python/lists/listsComp.py | 434 | 4.375 | 4 | #!/usr/bin/env python3
# List comprehension is fun
if __name__ == "__main__":
# populate list with some values
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
# Get all even elements
even = [i for i in a if i % 2 == 0]
print(a)
print("Even numbers in the above list")
print(eve... | true |
024d2adce8e739fb8aaaedd3da198a789efc7e70 | usamayazdani/Python | /Practice/Important/codes/Q1(proper_index_in_list).py | 1,081 | 4.34375 | 4 | """function that inserts a value in
the list at its proper position (index) such that after inserting the value the list is still sorted. The list can
either be in ascending or descending order, your function should work for both types. You can write a
separate function to which would tell you in which order the list i... | true |
069f6ae77c525f691cc557fe3b2ba713017e6de9 | usamayazdani/Python | /Assignments/Assignment 005/Code/code_get_comany_names.py | 1,461 | 4.25 | 4 | """function you need to write is called “get_companies”. It takes the list of
dictionaries representing companies along with a dictionary representing
location. This dictionary will have “City” and “Country” as its keys. The values of
these keys can be any strings. Your function should return a list of companies
which ... | true |
2ebde5681e35e4dbb7233320f4bb721fa1c01685 | usamayazdani/Python | /Practice/reverse_given_number.py | 638 | 4.375 | 4 |
# This function take input from the user and than pass into the function .
# the output is the reverse of the number .
# This will run for both positive and negative integers
num = int(input("Enter any positive or negative number : "))
def reverse_a_given_integer_num(num):
if num < 0:
num = -1*num
... | true |
a601e1cd64b8b1e77d02d22bddc50ff57b6c12ed | ZahraFarhadi19/Leetcode-practices | /Unique Email Addresses/Unique-Email-Addresses.py | 1,469 | 4.15625 | 4 | '''
Every email consists of a local name and a domain name,
separated by the @ sign.
For example, in alice@leetcode.com,
alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name... | true |
000c5f4b6aebd1b321becfaf011f4fdd70433a84 | jjnorris31/metodosNumericos | /flip_boolean.py | 497 | 4.40625 | 4 | """
Create a function that reverses a boolean value and returns the string "boolean expected" if another variable type is given.
Examples
True ➞ False
False ➞ True
0 ➞ "boolean expected"
None ➞ "boolean expected"
"""
def reverse(arg):
if type(arg) == type(0) or arg == {}:
result = "boolean expected"
... | true |
b45a147939f5983102fe08ac10871675f5a99c88 | jjnorris31/metodosNumericos | /even_generator.py | 241 | 4.1875 | 4 | """
Using list comprehensions, create a function that finds all even numbers from 1 to the given number.
Examples
8 ➞ [2, 4, 6, 8]
4 ➞ [2, 4]
2 ➞ [2]
"""
def find_even_nums(num):
return [i for i in range(1, num + 1) if i % 2 == 0]
| true |
bbc409b2e9d9212d4c40e738aca76d4767ccce81 | jjnorris31/metodosNumericos | /array_of_arrays.py | 607 | 4.4375 | 4 | """
Create a function that takes three arguments (x, y, z) and returns a list containing sublists (e.g. [[], [], []]), each of a certain number of items, all set to either a string or an integer.
x argument: Number of sublists contained within the main list.
y argument Number of items contained within each sublist(s).
... | true |
72d30654274571f5fad472c4090b8d2fd414682a | jjnorris31/metodosNumericos | /is_anagram.py | 281 | 4.15625 | 4 | """
Write a function that takes two strings and returns (True or False) whether they're anagrams or not.
Examples
'cristian', 'Cristina' ➞ True
'Dave Barry', 'Ray Adverb' ➞ True
'Nope', 'Note' ➞ False
"""
def is_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
| true |
5fdda35bdd889857a3dfb20bf12707f03b9b6ab3 | abhigyan709/dsalgo | /OOPS_CONCEPT/OOP Principles/class_progrm_21.py | 656 | 4.28125 | 4 | # Prinitig an object
class Shoe:
def __init__(self, price, material):
self.price = price
self.material = material
s1 = Shoe(1000, "Canvas")
print(s1)
# the above print of s1 object is not in more readable format, it gives hexagonal form
# to implement the more readable format for prining the obje... | true |
feed600182879d3f19c072e7275306cc97010d4a | abhigyan709/dsalgo | /Python_basics/while_loops.py | 323 | 4.28125 | 4 | # while loop repeats a block of code as long as a particular condition remains true
# a simple value
current_value = 1
while current_value <= 5:
print(current_value)
current_value += 1
# letting the user to choose when to quit
msg = ''
while msg != 'quit':
msg = input("What's your message? ")
print(ms... | true |
44590fe7a33d99a7a8e21a5200b78602502753ab | abhigyan709/dsalgo | /OOPS_CONCEPT/OOP Principles/class_program_20.py | 464 | 4.125 | 4 | # just like the ballons and ribbons, we can make one reference variable refer to another object.
# now any change made through this refernce varible will not affect the old object.
class Mobile:
def __init__(self, price, brand):
self.price = price
self.brand = brand
mob1 = Mobile(1000, "Apple")
mo... | true |
dfca9ad207774c458ad78c9b0477d2c31cadb154 | AnoopPS02/Launchpad | /P5.py | 257 | 4.34375 | 4 | *program that asks the user for a phrase/sentence & Print back to the user the same string, except with the words in backwards order*
String="My name is Anoop"
String1=String.split()
String2=String1[::-1]
Ans=""
for i in String2:
Ans=Ans+" "+i
print(Ans)
| true |
7ce893d37b6c60644004bf0c01bbbb09d5fe194c | informramiz/Unscramble-Computer-Science-Problems | /Task1.py | 1,583 | 4.15625 | 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... | true |
3497a9d3abc8ec8d38e813b741749ce120525950 | apugithub/MITx-6.00.1x-Programming-Using-Python | /Week-3/Hangman_Is The Word Guessed.py | 735 | 4.125 | 4 | ##### 1st Approach:
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN... | true |
e2309c0e661dd89b00106cc6d4e7131a3e342826 | JAYARAJ2014/python | /inheritance.py | 814 | 4.34375 | 4 | class Animal:
def __init__(self):
print("Animal Constructor")
self.age = 1
def eat(self):
print("Eat")
class Mammal(Animal):
def __init__(self): # THis will override the parent class constructor.
# invoke constructor of the superclass / parent class.
super().__ini... | false |
db97ad39dc4c39620b3285751f375d4c75fd167a | himu999/Python_oop | /H.inheritance/c.inheritance.py | 1,092 | 4.15625 | 4 | class Vehicle:
"""Base class for all vehicles"""
def __init__(self, name, manufacturer, color):
self.name = name
self.color = color
self.manufacturer = manufacturer
def drive(self):
print("Driving", self.manufacturer, self.name)
def turn(self, direction):
print... | true |
e730a2f4f5e0e752cb6304b604366dbce9d6ac12 | Jbranson85/Python | /drawface.py | 1,142 | 4.15625 | 4 | '''
drawface.py
Jonathan Branson, 3/27/17
This program will draw a face that has 2 eyes, nose and a mouth, by using the
tkinter mondule to draw the shapes on a canvas
'''
from tkinter import *
##Builds Frame
root = Tk()
##Creates the Canvas, for shapes to be drawn on
background = Canvas(root, ... | true |
45f38da8b7407cfb94885ddfc4f843e945167bf8 | 666sempron999/Abramyan-tasks- | /Series(40)/18.py | 717 | 4.15625 | 4 | """
Series18. Дано целое число N и набор из N целых чисел, упорядоченный
по возрастанию. Данный набор может содержать одинаковые элементы.
Вывести в том же порядке все различные элементы данного набора.
"""
import random
resultList = list()
N = int(input("Введите число элементов - "))
for x in range(0,N... | false |
721ac2a3f410a889ab412752fd7db8b26456f6e1 | 666sempron999/Abramyan-tasks- | /Begin(40)/21.py | 1,115 | 4.125 | 4 | '''
Даны координаты трех вершин треугольника: (x 1 , y 1 ), (x 2 , y 2 ), (x 3 , y 3 ).
Найти его периметр и площадь, используя формулу для расстояния меж-
ду двумя точками на плоскости (см. задание Begin20). Для нахождения
площади треугольника со сторонами a, b, c использовать формулу Герона:
S =
√ p·(p − a)·(p... | false |
97db6409c609d5f3c1aa4955fdd6c1face2762b1 | 666sempron999/Abramyan-tasks- | /Boolean(40)/29.py | 913 | 4.34375 | 4 | '''
Boolean29 ◦ . Даны числа x, y, x 1 , y 1 , x 2 , y 2 . Проверить истинность высказыва-
ния: «Точка с координатами (x, y) лежит внутри прямоугольника, левая
верхняя вершина которого имеет координаты (x 1 , y 1 ), правая нижняя —
(x 2 , y 2 ), а стороны параллельны координатным осям».
'''
x = int(input("Введи... | false |
d59cba0dd4e09ea0217dbabeea96034229437e00 | 666sempron999/Abramyan-tasks- | /For(40)/39.py | 680 | 4.125 | 4 | '''
For39. Даны целые положительные числа A и B (A < B). Вывести все целые
числа от A до B включительно; при этом каждое число должно выводиться
столько раз, каково его значение (например, число 3 выводится 3 раза).
'''
A = int(input("Введите A "))
B = int(input("Введите B "))
while A > B:
A = int(input("В... | false |
9e47d26e85a5071ba3860247c5f69e0ab27bafa7 | binnllii/classprojects | /cis122 HW/P4_while1.py | 267 | 4.3125 | 4 | hint = "Enter name of country or 'Quit':"
country_list = [ ]
nation = input(hint)
while nation != 'Quit':
country_list.append(nation)
nation = input(hint)
print()
print('Countries')
for country in country_list:
print(country)
print()
print('Finished')
| false |
3d3a23a1023bc4abee851a683211f05730818597 | binnllii/classprojects | /cis122 HW/P2_list.py | 283 | 4.125 | 4 | majors_list = ["Computer Science", "Biology", "Journalist", "Business", "Chemistry"]
n_majors = len(majors_list)
print('There are', n_majors, 'majors in my list.')
print(" ")
print("Majors")
for n_majors in majors_list:
print(" ", n_majors)
print("--------")
print("Finished")
| false |
ac7d3d379427f91dc20dc11731723ec3ecce0d36 | DaveRichmond-/sabine_learn_to_code | /pfk_exercises/review_chpt1_8.py | 1,913 | 4.21875 | 4 | # Chapter 2: Variables --------------->
# how much money would you have in your piggy bank, if you had 7 one dollar bills, 34 quarters, 71 dimes, 112 nickels and 42 pennies?
# create an equation below to calculate the result and store it in a variable called TOTAL.
# you can use the variables that I created for you:
... | true |
ecbef1dd6f3e8539940512a81a88dfdeeb130c7d | zeeshan13026/PythonRefresher | /14_destructuring_variables/code3.py | 280 | 4.125 | 4 | people = [('Bob', 42, 'Mechanic'), ('James', 24, 'Artist'),('Harry', 32, 'Lecturer')]
for name, age, job in people:
print(f"{name} is {age} year old and working as a {job}")
for person in people:
print(f"Name : {person[0]}, Age : {person[1]}, Profession : {person[2]} ") | false |
6cb8ca0e88370851e98b55c3778747352feb172e | ectrimble20/PythonExerciseCode | /PracticePython/ElementSearch.py | 2,609 | 4.1875 | 4 | # ElementSearch.py
import random
"""
Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to
largest) and another number. The function decides whether or not the given number is inside the list and
returns (then prints) an appropriate boolean.
Extras:
Use binary... | true |
502405c48c8a71d517817d1074c1ad766a99ead8 | ectrimble20/PythonExerciseCode | /PracticePython/Divisors.py | 689 | 4.34375 | 4 | # Divisors.py
"""
Create a program that asks the user for a number then prints out a list of all the divisors of that number
...divisor is a number that divides evenly into another number, ex 13 is a divisor of 26 because 26 % 13 == 0
"""
num = int(input("Enter a number to get it's divisors: "))
l = []
# for n in ran... | true |
176f1237183f9733598b42ef847ce809c188da52 | samarla/LearningPython | /fibonacci.py | 385 | 4.40625 | 4 | user_input = int(input('enter how many fibonacci numbers to be printed (not less than 3): \n'))
fibonacci = [1, 1]
def append_fibonacci(n):
"""this function appends the next fibonacci element into the list """
next_number = fibonacci[n-1]+fibonacci[n-2]
fibonacci.append(next_number)
for i in range(2, us... | true |
c7a67c23b2aae88e039c045f3dae89fe6b372e5e | samarla/LearningPython | /factorial using function.py | 289 | 4.25 | 4 | number = int(input('enter any number: '))
def factorial(n):
if n == 1: # The termination condition
return 1 # The base case
else:
res = n * factorial(n-1) # The recursive call
return res
print('the factorial of given number is: ',factorial(number))
| true |
e7847ad5d3351a90a5728fa84f6657f830663cec | mokpolar/FluentPython | /ch12_MixedIn.py | 1,451 | 4.1875 | 4 | """
Python MixedIn 클래스에만 다중 상속을 사용
http://brownbears.tistory.com/149
"""
class ToDictMixin:
def to_dict(self):
""" __dict__ 은 상속받은 value에 대해 dict타입으로 보여줌"""
print("to_dict", self.__dict__)
return self._traverse_dict(self.__dict__)
def _traverse_dict(self, instance_dict):
output... | false |
3b4b7774719a9a625ac876df22fa0c8240f4b543 | SonoDavid/python-ericsteegmans | /CH7_lists/indexSmallest.py | 1,080 | 4.40625 | 4 | def index_smallest_of(sequence, start=0):
"""
Return the position of the smallest element in the
given sequence starting from the given position.
- If several smallest elements can be found, the
function return the position of te leftmost
smallest element.
- None is return if no such sm... | true |
999b4c25b114ca8354eac7a2d3f4ea6ad6c18512 | SonoDavid/python-ericsteegmans | /CH4_strings/calc_num_digits.py | 504 | 4.34375 | 4 | # Calculate the sum of the digits in an integer number
# in decimal format
# - The program keeps on prompting for a non-negative
# integer number until it finally gets one
number = ""
while not str.isdigit(number):
number = input\
("Enter a non-negative number: ")
digit_sum = 0
current_pos = 0
whil... | true |
3d390d7d50f009bf9aaa30677332ed3d637a44d5 | SonoDavid/python-ericsteegmans | /CH1_integer_arithmetic/leapyear.py | 411 | 4.28125 | 4 | # Check whether a given year is a leap year.
# A year is a leap year if it is a multiple of 4 and
# not a multiple of 100, or it is a multiple of 400.
#
# Author: Joachim David
# Date: June 2019
year = int(input("Enter the year to examine: "))
if ((year % 4 == 0) and not (year % 100 == 0)) or (year % 400 == 0):
... | true |
31f9ea558320ac9863922444f2782c760d4e9369 | mpreddy960/pythonPROJECTnew | /padma/os_module.py | 2,570 | 4.125 | 4 | #chage current path using : chdir()
import os
# Functio to Get the current
# working directory
def current_path():
#print("Current working directory before")
print(os.getcwd())
print()
# Driver's code
# Printing CWD before
print("current working directory before")
current_path()
# Changing the CWD
os.chdir('../... | false |
ae60d94e8142658451e6f87f8d7f0c72d485eb2c | mpreddy960/pythonPROJECTnew | /list_functions.py | 1,036 | 4.375 | 4 | # Python program to print positive numbers in a list
fig = [6,5,5,4,3,-7,-8,-9,4]
print(fig)
f = []
def get_ele(fig):
"""teddyjjjj"""
for ty in fig:
if ty >=0:
f.append(ty)
print(ty, end=',')
return f
# first to last element
g = get_ele(fig)
print(get_ele.__doc__)
print(g... | false |
0f42460db3ed7c9ea2ae8c7f5d79f781d787c936 | 1141938529/ClassExercises | /week01/day02/OrdChr.py | 566 | 4.1875 | 4 | # 使用ord函数找出1,A,B,a,b的ascII码
print("1的ASCII码为:",ord('1'))
print("A的ASCII码为:",ord('A'))
print("B的ASCII码为:",ord('B'))
print("a的ASCII码为:",ord('a'))
print("b的ASCII码为:",ord('b'))
# 使用chr函数找出40,59,79,85 90 所对应的字母
print("----------------")
c = 40
print("40的ASCII码为:",chr(40))
print(str(c)+"的ASCII码为:",chr(c))
def Ascll(c):
... | false |
6ed5fe4e0dfce4016edc2301039318c74e91f344 | 1141938529/ClassExercises | /week01/day03/03hk2.12.py | 866 | 4.125 | 4 | # 打印表格
import math
print(format("a", "<8s"), end=(""))
print(format("b", "<8s"), end=(""))
print("a ** b")
for i in range(5):
print(format(i+1,"<8d"),end=(""))
print(format(i + 2, "<8d"),end=(""))
print(format((i+1)**(i+2), "<8d"))
# 2.13 分割数字
value = eval(input("enter an integer:"))
qian = value//1000
b... | false |
801faa729dc97d01fc50f8bf3a112f56777a6689 | EmpowerSecurityAcademy/daily_exercises | /lambda_operator/lambda_operator.py | 610 | 4.3125 | 4 | # list comprehensions follow the format
# [dosomething(num) for num in array if some_condition_is_true]
# use a list comprehension to return only even numbers
def even_numbers(array_numbers):
return [num for num in array_numbers if num % 2 == 0]
# use list comprehension to return words starting with the letter "a"
... | true |
720f47b5f02345025baf6102fa5b1550003e35fd | tainenko/gliacloud | /part1/Counting.py | 1,631 | 4.15625 | 4 | '''
Counting
Given a list of urls, print out the top 3 frequent filenames.
ex.
Given
urls = [
"http://www.google.com/a.txt",
"http://www.google.com.tw/a.txt",
"http://www.google.com/download/c.jpg",
"http://www.google.co.jp/a.txt",
"http://www.google.com/b.txt",
"https://facebook.com/movie/b.txt",
"http://yahoo.com/123... | false |
d78278d86a8e2b522e1845cb876fb9f9c85132f9 | flavienfr/bootcamp_ml | /day00/ex00/sum.py | 547 | 4.1875 | 4 | def sum_(x, f):
"""Computes the sum of a non-empty numpy.ndarray onto wich a function is
applied element-wise, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
f: has to be a function, a function to apply element-wise to the
vector.
Returns:
The sum as a float.
None if x is ... | true |
8e4a98d01dafe2d5845a965a2f2e4ba3456bbbcb | sanyamb22/python-101 | /insertionSortAlgo.py | 1,132 | 4.34375 | 4 | # INSERTION SORT ALGORITHM
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key <= arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# driver code
arr = [12, 11, 13, 8, 10]
print("array before sorting :"... | false |
d48bd9fab26d6876b882c9cb209a102e83d00a4a | Ciwonie/python_cs150 | /cs150/week_6/project_2.py | 1,472 | 4.34375 | 4 | # This project works with while loops and inputs . Your program will generate a random value, and ask for your guess.
# Upon submitting your guess, the program will return back if your guess is too high or too low.
# This will continue until you guess the correct number in which the program will output:
# "Correct con... | true |
9f25a9044a4f76db8a928a63f48864c62a383bfb | yangroro/gitpractice2 | /예제1.py | 250 | 4.125 | 4 | def is_odd(number):
if number % 2 == 1: # 2로 나누었을떄 나머지가 1이면 홀수이다.
return True
else:
return False
is_odd(3)
True
is_odd(4)
False
is_odd = lambda x: True if x % 2 == 1 else False
is_odd(3)
True
| false |
233a31e57427b5f4b0566215076380cd209a0365 | jatinsumai1104/Essence | /ml_model/text-module/readCsv.py | 1,501 | 4.125 | 4 | # importing csv module
import csv
# csv file name
filename = "aapl.csv"
# initializing the titles and rows list
fields = []
rows = []
# reading csv file
with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
# extracting field nam... | true |
62542722f9abba4f0eb97acce6c5a3b32bc95637 | erdemgokmuharrem/basic-python-projects | /celToFahrenheit.py | 686 | 4.34375 | 4 | print("-" * 30)
print("1- Celsius to fahrenheit")
print("2- Fahrenheit to celsius")
print("-" * 30)
choice = input("Your choice (1/2): ")
if choice == "1":
print("\n# Celsius to Fahrenheit")
celsius = float(input("Degree to convert: "))
fahrenheit = (celsius * 1.8) + 32
print("{} degree celsius is equ... | false |
408c8ed4a32e24c280f71baeb9a42c613a4269cc | rogermanzo99/Python-Ejercicios | /Calculadora/calculadora.py | 1,375 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
while True:
print("Presione '1' para realizar una suma")
print("Presione '2' para realizar una resta")
print("Presione '3' para realizar una multiplicacion")
print("Presione '4' para realizar una division")
print("Presione '5' para salir de la calculadora ")
user = i... | false |
d0dfb47058916c53ec30d41696a076a2d7430773 | devichandanpati/python | /conditionals_13.py | 669 | 4.28125 | 4 | week = [(0,"Sunday"), (1,"Monday"), (2,"Tuesday"), (3,"Wednesday"), (4,"Thursday"), (5,"Friday"), (6,"Saturday")]
x = int(input("Enter number for a week day between 0-6"))
for number,day in week :
if x == 0 :
print("Day is Sunday")
break
elif x == 1 :
print ("Day is Monday")
... | true |
463f670913fdbbe42ac74b8478e3e4ed2aafbf40 | devichandanpati/python | /functions_20.py | 624 | 4.25 | 4 | def turn_clockwise(direction) :
direction = str(input("Enter direction"))
if direction == "N" :
print("Direction is E")
direction == "E"
return direction
elif direction == "E" :
print("Direction is S")
direction == "S"
return d... | true |
200221ac7d1f59d0a140b1fe4ac8e9f7e9df6f28 | devichandanpati/python | /functions_30.py | 270 | 4.21875 | 4 | def slope(x1,y1,x2,y2) :
value = (y1-y2) / (x1 - x2)
return value
x1 = int(input("Enter value for x1 :"))
y1 = int(input("Enter value for y1 :"))
x2 = int(input("Enter value for x2 :"))
y2 = int(input("Enter value for y2 :"))
print(slope(x1,y1,x2,y2))
| false |
151d2bfe1877203953f52be0bfb297baf40a1697 | IIKovalenko/Python_Study | /Input&Output.py | 2,948 | 4.28125 | 4 | #I/O
#python中两种输出值的方式:表达式语句 和 print()函数, 第三种是使用文件对象的write()
#函数,标准输出文件可以使用sys.stdout引用
s = "Hello, World";
print(str(s));
print(repr(s));#打印出来有单引号 'Hello, World'
#repr()可以不转义特殊字符,原样输出
hello = "Hello\n";
print(hello);
print(r"Hello\n");
print(repr(hello));
#repr()参数可以使任何对象
print(repr(('1', "2", (1, 2))));
#两种方式打印出平方立... | false |
6b9ad3ee684ec53b2ea5e69445656e5de6d51b46 | srunas/he-aesar-cipher | /main.py | 2,083 | 4.125 | 4 | print("Программа для шифрования и расшифровки методом Цезаря")
while True:
alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
# Тут я написал алфавит 2 раза подряд для того чтобы может было производить поиск до 25 символов.
x = int(input("Encrypt/Decrypt(Зашифровать/Расшифровать)1/2: "))
... | false |
a67bc9cd1e949c13bae120b9dc1e035427a6c5d9 | tutunak/hackerrank | /python/Python If-Else.py | 357 | 4.5 | 4 | #!/bin/python3
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
n = int(input())
if n % 2:
print('Weird')
elif 6 <= n <= 20:
print('Weird')
elif (2 <= n <= ... | false |
98a722a91f143889d8b88442a2430d0d52c4606d | ulises28/PHW | /ClassCompositionExample.py | 1,182 | 4.5 | 4 | from typing import List #List, tuple, set... etc
import sys
class BookShelf:
def __init__(self, *books): #When calling a function, the * operator can be used to unpack an iterable into the arguments in the function call
self.books = books
#Type hinting -> the value that must be returned or ": str" afte... | true |
89f7be3862af86fdf222b2b3268795ed908983fd | rybli/Python-Class-Practice | /Vehicle/Exercise 4.py | 746 | 4.34375 | 4 | # Exercise Question 4: Class Inheritance
# Create a Bus class that inherits from the Vehicle class.
# Give the capacity argument of Bus.seating_capacity() a default value of 50.
# Use the following code for your parent Vehicle class. You need to use method overriding.
class Vehicle:
def __init__(self, name, max... | true |
063094016c88e3f76a69e919b11adf39ff762f31 | rybli/Python-Class-Practice | /Random/dice_rolling.py | 1,842 | 4.40625 | 4 | # Dice Rolling Program
# Original Problem Statement
# Write a program that will roll a 6-sided dice and display it with ascii art.
from random import randint
class Dice:
# Die face count that are allowed.
allowed_sides = [3, 4, 6, 8, 12, 20]
def __init__(self, sides: int):
"""
Create a ... | true |
44a1a3e66f8f029f67166a15733973e366d6d85a | ricardofqueiroz/Python | /exMenus.py | 2,781 | 4.46875 | 4 |
#Menu de opções
print("""
[1] - DadosPessoa
[2] - Calculos
[3] - cestaFrutas
[4] - HoraAtual
[5] - sair
""")
#=========================================================#
#Criando um contador para a estrutura de repetição while caso o usuário escolha opção não existente
contar=0
#========================================... | false |
e4ae5a3bf98ba5568d6f961b249ccec857f738eb | Csaba79-coder/SETI-python-practice | /seti.py | 1,814 | 4.375 | 4 | def decimal_to_binary(decimal_number):
"""Returns the array of digits in binary representation of a decimal number"""
list = []
while decimal_number > 0:
elem = decimal_number % 2
list.insert(0, elem)
decimal_number //= 2
return list
print(decimal_to_binary(24))
def binar... | false |
ba9615892470400493ff92ff97c59eb76b6e5a8b | cla473/PythonTest | /Genfuncs.py | 1,503 | 4.25 | 4 | """
A set of generic functions:
reverse_string(string) --> string
split_string(orig_str, no_chars) --> list
strip_leading_digits(orig_str) --> string
transcribe_DNA(orig_DNA) --> string
@author: cla473
"""
#Signature: string --> string
def reverse_string(orig_str):
""" return a reversed string
... | true |
3ca72ae79bcd3c5128f9391287fc32b75bee38ee | laminsawo/python-365-days | /python-fundamentals/day-6-Dictionaries/dictionary-labs-decisions.py | 2,000 | 4.53125 | 5 | dict1 = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'key': 54}
print(dict1)
print(dict1['one'])
print(dict1['two'])
print(dict1['three'])
# modify a dictionary key value
dict1['key'] = 22
print(dict1, '\n')
# add new a dictionary key and a value
dict1['newKey'] = 66
print(dict1, '\n')
# creat... | true |
a8bf71ee2acb3edf2a8cca85e819dba665f99465 | laminsawo/python-365-days | /python-fundamentals/day-1-Operators/advanced-operators.py | 1,185 | 4.8125 | 5 | # This Python file exhibits Advanced Python Maths operators
"""
Operators and usage:
// = Floor division - This rounds down the answer to the nearest whole number when two numbers are divided
% = Modulus - This gives the remainder when two numbers are divided e.g. 5 % 2 = 1
** = Exponent - gives the result of powe... | true |
115f7fb591125aca6b3b8a132aa3528b0cc169c9 | brandonmorren/python | /C7 text Files/oefTextFiles/extraOEF1.py | 1,241 | 4.25 | 4 | def read_month(input_month):
if input_month == 8:
file = open("./Files/weather_2018 08.csv")
elif input_month == 10:
file = open("./Files/weather_2018 10.csv")
file.readline() #titel lezen
line = file.readline().rstrip()
highest_temperature = 0
first_period = line.split(";")[0]... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.