blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
85d969c057da158c9b16bd1143b78e7f1be1a990 | vkagwiria/thecodevillage | /Python Week 2/Day 1/02_else_statements.py | 1,073 | 4.5625 | 5 | """
Else statements
The final part of a good decision is what to do by default. Else statements are used to cater for this.
How They Work
Else conditional statements are the end all be all of the if statement. Sometimes you’re
not able to create a condition for every decision you want to make, so that’s where t... | true |
54ebed866e5e015a47b3e2a23ff660dab7adf0af | vkagwiria/thecodevillage | /Python Week 2/Day 1/exercise2.py | 381 | 4.28125 | 4 | # ask the user to input a number
# check whether the number is higher or lower than 100
# print "Higher than 100" if the number is greater than 100
# print "Loweer than 100" if the number is lower than 100
num=int(input("Please insert your number here: "))
if(num>100):
print("The number is greater than 100.... | true |
fcc5b1cf3dc24a7f146f66147223bc577a753eef | vkagwiria/thecodevillage | /Python Week 5/Day 2/Day 3/Object Oriented Programming/classes.py | 810 | 4.1875 | 4 | # attributes (variables within a class)
# class Car():
# capacity = 2000
# colour = 'white'
# mazda = Car()
# print(mazda.capacity,mazda.colour)
# # methods (functions within a class)
# class Dog():
# def bark():
# return bark
# german_shepherd = Dog()
# # access methods
# german... | true |
5ddd60d5209a8d63bb1517ca403b4bfe4ad0d9f6 | vkagwiria/thecodevillage | /Python week 1/Python Day 1/if_statements.py | 924 | 4.5 | 4 | if statements give us the ability to have our programs decide what lines of code to run,
depending on the user inputs, calculations, etc
Checks to see if a given condition is True or False
if statements will execute only if the condition is True
# syntax:
if some condition:
do something
"""
number1 = 5
nu... | true |
28d1ddc682cd7054814d9598f7a7f938140cf5e5 | samdarshihawk/python_code | /sum_array.py | 1,169 | 4.5 | 4 | '''
Given a 2D Array
We define an hourglass in to be a subset of values with indices falling.
There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in,
then print the maximum hourglass sum.
Function Description
Complete the function hourglas... | true |
0a4aa3128121334cb84eb728b4316dde61f2f6a1 | zuoshifan/sdmapper | /sdmapper/cg.py | 2,471 | 4.15625 | 4 | """
Implementation of the Conjugate Gradients algorithm.
Solve x for a linear equation Ax = b.
Inputs:
A function which describes Ax <-- Modify this vector -in place-.
An array which describes b <-- Returns a column vector.
An initial guess for x.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
fro... | true |
98d1f01500ee4038a2acba3d39b3e820b0af7f21 | bjday655/CS110H | /901815697-Q1.py | 1,651 | 4.5 | 4 | '''
Benjamin Day
9/18/2017
Quiz 1
'''
'''
Q1
'''
#input 3 values and assign them to 'A','B', and 'C'
A=float(input('First Number: '))
B=float(input('Second Number: '))
C=float(input('Third Number: '))
#check if the numbers are in increasing order and if so print 'the numbers are in increasing order'
if A<B<C:
pr... | true |
83e91333dcc783026f7383020e919ff7cb29432b | gracewanggw/PrimeFactorization | /primefactors.py | 972 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
PrimeFactors
@Grace Wang
"""
def prime_factorization(num):
## Finding all factors of the given number
factors_list = []
factor = 2
while(factor <= num):
if(num % factor == 0):
factors_list.append(factor)
factor = factor + 1
print(f... | true |
28a302e680fecebd3acfc1f4f8c0aa183b5efa0b | dstrube1/playground_python | /codeChallenges/challenge9.py | 1,375 | 4.125 | 4 | #challenge9
#https://www.linkedin.com/learning/python-code-challenges/simulate-dice?u=2163426
#Simulate dice
#function to determine the probability of certain outcomes when rolling dice
#assume d6
#Using Monte Carlo Method: Trial 1 - 1,000,000
#Roll dice over and over, see how many times each occurs, calculate probab... | true |
479f2b2aa2fe422659aa9a7667bdc135d4117ac7 | jkalmar/language_vs | /strings/strings.py | 1,751 | 4.4375 | 4 | #!/usr/bin/python3
""" Python strings """
def main():
""" Main func """
hello = "Hello"
world = "World"
print(hello)
print(world)
# strings can be merged using + operator
print(hello + world)
# also creating a new var using + operator
concat = hello + world
print(concat)
... | true |
225877fca1af5d782e1fb5ac0f694b4dfa703014 | samandeveloper/Object-Oriented-Programming | /Object Oriented Programming.py | 672 | 4.4375 | 4 | #Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
cat1=Cat('Loosy',1)
cat2=Cat('Tom',5)
cat3=Cat('Johnny',10)
print(cat1.name)
print(cat1.age)
print(cat2.name)
print(cat2.age)
print(c... | true |
b5a0c7b1e3d99afef07497fc70019ee271ff3aa7 | FabianForsman/Chalmers | /TDA548/Exercises/week6/src/samples/types/CollectionsSubtyping.py | 2,098 | 4.125 | 4 | # package samples.types
# Using super/sub types with collections
from typing import List
from abc import *
def super_sub_list_program():
d = Dog("Fido", 3)
c = Cat("Missan", 4, False)
pets: List[Pet] = []
pets.append(d) # Ok, Dog is a Pet
pets.append(c) # Ok, C... | true |
c4df0605b50f9bff5df32e5bcb89bb1ab6f51305 | FabianForsman/Chalmers | /TDA548/Exercises/week4/src/samples/Stack.py | 1,900 | 4.46875 | 4 | # package samples
# Python program to demonstrate stack implementation using a linked list.
# Class representing one position in the stack; only used internally
class Stack:
class Node:
def __init__(self, value):
self.value = value
self.next = None
# Initializing a stack.
... | true |
5d696e7556db84b16e050e5d4f7263e13f937423 | bz866/Data-Structures-and-Algorithms | /bubblesort.py | 668 | 4.25 | 4 | # Bubble Sort
# - Assume the sequence contains n values
# - iterate the sequence multiple times
# - swap values if back > front (bubble)
# - Time: O(n^2)
# - [(n -1) + 1] * [(n - 1 + 1) / 1 + 1] / 2
# - 0.5 * n^2 + 0.5 * n
# - Spac: O(1)
# - sorting done by swapping
import warnings
# implementation of the bubble so... | true |
4cc05e77f7d7fabc3f2498c8d93426425cfabcc9 | bz866/Data-Structures-and-Algorithms | /radixSort.py | 637 | 4.15625 | 4 | # Implementation of the radix sort using an array of queues
# Sorts a sequence of positive integers using the radix sort algorithm
from array import array
from queueByLinkedList import Queue
def radixSort(intList, numDigits):
# Create an array of queues to represent the bins
binArray = Array(10)
for k in range(10)... | true |
c9a567f4bcd0536dd1f3933c081d35d59ccad7a7 | bz866/Data-Structures-and-Algorithms | /linkedListMergeSort.py | 2,267 | 4.40625 | 4 | # The merge sort algorithm for linked lists
# Sorts a linked list using merge sort. A new head reference is returned
def linkedListMergeSort(theList):
# If the list is empty, return None
if not theList:
return None
# Split the linked list into two sublists of equal size
rightList = _splitLinkedList(theList)
... | true |
752c7275e39eb3b4ce0e30cd99d738d8406733dd | cBarnaby/helloPerson | /sine.py | 420 | 4.125 | 4 | import math
def sin(x):
if x > 360:
x = x%360
print(x)
x = x/180*math.pi
term = x
sum = x
eps = 1E-8
n = 2
while abs(term/sum) > eps:
term = -(term*x*x)/(((2*n)-1)*((2*n)-2))
sum = sum + term
n += 1
return sum
print(sin(3000))
x = (float... | true |
8e6c241216f935be862425a1b8854c4876757e75 | cyinwei/crsa-rg-algs-1_cyinwei | /bin/divide_and_conquer/mergesort.py | 1,015 | 4.21875 | 4 | def merge(left, right):
combined = [None] * (len(left) + len(right))
i = 0 #left iterator
j = 0 #right iterator
for elem in combined:
#first do cases where one arr is fully used
#note that we won't have out bounds, since the length
# of combined is the the two smaller blocks... | true |
176f3cede6656a83f21adf57e69af59538c1cc61 | vlad-belogrudov/jumping_frogs | /jumping_frogs.py | 1,307 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Jumping frogs and lamps - we have a number of either.
All lamps are off at the beginning and have buttons in a row.
Frogs jump one after another. The first frog jumps on each button
starting with the first button, the second frog on button number 2,
4, 6... the third on button number 3, 6, 9... | true |
9bc9a24e5de1f990442b9c544c04bb56121e3a9e | Soham2020/Python-basic | /General-Utility-Programs/LCM..py | 258 | 4.15625 | 4 | # Calculate LCM of Two Numbers
a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))
if(a>b):
min = a
else:
min = b
while(1):
if(min%a == 0 and min%b == 0):
print("LCM is",min)
break
min = min + 1 | true |
92764bc93100ff1c7472e93608a96d88c4936ebd | Soham2020/Python-basic | /Numpy/Arrays.py | 576 | 4.15625 | 4 | """
The NumPy (Numeric Python) package helps us manipulate large arrays and matrices of numeric data.
To use the NumPy module, we need to import it using:
import numpy
A NumPy array is a grid of values. They are similar to lists, except that every element of an array must be the same type.
Task
You are given a space ... | true |
e5c118e589dc2e47944ef452cb70660c7f854c88 | Soham2020/Python-basic | /General-Utility-Programs/GCD_HCF.py | 247 | 4.125 | 4 | # Calculate The GCD/HCF of Two Numbers
def gcd(a, b):
if(b==0):
return a
else:
return gcd(b, a%b)
a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))
ans = gcd(a, b)
print("The GCD is",ans) | true |
ec160ee9cf8ba837fd261d5e922cf29f73ca6af0 | Bharti20/python_if-else | /age_sex.py | 546 | 4.15625 | 4 | age=int(input("enter the age"))
sex=(input("enter the sex"))
maretial_status=input("enter the status")
if sex=="female":
if maretial_status=="yes" or maretial_status=="no":
print("she will work only urban area")
elif sex=="male":
if age>=20 and age<=40:
if maretial_status=="yes" or maretial_stat... | true |
ca79f69bcb7096b0e6d13c61bcef7785c0de1e35 | phattarin-kitbumrung/basic-python | /datetime.py | 411 | 4.28125 | 4 | import datetime
#A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
#To create a date, we can use the datetime() class (constructor) of the datetime module.
x = dateti... | true |
3b15fff39e3e4cc1ecbf5ed0e7d95fdcd15f662d | tj1234567890hub/pycharmed | /i.py | 514 | 4.25 | 4 | def findPrime(num):
prime = True
if num < 1:
print("This logic to identify Negative prime number is not yet developed.. please wait")
else:
for i in range(2, num - 1, 1):
if num % i == 0:
prime = False
break
print (prime)
return prime
if... | true |
0faccfc350ba25e81ae58256cfa90186a7310d12 | tchitchikov/data_structures_and_algorithms | /sorting/insertion_sort.py | 1,258 | 4.375 | 4 | __author__ = 'tchitchikov'
"""
An insert sort will allow you to compare a single element to multiple at once
The first value is inserted into the sorted portion, all others remain in
the unsorted portion. The next value is selected from the unsorted array and
compared against each value in the sorted array and inserted... | true |
a47002a92364beda833760095fdb204a48b68c29 | Serge-N/python-lessons | /Basics/strings/exercise2.py | 305 | 4.125 | 4 | user = input('Would you like to continue? ')
if(user=='no' or user =='No' or user == 'NO' or user=='n'):
print('Exiting')
elif (user=='yes' or user =='Yes' or user == 'YES' or user=='y'):
print('Continuing...')
print('Complete!')
else:
print('Please try again and respond with yes or no') | true |
d279c333259192f4c397269c8dde2fdb605527c4 | Serge-N/python-lessons | /Basics/Numeric/calculator.py | 1,484 | 4.375 | 4 | print ('Simple Calculator!')
first_number = input ('First number ?')
operation = input ('Operation ?')
second_number = input ('Second number ?')
if not first_number.isnumeric() or not second_number.isnumeric():
print('One of the inputs is not a number.')
operation = operation.strip()
if operation == '+' :
fi... | true |
ce7678a04a4faf67239c8131b7db9f42bfcaf579 | mikelhomeless/CS490-0004-python-and-deep-learning- | /module-1/python_lesson_1.py | 1,345 | 4.375 | 4 | # QUESTION 1: What is the difference between python 2 and 3?
# Answer: Some of the differences are as follows
# Print Statement
# - Python 2 allowed for a print statement to be called without using parentheses
# _ Python 3 Forces parentheses to be used on the print statement
#
# ... | true |
cdddf8d99ef523049380a7a9d659f6c02a77572a | tsholmes/leetcode-go | /02/84-peeking-iterator/main.py | 1,846 | 4.34375 | 4 | # Below is the interface for Iterator, which is already defined for you.
#
class Iterator(object):
def __init__(self, nums):
"""
Initializes an iterator object to the beginning of a list.
:type nums: List[int]
"""
self.nums = nums
def hasNext(self):
"""
R... | true |
c9d1bf857bd0a38c69c14069dc6801e8a034b143 | icarlosmendez/dpw | /wk1/day1.py | 2,249 | 4.15625 | 4 | # print 'hello'
# # if, if/else
# grade = 60
# message = 'you really effed it up!'
# if grade > 89:
# message = "A"
# elif grade > 79:
# message = 'B'
# elif grade > 69:
# message = 'C'
#
# print message
# # if, if/else
#
# name = 'bob'
#
# if(name == 'bob'):
# print 'your name is bob'
# elif(name ... | true |
09405c197f8fdd64081dda2c24197c37ad5da468 | kfactora/coding-dojo-python | /python_oop/bankAccount.py | 1,319 | 4.5 | 4 | # Assignment: BankAccount
# Objectives
# Practice writing classes
# The class should also have the following methods:
# deposit(self, amount) - increases the account balance by the given amount
# withdraw(self, amount) - decreases the account balance by the given amount if there are sufficient funds; if there is not ... | true |
1e99ffac6aebd8568435cd24162c5c20cd20185b | airportyh/begin-to-code | /lessons/javascript/guess_number_bonus.py | 948 | 4.125 | 4 |
while True:
import random
secret_number = random.randint(1, 10)
counter = 0
guess = int(input("I'm thinking of a number from 1-10. Pick one!"))
while counter <= 3:
if guess > secret_number:
print("Nope. Too high! Keep guessing!")
if guess < secret_number:
... | true |
91cbeb7914b033c2983011c6e270a5efa10a8f31 | Success2014/AlgorithmStanford | /QuickSort.py | 2,141 | 4.125 | 4 | __author__ = 'Neo'
def QuickSort(array, n):
"""
:param array: list
:param n: length of the array
:return: sorted array and number of comparison
"""
if n <= 1:
return array, 0
pivot = ChoosePivot2(array, n)
pivot_idx = array.index(pivot)
array = Partition(array, pivot_idx)
... | true |
864fb4584710cd28db4f0f9cec58ab1e60068662 | FakeEmpire/Learning-Python | /inheritance vs composition.py | 1,819 | 4.5 | 4 | # Most of the uses of inheritance can be simplified or replaced with composition
# and multiple inheritance should be avoided at all costs.
# here we create a parent class and a child class that inherits from it
class Parent(object):
def override(self):
print("PARENT override()")
def i... | true |
f38e472b66609a02b34c26746d4280f6fb869157 | FakeEmpire/Learning-Python | /lists.py | 1,192 | 4.46875 | 4 | # They are simply ordered lists of facts you want to store and access randomly or linearly by an index.
# use lists for
# If you need to maintain order. Remember, this is listed order, not sorted order. Lists do not sort for you.
# If you need to access the contents randomly by a number. Remember, this is us... | true |
328645b0543f27cc5b2bb471fb71bc33f6adf9ca | momentum-cohort-2019-02/w2d1--house-hunting-lrnavarro | /house-hunting.py | 1,143 | 4.40625 | 4 | print("How many months will it take to buy a house? ")
annual_salary = int(input("Enter your annual salary: ") )
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ") )
total_cost = int(input("Enter the cost of your dream home: ") )
down_payment_percent = input("Enter the percent of ... | true |
ac1558fae111c31f0d18e714807f93178e6ec275 | eflipe/python-exercises | /codewars/string_end_with.py | 682 | 4.28125 | 4 | '''
Link: https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d/train/python
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
'''
def solution(string... | true |
9dd2f246428cf6227a0f110cc2cf4efb468ad292 | eflipe/python-exercises | /apunte-teorico/gg/reverse_string.py | 249 | 4.28125 | 4 | # https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/
def reverse(s):
str = ""
for i in s:
str = i + str
return str
# otra
# Function to reverse a string
def reverse(string):
string = string[::-1]
return string
| true |
9c8fd4d8675080e4551348d61e1846d2a9b14f62 | eflipe/python-exercises | /automateStuff/strings_manipulation_pyperclip.py | 748 | 4.3125 | 4 | '''
Paste text from the clipboard
Do something to it
Copy the new text to the clipboard
#! python3
# Adds something to the start
# of each line of text on the clipboard.
'''
import pyperclip
text = pyperclip.paste()
print('Texto original :')
print(text)
print(type(text))
# split() return a list of strings, one fo... | true |
a854977aeab48172b818526ab814c99b2846fc72 | julianikulski/cs50 | /sentimental_vigenere/vigenere.py | 1,911 | 4.21875 | 4 | import sys
from cs50 import get_float, get_string, get_int
# get keyword
if len(sys.argv) == 2:
l = sys.argv[1]
else:
print("Usage: python vigenere.py keyword")
sys.exit("1")
# if keyword contains a non-alphabetical character
for m in range(len(l)):
if str.isalpha(l[m]) is False:
print("Please... | true |
4a35f649b74b1103a6520c8d04551038636613ba | JRMfer/dataprocessing | /Homework/Week_3/convertCSV2JSON.py | 695 | 4.34375 | 4 | #!/usr/bin/env python
# Name: Julien Fer
# Student number: 10649441
#
# This program reads a csv file and convert it to a JSON file.
import csv
import pandas as pd
import json
# global variable for CSV file
INPUT_CSV = "unemployment.csv"
def csv_reader(filename, columns):
"""
Loads csv file as dataframe and ... | true |
3152f88c91ac47190be22d71cc04623d4b8029ce | MarioAP/saturday | /sabadu/three.py | 390 | 4.15625 | 4 | # Create a variable containing a list
my_list = ['ano', 'mario', 'nando', 'niko']
# print that list
print my_list
# print the length of that list
print len(my_list)
# add an element to that list
my_variable = "hello world"
my_list.append(my_variable)
# print that list
print my_list
# print the length of that list
print... | true |
efccc9931fcb7b9594a54e383449557fa7a38ea7 | PalakSaxena/PythonAssigment | /Python Program that displays which letters are in two strings but not in both.py | 549 | 4.15625 | 4 | List1 = []
List2 = []
def uncommon(List1, List2):
for member in List1:
if member not in List2:
print(member)
for member in List2:
if member not in List1:
print(member)
num1 = int(input(" Enter Number of Elements in List 1 : "))
for i in range(0, num1):
ele = int... | true |
409615f7a9e1c85e8402fcde1e1ee1e3a20dcc78 | spartus00/PythonTutorial | /lists.py | 2,324 | 4.46875 | 4 | #Showing items in the list
food = ['fruit', 'vegetables', 'grains', 'legumes', 'snacks']
print(food)
print(food[-2])
print(food[0:-2])
#Add an item to a list
food.append('carbs')
print(food)
#Insert a new thing to a certain area in the list
food.insert(-1, 'beverages')
print(food)
#Extend method - add the items from... | true |
11fdf182212f1cabf7d32f2e741890f7d18923f1 | muyie77/Rock-Paper-Scissors | /RPS.py | 2,528 | 4.1875 | 4 | from random import randint
from sys import exit
# Function Declarations
# Player
def player():
while True:
choice = int(input("> "))
if choice == 1:
print("You have chosen Rock.")
break
elif choice == 2:
print("You have chosen Paper.")
break
... | true |
3fd9efdb51612106ecb7284f02490157906a7aaf | jitesh-cloud/password-guesser | /passGuesser.py | 1,082 | 4.375 | 4 | # importing random lib for checking out random pass
from random import *
# Taking a sample password from user to guess
give_pass = input("Enter your password: ")
# storing alphabet letter to use thm to crack password
randomPass = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k',
'l', 'm', 'n'... | true |
5da4f6ff26a580665ead28ed30b01cfc93cdf29a | devtony168/python-100-days-of-code | /day_09/main.py | 861 | 4.15625 | 4 | from replit import clear
from art import logo
#HINT: You can call clear() to clear the output in the console.
print(logo)
print("Welcome to the secret auction program!")
bidders = {}
def add_bid():
name = input("What is your name? ") # Key
bid = int(input("What is your bid? $")) # Value
bidders[name] = bid
add... | true |
1888175e01d6c4548fdd943699435df2d6d8ab44 | TravisMWeaver/Programming-Languages | /ProblemSet5/SideEffects2.py | 391 | 4.125 | 4 | #!/usr/bin/python
# Note that as arr1 is passed to changeList(), the values are being changed
# within the function, not from the return of the function. As a result, this
# behavior is indicative of a side effect.
def changeList(arr):
arr[0] = 9
arr[1] = 8
arr[2] = 7
arr[3] = 6
arr[4] = 5
return arr
arr1 = ... | true |
cffe973b153db29bc9b58010da4c7a0204a02169 | bhanukirant99/AlgoExpert-1 | /Arrays/TwoNumberSum.py | 465 | 4.125 | 4 | # time complexity = o(n)
# space complexity = o(n)
def twoNumberSum(array, targetSum):
# Write your code here.
dicti = {}
for i in range(len(array)):
diff = targetSum - array[i] # calculate diff between target and every other item in the array
if diff in dicti:
return ([diff, array[i]])
else:
... | true |
b0545ce4169a0b4f176f128cc990001be3068ebe | QiuFeng54321/python_playground | /while/Q5.py | 424 | 4.125 | 4 | # Quest: 5. Input 5 numbers,
# output the number of positive numbers and
# negative number you have input
i: int = 0
positives: int = 0
negatives: int = 0
while i < 5:
num: float = float(input(f"Number {i + 1}: "))
if num >= 0:
positives += 1
else:
negatives += 1... | true |
25116ccdfd3d7e7663d1764544bbd3bc4de4a664 | QiuFeng54321/python_playground | /loop_structure/edited_Q2.py | 323 | 4.1875 | 4 | # Quest: 2. Input integer x,
# if it is an odd number,
# output 'it is an odd number',
# if it is an even number,
# output 'it is an even number'.
print(
[
f"it is an {'odd' if x % 2 == 1 else 'even'} number"
for x in [int(input("Input a number: "))]
][0]... | true |
6ed9d9b9a39a91941c3c9ce522a9b2427b922be5 | koushikbhushan/python_space | /Arrays/replce_next_greatest.py | 562 | 4.28125 | 4 | """Replace every element with the greatest element on right side
Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is {16, 17, 4, 3, 5, 2}, ... | true |
2d157098f1f22a0940dd413d5459cd8e6027fc0b | mikaylakonst/ExampleCode | /loops.py | 1,222 | 4.375 | 4 | # This is a for loop.
# x takes on the values 0, 1, 2, 3, and 4.
# The left end of the range is inclusive.
# The right end of the range is exclusive.
# In other words, the range is [0, 5).
for x in range(0, 5):
print(x)
# This is another for loop.
# x takes on the values 0, 1, 2, 3, and 4. In other words,
# x tak... | true |
b4b3197fdd4fbea2e6b219e55e4bd87653123005 | Nishith/Katas | /prime_factors.py | 879 | 4.21875 | 4 | import sys
"""List of primes that we have seen"""
primes = [2]
def generate(num):
"""Returns the list of prime factors for the given argument
Arguments:
- `num`: Integer
Returns:
List of prime factors of num
"""
factors = []
if num < 2:
return factors
loop = 2
whi... | true |
c355a311ae7d97d282cf9c5788d05d77e6a9de83 | pruty20/100daysofcode-with-python-course | /days/01-03-datetimes/code/Challenges/challenges_3_yo.py | 1,743 | 4.28125 | 4 | # https://codechalleng.es/bites/128/
from datetime import datetime
from time import strptime, strftime
THIS_YEAR = 2018
"""
In this Bite you get some more practice with datetime's useful
strptime and stftime.
Complete the two functions: years_ago and convert_eu_to_us_date
following the instructions in their docstri... | true |
c7f351833cc35883cbc542a76d6659a112607a93 | kiddlu/kdstack | /python/programiz-examples/flow-control/if-else.py | 1,415 | 4.53125 | 5 | #!/usr/bin/env python
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = 1
if not num <= 0:
print(num, "is a positive number.")
print("This is also always printed.")
num = 3
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print(... | true |
b5ca219951a291a323d3e93c8b2c46369de54ba9 | alex99q/python3-lab-exercises | /Lab2/Exercise5.py | 676 | 4.15625 | 4 | range_start = int(input("Beginning of interval: "))
range_end = int(input("End of interval: "))
if range_start < range_end:
for num in range(range_start, range_end + 1):
if 0 < num < 10:
print(num)
continue
elif 10 <= num < 100:
continue
else:
... | true |
3a5ac90e5105ef1d1be19c786f79f553dfc5b7db | honda0306/Intro-Python | /src/dicts.py | 382 | 4.21875 | 4 | # Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
waypoints = [
{'hometown': 'Rescue, CA'},
{'age': 42},
{'hobbies': 'smiling'}
]
# Write a loop that prints out all the field ... | true |
7c1667f2c28599a74f27953fa8752f8162e05987 | krishia2bello/N.B-Mi-Ma-Sorting-Algorithm | /NB_MiMa_Sorting_Algorithm.py | 2,046 | 4.34375 | 4 | def sort_list(list_of_integers):
list_input = list_of_integers # copying the input list for execution
sorted_list = [] # defining the new(sorted) list
min_index = 0 # defining the index of the minimum ... | true |
a333e519c0b53b1649c07102417a38ae4f13c8a5 | Ler4onok/ZAL | /3-Calculator/calculator.py | 2,010 | 4.21875 | 4 |
import math
def addition(x, y):
addition_result = x + y
return addition_result
def subtraction(x, y):
subtraction_result = x - y
return subtraction_result
def multiplication(x, y):
# multiplication_result = args[0]*args[1]
multiplication_result = x * y
return multiplication_result
de... | true |
55873f77d5e19e886a182236b4658eee94b21ec2 | clairepeng0808/Python-100 | /07_mortgage:-calculator.py | 2,756 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 18:04:17 2020
@author: clairepeng
Mortgage Calculator - Calculate the monthly payments of a f
ixed term mortgage over given Nth terms at a given interest rate.
Also figure out how long it will take the user to pay back the loan.
For added comp... | true |
4f483712e0265702305407df328a349d9ad00b84 | clairepeng0808/Python-100 | /08_change_return_program.py | 2,610 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 18:53:27 2020
@author: clairepeng
Change Return Program -
The user enters a cost and then the amount of money given.
The program will figure out the change and the number of
quarters, dimes, nickels, pennies needed for the change.
"""
def en... | true |
0932555326668cc6127d1d4b3adfe644e6da19f8 | clairepeng0808/Python-100 | /37_check_if_palindrome.py | 753 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 15:52:44 2020
@author: clairepeng
**Check if Palindrome** - Checks if the string entered by the user
is a palindrome. That is that it reads the same forwards as backwards
like “racecar”
"""
from utility import utility as util
def enter_strin... | true |
2413e3107fbf48938c305f595a678c8ab1b5dbaa | thuytran100401/HW-Python | /multiply.py | 549 | 4.28125 | 4 | """
Python program to take in a list as input and multiply all of the
elements in the list and return the result as output.
Parameter
inputList: list[]
the integer list as input
result: int
the result of multiplying all of the element
"""
def multiply_list(inputList):
resu... | true |
871e54ac66b3349a0e66a0117f4a800177f18a2b | SamCadet/PythonScratchWork | /Birthdays.py | 494 | 4.21875 | 4 | birthdays = {'Rebecca': 'July 1', 'Michael': 'July 22', 'Mom': 'August 22'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is ' + str(name) + '\'s birthday.')
else:
print('I do not have ... | true |
c72c90e0c2dfe865eab1d40b99073a8e757cca95 | taharBakir/code_cademy-python | /string_stuff.py | 1,121 | 4.375 | 4 | #Print a
s="Hella"[4]
print s
#Print the length of the string
parrot = "Norwegian Blue"
print len(parrot)
#Print the string in lower case
parrot = "Norwegian Blue"
print parrot.lower()
#Print the string in upper case
parrot = "norwegian blue"
print parrot.upper()
#toString
pi = 3.14
print str(pi)
#Methods that us... | true |
ccebdf820de15e6ff5c5e06b20fa75bbd06448f9 | mitchell-hardy/CP1404-Practicals | /Week 3/asciiTable.py | 1,280 | 4.125 | 4 | __author__ = 'Mitch Hardy'
def main():
NUMBER_MINIMUM = 33
NUMBER_MAXIMUM = 127
# get a number from the user (ASCII) and print the corresponding character.
user_number = get_number(NUMBER_MINIMUM, NUMBER_MAXIMUM)
# get a character from the user and print the corresponding ASCII key
print("The... | true |
a48c5ea84c3d9d6a8af8517150977ae2c99b8ad7 | abhisheknm99/APS-2020 | /52-Cartesian_product.py | 245 | 4.3125 | 4 | from itertools import product
#only with one list
arr=[1,2,3]
#repeat=2 i.e arr*,repeat=3 i.e arr*arr*arr
l=list(product(arr,repeat=3))
#different arrays
arr1=[1,2,3]
arr2=[2,3]
arr3=[3]
cartesian=list(product(arr1,arr2,arr3))
print(cartesian) | true |
3e05e88a61f112f293f4efb6a0a81f63e0909410 | abdullahw1/CMPE131_hw2 | /calculator.py | 1,529 | 4.46875 | 4 | def calculator(number1, number2, operator):
"""
This function will allow to make simple calculations with 2 numbers
parameters
----------
number1 : float
number2 : float
operator : string
Returns
-------
float
"""
# "... | true |
872fe63e47975aaf586df582e37aced46ed5f8c2 | ZY1N/Pythonforinfomatics | /ch9/9_4.py | 940 | 4.28125 | 4 | #Exercise 9.4 Write a program to read through a mail log, and figure out who had
#the most messages in the file. The program looks for From lines and takes the
#second parameter on those lines as the person who sent the mail.
#The program creates a Python dictionary that maps the senders address to the total
#number of... | true |
d33211f78829e397346809c11dd08ea732d61363 | ZY1N/Pythonforinfomatics | /ch11/11_1.py | 491 | 4.15625 | 4 | #Exercise 11.1 Write a simple program to simulate the operation of the the grep
#command on UNIX. Ask the user to enter a regular expression and count the number of lines that matched the regular expression:
import re
fname = open('mbox.txt')
rexp = raw_input("Enter a regular expression : ")
count = 0
for line in ... | true |
bf4fb0bb615781cd26ea4c7fde9ee78f21c5dff0 | archana-nagaraj/experiments | /Udacity_Python/Excercises/testingConcepts.py | 890 | 4.21875 | 4 | def vehicle(number_of_tyres, name, color):
print(number_of_tyres)
print(name)
print(color)
vehicle(4, "Mazda", "blue")
# Trying Lists
courses = ['Math', 'Science', 'CompSci']
print(courses)
print(len(courses))
print(courses[1])
print(courses[-1])
#Lists slicing
print(courses[0:2])
print(courses[:2])
pr... | true |
9a2a1d2058cc7a2b6345d837173e109f20b39ed5 | jeb26/Python-Scripts | /highestScore.py | 622 | 4.21875 | 4 | ##Write a prog that prompts for a number of students. then each name and score and
##then displays the name of student with highest score.
scoreAcc = 0
nameAcc = None
currentScore = 0
currentName = None
numRuns = int(input("Please enter the number of students: "))
for i in range(numRuns):
currentName ... | true |
fdb5d39c2ed2c61416aeffb1e4dbc491241ce316 | sonht113/PythonExercise | /HoTrongSon_50150_chapter5/Chapter5/Exercise_page_145/Exercise_04_page_145.py | 338 | 4.1875 | 4 | """
Author: Ho Trong Son
Date: 18/08/2021
Program: Exercise_04_page_145.py
Problem:
4. What is a mutator method? Explain why mutator methods usually return the value None.
Solution:
Display result:
58
"""
#code here:
data = [2, 5, 24, 2, 15, 10]
sum = 0
for value in data:
sum +=... | true |
25a467d72816cf35cf0b5ef9b94503dd40376c2a | sonht113/PythonExercise | /HoTrongSon_50150_chapter2/Chapter2/exercise_page_46/exercise_04_page_46.py | 624 | 4.125 | 4 | """
Author: Ho Trong Son
Date: 11/07/2021
Program: exercise_04_page_46.py
PROBLEM:
4) What happens when the print function prints a string literal with embedded
newline characters?
SOLUTION:
4)
=> The print function denoted print() in a computer programming language such as Python is a function that pr... | true |
7d4ed044ec86306dff4cb4752b0d6d9202fad492 | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Project_page_132-133/project_12_page_133.py | 1,421 | 4.15625 | 4 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Project_12_page_133.py
Problem:
12. The Payroll Department keeps a list of employee information for each pay period in a text file.
The format of each line of the file is the following:
<last name> <hourly wage> <hours ... | true |
805f1755caf35c97cf3c31dfe3436ffc407ccb01 | sonht113/PythonExercise | /HoTrongSon_50150_chapter5/Chapter5/Exercise_page_149/Exercise_04_page_149.py | 522 | 4.125 | 4 | """
Author: Ho Trong Son
Date: 18/08/2021
Program: Exercise_04_page_149.py
Problem:
4. Define a function named summation. This function expects two numbers, named low and high, as arguments.
The function computes and returns the sum of the numbers between low and high, inclusive.
Solution:
Disp... | true |
ca59990c60f302bcb8521710ad34a14d493224f4 | sonht113/PythonExercise | /HoTrongSon_50150_chapter3/Chapter3/Exercise_page_70/exercise_02_page_70.py | 364 | 4.1875 | 4 | """
Author: Ho Trong Son
Date: 23/07/2021
Program: exercise_02_page_70.py
PROBLEM:
2. Write a loop that prints your name 100 times. Each output should begin on a new line.
SOLUTION:
"""
# Code here:
name = "Ho Trong Son"
for i in range(100):
print(name, "(" + str(i+1) + ")")
# Result:
# Ho Trong Son (1... | true |
e8e4d0c2a84f2bf905a9a4c3721e132249cfd403 | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Project_page_132-133/project_05_page_132.py | 1,139 | 4.5625 | 5 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Project_05_page_132.py
Problem:
5. A bit shift is a procedure whereby the bits in a bit string are moved to the left or to the right.
For example, we can shift the bits in the string 1011 two places to the left to produce the string 1110.
Not... | true |
1e23187a25a230abed4a21b60cdda3e90ae27930 | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Exercise_page_118/Exercise_01_page_118.py | 805 | 4.25 | 4 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Exercise_01_page_118.py
Problem:
1. Assume that the variable data refers to the string "Python rules!". Use a string method from Table 4-2
to perform the following tasks:
a. Obtain a list of the words in the string.
b. Convert the ... | true |
a6971bf97f895b2eafc8af4aba0a631b0bc3dfbe | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Exercise_page_125/Exercise_03_page_125.py | 682 | 4.3125 | 4 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Exercise_03_page_125.py
Problem:
3. Assume that a file contains integers separated by newlines. Write a code segment that opens the
file and prints the average value of the integers.
Solution:
Display result:
Average: 5.0
"""
#Cod... | true |
8fe5c46bdf8a1c42a910d3135d1a8f0dde4fee4f | sonht113/PythonExercise | /HoTrongSon_50150_chapter6/Chapter6/Exercise_page_182/Exercise_04_page_182.py | 522 | 4.125 | 4 | """
Author: Ho Trong Son
Date: 01/09/2021
Program: Exercise_04_page_182.py
Problem:
4. Explain what happens when the following recursive function is called with the value 4 as an argument:
def example(n):
if n > 0:
print(n)
example(n - 1... | true |
4ba7d4715f7716794594ae54630d63a3ad3e3745 | sonht113/PythonExercise | /HoTrongSon_50150_chapter3/Chapter3/Project_page_99-101/project_07_page_100.py | 1,986 | 4.1875 | 4 | """
Author: Ho Trong Son
Date: 24/07/2021
Program: project_07_page_100.py
Problem:
7. Teachers in most school districts are paid on a schedule that provides a salary based on their number of years
of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,0... | true |
9ddbfa493304a945a607310e245ba8265ebd8a26 | AAM77/Daily_Code_Challenges | /codewars/6_kyu/python3/who_likes_it.py | 2,339 | 4.28125 | 4 | # Name: Who Likes It
# Source: CodeWars
# Difficulty: 6 kyu
#
# URL: https://www.codewars.com/kata/who-likes-it/train/ruby
#
#
# Attempted by:
# 1. Adeel - 03/06/2019
#
#
##################
# #
# Instructions #
# #
##################
#
#
# You probably know the "like" system from Faceboo... | true |
fca476b8dd0f39eacd82ee137010acc742dfb1c3 | keshopan-uoit/CSCI2072U | /Assignment One/steffensen.py | 1,470 | 4.28125 | 4 | # Keshopan Arunthavachelvan
# 100694939
# January 21, 2020
# Assignment One Part Two
def steffensen(f, df, x, epsilon, iterations):
'''
Description: Calculates solution of iterations using Newton's method with using recursion
Parameters
f: function that is being used for iteration (residual)
df: d... | true |
eae0607b690abe39fd59214c1d018ac0ddc24d13 | fhorrobin/CSCA20 | /triangle.py | 290 | 4.125 | 4 | def triangle_area(base, height):
"""(number, number) -> float
This function takes in two numbers for the base and height of a
triangle and returns the area.
REQ: base, height >= 0
>>> triangle_area(10, 2)
10.0
"""
return float(base * height * 0.5)
| true |
42467a9b02e36935f5c34815dc53081841a156fb | tsung0116/modenPython | /program02-input.py | 479 | 4.125 | 4 | user_name = input("Enter your name:")
print("Hello, {name}".format(name=user_name))
principal = input("Enter Loan Amount:")
principal = float(principal)
interest = 12.99
periods = 4
n_years = 2
final_cost = principal * (1+interest/100.0/periods)**n_years
print(final_cost)
print("{cost:0.02f}".format(cost=final_cost)... | true |
0e034002296b0cf3d7c0486907d571802341606d | DanaAbbadi/data-structures-and-algorithms-python | /data_structures_and_algorithms/stacks_and_queues_challenges/stacks.py | 1,922 | 4.28125 | 4 | from data_structures_and_algorithms.stacks_and_queues_challenges.node import Node
# from node import Node
class Stack(Node):
def __init__(self):
self.top = None
def push(self, *args):
"""
Takes a single or multiple values as an argument and adds the new nodes with that value ... | true |
ddb6bb1bc35904275e44ba87e46cf1efe7983c0f | DanaAbbadi/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/binary_tree/breadth_first.py | 1,541 | 4.1875 | 4 | class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
"""
This class is responsible of creating and traversing the Binary Search Tree.
"""
def __init__(self):
self.root = None
def breadth_first(self... | true |
30b58144b16e936bea70ff6d1bb79c56db04947c | avikchandra/python | /Python Assignment/centredAverage.py | 574 | 4.28125 | 4 | #!/usr/bin/env python3
'''
"centered" average of an array of integers
'''
# Declare the list
num_list=[-10, -4, -2, -4, -2, 0]
# Find length
list_len=len(num_list)
# Check if length is odd or even
if list_len%2 == 0:
# For even length, find average of two centred numbers
mean_result=(num_list... | true |
8d812c5251edda45c2a531b9bf28ed4b138e233c | avikchandra/python | /Python Assignment/wordOccurence.py | 1,459 | 4.125 | 4 | #!/usr/bin/env python3
'''
highest occurences of words in file "sample.txt"
'''
def main():
# Declare dict
word_dict={}
punct_list=[',','.','\'',':','?','-'] # list of punctuations
# Create file object from file
file_obj=open("sample.txt", 'r')
word_list=[]
# Read line fro... | true |
fbb14a7e554803b8d3e42998a545bd399ab9c795 | avikchandra/python | /Python Advanced/sentenceReverse.py | 303 | 4.4375 | 4 | #!/usr/bin/env python3
'''
Reverse words in sentence
'''
# Take input from user
orig_string=input("Enter the string: ")
str_list=orig_string.split()
# Option1
#str_list.reverse()
#print(' '.join(str_list))
# Option2
reversed_list=list(str_list[::-1])
print(' '.join(reversed_list))
| true |
ee1aeab37fc4b91f7f8f65b50aba287b8e9c1801 | Joldiazch/holbertonschool-higher_level_programming | /0x06-python-classes/2-square.py | 460 | 4.375 | 4 | #!/usr/bin/python3
class Square:
"""class Square that defines a square by: (based on 0-square.py)
Attributes:
size_of_square (int): Description of `attr1`.
"""
def __init__(self, size_of_square=0):
if type(size_of_square) is not int:
raise TypeError('size must be an integer'... | true |
54c574df0d191bcd3e68f076859588c74827b1ef | beckam25/ComputerScience1 | /selectionsort.py | 2,652 | 4.375 | 4 | """
file: selectionsort.py
language: python3
author: bre5933@rit.edu Brian R Eckam
description:
This program takes a list of numbers from a file and
sorts the list without creating a new list.
Answers to questions:
1) Insertion sort works better than selection sort in a case where you have
a very long list t... | true |
079ac76649cfff4b61345dd077e68178de0ffc52 | joseluismendozal10/test | /DATA ANALYTICS BOOTCAMP/June 19/Python/2/quick check up .py | 266 | 4.125 | 4 | print("Hello user")
name = input("what is your name?")
print ("Hello" + name)
age = int(input("whats your age?"))
if age >= 21:
print("Ah, a well traveled soul you are ye")
else:
print("aww.. you're just a baby!")
| true |
25f5ba74734da7afb773999499cca4c79685c717 | r0hansharma/pYth0n | /prime number.py | 319 | 4.125 | 4 | no=int(input('enter the no to check\n'))
if(no>1):
for i in range(2 , no):
if(no%i==0): print(no,'is not a prime number')
else:
print( no,"is a prime number")
elif(no==1):
print("1 is neither a prime nor a compposite number")
else:
print("enter a number greater than 1") | true |
27908d6450779964609a859a83c29decd4e67d3e | bnsh/coursera-IoT | /class5/week4/leddimmer.py | 605 | 4.25 | 4 | #! /usr/bin/env python3
"""This is week 4 of the Coursera Interfacing with the Raspberry Pi class.
It simply dims/brightens the LED that I've attached at pin 12 back and forth."""
import math
import time
import RPi.GPIO as GPIO
def main():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
pwm = GPIO.PWM(12, 50... | true |
e2fda25298068dda88406226945b707a7514a200 | JesNatTer/python_fibonacci | /fibonacci.py | 464 | 4.1875 | 4 | numbers = 20 # amount of numbers to be displayed
def fibonacci(n): # function for fibonacci sequence
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2) # function formula for fibonacci
if numbers <= 0:
print("Please enter positive value") # amount of numbers cannot be l... | true |
15cfa3ed4506417d5eb879b43e1ac0a6f3d9b5bc | Moiseser/pythontutorial | /ex15.py | 719 | 4.375 | 4 | #This allows your script to ask you on the terminal for an input
from sys import argv
#this command asks you what the name of your text file you want to read is
script,filename = argv
#this opens the file and then assigns the opened file to a variable
txt = open(filename)
#here we print the name of the file
print 'Her... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.