blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b01ea9552782249f526040b1621b4218adb68a7a | jaewon4067/Codes_with_Python | /Object-oriented programming/Creating a simple blog.py | 1,576 | 4.5 | 4 | """
As I'm learning OOP, I'm going to make a mini blog where people can post with me.
I'm going to create a 'Post' class and a BlogUser' class to print out the full contents of the blog.
"""
class Post:
def __init__(self, date, content):
# The post class has date and content as attributes.
self.... | true |
08208fe3612826d96129e5fcf3e87131e11f3a24 | namaslay33/Python | /Day1.py | 1,368 | 4.375 | 4 | # Write a Python program to print the following string in a specific format (see the output). Go to the editor
# Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
# Output :
# Twink... | true |
c945a40c704f1620193151da431a184542c957ad | namaslay33/Python | /FunctionExercises/FunctionExercise4.py | 435 | 4.15625 | 4 | # 4. Odd or Even
# Write a function f(x) that returns 1 if x is odd and -1 if x is even. Plot it for x values of -5 to 5 in increments of 1. This time, instead of using plot.plot, use plot.bar instead to make a bar graph.
import matplotlib.pyplot as plot
def f(x):
if x % 2 != 0:
return 1
else:
... | true |
e09253f9a7610a88e51bb69920829a69ad5fb3a1 | spettigrew/cs2-guided-project-ram-basics | /src/lower_case_demo1.py | 1,660 | 4.59375 | 5 | """
Given a string, implement a function that returns the string with all lowercase
characters.
Example 1:
Input: "LambdaSchool"
Output: "lambdaschool"
Example 2:
Input: "austen"
Output: "austen"
Example 3:
Input: "LLAMA"
Output: "llama"
*Note: You must implement the function without using the built-in method on... | true |
fa9f821dd75ab2d98c2f8fdc7a62b275f905d5c7 | Gcriste/Python | /listAppendInsertExtend.py | 1,579 | 4.3125 | 4 | # Create a list called instructors
instructors = []
# Add the following strings to the instructors list
# "Colt"
# "Blue"
# "Lisa"
instructors.append("Colt")
instructors.append("Blue")
instructors.append("Lisa")
# Create a list called instructors
instructors = []
# Add the following str... | true |
f525573e903ced3083429eab40cb5e20af07ea70 | Ivaylo-Atanasov93/The-Learning-Process | /Python Advanced/Lists_as_Stacks_and_Queues-Exercise/Balanced Paretheses.py | 874 | 4.125 | 4 | sequence = input()
open_brackets = ['(', '{', '[']
closing_brackets = [')', '}', ']']
def balanced(sequence):
stack = []
for bracket in sequence:
if bracket in open_brackets:
stack.append(bracket)
elif bracket in closing_brackets:
index = closing_brackets.index(bracket)
... | true |
376a1185f116eebf1b94ecaa5669cfc799a7dacb | santhosh790/competitions | /DailyCodingProblem/D130a_MaxProfitStockList.py | 1,447 | 4.1875 | 4 | '''
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in
those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by
buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the gi... | true |
9172b5f15b2faef2f93a79417f72647832ebdaf9 | mr-vaibh/python-payroll | /PRACTICAL-FILES/string/string2.py | 371 | 4.34375 | 4 | # This function prints a pyramid
def make_pyramid(n):
k = n - 1 # for spaces
# loop for number of rows
for i in range(0, n):
# loop for number spaces
for j in range(0, k):
print(end=" ")
k -= 1
# loop for number of columns
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = int(input(... | true |
4d32a642c347bed483aa859d9b499485e2818265 | mr-vaibh/python-payroll | /PRACTICAL-FILES/string/string1.py | 293 | 4.25 | 4 | # this program simply prints a string in vertical reverse order
string = str(input("Enter a string: "))
length = len(string)
initial = 0
# the range in the loop below basically deals with length
for i in range(-1, -(length + 1), -1):
print(string[initial] + "\t" + string[i])
initial += 1 | true |
ba973167bfcc7d3842194a2e1d190c276ec5b74e | mr-vaibh/python-payroll | /PRACTICAL-FILES/others/3-stack.py | 609 | 4.28125 | 4 | # implementation of stack using list
stack = []
choice = 'y'
print('1. Push\n2. Pop\n3. Display elements of stack')
while True:
choice = int(input("Enter your choice: "))
if choice == 1:
elem = input("Enter your element which you want to push: ")
stack.append(elem)
elif choice == 2:
... | true |
8fef69e5d705f817e78315d18611a2c3a77f09b4 | love-adela/algorithm-ps | /acmicpc/4504/4504.py | 215 | 4.15625 | 4 | n = int(input())
number = int(input())
while number:
if number % n == 0:
print(f'{number} is a multiple of {n}.')
else:
print(f'{number} is NOT a multiple of {n}.')
number = int(input())
| true |
3785c2340cc205f09c94f5d1753ff221f53aa041 | wmichalak/algorithms_and_datastructures | /Session 1/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py | 1,337 | 4.125 | 4 | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
"""Find the maximal value of items that fit into the backpack
:param capacity:
:param weights:
:param values:
:return maximum price of items that fit into the backpack of given capacity"""
# Get price per weight list s... | true |
44cb4188e6949960326659bdd6ee4db10f9d8046 | cesarramos95/Algotitmo-Shannon-Fano | /encode.py | 1,043 | 4.15625 | 4 | #!/usr/bin/env python3
from calculations import calculate_codes
def encode(symbol_sequence, codes):
encoded = []
codes_dict = dict(codes)
for symbol in symbol_sequence:
code = codes_dict.get(symbol)
if code is None:
raise Exception(f"Invalid symbol: {symbol}")
encoded... | true |
515e1f803403b0da28345dab126a0c43ee26c855 | EshSubP/Advent-of-code2020 | /Day 5/Solution/Day5_1.py | 274 | 4.125 | 4 | fname = input("Enter file name: ")
fh = open(fname)
s = ""
largest = 0
for line in fh:
s = line.replace('F','0').replace('B','1').replace('L','0').replace('R','1')
decimal = int(s,2)
if decimal>largest:
largest = decimal
print(largest)
| true |
74496e40f3712ea5a0a66e12f6bc8379319be36a | ag220502/Python | /Programs/ForLoops/nDiffInputsSumAndAverage.py | 297 | 4.15625 | 4 | #Take N different inputs and print their sum and average
n = int(input("Enter the Number Of Values : "))
sum1 = 0
for i in range(1,n+1):
inp = int(input("Enter Value",i," : "))
sum1 = sum1 + inp
print("The Sum Of Inputs are : ",sum1)
avg = sum1/n
print("The Average Of Inputs are : ",avg)
| true |
3d51fc9dc33632d4b7716a77322f25c4c60087d4 | ag220502/Python | /PythonWorbook/IntroductionToProgramming/ex1.py | 602 | 4.5625 | 5 | '''
Exercise 1: Mailing Address
Create a program that displays your name and complete mailing address.
The address should be printed in the format that is normally used in the
area where you live.Your program does not need to read any input from the user.
'''
name = "Narendra Aliani"
comp = "Pragati Computers"
street =... | true |
536ee6d0932a23527435bf198a2ad25b7a67b846 | hwulfmeyer/NaiveBayesClassifier | /filehandling.py | 2,133 | 4.15625 | 4 | """
This file is for the methods concerning everything from file reading to file writing
"""
import re
import random
def read_data_names(filepath: str):
"""
function to read class names & attributes
:param filepath: the relative path to the file containing the specifications of the attribute_values
:... | true |
ccd2ad36f3775d3697aa5b95913cb371047aa272 | vaishalicooner/Practice-Linked-list | /practice_linkedlist/llist_palindrome.py | 484 | 4.15625 | 4 | # Implement a function to check if a linked list is a palindrome.
def is_palindrome(self):
head = self
prev = None
while self.next:
self.prev = prev
prev = self
self= self.next
tail = self
tail.prev = prev
while head is not tail and head.data == tail.data:
head... | true |
d2637b319939be641a6c2a7c41e65e4aa0c09087 | caitp222/algorithms | /quicksort.py | 396 | 4.125 | 4 | def quicksort(lst):
if len(lst) <= 1:
return lst
else:
pivot = lst[-1]
less = []
more = []
for x in lst:
if x < pivot:
less.append(x)
elif x > pivot:
more.append(x)
return quicksort(less) + [pivot] + quicksor... | true |
125983d80ed08e174a0b4fa12298dea058c6dbff | tiagoColli/tcc | /oam/preprocess/__init__.py | 1,066 | 4.28125 | 4 | import pandas as pd
def normalize(df: pd.DataFrame, min: int, max: int, weights: dict = None) -> pd.DataFrame:
''' A min-max normalization to all the columns in the dataframe.
If desired you can change the scale of a given column using the 'weights'
param. The weight will be multiplied by every value in t... | true |
81907a9c79fd38a1eaf3f0f3ca3bcfad2822eed7 | Environmental-Informatics/building-more-complex-programs-with-python-walcekhannah | /program_6.5.py | 553 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Due January 31, 2020
Created on Tue Jan 28 14:49:13 2020
by Hannah Walcek
ThinkPython Exercise 6.5
This program creates the function gcd which finds the greatest common divisor
between two values, a and b.
"""
def gcd(a,b):
"""
This function takes two integers... | true |
db80e754a496e9bbfe46e4bc6221f88db2881867 | nimesh-p/python | /Programs/prime.py | 368 | 4.25 | 4 | def check_prime_number():
num = int(input("Enter the number to check prime or not: "))
if (num == 1):
return "1 is neither prime nor composite"
elif (num <= 0):
return "Enter valid number"
else:
for number in range(2, num):
if(num % number == 0):
return "Number is not prime"
br... | true |
dde3119b0326f82c7fc6a841a65c743996761905 | EmilyM1/IteratorAndGenerator | /iterateGenerate.py | 2,325 | 4.21875 | 4 | #!/usr/bin/python 3
#counts letters in words
words = """When we speak we are afraid our words will not be heard or welcomed.
But when we are silent, we are still afraid. So it is better to speak.""".split()
print(words)
numberoflettersineachword = [len(word) for word in words]
print(numberoflettersineachword)
#FOR ... | true |
5f4bbef7e4d835b91cd01c0b40820d3ce2b33fb1 | masonbot/Wave-1 | /volumeofcylinder.py | 223 | 4.125 | 4 | import math
pi = math.pi
Height = input("Height of cylinder in metres: ")
Radius = input("Radius of cylinder in metres: ")
r2 = float(Radius) * float(Radius)
area = float(pi) * (r2) * float(Height)
print(round(area,1)) | true |
93aecb1e3e72c0bf869e318fc8bd42a087f4df2f | MTGTsunami/LeetPython | /src/leetcode/graph/union_find/1202. Smallest String With Swaps.py | 1,848 | 4.25 | 4 | """
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to afte... | true |
722ce61e45de006519ae80918965d818eb1a749a | MTGTsunami/LeetPython | /src/leetcode/graph/union_find/547. Friend Circles.py | 1,882 | 4.25 | 4 | """
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect frien... | true |
29c910f3e2c4c5f71d547c819d2b52cf33c1d6fb | TamishaRutledge/LearningPython | /learning_strings.py | 554 | 4.59375 | 5 | #Learning about strings and string manipulation
strings = "The language of 'Python' is named for Monty Python"
print(strings)
"""
The title method changes each word to title case
Where each word begins with a capital letter
The upper method converts the string to all uppercase
The lower method converts the string to ... | true |
b69b7875b640001a743e3d51961b81e6ccf64299 | Whit3bear/yogurt | /katas/5kky_The_Clockwise_Spiral.py | 1,031 | 4.8125 | 5 | """ Do you know how to make a spiral? Let's test it!
Classic definition: A spiral is a curve which emanates from a central point, getting progressively farther away as it revolves around the point.
Your objective is to complete a function createSpiral(N) that receives an integer N and returns an NxN two-dimensional a... | true |
e4719f01ead333588f33677263df9745019bbc4c | Whit3bear/yogurt | /katas/6kky_Build_Tower.py | 989 | 4.1875 | 4 | """ Build Tower
Build Tower by the following given argument:
number of floors (integer and always greater than 0).
Tower block is represented as *
Python: return a list;
JavaScript: returns an Array;
C#: returns a string[];
PHP: returns an array;
C++: returns a vector<string>;
Haskell: return... | true |
9c04455fc47972869896529685f7887bb5f79458 | Lcarpio69/Interactive-Python-Temperature-Converter | /myController.py | 1,623 | 4.34375 | 4 | import tkinter
import myView # the VIEW
import myModel # the MODEL
# this is controller class that binds the View and Model classes
class Controller:
"""
The Controller for an app that follows the Model/View/Controller architecture.
When the user presses a Button on the View, this Controller call... | true |
f905cfcc20b56b5c3e5c089e878869aa4422b80a | AngelVasquez20/APCSP | /Angel Vasquez - Magic 8 Ball.py | 982 | 4.125 | 4 | import time
import random
answers = ["maybe", "not sure", "could be", "positive", "ask again", "Yes", "no", "Possibly", "Ask later", "I'm tired",
"I don't know", "YESSS", "I think you are"]
name = input("What is your name:")
print("Welcome to Magic 8 Ball %s where you ask a question and the magic ball will... | true |
ead07a51b9790967e90c5cd0e81dffeddd863046 | AngelVasquez20/APCSP | /Challenge 5.py | 212 | 4.15625 | 4 | def rectangle():
length = int(input("Please enter the following length of a rectangle: "))
width = int(input("Please enter the following width of the rectangle: "))
print(length * width)
rectangle() | true |
ea4e20dda65d32fdadcdcaa8035abf5eb452e4b2 | Vakicherla-Sudheethi/Python-practice | /count.py | 215 | 4.21875 | 4 | o=input('Enter a string as input:')
p={}#{} are used to define a dictionary.
for i in set(o):
p[i]=o.count(i)#count() function returns the number of occurrences of a substring in the given string.
print(p)
| true |
186e12c1d208a7637635ef204bdccf4bd79d0a8b | Iandavidk/Web-development-2021 | /Numerical_grade_to_letter_grade.py | 333 | 4.3125 | 4 | #get user input of a numerical grade
grade = input("Enter your grade: ")
#cast to an int
grade = int(grade)
#test the range of the number and print the appropriate letter grade
if grade >= 90:
print('A')
elif grade >= 80:
print('B')
elif grade >= 70:
print('C')
elif grade >= 60:
print('D')
else:
... | true |
ccf306f58c97d71600d74907fe1552c2d23aedbb | Iandavidk/Web-development-2021 | /Iterate_over_name.py | 210 | 4.1875 | 4 | name = input("What is your first name?")
letter_count = 0
print(name, "is spelled:")
for x in name:
print(x, end = '')
letter_count += 1
print("")
print(letter_count, "letters in the name", name)
| true |
6af7c1099fabb4e8f14d29224113a35fd252f95d | vivek-x-jha/practiceML | /LogisticRegression/LogisticRegression.py | 1,497 | 4.15625 | 4 | # Implement Logistic Regression from scratch
# Performs Linear Regression (from scratch) using randomized data
# Optimizes weights by using Gradient Descent Algorithm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(0)
features = 3
trainingSize = 10 ** 1
trainingSteps = 10 ** 3
... | true |
9b1d5204cb8a3a1b5aa66d58323feda831bef1da | jackson097/Exam_Calculator | /functions.py | 2,121 | 4.34375 | 4 | """
Determines if the number is a floating point number or not
Parameters: number - the value entered by the user
"""
def is_float(number):
try:
float(number)
return True
except:
return False
"""
Determines if the number provided is a valid float
Parameters: number - the value entered by t... | true |
2152125ba808c6e177a2dbaf26ed313490f4809b | BrianArb/CodeJam | /Qualification_Round_Africa_2010/t9_spelling.py | 2,859 | 4.1875 | 4 | #!/usr/bin/env python
"""
Problem
The Latin alphabet contains 26 characters and telephones only have ten digits on
the keypad. We would like to make it easier to write a message to your friend
using a sequence of keypresses to indicate the desired characters. The letters
are mapped onto the digits as shown below. To i... | true |
1aab08b258a9cf37d22bcbd707142377720b906c | mosestembula/andela-day4 | /find_missing.py | 661 | 4.21875 | 4 |
# ============================================================================
# missing number function implementation
# ============================================================================
def find_missing(list_one, list_two):
"""find_missing function
find the missing number between two lists
""... | true |
c2f4ea87cbf17bb311b550b701f52e3292e8d910 | MadeleineNyhagen-zz/coursework | /Python/Lynda-Python-Courses/Python GUI Development with tkinter/Ch06_01_pack.py | 1,918 | 4.15625 | 4 | #!/usr/bin/python3
# template.py by Barron Stone
# This is an exercise file from Python GUI Development with Tkinter on lynda.com
from tkinter import *
from tkinter import ttk
root = Tk()
### Using fill and expand properties:
##ttk.Label(root, text = 'Hello, Tkinter!',
## background = 'yellow').... | true |
0a987c5193de317a08bd3e0092c28a8129085cef | MadeleineNyhagen-zz/coursework | /Python/Lynda-Python-Courses/Python GUI Development with tkinter/Ch05_05_scrollbar.py | 1,386 | 4.3125 | 4 | #!/usr/bin/python3
# scrollbar.py by Barron Stone
# This is an exercise file from Python GUI Development with Tkinter on lynda.com
from tkinter import *
from tkinter import ttk
root = Tk()
### text with scrollbar:
##text = Text(root, width = 40, height = 10, wrap = 'word')
##text.grid(row = 0, column = 0... | true |
94cfee2114c031675bad9a6c4a598268c8b65f4a | MadeleineNyhagen-zz/coursework | /Python/Python-in-a-Day/simple_script9.py | 1,943 | 4.34375 | 4 | epic_programmer_dict = {'ada lovelace' : ['lordbyronsdaughter@gmail.com', 111],
'margaret hamilton' : ['asynchronous.apollo@mit.edu', 222],
'grace hopper' : ['commodore.debug@vassar.edu', 333],
'jean jennings bartik' : ['bartik@eniac.mil', 444],
... | true |
fa8119fbd9a657952ef79880744cdcfad6a0f758 | HugoSantiago/Quickest-Way-Up | /Dijkstra/dijkstra.py | 2,313 | 4.1875 | 4 | # Python3 implementation to find the
# shortest path in a directed
# graph from source vertex to
# the destination vertex
infi = 1000000000
# Function to find the distance of
# the node from the given source
# vertex to the destination vertex
def dijkstraDist(g, s, path):
# Stores distance of ea... | true |
b9b20a0d8fb550b18852a1b063e8e006f6c50833 | jpragasa/Learn_Python | /Basics/3_Variables.py | 385 | 4.28125 | 4 | greeting = "This is stored in greeting"
#Basic data types
#Integer: numbers with no decimals
#Float: numbers with decimals
a = 5
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b) #The 2 slashes mean the number is returned as an integer
print(a % b)
for i in range(1, a // b):
... | true |
c0e7ca6c23d2cfd041c3e1d5663ef9724bd3af54 | SharmaSwapnil/Py_Stats_Scripts | /HR_StringUpdate.py | 375 | 4.15625 | 4 | def count_substring(string, sub_string):
counter = []
for i in range(len(string)):
ss = string.count(sub_string,i,i+len(sub_string))
counter.append(ss)
return sum(counter)
if __name__ == '__main__':
string = input("Enter string ").strip()
sub_string = input("Enter substring ").strip()
count... | true |
032f6f4b8860955361d854b7134fd13ca3670691 | inbalalo/Python | /hw1_question1.py | 541 | 4.25 | 4 | def trifeca(word):
"""
Checks whether word contains three consecutive double-letter pairs.
word: string
returns: bool
"""
for i in range(0, len(word)):
if (len(word)-i) >= 6:
if word[i] == word[i+1] and word[i+2] == word[i+3] and word[i+4] == word[i+5]:
... | true |
e458a1e97a36eb70d0d602bc920f58d16cca0b9a | Dsgra/python_examples | /ExamplesWordCount.py | 945 | 4.125 | 4 | #!/usr/bin/python
#The code used below will return the content of a file from the directory
# in fact it will do with any file.
f = open("example.txt", "r")
data = f.read()
f.close()
print(data)
# Another example below will show a more complex data readed structure
f = open("New_File_Reading.txt", "r")
data ... | true |
b0ad65d0f6dfc06546385afa9a7f69bfe3cc017d | vineeta786/geeksForGeeks_python | /String/Stng functions - II.py | 315 | 4.3125 | 4 | #User function Template for python3
# Function to check if string
# starts and ends with 'gfg'
def gfg(a):
b = a.lower()
if((b.startswith('gfg') or b.startswith('GFG')) and b.endswith('gfg') or b.endswith('GFG')): # use b.startswith() and b.endswith()
print ("Yes")
else:
print ("No") | true |
fcdae2fbe26fdc25a813d3e14e72d358903c78aa | super-aardvark/project-euler | /problem-001-100/problem-011-020/problem-015.py | 951 | 4.1875 | 4 | '''
Created on Jan 10, 2017
@author: jfinn
'''
def paths_through_lattice(grid_size):
# Problem defines the grid size as the number of squares. Add one to get the number of intersections.
grid_size += 1
# We'll track the number of different paths that may be taken to get to each node
nodes = [ [... | true |
a452d18e79c15e6563ebffe6b5b6ce8d492d1916 | vivekdhayaal/first-repo | /aoi/algorithms_data_structures/tree_path_bet_two_nodes.py | 2,559 | 4.125 | 4 | # Python Program to find path between
# n1 and n2 using tree DFS
class Node:
def __init__(self, data, children = []):
self.data = data
self.children = children
def pathToNode(node, path, data):
# base case handling
if node is None:
return False
# append the node data in p... | true |
afb38416d9deadd585772a19edddbad676afc7e8 | ChuChuIgbokwe/Python-2.7-code | /alice_words.py | 1,522 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Chukwunyere Igbokwe on March 15, 2016 by 3:11 AM
# with open('alice_in_wonderland.txt', 'r') as f:
# data = [aline.split() for aline in f]
import string
def remove_punctuation(s):
s_without_punct = ""
for letter in s:
if letter not in ... | true |
209d9a593a6a5c8effcef7031c5c4092ba19384c | ChuChuIgbokwe/Python-2.7-code | /dispatch.py | 2,392 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Created by Chukwunyere Igbokwe on September 27, 2016 by 10:29 PM
## Function to find the maximum contiguous subarray
# def maxSubArraySum(a,size):
#
# max_so_far = 0
# max_ending_here = 0
#
# for i in range(0, size):
# max_ending_here = max_ending_her... | true |
9c29c52024229f7593f3f96946935099f224a06f | weiyangedward/Design-of-Computer-Programs | /exam/LogicPuzzle.py | 2,971 | 4.1875 | 4 | """
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes.
3. Of the programmer and the person who bought the droid, one is Wilkes and the other is Hamming.
4. The writer is not Minsky.
5. Neither Knuth n... | true |
eadcc15fe383c94ac3b4539d3de691e2f55a014f | iskibinska/Python-Class | /python1/lesson4/guess.py | 477 | 4.15625 | 4 | count = 1
secret = 18
num = int(input("\nGuess a number between 1 and 20: "))
while True:
if (num == secret or count == 5):
break
elif (num > secret):
num = int(input("It was too high. Guess again: "))
elif (num < secret):
num = int(input("It was too low. Guess again: "))
count... | true |
7f467cb87066f217c42608111486bc1e41158454 | chaudharyishan/PythonGame | /GuessGame.py | 2,579 | 4.21875 | 4 | import random
print("\t\t\tWelcome to Guess- The Number Game")
print("\n")
print("\tRules: You have to guess the number which I am thinking out,\n\tI will give you a hint wheather the guess number is too HIGH,LOWER \n\tto thenumber which I have guessed")
print("\n\tScore Card: 1st Attempt= 50 Points")
print("\t\t 2... | true |
b8e228996ad5030ef7b455769733e1af4f48661c | PythonCore051020/HW | /HW04/AndriyKapelian/Task_1.py | 515 | 4.1875 | 4 | # function that can transform a number into a string
def number_to_string(num):
transformed_num = str(num)
return transformed_num
# function that reverses the words in a given string
def reverse(st):
# Your Code Here
words = st.split()
words = list(reversed(words))
reversed_string = " ".join(w... | true |
b0ef182023e47f753991c83199f49d0a3f29d1a9 | mahekdeep/DiceRole | /main.py | 760 | 4.28125 | 4 | #DiceRole
import random
#Setting Input Variables
min = 1
max = 6
#Setting Dices at Ints
dice1 = 0
dice2 = 0
#Using "Y or N" to incidcate if user wants to role again.
roll = "y"
#Asking Users Input for role
print("Would you like to Roll the Dice? ")
roll =input("Please Type y/n: ")
while roll == "y":
print("... | true |
5eb41bc76833a07bfc27749f767e98d3601b9306 | gourav3017/code-samples | /tasks/primes.py | 1,348 | 4.375 | 4 | #!/usr/bin/env python
from math import sqrt, ceil
"""
Write a program that accepts two integer parameters, X and Y. Have it print all prime numbers between X and Y, inclusive.
"""
def isPrime(n):
"""
Basically the quick test for whether or not a prime
Arguments:
n - an int
Returns:
A b... | true |
c210369911fe124ded804f7fee295fb5df3e2663 | skeptycal/algo | /snippets/python/prime_sieve.py | 1,529 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# # Prime Number Sieve
# http://inventwithpython.com/hacking (BSD Licensed)
# https://inventwithpython.com/hacking/chapter23.html
import math
from typing import Tuple, List
def isPrime(num):
""" # Returns True if num is a prime number, otherwise False.
# N... | true |
c75993571a65502d628a498cf95f81f676d8767c | PedroLSF/PyhtonPydawan | /6b - CHALLENGE ADV/6.4.2_Tip.py | 492 | 4.34375 | 4 | # Let’s say we are going to a restaurant and we decide to leave a tip.
# We can create a function to easily calculate the amount to tip based on the total cost of the food and a percentage.
# This function will accept both of those values as inputs and return the amount of money to tip.
def tip(total, percentage):
... | true |
ba0912e0ad5371abb3e4affd7c6255dd52abc1cf | PedroLSF/PyhtonPydawan | /6a - CHALLENGE_Basic/6.3.5_Exponents.py | 498 | 4.46875 | 4 | #In this challenge, we will be using nested loops in order to raise a list of numbers to the power of a list of other numbers.
#What this means is that for every number in the first list, we will raise that number to the power of every number in the second list.
def exponents(bases,powers):
new_lst = []
for base ... | true |
6042920d1d5d685e7fd94a09699c52260cebbac1 | PedroLSF/PyhtonPydawan | /6b - CHALLENGE ADV/6.3.1_LargerSum.py | 485 | 4.21875 | 4 | #calculating which list of two inputs has the larger sum.
#We will iterate through each of the list and calculate the sums
#afterwards we will compare the two and return which one has a greater sum
def larger_sum(lst1, lst2):
sum1 =0
sum2 =0
for index1 in lst1:
sum1 += index1
for index2 in lst2:
sum2 +... | true |
9e7aff80dbdfb9463101beca436bc975bcc86d02 | Preksha1998/python | /functions/decorators.py | 405 | 4.1875 | 4 | # decorators is used to add the extra features in the existing function
#create fun which take argument as function and inner function and inner function can swap value for that function
def division(a,b):
print(a/b)
def smart_div(func):#take function as argument
def inner_fun(a,b):# same as division
if a < b:
... | true |
bce0752294a408b97b2969b87932a9e1788b5785 | guido-lab/random-password-generator | /password-generator.py | 1,805 | 4.125 | 4 | import random
import string
class RandPasswordGenerator():
def generate_password(self, lenght, wantNums, wantUppers):
password = ""
chars = string.ascii_letters
# Checking if the user want to include numbers to his password
if wantNums.lower() == "yes":
chars = chars + ... | true |
09d786a57b572c5d43409bee920ae49645622ee2 | RitchieHollis/Python-projects | /Guessing-number game.py | 1,901 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Number guessing game
Author: RitchieHollis
game not finished, works in overall
"""
import random
def loop():
score = 0
random_number = int(random.randint(1,10))
while n == True:
num_pers = input("Choose a number between 1 and 10: ")
... | true |
77362cee3b8da0be4c9deb2de4e2101aa167dfac | LayanCS/LeetCode | /Algorithms/Reverse_Integer.py | 605 | 4.15625 | 4 | # Reverse Integer - Given a 32-bit signed integer, reverse digits of an integer.
# Input: 123 Output: 321
# Input: -123 Output: -321
class Solution:
def reverse(self, x: int) -> int:
if x >= 2**31-1 or x <= -2**31:
return 0
else:
s = str(x)
if x >= 0: # positive
... | true |
b218395e7f738bc45386810128ae33b599531400 | KathrynDH/MyMatrix | /examples.py | 1,345 | 4.40625 | 4 | """
Created on Wed Jun 16 2021
@author: Kathryn Haske
Example usage for MatrixMath Python class
"""
from matrix_math import MatrixMath
def demonstrate(a):
"""
Function to demonstrate some of the MatrixMath methods
Args:
a (MatrixMath): Matrix
Returns:
nothing
"""
print('Matrix:')
a.prin... | true |
192d930858c70886a845b1afd8565bee135eb5cf | ashirsh/PY111_work | /Tasks/g1_merge_sort.py | 1,000 | 4.15625 | 4 | from typing import List
def sort(container: List[int]) -> List[int]:
"""
Sort input _list with merge sort
:param container: _list of elements to be sorted
:return: _list sorted in ascending order
"""
def merge(left_part, right_part):
result = []
while left_part or right_part:
... | true |
0b6315d879d57ebe3c016cf0b06e2aa457ebf7a3 | CKDarling/django | /Python_Web_Development/my_practice_files/py_files/lists.py | 1,614 | 4.28125 | 4 | # Pythons array
# LISTS
my_list=[1,2,2,3,3,3]
my_2list=[3.4,4.5,4.6]
my_3list=['String',3,True,[1,2,3]] #string,numeral,boolean,nested array
print(my_list)
print(my_2list)
print(my_3list)
print(len(my_3list))
another_list=["a","b","c"]
print(another_list[2])
another_list[1]="FUCK YOU" # LISTS ARE MUTABLE
print(another_... | true |
e2ea03d7a5474981ef0e7dce40549cbdeaf52253 | liyuan789/Leetcode_liyuan | /912.Sort_Array_MergeSort.py | 1,321 | 4.1875 | 4 |
def MergeSort(array):
if array is None or len(array) <= 1:
return array
return mergeSort(array, 0, len(array) - 1)
# Split array into two sub-arrays and mergeSort both sides separately
def mergeSort(array, start, end):
# Base Case
if start == end:
return [array[start]]
# Recursio... | true |
4d092cb19ed4f6fa5d757d99f227f1966c43f25e | Aniket1298/engg_math | /scalar.py | 845 | 4.4375 | 4 | import numpy as np
def scalar():
print("Scalar multiplication is the multiplication of a vector by a scalar (where the product is a vector), and must be distinguished from inner product of two vectors (where the product is a scalar)")
print("For example consider a Matrix A and a scalar value k given below")
... | true |
4d2ad390bab6e1aa17636deddc2f745f4844a11e | dsiu13/python-notes | /OOP/exercise.py | 490 | 4.375 | 4 | # Write and object oriented program that performs the following
# tasks:
# 1. Define a class called "Employee" and create an instance
# of that class
# 2. Create an attribute called name and assign it with a
# value
# 3. Change the name you previously defined within a
# method and call this method by making use of the... | true |
9c0314c72377ec98912275101a50b46cfab8cfb6 | blad00/HPCTutorial | /TestingFile.py | 1,281 | 4.125 | 4 | def encode(text):
"""
>>> encode("robber language")
"rorobbobberor lolangonguagoge"
>>> encode("Kalle Blomkvist")
"Kokallolle Bloblomkvomkvistost"
>>> encode("Astrid Lindgren")
"Astrostridod Lolindgrondgrenon"
"""
# define vowels
vowels = "aeiou"
decoded, consonants = "", ""
... | true |
c462aa9e4d578d73602c01054e81dcd481c59c2b | Pepperbrow/100DaysOfCode | /Day2.py | 742 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 8 21:00:34 2021
@author: peppe
"""
#To change type, cast by adding int()
x = int(input('Please provide number'))
if x < 10:
print('Smaller')
if x == 11:
print('your number was 11')
if x <= 19:
print('your number was less than or equal to 19')
if... | true |
49126841f094caed58b56a3c875dcdb141c876e8 | easmah/topstu | /userinputWhileLoop/input_while.py | 1,288 | 4.375 | 4 | """ The input() function pauses your program and waits for the user to enter some text. """
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
name = input("Please enter your name: ")
print("Hello, " + name.title())
# Sometimes you’ll want to write a prompt that’s longer than one ... | true |
c8789e373bca04b52d594e7cc478ebefd0434267 | Tuseeq1/PythonPractice | /9_Time Conversion.py | 873 | 4.375 | 4 | # Write a procedure, convert_seconds, which takes as input a non-negative
# number of seconds and returns a string of the form
# '<integer> hours, <integer> minutes, <number> seconds' but
# where if <integer> is 1 for the number of hours or minutes,
# then it should be hour/minute. Further, <number> may be an in... | true |
695c744b906306a271e7fd4645a63b58a4215a32 | tommyconner96/cs-module-project-hash-tables | /notes.py | 2,678 | 4.40625 | 4 | # A hash function needs to take a string and return a single number
# It must be deterministic (i.e the same result every time given the same input)
def hash_fn(s):
# convert the string to a UTF-8 (Unicode) representation
encoded_string = s.encode() # O(1)
result = 0
# every character is now a number b... | true |
0b1e6156bffcb601df2f45c6cf1d1e8b252a36b1 | DavidStarshaw/Python | /barcode.py | 433 | 4.15625 | 4 | barcode = raw_input("Type the barcode without the last digit: ")
total = 0
for count, digit in enumerate(barcode):
digit = int(digit)
if (count % 2 == 0):
total += digit
else:
total += digit * 3
difference = (-1 * total) % 10
print "The last digit is: ", difference
"""if (remainder == ... | true |
10caf2cda3fad122e3999ed24647ccf73c9e7d8b | olegbrz/coding_every_day | /CodeWars/020_011220_valid_parentheses.py | 859 | 4.40625 | 4 | """Write a function called that takes a string of parentheses, and determines
if the order of the parentheses is valid. The function should return true if
the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => tr... | true |
ed4446ad65253321e42136f2e85b6bf0f3c8342c | olegbrz/coding_every_day | /CodeWars/001_231120_pascals_triangle.py | 787 | 4.125 | 4 | """
In mathematics, Pascal's triangle is a triangular array of the binomial
coefficients expressed with formula (n k) = n!/(n-k)!, where n denotes a
row of the triangle, and k is a position of a term in the row.
Test.assert_equals(
pascals_triangle(1), [1],"1 level triangle incorrect");
Test.assert_equals(
pas... | true |
d228fcc7e86e40715a263f8f4fe8805cd75c134f | DanielSmithP/Code-Challenge-Solutions | /cipher-map.py | 1,835 | 4.125 | 4 | """ Write a module that enables the robots to easily recall their passwords through codes when they return home.
The cipher grille and the ciphered password are represented as an array (tuple) of strings.
Input: A cipher grille and a ciphered password as a tuples of strings.
Output: The password as a string. """
de... | true |
12b91df7530aa626ddb518bf68ad18f4a287fbdd | hoannt110/hoan | /hoan/vehinh.py | 639 | 4.125 | 4 | from turtle import*
speed(5)
color("green","yellow")
def square():
begin_fill()
for i in range(4):
forward(100)
left(90)
end_fill()
return
def triangle():
begin_fill()
for i in range(3):
forward(100)
left(120)
end_fill()
return
print("Enter 1 if... | true |
fd9737c97e289f6275c034aecf4a35f4911655cc | vijayv/Projects | /ThinkPython/chapter10.py | 1,853 | 4.21875 | 4 | #!/usr/bin/python
'''
Exercise 10.1. Write a function called nested_sum that takes a nested list of integers and add up the elements from all of the nested lists.
'''
def nested_sum(x):
total = 0
for each in x:
for number in each:
total += number
return total
'''
Exercise 10.2. Use c... | true |
95c85bb92454f8f12885638fefd0e9d29a18de5e | vijayv/Projects | /ThinkPython/chapter15.py | 644 | 4.21875 | 4 | #!/usr/bin/python
'''
Exercise 15.1. Write a function called distance_between_points
that takes two Points as arguments and returns the distance between them.
'''
def distance_between_points(p1, p2):
import math
v1 = (p1['x'] - p2['x'])**2
v2 = (p1['y'] - p2['y'])**2
return math.sqrt(v1 + v2)
'''
Ex... | true |
12beb34be50d55ce6546f3b972b2420e1d8bf1a1 | vijayv/Projects | /ThinkPython/exercise7.py | 1,937 | 4.65625 | 5 | #/usr/bin/python
'''
To test the square root algorithm in this chapter, you could compare it with
math.sqrt. Write a function named test_square_root that prints a table like this:
The first column is a number, a; the second column is the square root of a computed with the function
from Section 7.5; the third column is... | true |
2cdf664739631e25f099af33995201d597730b7c | veronikam/aspp_d1 | /generator/example3.py | 717 | 4.3125 | 4 | # 'break' works on the innermost loop. If we want to break out
# of the outer loop, we often have to resort to flag variable.
# Rewrite the following example to use .close() to stop the
# outer loop.
from __future__ import print_function
def counter(n):
i = 1
while i <= n:
yield i
i += 1
def ... | true |
c7486296cee7c8df3d5b65e28bc96714def03e31 | DoctorBear-it/ServiceLife | /Diffusion/TEST.py | 2,388 | 4.125 | 4 | import numpy as np
from PyQt4 import QtCore, QtGui
class ClassName(object):
"""docstring for ClassName"""
"""
The first def in a class is the __init__, which is the initial properties given
to an instance of the called class. These properties will then be associated
with a specific instance rather than the... | true |
82ad5671e52b08115450d59a72baf3c33577423a | afernsmavany/cohort3 | /python/12_list_comprehension/code12.py | 1,431 | 4.40625 | 4 | #creating a new list of values (doubled):
numbers = [1, 3, 5]
doubled = []
for num in numbers:
doubled.append(num * 2)
#doing the same with list comprehension:
numbers = [1, 3, 5]
doubled = [num *2 for num in numbers]
# or alternately:
numbers = [1, 3, 5]
doubled = [x *2 for x in numbers]
#example 2:
friend... | true |
8286e666e6664af4bea07ee3687c149b026c0859 | FizzyBubblech/MIT-6.00 | /ps1/ps1a.py | 1,351 | 4.1875 | 4 | # 6.00 Problem Set 1a
# Denis Savenkov
# ps1a.py
# Determines remaining credit card balance after a year of making
# the minimum payment each month
# retrieve user input
out_bal = float(raw_input("Enter the outstanding balance on your credit card: "))
ann_rate = float(raw_input("Enter the annual credit card ... | true |
9c03d043cadc4a85699477765b7866f341071d09 | TheGreatAbyss/CodeSamples | /algos/Floyd-Warshall.py | 2,456 | 4.3125 | 4 | """
Below is the Floyd Warshall algorithm for computing the shortest path between all nodes in a directed graph
The graph can have negative edges, but if it has a negative cycle the algo will stop.
This runs in O(n^3) time
"""
import numpy as np
from collections import defaultdict
node_dict = defaultdict(dict)
distin... | true |
fe0c30f9c7912786ed195049b63eb7dce03cc3d9 | anhcuonghuynhnguyen/Toplevel-Widgets | /5.MessageBox.py | 1,165 | 4.21875 | 4 | #messagebox.Function_Name(title, message [, options])
''''
Function_Name: This parameter is used to represents an appropriate message box function.
title: This parameter is a string which is shown as a title of a message box.
message: This parameter is the string to be displayed as a message on the message box.
o... | true |
d9e1ed04826886009a8e763dfcfcd249c1326a1e | anhcuonghuynhnguyen/Toplevel-Widgets | /1.TopLevel.py | 2,811 | 4.40625 | 4 | '''A Toplevel widget is used to create a window on top of all other windows.
The Toplevel widget is used to provide some extra information to the user and also when our program deals with more than one application.
These windows are directly organized and managed by the Window Manager and do not need to have any pa... | true |
80a3f43158aec4bc6262f675f8513395053cfe4c | yyyuaaaan/pythonfirst | /crk/3.6.py | 1,415 | 4.25 | 4 | import Queue
"""
__author__ = 'anyu'
Write a program to sort a stack in ascending order. You should not make any assumptions
about how the stack is implemented. The following are the only functions that should be
used to write this program: push | pop | peek | isEmpty.
1,insertion sort, use the helping stack
2,unli... | true |
be3de17915c0402f455bb8a632d7a4bb0b6ca470 | yyyuaaaan/pythonfirst | /crk/4.1.py | 1,628 | 4.21875 | 4 | """__author__ = 'anyu'
Implement a function to check if a tree is balanced.
For the purposes of this question, a balanced tree is defined
to be a tree such that the heights of the two subtrees of any # this is so called AVL-tree
node never differ by more than one.
"""
class Node(object):
def __init__(self):
... | true |
2647f5ac10bf8a1150aacaef724d89b9fb323130 | gcbastos/Baseball | /Chapter-1/pythagorean.py | 1,330 | 4.21875 | 4 | ###########################################################################
### Chapter 1 - Pythagorean Theorem in Baseball ###
# Mathletics: How Gamblers, Managers, and Sports Enthusiasts #
# Use Mathematics in Baseball, Basketball, and Football #
################... | true |
05cb6d191208de2e4adb3a32d151f6632514c005 | mar1zzo/cs50-havard-edx | /pset6/mario/less/mario.py | 492 | 4.28125 | 4 | # program that prints out a half-pyramid of a specified height
from cs50 import get_int
def main():
n = get_positive_int()
pyramid(n)
# Prompt user for positive integer
def get_positive_int():
while True:
n = get_int("Height: ")
if n > 0 and n < 9:
break
return n
# Pri... | true |
63402d3ae65bb580f6154c772e87020ddef8c067 | mothermary5951/videau | /Emacs_Folder/ex12.py | 1,166 | 4.3125 | 4 | from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print ... | true |
5a3dd0e29ef7247e928bc232f3c59d5258d928b8 | mothermary5951/videau | /Emacs_Folder/ex3emacs.py | 964 | 4.25 | 4 | # escape sequences ("\\", "\'", "\n", "\t", etc.) are ways to change python's
# default behavior.
# formatters are just that: they format output. """ print it all the way it
# it is entered, %s prettier output, %r output exactly like the input, %d used for numbers
# correct output for print "%r" %x and prin... | true |
396255eba575b069f46f96c524aa1632c0c42be4 | ablimit/cs130r | /sep18/bmi.elif.py | 518 | 4.1875 | 4 |
# BMI (body mass index) example for Sep 18
# Formula --> BMI = (weight in punds * 703) / (height in inches)^2
# Below 18.5 Underweight
# 18.5 -24.9 Normal
# 25 - 29.9 Overweight
# 30 & Above Obese
bmi = 22.0
print("Your Body Mass Index is " + str(bmi))
if bmi < 18.5:
print(" Eat more protin.")
elif bm... | true |
de075c4bcea95e820125af141c0d785a2fbd8246 | ablimit/cs130r | /oct02/tuples.py | 1,340 | 4.1875 | 4 | # THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING CODE WRITTEN BY OTHERS.
# empty tuple creation
myGarage = ("MACBOOK")
print (len(myGarage)) # length should be zero
print(myGarage) # prints contents of the tuple
# a tuple with similar (same types) of items
neighborGarage = ("Veyron", "cat", "sh... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.