blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d13de094d5bf439de91ef83cc78e2c1fc750a1d8 | sanjidahw/python-bootcamp | /Week 1/Day 2/lists.py | 959 | 4.1875 | 4 | my_first_list = [2, 4, 6, 8]
print(my_first_list[2])
length = len(my_first_list)
print("the length of this is: ", length)
for index in range(0, len(my_first_list)):
element = my_first_list[index]
print(element)
print("Original List: ", my_first_list)
my_first_list.append(10)
print("List after Append: ", my_first_l... | false |
4a6caafad025f117dcde3d67da1e8da181b102d1 | sanjidahw/python-bootcamp | /Week 1/Day 1/loops.py | 312 | 4.125 | 4 | counter = 0
while counter <= 10:
print(counter)
counter += 1
# range(start, stop, increment)
# includes the start, does not include the stopping number
print("using the inputs to range()")
for number in range(0,5,1):
print(number)
print("using one input to range()")
for number in range(5):
print(number)
| true |
a8ab0e47061f2c9f26a3577ab2f613b9d66cd2d3 | RemonComputer/hacker_rank_problems | /python/designer_door_mat.py | 910 | 4.21875 | 4 | # Link: https://www.hackerrank.com/challenges/designer-door-mat/problem
def draw_upper_part_lock_line(m, line_idx):
number_of_or_sign = 1 + 2 * line_idx
intermidiate_or_signs = '..'.join(['|'] * number_of_or_sign)
middle_locks = '.' + intermidiate_or_signs + '.'
lock_line = middle_locks.center(m, '-')
... | false |
341e1ef288d4cc92e435399d224d2a7ada282f9c | Innocent2240/calculations | /calculation_Operation.py | 905 | 4.25 | 4 | print("Choose your calculation operator")
print("1: ADDITION")
print("2: SUBTRACTION")
print("3: MULTIPLICATION")
print("4: DIVISION")
calculation = input()
if calculation == "1":
value1=input("Enter first value: ")
value2 = input("Enter second value: ")
print("The sum is " + str(int(value1) + ... | true |
5136c6d0b4a0fb45df849944d475d673e406a0b3 | qetennyson/CThink2018-LessonPlans | /tuples_ex.py | 1,323 | 4.65625 | 5 | ''' Lists are great for storing items we may want to change throughout the life of a program. We can also modify lists, they are mutable! However, there are situations where we may want a data structure that cannot be modified.
An immutable data structure! Hello tuples.'''
# here's a basic tuple that we might use ... | true |
f008853f6a2f3491a93297874181c1bf59a21506 | rybread32/cmpt120straub | /calc_functions.py | 1,696 | 4.34375 | 4 | #calculator.py
#Acts as a Working Calculator for basic arithmetic and PEMDAS
#Created by Ryan Straub
#3/5/19
#def main()
#Where you insert a formula.
#equation = input("Insert Problem: ").split(" ")
#Is what you inserted just a number or not?
#if len(equation)<=2:
#print("This is not ... | true |
b4eae0dc93b5f8d007c550727cdd8e210eafaa36 | ilanasufrin/dsa | /dynamicProgramming/uniquePaths.py | 1,153 | 4.28125 | 4 | """
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?
"""
class Solution(object):
def uni... | true |
b95a94ded927b4cbc3cd1e0ab8da0e63ff5dac12 | Ayamin0x539/Python-Homework | /Exercise_1.7_rockpaperscissors.py | 1,212 | 4.375 | 4 | #Exercise 1.7 - Rock, Paper, Scissors
'''
In this exercise, you are going to practice using conditionals (if, elif, else). You will write a small program that will
determine the result of a rock, paper, scissors game, given Player 1 and Player 2s choices. Your program will print out the result.
'''
#constants to print... | true |
602382747b1729970edc2e18b17fcdcfacc3b4ac | pshimanshu/AdvPython | /day_5/classes/special_methods.py | 903 | 4.21875 | 4 |
# special methods or magic methods or dunder methods
# __init__ -> constructor -> to initialize all intance attributes
# __str__ -> string representation of the class
# class Employee:
# def __init__(self, first, last, address, phone, salary):
# self.first = first
# self.last = last
# se... | true |
cbe63efe5bbf50c149dba5bfbf2d8f52ece79179 | pshimanshu/AdvPython | /day_4/db_programming/file1.py | 941 | 4.15625 | 4 | # Python with SQL database
def takeInput():
arr = []
arr.append(input("Enter name: "))
arr.append(input("Enter phone number: "))
arr.append(input("Enter address: "))
return arr
import sqlite3
# create a datbase object, if doesnt exist, else access it
db = sqlite3.connect("DB1.sqlite")
# create a ... | true |
9d7914e8b2225e21359fdd62217e1fc93be08b58 | satishp962/40-example-python-scripts | /14.py | 306 | 4.3125 | 4 | file = open('file_write.txt', 'r')
print("File contents: ")
for i in file:
print(i)
file = open('file_write.txt', 'a')
str = input("Enter the text to append to the file: ")
file.writelines(str)
file = open('file_write.txt', 'r')
print('File contents after appending: ')
for i in file:
print(i); | true |
0ba01a37bde108aca0775579b2e7cfe1711624f8 | satishp962/40-example-python-scripts | /4.py | 274 | 4.15625 | 4 | num = int(input("Enter an integer: "))
root = None
for i in range(num):
if i*i == num:
root = i
if root is not None:
pwr = None
for i in range(1, 6):
if root**i == num:
pwr = i
print("Root:", str(root) + ", Power:", str(pwr))
| false |
704a722c87fc658cc6cd3d406a3eea15acf10176 | satishp962/40-example-python-scripts | /22.py | 1,021 | 4.21875 | 4 | import abc
class Car:
def __init__(self, make, model, price):
self.make = make
self.model = model
self.price = price
def __str__(self):
return "Make: " + self.make + ", Model: " + self.model + ", Price: " + str(self.price)
@abc.abstractmethod
def show_details(self)... | false |
ee71aeb05da5e440703ea42b3bdf311568fc9560 | Jaden5672/Python_Coding | /leap.py | 319 | 4.1875 | 4 | year=input("Type in any year!")
year=int(year)
if year%4==0:
if year%100==0:
if year%400==0:
print("This year is a leap year!")
else:
print("This year is not a leap year!")
else:
print("This is a leap year!")
else:
print("This is not a leap year!") | false |
cd39cce6b84c9126bd0c3635ac9aee4819a2bd10 | Jaden5672/Python_Coding | /Miles_Km.py | 485 | 4.1875 | 4 | pick=input("Type in A to convert miles to kilometers,or type in B to convert kilometers to miles:")
pick=pick.upper()
if pick=="A":
miles=input("Enter any number of miles to convert to kilometers")
miles=float(miles)
km=miles*1.609
print(km)
elif pick=="B":
kilometers=input("Enter any number... | true |
91da38c68e062f26de4ec2190ee625134461b18c | module6create2020/tutorial08template | /exercises/example.py | 482 | 4.28125 | 4 | """An example illustrating a few aspects of inheritance"""
class Alice:
def __init__(self, n):
self.value = n
def yell(self):
return "Hei"
def get_value(self):
return self.value
class Bob(Alice):
def __init__(self, n):
Alice.__init__(self, n)
def yell(self):
... | false |
90a3020ea45bd4d51164bdaff21813ae02bb6099 | mmore21/ds_algo | /python/lib/bubble_sort.py | 703 | 4.1875 | 4 | """
Topic: Bubble Sort
Category: Algorithm
Author: Mason Moreland
Runtime: O(n^2)
"""
def bubble_sort(arr):
"""
Passes over a list comparing two elements and repeats with a smaller,
sliced off end of the list each iteration until sorted.
"""
for i in range(len(arr)):
for j in r... | true |
1610d166715de41a88683656df02011d3ac7453e | thommms/python-projects | /check if a number is in a given range.py | 313 | 4.21875 | 4 | #to check if a number is in a given range
start=int(input("enter the beginning of the range: "))
end=int(input("enter the end of the range:"))
number=int(input("enter the number to check: "))
if number not in range (start,end):
print ("\n",number," not in range")
else:
print ("\nnumber is in the range") | true |
77f444f9992ef92db3d961768d6109343c7afa2f | santifinland/CursoTecnicasAnaliticasConSpark | /python/circle/circle_while.py | 701 | 4.25 | 4 | # -*- coding: utf-8 -*-
# Programa de cálculo de circunferencia de un círculo
from math import pi
def calcula_circunferencia(r):
return 2 * pi * float(r)
def is_numeric(x):
try:
float(x)
return True
except:
return False
print("Programa de cálculo de la circunferencia de un cír... | false |
a906b608b4bb453d19950b0ac63605d0f0d5c3f1 | santifinland/CursoTecnicasAnaliticasConSpark | /python/circle/circle_fun.py | 535 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# Programa de cálculo de circunferencia de un círculo
from math import pi
def calcula_circunferencia(r): # Definición de una función con parámetros
return 2 * pi * r # Uso de sentencia return
print("Programa de cálculo de la circunferencia de un círculo dado su radio")
radio ... | false |
933940c1f977d198dc54044ee709280c088e5b34 | hfyblnh/WorkSpaces | /JetProjects/PyCharm/learn-python3/samples/advance/do_iter.py | 2,428 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import Iterable
from collections import Iterator
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for k in d:
print(k)
for v in d.values():
print(v)
for k, v in d.items():
print(k, v)
for ch in "2ez4rtz":
print(ch)
print(isinstan... | false |
d770deaf2335fb6a54a6205e74fe37c1e350afc9 | shirazh7/caesarCipher | /cipher.py | 2,153 | 4.25 | 4 |
# This is my Ceaser Cipher encryption program
# Written in python
def encryption():
print("******** Encryption ********")
msg = input("Enter message: ")
key = int(input("Enter cipher key (0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32: # ord() will give t... | true |
89a5b8dd71ea1b785b4581ec2530047c1e4167ef | brommista/Login_credentials_creator | /login_credentials_creator.py | 1,288 | 4.25 | 4 | import random
import string
#Ask for User's First name
first_name = input("Please enter user's first name: ")
#Ask for User's last name
last_name = input("Please enter user's last name: ")
#defining a function to create username using firstname and lastname
def username(fisrt_name, last_name):
#Username will con... | true |
c09ca07feef647ee737f255e3afd88af685957e6 | michaelrbull/weathermantask | /runweathercheck.py | 2,838 | 4.1875 | 4 | ###
# Import both the list of sunny cities and the corresponding flight numbers
# from both the flight and weather program.
from weather_services import sunny_cities
from flight_services import sunny_flight_num
# Prints both lists but tidied up with string concentation.
print("Sunny Cities: " + str(sunny_cities))
p... | true |
51b146b590d9ee041588aa69e8dd0305d69056f1 | kimjane93/udemy-python-100-days-coding-challenges | /day-5-password-generator/even-nums.py | 708 | 4.28125 | 4 | # using range function
# use for loops with the rnage funciton
# good for genrating a range of numbers to loop through
# for number in range(a, b):
# print(number)
# DOES NOT INCLUDE END OF THE RANGE
# for number in range(1, 10):
# print(number)
# out puts 1-9
# if wanted all, would have to make it 1... | true |
55928cf794e01fbb58df8535557703841224712e | kimjane93/udemy-python-100-days-coding-challenges | /day-2-tip-calc/main.py | 2,281 | 4.28125 | 4 | print("Welcome To The Tip Calculator!")
total_bill = input("What was the total of your meal? \n$")
number_of_payers = input("How many of you will be splitting the cost? \n")
tip_percentage = input("What percentage would you like to tip? \n15, 18, or 20: \n")
total_bill_int = int(total_bill)
number_of_payers_int = int(... | true |
590f45f9a3071788b36c25d130dfb82cb498ca89 | kimjane93/udemy-python-100-days-coding-challenges | /day-8-create-caesar-ciper-inputs/prime_number_checker.py | 383 | 4.125 | 4 | # check if number is prime
# can only divided by one and itself without decimals
def prime_checker(number):
for n in range(2, number):
if number % n == 0:
print(f"{number} is not a prime number")
break
else:
print(f"{number} is a prime number")
break... | true |
52682fbd4fe8d676fc6ddcd274470a006db87193 | DushyantVermaCS/Python-Tuts | /practice quiz1.py | 525 | 4.21875 | 4 | #Practice Quiz:
'''In this scenario, two friends are eating dinner at a restaurant.
The bill comes in the amount of 47.28 dollars.
The friends decide to split the bill evenly between them,
after adding 15% tip for the service. Calculate the tip, the total amount to pay,
and each friend's share,then output a messag... | true |
bfd80edb5aa331477c537b233e77d6f832e47fe5 | DushyantVermaCS/Python-Tuts | /7.1.py | 403 | 4.5 | 4 | '''7.1 Write a program that prompts for a file name, then opens that file and
reads through the file, and print the contents of the file in upper case.
Use the file words.txt to produce the output below.
You can download the sample data at'''
#http://www.py4e.com/code3/words.txt
#Ans:
fname = input("Enter file ... | true |
fb1c90346864aabef133791cf080b3a30c3fcbdd | blackwer/sciware-testing-python | /sciware_testing_python/main.py | 1,192 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""Main module template with example functions."""
def sum_numbers(number_list):
"""Example function. Sums a list of numbers using a for loop.
Parameters
----------
number_list : list
List of ints or floats
Returns
-------
int or float
Sum of list
... | true |
e4b5ef9fe4a88ccc92e043d808dfbab567c315ea | KunalKokate/Python-Workshop | /ExceptionHandling.py | 1,250 | 4.40625 | 4 | # #Exception Handling
# try: #put that code in it which you think is a error
# except <Exception>: #put the posssible exception here
# print("Some error")
# else
# print("All went well")
#ex1-IOError
try:
fh = open("example_23.txt","w")
fh.write("This is my test file for exception ha... | true |
e3910278e81f810231b33c4557d0ebf4af9abfef | asaini/algo-py | /algos/max_diff_two.py | 519 | 4.28125 | 4 | def maximum_diff(array):
"""
Given an array array of integers,
find out the difference between any two elements such that
larger element appears after the smaller number in array
"""
max_diff = array[1] - array[0]
min_element = array[0]
n = len(array)
for i in range(1, n):
if array[i] - min_element > max_... | true |
a0c69c20ff2e64a4facb5ae0ffe72bd970d090e8 | asaini/algo-py | /algos/triangles.py | 459 | 4.1875 | 4 | def number_of_triangles(array):
"""
Given an array find the number of triangular
pairs in it
"""
array = sorted(array)
n = len(array)
count = 0
for i in range(n-2):
k = i+2
for j in range(i+1, n):
print count
while k < n and array[i] + array[j] < array[k]:
k += 1
count += k - j - 1
return co... | true |
966da861bcf16b3aef9480350356641b0e1679d8 | asaini/algo-py | /algos/word_break.py | 2,523 | 4.15625 | 4 | """
Given an input string and a dictionary of words,
segment the input string into a space-separated
sequence of dictionary words if possible. For
example, if the input string is "applepie" and
dictionary contains a standard set of English words,
then we would return the string "apple pie" as output.
See : http://then... | true |
114c8f6f3c901362a6bfd60eab2b9687132b7631 | Hayasak-a/E02a-Control-Structures | /main10.py | 2,103 | 4.34375 | 4 | #!/usr/bin/env python3
import sys, random
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
print('Greetings!') # The program greets the user.
colors = ['red','orange','yellow','green','blue','violet','purple'] # The program initializes an array of colors.
play_again = '' # the variable pl... | true |
14b7d57641e5ce1c727a4f7f36968ab417d270b2 | avi527/Decorator | /MultipleDecoratorstoaSingleFunction.py | 591 | 4.28125 | 4 | '''the decorators will be applied in the order that we've called them. Below we'll
define another decorator that splits the sentence into a list.
We'll then apply the uppercase_decorator and split_string decorator to a single function.'''
def splitString(function):
def wrapper():
fun=function()
funSplit=... | true |
b80defe74fc40a470982bbbac629e1ea78b05195 | vaibhavmathur91/GeeksForGeeks | /Arrays/15_print-missing-elements-that-lie-in-range-0-99.py | 1,316 | 4.25 | 4 | """
Print missing elements that lie in range 0 – 99
Given an array of integers print the missing elements that lie in range 0-99.
If there are more than one missing, collate them, otherwise just print the number.
Note that the input array may not be sorted and may contain numbers outside the range [0-99],
but only this... | true |
d59fdcf6ea0c733d27962abefcb1cd87074b55f5 | Daransoto/holbertonschool-machine_learning | /math/0x05-advanced_linear_algebra/2-cofactor.py | 2,811 | 4.15625 | 4 | #!/usr/bin/env python3
""" This module contains the functions determinant, minor and cofactor. """
def determinant(matrix):
"""
Calculates the determinant of a matrix.
matrix is a list of lists whose determinant will be calculated.
If matrix is not a list of lists, raises a TypeError with the message
... | true |
d4017458ff2330ae832679fd0779d14daecf3bb1 | Daransoto/holbertonschool-machine_learning | /math/0x03-probability/poisson.py | 2,052 | 4.28125 | 4 | #!/usr/bin/env python3
""" This module contains the Poisson class. """
class Poisson:
""" Class that represents a poisson distribution. """
e = 2.7182818285
def __init__(self, data=None, lambtha=1.):
"""
Constructor of the class. Sets the instance attribute lambtha as float.
data... | true |
0e644a3a1fefbc155515718c3c673db1492e0ac6 | Daransoto/holbertonschool-machine_learning | /supervised_learning/0x07-cnn/0-conv_forward.py | 2,266 | 4.15625 | 4 | #!/usr/bin/env python3
""" This module contains the function conv_forward. """
import numpy as np
def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)):
"""
Performs forward propagation over a convolutional layer of a neural
network.
A_prev is a numpy.ndarray of shape (m, h_prev, ... | true |
e0215726de40d2dd12c713a53114c0520ff19c5e | prince002021/College-Assignments | /Big Data/Python/Ex/ex1/mapper.py | 616 | 4.125 | 4 | import sys
#input comes from STDIN (standard input), i.e type file.txt brings the content of the file to the terminal, and we read it
for line in sys.stdin:
#remove leading and trailing whitespaces.(\n)
line = line.strip()
#split the line into words.
words = line.split()
#increase counter.
f... | true |
cfb0b17e9dc8cbcb5dab580c07632b14666129b3 | lvrbanec/100DaysOfCode_Python | /Project09, Beginner, Calculator/main.py | 1,395 | 4.375 | 4 | # 03.02.21, Frollo
# Level: beginner
# Project: Easy calculator
from art import logo
print(logo)
# Operations
# Add
def add(n1, n2):
return n1 + n2
# Substract
def substract(n1, n2):
return n1 - n2
# Multipy
def multipy(n1, n2):
return n1 * n2
# Divide
def divide(n1, n2):
return n1 / n2
operations = {
"+... | true |
d97018c87c0ef051616f1b15fa102759167061ab | lvrbanec/100DaysOfCode_Python | /Project16, Intermediate, TurtleRace using turtle module/main.py | 1,238 | 4.34375 | 4 | # 08.02.2021, Frollo
# Level: Intermediate
# Project: Make a turtle race betting game
from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
co... | true |
5c9696e2093d8ccf15a5da2705c6da6886a95df4 | andrescanovas/programacion | /Programacion 3/ejercicio02.py | 1,335 | 4.21875 | 4 | # ___________CONSULTAR NO DEJA RESPUESTA EN CADA NOMBRE___________
# for i in range (0, 3):
# nombre = input("ingrese su nombre :").capitalize()
# anio_nacimiento = int(input("ingrese año de nacimiento :"))
# edad = 2021 - anio_nacimiento
# if(edad >= 18):
# print(nombre,"ES MAYOR DE EDAD")
# e... | false |
23fa9655019a2fff8a661ef1e275f2df9d18cd5a | anhnguyendepocen/Python-for-Research | /Part5/Linear Regression.py | 1,898 | 4.28125 | 4 | # Introduction to Statistical Learning
# Generating Example Regression Data
import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
n = 100
beta_0 = 5
beta_1 = 2
np.random.seed(1)
x = 10 * ss.uniform.rvs(size=n)
y = beta_0 + beta_1 * x + ss.norm.rvs(loc=0,scale=1,size=n)
plt.figure()
plt.plot(x... | false |
8912bd0934d08ba0573043e92ca11925324928c3 | anhnguyendepocen/Python-for-Research | /Part1/exercise 2c.py | 490 | 4.125 | 4 | #EXERCISE 2C
"""
The distance between two points x and y is the square root of the sum of s
quared differences along each dimension of x and y.
Create a function distance(x, y) that takes two vectors and outputs
the distance between them. Use your function to find the distance
between x=(0,0) and y=(1,1).
Print your ... | true |
87219f5f93f82ed8a9eaecccb2e894f73b6b6c98 | ankolaver/ALevel_Computing_Material | /Algorithms/sorting/bubblesort_iter.py | 815 | 4.1875 | 4 | '''Bubble sort has a worst-case and average complexity
of О(n2), where n is the number of items being sorted.
Most practical sorting algorithms have substantially
better worst-case or average complexity, often O(n log n).
The function below always runs O(n^2) time even if the array is sorted.
It can be optimized by sto... | true |
b8b08895fdf9703474a24e97e1fa0bda7a78ffed | shubhra2/PythonC | /lab2.py | 2,015 | 4.25 | 4 |
def readnum() :
nm = float(input("Enter Number(s) : "))
return nm
def add() :
numarr = []
for i in range(2) :
n1 = readnum()
numarr.append(n1)
print("{} + {} = {}".format(numarr[0], numarr[1], numarr[0] + numarr[1]))
def maxmin() :
maxminnumary = []
for i in range(3) :
... | false |
263e4a8e66f719ad1c39d97b68f8f5a75a51112f | Widdershin/CodeEval | /challenges/007-lowercase.py | 818 | 4.3125 | 4 | """
https://www.codeeval.com/browse/20/
Lowercase
Challenge Description:
Given a string write a program to convert it into lowercase.
Input Sample:
The first argument will be a text file containing sentences, one per line.
You can assume all characters are from the english language. E.g.
HELLO CO... | true |
36517dd0165ff7a251258d7a26795d6cf1d5a1b0 | Widdershin/CodeEval | /challenges/011-sumofintegersfromfile.py | 801 | 4.125 | 4 | """
https://www.codeeval.com/browse/24/
Sum of Integers from File
Challenge Description:
Print out the sum of integers read from a file.
Input Sample:
The first argument to the program will be a text file containing
a positive integer, one per line. E.g.
5
12
Output Sample:
Print out t... | true |
b83a41143117339fe319f2b5654dfdca97bcbf6a | Nafisa-tabassum2046/my-pycharm-project | /if elif sestetment anisul.py | 1,600 | 4.1875 | 4 |
# #
# a = 78
# if (a>33):
# print("pass")
#
# else:
# print("fail")
#
# # greater then less than number print
#
# a = 20
# b= 10
# if (a>b):
# print("a is greater then b")
#
# else:
# print("b is greater then a")
#
# # odd even number check:
#
# a = 10
#
# if(a%2==0):
# pri... | false |
6e166497b93e4630729d919dd692231c67497830 | xeroxzen/Coding-Challenges | /Minimum Waiting Time.py | 2,672 | 4.15625 | 4 | # O(nlogn) - time | O(1) - space : where n is the number of queries
def minimumWaitingTime(queries):
## Understand:
'''
- executing the shortest query first is what will lead to the minimum waiting time
- because all queries after it will also have to wait a short/minimum time
- if we execute the query with the... | true |
bc1c7608fe9408b6831c288476894cb7d3ab4213 | MattPaul25/PythonPatterns | /DesignPatterns/Creational/AbstractFactory.py | 1,476 | 4.375 | 4 |
class Dog:
def speak(self):
return "Woof!"
def __str__(self):
return "Dog"
class Cat:
def speak(self):
return "Meow!"
def __str__(self):
return "Cat"
class DogFactory:
def get_pet(self):
#returns dog object
return Dog()
def get_food(self):
... | true |
41c984b50c251479bbb32e5fa4e672e52994ce4d | MattPaul25/PythonPatterns | /DesignPatterns/Behavorial/Visitor.py | 1,823 | 4.1875 | 4 | #visitor allows adding new features to existing class heirarchy without changing it
#scenario: house class, HVAC specialist is a vistor,
#Electrician is visitor 2 -- new actions to be performed on an existing class heirarchy.
class House(object): #the class being visited
"""this is the object that gets visite... | true |
8ffa476ccd0cdfcdb2078b610448cd45c7e54f28 | anitrajpurohit28/PythonPractice | /python_practice/String_programs/10_remove_duplicates.py | 1,485 | 4.15625 | 4 | # 10 Remove all duplicates from a given string in Python
input1 = 'aabbcccddekll12@aaeebbbb'
print(input1)
# by using set; unordered
print("----unordered set------")
def remove_duplicates_set(string):
unique_chars = set(string)
print(''.join(unique_chars))
remove_duplicates_set(input1)
print("----OrderedDict... | true |
1fcdf7077619788f8df2cece109e92bd49a4af58 | anitrajpurohit28/PythonPractice | /python_practice/List_programs/2_swap_2_elements_of_given_positions.py | 1,041 | 4.25 | 4 | # 2 Python program to swap two elements in a input_list
given_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
p1 = 2
p2 = 5
def swap_positions_comma_assignment(input_list, pos1, pos2):
input_list[pos1], input_list[pos2] = input_list[pos2], input_list[pos1]
print(given_list)
swap_positions_comma_assignment(given_list, p1, p... | false |
bfad97f35cee5bbd84fb0133555872db1695a97c | anitrajpurohit28/PythonPractice | /python_practice/List_programs/1_interchange_first_last_elements.py | 2,372 | 4.46875 | 4 | # 1 Python program to interchange first and last elements in a list
print("-----1------")
def swap_list_using_temp1(input_list):
temp = input_list[0]
input_list[0] = input_list[-1]
input_list[-1] = temp
my_list = [1, 2, 3, 4, 5, 6, 7]
swap_list_using_temp1(my_list)
print(my_list)
print("-----2------")
d... | false |
8c4e3d0b18fac03abaf0ca86b1841ae0d5432d1f | anitrajpurohit28/PythonPractice | /python_practice/String_programs/14_remove_ith_char_from_string.py | 248 | 4.28125 | 4 | # 14 Python program for removing i-th character from a string
import string
### already covered in "3_remove_i_th_character.py"
string1 = "input string, input variable"
string2 = string1.replace("input", "abcdefg")
print(string1)
print(string2)
| true |
2f5085943ab773cdf407bb7d65f76cd4c5f63117 | anitrajpurohit28/PythonPractice | /python_practice/String_programs/11_check_for_special_char.py | 1,217 | 4.375 | 4 | # 11 Python | Program to check if a string contains any special character
txt1 = "CompanyA12"
txt2 = "andfa322ABGFDASVF"
txt3 = "!@asdesad fx"
print(txt1.isalnum())
print(txt2.isalnum())
print(txt3.isalnum())
print("-----my_isalnum------")
def my_isalnum(string):
special_char = """'[@_!#$%^"&*()<>?/\\|}{~:]"""
... | false |
fa9b36a68ec5c3bedecabeeafd69e9f4050bcd26 | anitrajpurohit28/PythonPractice | /python_practice/String_programs/1_is_palindrome.py | 1,943 | 4.5 | 4 | # 1 Python program to check if a string is palindrome or not
input1 = "malayalam"
input2 = "geeks"
input3 = "12345678987654321"
print("---reversing string---")
def is_palindrome_reverse(input_str):
rev_str = input_str[::-1]
if rev_str == input_str:
return True
else:
return False
print(f... | false |
085617c6a15fb5100aeda22ffcca64eb89e8bb62 | zuping-qin/SDET-QA | /docker/app/cambia.py | 1,339 | 4.21875 | 4 | # This function tokenlizes the CSV content line by line
# into an array of list of words after stripping off the
# whitespace, including new line characters. It then
# sorts the line word list in an ascending order. Finally,
# it writes out the word lists into csv lines in the output
# file.
import sys
def ... | true |
fd0b5eb9c303335168e4ed3ec8b76ee5b24369fe | yinhaiquan/python_basic | /demo/hq/com/function.py | 1,262 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 函数
# 无返回值函数 void
def showName(name):
print name
showName("fuck")
# 有返回值函数 return
def getName(name,age):
return str(age)+name
print getName("fuck",12)
# 缺省参数 最少得赋值一个参数,且缺省参数必须初始化,否则抛异常
def getParamters(var1,var2=12):
print var1,var2
getParamters(var1="sdf... | false |
84b5c7618e98c8d1e3b62ab8dfc6c2ec49c9b304 | ManuelPPonce/Programacion-Visual | /Examen/diccionario.py | 692 | 4.25 | 4 | """
5.- Escribir un programa llamado diccionario.py que pregunte al usuario su nombre, edad, dirección y teléfono y lo guarde en un diccionario. Después debe mostrar por pantalla el mensaje
<nombre> tiene <edad> años, vive en <dirección> y su número de teléfono es <teléfono>.
"""
Nombre = input ("Nombre : ")
Edad = in... | false |
a30beff7fc2b6b70debd39071ee3d92ea233a959 | cdhop/headfirstprogramming | /greeter.py | 628 | 4.15625 | 4 | #!/usr/bin/python3
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = first_name + " " + last_name
return full_name.title()
done = False
while done != True:
print("\nPlease tell me your name:")
print("enter 'q' at any time to quit")
first_... | true |
f49bba91c297b11bbbd857045055ad3baa13840f | gwcahill/CodeEval | /capitalize_words/capitalize_words.py | 1,129 | 4.125 | 4 | '''
Created on Feb 24, 2015
https://www.codeeval.com/open_challenges/93/
Write a program which capitalizes the first letter of each word in
a sentence.
Input sample:
Your program should accept as its first argument a path to a filename.
Input example is the following:
Hello world
javaScript languag... | true |
50f472879fddad1453a99649717e688b23c02bc2 | gwcahill/CodeEval | /calculate_distance/calculate_distance.py | 2,334 | 4.15625 | 4 | '''
Created on Mar 27, 2015
https://www.codeeval.com/open_challenges/99/
You have coordinates of 2 points and need to find the distance
between them.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename.
Input example is the following
(25, 4) (1, -6)
(47, 43) (-25, -11)
All number... | true |
311cca70160671252efd6d2116f633249ef315ea | gwcahill/CodeEval | /n_mod_m/n_mod_m.py | 943 | 4.125 | 4 | '''
Created on Mar 11, 2015
https://www.codeeval.com/open_challenges/62/
Given two integers N and M, calculate N Mod M (without using any inbuilt
modulus operator).
Input sample:
Your program should accept as its first argument a path to a filename.
Each line in this file contains two comma separated p... | true |
3f3f9758332bbbbd05e2c3b42f3b1baadcf83fc4 | linhnvfpt/homework | /python/practice_python/exer6.py | 511 | 4.5 | 4 | # Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
import math
string = input("Input a string: ")
lenstr = len(string)
stop = math.floor(lenstr / 2)
strLeft = string[0:stop:1]
if lenstr % 2 == 1:
st... | true |
c57e06c0a030903d5cd949ee03e4575760f9058a | linhnvfpt/homework | /python/practice_python/exer9.py | 797 | 4.25 | 4 | #Generate a random number between 1 and 9 (including 1 and 9).
#Ask the user to guess the number, then tell them whether they guessed too low,
#too high, or exactly right.
#(Hint: remember to use the user input lessons from the very first exercise)
#Extras:
#Keep the game going until the user types “exit”
... | true |
382a04567820ccba224bfa9301aa2b03b8c55d8f | linhnvfpt/homework | /python/w3resource/python-execises/part-I/18.py | 254 | 4.125 | 4 | # Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times of their sum
def sum(a,b,c):
if a == b == c:
return 3 * a
return a + b + c
print(sum(1,2,3))
print(sum(1,1,1)) | true |
0ef8cb7de0f18c6c2841e091ac887947d0202e32 | SparshRajGupta/MyPythonStudy | /function2.py | 214 | 4.15625 | 4 | def max(a,b):
if a > b:
print 'a is greater than b'
if b > a:
print 'b is greater than a'
if b == a:
print "a is equal to b"
max(15,6)
x = 15
y = 15
max(x, y)
| true |
ff4234f503c0fa2950290a15fa7812a929339666 | shelkesagar29/CTCI | /Chapter2/p8_loop_detection.py | 2,880 | 4.1875 | 4 | import unittest
from DS.linkedlist import LinkedList
def solution1(ll):
"""
Time Complexity: O(n) where n is the length of the linked list
Space Complexity: O(1)
Args:
ll (LinkedList): linked list object
Returns:
data: Node value where loop starts if LL has loop.
-1: If LL h... | true |
71885218b778cc0cc9afadbafb326b99569b469f | joshavenue/TIL-python | /confusing_forloop.py | 378 | 4.1875 | 4 | # you divide it in 3 parts: the _yielding_ part is the first `Word` ,
# then you have the _loop_ `for Word in WORD_TOKENS` and lastly,
# you have the _condition_ `if not Word in STOP_WORDS`
FILTERED_SENTENCE = [Word for Word in WORD_TOKENS if not Word in STOP_WORDS]
# IS THE SAME AS BELOW
for Word in WORD_TOKENS:
... | false |
23bc0cc710743858138edb3f0072f5665f5e79dc | Lokesh824/DataStrucutres | /SinglyLinkedList/LinkedList_RotateList.py | 2,201 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 15:56:37 2019
@author: inkuml05
"""
class Node:
def __init__(self, data):
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.Head = None
def append(self,data):
new_nod... | true |
334e546c84d7885009414d79597c9094b1fa4aaf | DesireeRainey/sorts | /merge.py | 1,381 | 4.3125 | 4 |
#Python Merge Sort
import time
import random
def merge(arr1, arr2):
results = []
while len(arr1) > 0 and len(arr2) > 0:
if arr1[0] > arr2[0]:
results.append(arr2.pop(0))
else:
results.append(arr1.pop(0))
return results + arr1 + arr2
def merge_sort(arr):
#base case: array length is ... | true |
dc7f52c08038a2921da8e5727eab7d08bc93e231 | lily-liu-17/ICS3U-Unit3-04-Python-Month_Number | /month_number.py | 1,049 | 4.46875 | 4 | #!/usr/bin/env python3
# Created by: Lily Liu
# Created on: Sept 2021
# This program converts the number to its corresponding month
def main():
# This program converts the number to its corresponding month
# input
user_input = int(input("Enter the number of the month (ex: 5 for May) : "))
# process... | true |
9e228a898159f911345e282a57e739435c13b58a | mrthomasjackson/DPW | /learning_python/main.py | 1,763 | 4.1875 | 4 | #I am trying python for the first time
__author__ = 'tjackson'
welcome_message = "Welcome!"
space = " "
#this is a one line comment
'''
Doc string (multiple line comments)
'''
first_name = "Thomas"
last_name = "Jackson"
#print(first_name + " " + last_name)
#response = raw_input("Enter Your Name")
#print welcome_me... | true |
7255ae920308382d90f7429a6fdd1b4ad5fbacf2 | CesaireTchoudjuen/programming | /week04-Flow/Weeklytask04-collatz.py | 597 | 4.40625 | 4 | # Program that asks the user to input any positive integer and outputs the successive values of the following calculation
# At each step calculate the next value by taking the current value and, if it is even, divide it by two, but if it is odd, multiply it by three and add one
# Program ends if the current value is on... | true |
ca6c1e7b3c4ada5a12875b77b2ed1fd98b14b5d0 | CesaireTchoudjuen/programming | /Week05-Datastructures/Lab5.1.py | 392 | 4.25 | 4 | # Author: Cesaire Tchoudjuen
# Create a tuple that stores the months of the year, from that tuple create another tuple with just the summer months (May, June, July),
# print out the summer months one at a time
months =("January",
"February",
"March",
"April",
"May",
"June",
"july",
"August",
"September",
"October",
"... | true |
0ddf38f7db811222edabfc4e52e8a105e1a64bd8 | CesaireTchoudjuen/programming | /Week05-Datastructures/Lab5.4.py | 477 | 4.3125 | 4 | # Author: Cesaire Tchoudjuen
# Program that stores a student name and a list of her courses and grades in a dict
student = {
"name":"Mary",
"modules": [
{
"courseName":"Programming",
"grades": 45
},
{
"courseName":"History",
"grades": 99
... | true |
cc1d552b37290d710e1527ba18251d93566212ce | ni/NI-ELVIS-III-Python-Examples | /examples/digital/DIO_multipleChannels.py | 2,510 | 4.28125 | 4 | """
NI ELVIS III Digital Input and Output Example - Single Point, Multiple Channels
This example illustrates how to write values to and read values from multiple
digital input and output (DIO) channels. The program first defines the
configuration for the DIO channels, and then writes to and reads from the DIO
channels.... | true |
80b1f540dbef03dccfa59a0018bd159b09e0667f | TripleM98/CSI-127-Assignments | /04/TheCollatzSequence.py | 377 | 4.25 | 4 | def collatz(number):
if (number % 2 == 0):
return number//2
elif(number % 2!=0):
return number*3+1
try:
n = int(input('Enter number:'))
while n>1:
print (collatz(n))
n=(collatz(n))
if(n<1):
print('You must enter a number greater than or equal to 1.')
except... | true |
03205d727383b65eebcc20252fe6831a82a65f4f | disfear86/Data-Analysis | /Udacity_Data_Analysis/convert_cols.py | 709 | 4.125 | 4 | import pandas as pd
grades_df = pd.DataFrame(
data={'exam1': [43, 81, 78, 75, 89, 70, 91, 65, 98, 87],
'exam2': [24, 63, 56, 56, 67, 51, 79, 46, 72, 60]},
index=['Andre', 'Barry', 'Chris', 'Dan', 'Emilio',
'Fred', 'Greta', 'Humbert', 'Ivan', 'James']
)
def convert_one(grade):
if grad... | true |
181a446bb977ca8cec16c9eb1e9d57b0f90579d4 | Dan-Blanchette/cs270-system-software | /pa5-Deadhuckabee-DanB-master/quick_sort/main.py | 2,180 | 4.25 | 4 | #!/usr/bin/env python3
# Dan Blanchette
# CS-270
# quick sort and binary search part 2B
# Acknowledgements: For removing encoding='uft-8-sig'
# https://stackoverflow.com/questions/53187097/how-to-read-file-in-python-withou-ufef
from quicksrt import quickSort
from binSearch import binarySearch
from PyDictionary impor... | true |
d95ca70a76412181d75b5a0f74ef43de76a3f910 | zezhouliu/am106 | /p2/mmi.py | 537 | 4.125 | 4 | import sys
import extended_euclid
def mult_mod_inverse(n, p):
'''
Applies the extended euclids in order to calculate the
multiplicative modular inverse.
returns x such that n * x = 1 mod p
'''
r1, r2 = extended_euclid.extended_euclids(n, p)
if r1 < 0:
r1 = r1 + p
return r1
if _... | true |
533cb3d8959636d0a559f5a60fa08134c657244e | iAreth/arm | /strings.py | 880 | 4.625 | 5 | myStr = "AdayDos"
print("My name is " + myStr) # Sumando | Uniendo Strings
print("Uso de {f}")
print(f"My name is {myStr}")
# Palabra clave de Python | Que es lo que podemos hacer con un cierto tipo de datos
# upper | Mayuscula
# lower | Minuscula
# count | Contar cuantas veces se esta utilizando un caracter
# print(... | false |
d82d9f4cf66e670676417cf7109d7cdfd4cda43c | AcerAspireE15/python-exception-handling | /12.py | 744 | 4.125 | 4 | def function1(a, b):
print(a+b)
print(a*b)
print(a-b)
print(a/b)
print(a%b)
function1(20, 3)
print('hello')
try:
a = 20
b = 0
print(a/b)
except ZeroDivisionError:
print('there is a divide by zero error')
try:
a = 20
b = 10
print(a/b)
except ZeroDivis... | true |
45096fc08cf5eefb39ec06eb1f85aa3fe1191ac5 | Omiee123/Mordern-Cryptography | /Diffi Hellman Algo.py | 943 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
#Diffi Hellman Key Exchange Algorithm
#Step 1 : Choose Random Number A,B (Private Random Number)
#Step 2 : Choose g and p (Shared Value)
#Step 3 : Find Xa and Xb (Xa = g**a mod p & Xb = g**b mod p)
#Step 4 : Share Xa and Xb
#Step 5 : Key Generation k = Xb**a mod p = xa**b mod p
#... | false |
4f6a55c21dd48d5730f61e46124d8dcfc90527ed | shrikantnarvekar/Python-GUI | /checkdates.py | 513 | 4.125 | 4 | from date import Date
def main():
bornBefore = Date(6, 1, 1988)
date = promptAndExtractDate()
while date is not None :
if date <= bornBefore :
print( "Is at least 21 years of age: ", date )
date = promptAndExtractDate()
print( "Enter a birth date." )
... | true |
7fdee8036dbffc95abe749d3e6dd8fd7456442df | brittanyp/CP1404-Workshops | /WS2/shipCalc.py | 382 | 4.1875 | 4 | quantity = int(input("Enter amount of item: "))
while quantity < 0 :
print("Invalid input")
quantity = int(input("Enter amount of item: "))
costPerItem = float(input("Enter shipping cost per item: "))
totalCharge = costPerItem * float(quantity)
if totalCharge > 100 :
totalCharge = totalCharge - (0.1 * to... | true |
a528f8676030d3c51cd07a913f030a769b781522 | chipoltie0/Roguelike_v1.1 | /GamePiece.py | 1,412 | 4.28125 | 4 |
class Piece:
"""
This is the base object that interacts with the map object, contains information such as
the location of the object, what map it is on, and possible a connected character sheet
"""
def __init__(self,map, start_point, collision=False,color=(0,0,0),char='*'):
self.map = map ... | true |
89158eb6b1effb875571a0fcdebf4b6396901f9e | SoniaRode21/Python | /SearchingAndSorting/FOAproject1/quickSort.py | 1,159 | 4.25 | 4 | _author = 'Soniya Rode'
'''
The program includes functions to partition the array
and quick sort the data.
'''
def partition(arr, l, r):
'''
Function to partition the array based on pivot value
:param array: list containing elements to be sorted
:param l : left most index of the list
:par... | true |
c8763f1099ce7b22739d80cce03a639ef1eb18ec | jaehyunan11/Python_Learning | /Day_27/challenge_1.py | 921 | 4.28125 | 4 | from tkinter import *
"""
1. Pack
-> default located in the upper center
ex: input.pack(side="left")
2. Place
-> Specific coordinate
ex: my_label.place(x=100, y=200)
3. Grid
-> Row and column
"""
# Window setup
window = Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
window.config(pa... | true |
fc47f571e5d321bf5de59b7a82f2e85b8f763719 | jaehyunan11/Python_Learning | /Day_27/main.py | 2,311 | 4.15625 | 4 | from tkinter import *
window = Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
#Label
my_label = Label(text="I am a Label", font=("Arial", 24, "bold"))
my_label.pack()
# my_label["text"] = "New Text"
my_label.config(text= "New Text")
# Button
def button_clicked():
print("I got... | true |
769f56fe12f0c5f4557142390f77794e85ba6696 | joyc/python-book-test | /AutomatePython/scr/isPhoneNumber.py | 857 | 4.15625 | 4 | def isPhoneNumber(text):
if len(text) != 13:
return False # not phone number-sized
for i in range(0, 3):
if not text[i].isdecimal():
return False # not an area code
if text[3] != '-':
return False # does not have first hyphen
for i in range(4, 8):
if not te... | true |
479efa73a80822daa2a50e7a3e29df47bc206b63 | Ellipse404/100-Exercises-Python-Programming- | /100+ Exercises Solved/Question - 4.py | 494 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 13 19:47:56 2019
@author: BHASKAR NEOGI
"""
# Level 1
try :
l = input("Enter Comma(,) Seperated Numbers : ")
y = l.split(",")
t = tuple(y)
print(t,y)
# print(y)
print("::------------ Another One ------------::"... | false |
f0095dcba414f444da0fc2290894261f554ab373 | Ellipse404/100-Exercises-Python-Programming- | /100+ Exercises Solved/Question - 8.py | 323 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 13:04:41 2019
@author: BHASKAR NEOGI
"""
# Level - 2
w = input("Enter the Words You Want To list Alphabetically Seperated By Comma ',' :: ").split(",")
w.sort()
print("Output In List : ",w)
print("Output In Comma Seperated Style : ",',... | false |
b410b9665dd20ae1203f8cf7d474fbb50046a331 | Matheusdehsouza/Process_Kaffa | /exercise 1/CNPJ1.py | 681 | 4.125 | 4 | #Programa desenvolvido em Python para verificação se o digitado se parece com um CNPJ
cnpj = input(' Digite os 14 números do seu CNPJ: ') .replace (".","") .replace ("/","") .replace ("-", "") #Linha para a digitação do CNPJ e comandos para que o ponto, barra e traço não sejam contados
conta = len(cnpj) #linh... | false |
301ac2b22fd395a78ceb5d8bbe9f75e05dee0c1b | SamuelVera/Algorithims-Misc | /bucketSort/Python/bucketSort.py | 2,159 | 4.3125 | 4 | def insertSort(arr: list, order: str = "asc") -> list:
"""Apply insert sort in the given order for the given array of integers
-------------------
Complexity:
Time: O(n^2)
Space: O(n) Array in memory
-------------------
Parameters:
arr : list
List to order
order ... | true |
d61520033fdb1d0402bb719b9242cf18095d62e2 | achillesecos/15-112-term-project | /dijkstra.py | 2,139 | 4.15625 | 4 | #Term Project
#Achilles Ecos
#aecos
#Graph Theory
#Cite Pseudo code from Wikipedia
#https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
class Graph:
def __init__(self):
#dictionary of nodes to its neighboring nodes where key is node and
#value is array of neighboring nodes
self.graph = {}
self.weight = {... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.