blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f76c1e50db88f9f61b22f0a655faf0ff1ed817f7 | ryanhgunn/learning | /unique.py | 382 | 4.21875 | 4 | # A script to determine if characters in a given string are unique.
import sys
string = input("Input a string here: ")
for i in range(0, len(string)):
for j in range(i + 1, len(string)):
if string[i] == string[j]:
print("The characters in the given string are not unique.")
sys.exi... | true |
d279398b290a9f0320bacaa23864b3be614100c3 | AndrewGreen96/Python | /math.py | 1,217 | 4.28125 | 4 | # 4.3 Counting to twenty
# Use a for loop to print the numbers from 1 to 20.
for number in range(1,21):
print(number)
# 4.4 One million
# Make a list from 1 to 1,000,000 and use a for loop to print it
big_list = list(range(1,1000001))
print(big_list)
# 4.5 Summing to one million
# Create a list... | true |
f003dd889cdce228f66dbad8f66955c9c32563c0 | csgray/IPND_lesson_3 | /media.py | 1,388 | 4.625 | 5 | # Lesson 3.4: Make Classes
# Mini-Project: Movies Website
# In this file, you will define the class Movie. You could do this
# directly in entertainment_center.py but many developers keep their
# class definitions separate from the rest of their code. This also
# gives you practice importing Python files.
# https://w... | true |
e8e71c47bd34a628562c9dfcd351bcd336a99d70 | endar-firmansyah/belajar_python | /oddevennumber.py | 334 | 4.375 | 4 | # Python program to check if the input number is odd or even.
# A number is even if division by given 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number
# div = 79
div = int(input("Input a number: "))
if (div % 2) == 0:
print("{0} is even Number".format(div))
else:
print("{0} is Odd Number".... | true |
2681542783b3751bd885d3f5d829d6bf2ccde4be | code-wiki/Data-Structure | /Array/(Manacher's Algoritm)Longest Palindromic Substring.py | 1,046 | 4.125 | 4 | # Hi, here's your problem today. This problem was asked by Twitter:
# A palindrome is a sequence of characters that reads the same backwards and forwards.
# Given a string, s, find the longest palindromic substring in s.
# Example:
# Input: "banana"
# Output: "anana"
# Input: "million"
# Output: "illi"
# class Solut... | true |
f503e91072d0dd6c7402e8ae662b6139feed05e0 | adykumar/Leeter | /python/104_maximum-depth-of-binary-tree.py | 1,449 | 4.125 | 4 | """
WORKING....
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its... | true |
c5765011e3f9b07eae3a52995d20b45d0f462229 | adykumar/Leeter | /python/429_n-ary-tree-level-order-traversal.py | 1,083 | 4.1875 | 4 | """
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary tree:
1
/ | \
3 2 4
/ \
5 6
We should return its level order traversal:
[
[1],
[3,2,4],
[5,6]
]
Note:
The depth of th... | true |
2b65c4cf9a9372262d2cc927904e36f69cec9cd4 | mosabry/Python-Stepik-Challenge | /1.06 Compute the area of a rectangle.py | 323 | 4.15625 | 4 | width_string = input("Please enter width: ")
# you need to convert width_string to a NUMBER. If you don't know how to do that, look at step 1 again.
width_number = int(width_string)
height_string = input("Please enter height: ")
height_number = int(height_string)
print("The area is:")
print(width_number * height_numb... | true |
b7b296552886fe0ca8d13d543770e0575361837c | joanamdsantos/world_happiness | /functions.py | 1,018 | 4.125 | 4 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_countrybarplot(df, var, top_num):
'''
INPUT:
df - pandas dataframe with the data
var- variable to plot, not categorical
top_num - number of top countries to pl... | true |
70d87e6fe32ad1b0d647e85cf8a64c8f59c9398a | marcin-skurczynski/IPB2017 | /Daria-ATM.py | 568 | 4.125 | 4 | balance = 542.31
pin = "1423"
inputPin = input("Please input your pin: ")
while pin != inputPin:
print ("Wrong password. Please try again.")
inputPin = input("Please input your pin: ")
withdrawSum = float(input("How much money do you need? "))
while withdrawSum > balance:
print ("The sum you are trying to wi... | true |
296dd75cbc77a834515929bc0820794909fb9e54 | sdaless/pyfiles | /CSI127/shift_left.py | 414 | 4.3125 | 4 | #Name: Sara D'Alessandro
#Date: September 12, 2018
#This program prompts the user to enter a word and then prints the word with each letter shifted left by 1.
word = input("Enter a lowercase word: ")
codedWord = ""
for ch in word:
offset = ord(ch) - ord('a') - 1
wrap = offset % 26
newChar = chr(ord('a... | true |
5f7c7a681de3287b0e2c05bb05d18df626eb3b54 | sudev/dsa | /graph/UsingAdjacencyList.py | 1,677 | 4.15625 | 4 | # A graph implementation using adjacency list
# Python 3
class Vertex():
def __init__(self, key):
self.id = key
# A dictionary to act as adjacency list.
self.connectedTo = {}
def addEdge(self, vert, w=0):
self.connectedTo[vert] = w
# Repr
def __str__(self):
return str(self.id) + ' connectedTo: ' +... | true |
0406e3cc0d3d09c9bbaf400c2808ebf0737d31d4 | bharathkkb/peer-tutor | /peer-tutor-api/timeBlock.py | 1,230 | 4.25 | 4 | import time
import datetime
class TimeBlock:
"""
Returns a ```Time Block``` object with the given startTime and endTime
"""
def __init__(self, start_time, end_time):
self.start_time = start_time
self.end_time = end_time
print("A time block object is created.")
def __str__(... | true |
6edfeb4705a4f49b354ef9571029d19b9848f8e5 | dani3l8200/100-days-of-python | /day1-printing-start/project1.py | 454 | 4.28125 | 4 | #1. Create a greeting for your program.
print('Welcome to Project1 of 100 Days of Code Python')
#2. Ask the user for the city that they grew up in.
city_grew_user = input('Whats is your country that grew up in?\n')
#3. Ask the user for the name of a pet.
pet_of_user = input('Whats is the name of any pet that having?\n'... | true |
215ae22230731d3c486c7b652128fb1b212c78e0 | islamrumon/PythonProblems | /Sets.py | 2,058 | 4.40625 | 4 | # Write a Python program to create a new empty set.
x =set()
print(x)
n = set([0, 1, 2, 3, 4])
print(n)
# Write a Python program to iteration over sets.
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n)
# Write a Python program to add member(s) in a set.
color_set = set()
color_set.add("Red")
print... | true |
aae16277602c86460bafa3df51c1eb258c7d85db | roxdsouza/PythonLessons | /Dictionaries.py | 2,088 | 4.65625 | 5 | # Dictionary is written as a series of key:value pairs seperated by commas, enclosed in curly braces{}.
# An empty dictionary is an empty {}.
# Dictionaries can be nested by writing one value inside another dictionary, or within a list or tuple.
print "--------------------------------"
# Defining dictionary
dic1 = {'... | true |
4fa1560b335f86dae73766c7f6b316e339d54671 | roxdsouza/PythonLessons | /Classes04.py | 964 | 4.125 | 4 | # Program to understand class and instance variables
# class Edureka:
#
# # Defining a class variable
# domain = 'Big data analytics'
#
# def SetCourse(self, name): # name is an instance variable
# # Defining an instance variable
# self.name = name
#
#
# obj1 = Edureka() # Creating an inst... | true |
4e7b02140879900cbbb4e3889789c8b3dcd15291 | LewisT543/Notes | /Learning_Data_processing/3SQLite-update-delete.py | 1,440 | 4.46875 | 4 | #### SQLITE UPDATING AND DELETING ####
# UPDATING DATA #
# Each of the tasks created has its own priority, but what if we decide that one of them should be done earlier than the others.
# How can we increase its priority? We have to use the SQL statement called UPDATE.
# The UPDATE sta... | true |
100a33b667fa60386fabf26718b7bdf71d25d26c | satlawa/ucy_dsa_projects | /Project_0/Task2.py | 1,759 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the ... | true |
89309e6aa3917fee2427a1e16113a3de202994d5 | achmielecki/AI_Project | /agent/agent.py | 2,136 | 4.25 | 4 | """
File including Agent class which
implementing methods of moving around,
making decisions, storing the history of decisions.
"""
class Agent(object):
""" Class representing agent in game world.
Agent has to reach to destination point
in the shortest distance. World is random generat... | true |
b1e4492ff80874eeada53f05d6158fc3ce419297 | lovepurple/leecode | /first_bad_version.py | 1,574 | 4.1875 | 4 | """
278. 2018-8-16 18:15:47
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose y... | true |
29ef17e51ae29ba273a3b59e65419d73bacf6aa0 | mathivananr1987/python-workouts | /dictionary-tuple-set.py | 1,077 | 4.125 | 4 | # Tuple is similar to list. But it is immutable.
# Data in a tuple is written using parenthesis and commas.
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print("count of orange", fruits.count("orange"))
print('Index value of orange', fruits.index("orange"))
# Python Dictionary is an unord... | true |
63cd3250a2453bc5dcf1083a3f9010fd6496fe1f | BrandonCzaja/Sololearn | /Python/Control_Structures/Boolean_Logic.py | 650 | 4.25 | 4 | # Boolean logic operators are (and, or, not)
# And Operator
# print(1 == 1 and 2 == 2)
# print(1 == 1 and 2 == 3)
# print(1 != 1 and 2 == 2)
# print(2 < 1 and 3 > 6)
# Example of boolean logic with an if statement
# I can either leave the expressions unwrapped, wrap each individual statement or wrap the whole if con... | true |
674d9922f89514e4266c48ec91b98f223fdcf313 | Ang3l1t0/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 410 | 4.1875 | 4 | #!/usr/bin/python3
"""Append
"""
def append_write(filename="", text=""):
"""append_write method
Keyword Arguments:
filename {str} -- file name or path (default: {""})
text {str} -- text to append (default: {""})
Returns:
[str] -- text that will append
"""
with open(filena... | true |
982c7852214a41e505052c5674006286fc26b4b9 | Ang3l1t0/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 444 | 4.34375 | 4 | #!/usr/bin/python3
"""print_square"""
def print_square(size):
"""print_square
Arguments:
size {int} -- square size
Raises:
TypeError: If size is not an integer
ValueError: If size is lower than 0
"""
if type(size) is not int:
raise TypeError("size must be an integ... | true |
af528387ea37e35a6f12b53b392f920087e5284b | Ang3l1t0/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 596 | 4.375 | 4 | #!/usr/bin/python3
import sys
from sys import argv
if __name__ == "__main__":
# leng argv starts in 1 with the name of the function
# 1 = function name
if len(argv) == 1:
print("{:d} arguments.".format(len(sys.argv) - 1))
# 2 = first argument if is equal to 2 it means just one arg
elif len(a... | true |
5253817eac722b8e72fa1eadb560f8b7c7d73250 | weeksghost/snippets | /fizzbuzz/fizzbuzz.py | 562 | 4.21875 | 4 | """Write a program that prints the numbers from 1 to 100.
But for multiples of three print 'Fizz' instead of the number.
For the multiples of five print 'Buzz'.
For numbers which are multiples of both three and five print 'FizzBuzz'."""
from random import randint
def fizzbuzz(num):
for x in range(1, 101):
if x ... | true |
33d66808b44b182de3a9978dee9a8e88ce2d8b83 | kranthikiranm67/TestWorkshop | /question_03.py | 1,044 | 4.1875 | 4 | #question_03 =
"""
An anagram I am
Given two strings s0 and s1, return whether they are anagrams of each other. Two words are anagrams when you can rearrange one to become the other. For example, “listen” and “silent” are anagrams.
Constraints:
- Length of s0 and s1 is at most 5000.
Example 1:
Input:
s0 = “listen”
... | true |
26c06e9f868010768bdc7c7248cd1bf69032b1c4 | AlenaRyzhkova/CS50 | /pset6/sentimental/caesar.py | 628 | 4.21875 | 4 | from cs50 import get_string
import sys
# 1. get the key
if not len(sys.argv)==2:
print("Usage: python caesar.py <key>")
sys.exit(1)
key = int(sys.argv[1])
# 2. get plain text
plaintext = get_string("Please, enter a text for encryption: ")
print("Plaintext: " + plaintext)
# 3. encipter
ciphertext=""
for c in ... | true |
df9a22117bd98acc6880792e5c3c0273f270067d | umasp11/PythonLearning | /polymerphism.py | 1,482 | 4.3125 | 4 | #polymorphism is the condition of occurrence in different forms. it uses two method overRiding & overLoading
# Overriding means having two method with same name but doing different tasks, it means one method overrides the other
#Methd overriding is used when programmer want to modify the existing behavior of a method
... | true |
62c33ddc7ddc1daba876dd0422432686fcf361eb | umasp11/PythonLearning | /Threading.py | 890 | 4.125 | 4 | '''
Multitasking: Execute multiple task at the same time
Processed based multitasking: Executing multi task at same time where each task is a separate independent program(process)
Thread based multitasking: Executing multiple task at the same time where each task is a separate independent part of the same program(proce... | true |
116936cad73564abb9355199f5c8604d0b0bb8e7 | girish75/PythonByGireeshP | /pycode/Quesetion1assignment.py | 925 | 4.40625 | 4 | # 1. Accept user input of two complex numbers (total 4 inputs, 2 for real and 2 for imaginary part).
# Perform complex number operations (c1 + c2, c1 - c2, c1 * c2)
a = int(input("For first complex number, enter real number"))
b = int(input("For first complex number, enter imaginary number"))
a1 = int(input("For sec... | true |
ac235a932c259aac16a2a47fe0a45f9255e8a6f0 | girish75/PythonByGireeshP | /pythonproject/FirstProject/jsong.py | 1,813 | 4.3125 | 4 | import json
'''
The Json module provides an easy way to encode and decode data in JSON
Convert from Python to JSON:
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
convert Python objects of the following types, into JSON strings: dict, list
tuple, string... | true |
75260678d000751037a56f69e517b253e7d82ad9 | aasmith33/GPA-Calculator | /GPAsmith.py | 647 | 4.1875 | 4 | # This program allows a user to input their name, credit hours, and quality points. Then it calculates their GPA and outputs their name and GPA.
import time
name = str(input('What is your name? ')) # asks user for their name
hours = int(input('How many credit hours have you earned? ')) # asks user for credit hours ea... | true |
eaa7fec6da4273925a0cb7b68c910a729bf26f3c | Yaguit/lab-code-simplicity-efficiency | /your-code/challenge-2.py | 822 | 4.15625 | 4 | """
The code below generates a given number of random strings that consists of numbers and
lower case English letters. You can also define the range of the variable lengths of
the strings being generated.
The code is functional but has a lot of room for improvement. Use what you have learned
about simple and efficien... | true |
59a5e4e86c2ccfd9b33ca254a220754fe981ebf7 | newkstime/PythonLabs | /Lab07/Lab07P4.py | 2,277 | 4.1875 | 4 | def main():
numberOfLabs = int(input("How many labs are you entering?"))
while numberOfLabs <= 0:
print("Invalid input")
numberOfLabs = int(input("How many labs are you entering?"))
labScores = []
i = 0
while i < numberOfLabs:
score = float(input("Enter a lab score:"))
... | true |
842938b66f413e4a260395823d59a0a589bbdecf | newkstime/PythonLabs | /Lab03 - Selection Control Structures/Lab03P2.py | 824 | 4.21875 | 4 | secondsSinceMidnight = int(input("Please enter the number of seconds since midnight:"))
seconds = '{:02}'.format(secondsSinceMidnight % 60)
minutesSinceMidnight = secondsSinceMidnight // 60
minutes = '{:02}'.format(minutesSinceMidnight % 60)
hoursSinceMidnight = minutesSinceMidnight // 60
if hoursSinceMidnight < 24 and... | true |
762f0115352b4b776ece45f8d5998b5ec06cd2ea | M-Karthik7/Numpy | /main.py | 2,932 | 4.125 | 4 | Numpy Notes
Numpy is faster than lists.
computers sees any number in binary fromat
it stores the int in 4 bytes ex : 5--> 00000000 00000000 00000000 00000101 (int32)
list is an built in int type for python it consists of 1) size -- 4 bytes
2) reference count -- 8... | true |
1ca0d3089cf33131b408c6f11ff4ec813a02f6f4 | chengyin38/python_fundamentals | /Fizz Buzz Lab.py | 2,092 | 4.53125 | 5 | # Databricks notebook source
# MAGIC %md
# MAGIC # Fizz Buzz Lab
# MAGIC
# MAGIC * Write a function called `fizzBuzz` that takes in a number.
# MAGIC * If the number is divisible by 3 print `Fizz`. If the number is divisible by 5 print `Buzz`. If it is divisible by both 3 and 5 print `FizzBuzz` on one line.
# MAGIC ... | true |
77091f08b893364629e2d7170dbf1aeffe5fab5a | Gangamagadum98/Python-Programs | /sample/Calculator.py | 451 | 4.15625 | 4 | print("Enter the 1st number")
num1=int(input())
print("Enter the 2nd number")
num2=int(input())
print("Enter the Operation")
operation=input()
if operation=="+":
print("the addition of two numbers is",num1+num2)
elif operation == "-":
print("the addition of two numbers is", num1 - num2)
... | true |
6f4786334da4a577e81d74ef1c58e7c0691b82b9 | Obadha/andela-bootcamp | /control_structures.py | 354 | 4.1875 | 4 | # if False:
# print "it's true"
# else:
# print "it's false"
# if 2>6:
# print "You're awesome"
# elif 4<6:
# print "Yes sir!"
# else:
# print "Okay Maybe Not"
# for i in xrange (10):
# if i % 2:
# print i,
# find out if divisible by 3 and 5
# counter = 0
# while counter < 5:
# print "its true"
# print c... | true |
e129e980c58a0c812c96d4d862404361765cbaa6 | rafiqulislam21/python_codes | /serieWithValue.py | 660 | 4.1875 | 4 | n = int(input("Enter the last number : "))
sumVal = 0
#avoid builtin names, here sum is a built in name in python
for x in range(1, n+1, 1):
# here for x in range(1 = start value, n = end value, 1 = increasing value)
if x != n:
print(str(x)+" + ", end =" ") #this line will show 1+2+3+............
#... | true |
407ae0b9bd3004e0655b747f9f5ffda563ae8cae | anooptrivedi/workshops-python-level2 | /list2.py | 338 | 4.21875 | 4 | # Slicing in List - more examples
example = [0,1,2,3,4,5,6,7,8,9]
print(example[:])
print(example[0:10:2])
print(example[1:10:2])
print(example[10:0:-1]) #counting from right to left
print(example[10:0:-2]) #counting from right to left
print(example[::-3]) #counting from right to left
print(example[:5:-1]) #counting ... | true |
ca7c8607e41db501f958a746028fb28040133d54 | anooptrivedi/workshops-python-level2 | /guessgame.py | 460 | 4.125 | 4 | # Number guessing game
import random
secret = random.randint(1,10)
guess = 0
attempts = 0
while secret != guess:
guess = int(input("Guess a number between 1 and 10: "))
attempts = attempts + 1;
if (guess == secret):
print("You found the secret number", secret, "in", attempts, "attempts")
... | true |
8f8e8651d25ac8333692a5aa18bc26589f3fefe4 | swaraj1999/python | /chap 8 set/set_intro.py | 1,092 | 4.1875 | 4 | # set data type
# unordered collection of unique items
s={1,2,3,2,'swaraj'}
print(s) # we cant do indexing here like:: s[1]>>wrong here,UNORDERED
L={1,2,4,4,8,7,0,9,8,8,0,9,7}
s2=set(L) # removes duplicate,unique items only
print(s2)
s3=list(set(L))
print(s3) ... | true |
15c3309d2d94b809fccc1c1aaaa0cd66cdfd3954 | swaraj1999/python | /chap 4 function/exercise11.py | 317 | 4.375 | 4 | # pallindrome function like madam,
def is_pallindrome(name):
return name == name[::-1]
#if name == reverse of name
# then true,otherwise false
# print(is_pallindrome(input("enter name"))) #not working for all words
print(is_pallindrome("horse")) #working for all words | true |
6d08454da7f8c3b15ec404505a6b77b9192e570e | breschdleng/Pracs | /fair_unfair_coin.py | 1,307 | 4.28125 | 4 | import random
"""
Given an unfair coin, where probability of HEADS coming up is P and TAILS is (1-P), implement a fair coin from the given unfair coin
Approach: assume an unfair coin that gives HEADS with prob 0.3 and TAILS with 0.7. The objective is to convert this
to a fair set of probabilities of 0.5 each
Solution... | true |
5b6fc5dbfa1e7d85d4c80642ecb2822c23d5a6be | ShainaJordan/thinkful_lessons | /fibo.py | 282 | 4.15625 | 4 | #Define the function for the Fibonacci algorithm
def F(n):
if n < 2:
return n
else:
print "the function is iterating through the %d function" %(n)
return (F(n-2) + F(n-1))
n = 8
print "The %d number in the Fibonacci sequence is: %d" %(n, F(n)) | true |
8d852b9ba3fb4403dc783cc6c703c451ee0197f7 | Pranav-Tumminkatti/Python-Turtle-Graphics | /Turtle Graphics Tutorial.py | 979 | 4.40625 | 4 | #Turtle Graphics in Pygame
#Reference: https://docs.python.org/2/library/turtle.html
#Reference: https://michael0x2a.com/blog/turtle-examples
#Very Important Reference: https://realpython.com/beginners-guide-python-turtle/
import turtle
tim = turtle.Turtle() #set item type
tim.color('red') #set colour
tim.pensize(5... | true |
b68c9db55ce6af793f0fc36505e12e741c497c31 | sAnjali12/BsicasPythonProgrammas | /python/userInput_PrimeNum.py | 339 | 4.1875 | 4 | start_num = int(input("enter your start number"))
end_num = int(input("enter your end number"))
while (start_num<=end_num):
count = 0
i = 2
while (i<=start_num/2):
if (start_num):
print "number is not prime"
count = count+1
break
i = i+1
if (count==0 and start_num!=1):
print "prime number"
start_... | true |
3750e8f1fc7137dddda348c755655db99026922b | xilaluna/web1.1-homework-1-req-res-flask | /app.py | 1,335 | 4.21875 | 4 |
# TODO: Follow the assignment instructions to complete the required routes!
# (And make sure to delete this TODO message when you're done!)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
"""Shows a greeting to the user."""
return f'Are you there, world? It\'s me, Ducky!'
@app.r... | true |
f2640a1412c6ee3414bf47175439aba242d5c81f | KurinchiMalar/DataStructures | /LinkedLists/SqrtNthNode.py | 1,645 | 4.1875 | 4 | '''
Given a singly linked list, write a function to find the sqrt(n) th element, where n is the number of elements in the list.
Assume the value of n is not known in advance.
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
import ListNode
def sqrtNthNode(node):
if node == None:
return None
... | true |
ec4a2fc2faea5acfea8a352c16b768c79e679104 | KurinchiMalar/DataStructures | /Hashing/RemoveGivenCharacters.py | 507 | 4.28125 | 4 | '''
Give an algorithm to remove the specified characters from a given string
'''
def remove_chars(inputstring,charstoremove):
hash_table = {}
result = []
for char in charstoremove:
hash_table[char] = 1
#print hash_table
for char in inputstring:
if char not in hash_table:
... | true |
82ecc3e32e7940422238046cd7aa788979c51f9c | KurinchiMalar/DataStructures | /Stacks/Stack.py | 1,115 | 4.125 | 4 |
from LinkedLists.ListNode import ListNode
class Stack:
def __init__(self,head=None):
self.head = head
self.size = 0
def push(self,data):
newnode = ListNode(data)
newnode.set_next(self.head)
self.head = newnode
self.size = self.size + 1
def pop(self):
... | true |
30a81157968dcd8771db16cf6ac48e9cd235d713 | KurinchiMalar/DataStructures | /Stacks/InfixToPostfix.py | 2,664 | 4.28125 | 4 | '''
Consider an infix expression : A * B - (C + D) + E
and convert to postfix
the postfix expression : AB * CD + - E +
Algorithm:
1) if operand
just add to result
2) if (
push to stack
3) if )
till a ( is encountered, pop from stack and append to result.
4) if operator
... | true |
08ef8703147476759e224e66efdc7b5de5addf6e | chaoma1988/Coursera_Python_Program_Essentials | /days_between.py | 1,076 | 4.65625 | 5 | '''
Problem 3: Computing the number of days between two dates
Now that we have a way to check if a given date is valid,
you will write a function called days_between that takes six integers (year1, month1, day1, year2, month2, day2)
and returns the number of days from an earlier date (year1-month1-day1) to a later date... | true |
562ac5cebcf516d7e40724d3594186209d79c2f4 | Vyara/First-Python-Programs | /quadratic.py | 695 | 4.3125 | 4 | # File: quadratic.py
# A program that uses the quadratic formula to find real roots of a quadratic equation.
def main():
print "This program finds real roots of a quadratic equation ax^2+bx+c=0."
a = input("Type in a value for 'a' and press Enter: ")
b = input("Type in a value for 'b' and press... | true |
852cba828e67b97d2ddd91322a827bfdc3c6a849 | ridhamaditi/tops | /Assignments/Module(1)-function&method/b1.py | 287 | 4.3125 | 4 | #Write a Python function to calculate the factorial of a number (a non-negative integer)
def fac(n):
fact=1
for i in range(1,n+1):
fact *= i
print("Fact: ",fact)
try:
n=int(input("Enter non-negative number: "))
if n<0 :
print("Error")
else:
fac(n)
except:
print("Error")
| true |
287f5f10e5cc7c1e40e545d958c54c8d01586bfb | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a2.py | 252 | 4.15625 | 4 | #write program that will ask the user to enter a number until they guess a stored number correctly
a=10
try:
n=int(input("Enter number: "))
while a!=n :
print("Enter again")
n=int(input("Enter number: "))
print("Yay")
except:
print("Error")
| true |
1d2389112a628dbf8891f85d6606ec44543fc81d | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a4.py | 791 | 4.21875 | 4 | #Write program that except Clause with No Exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# user guess... | true |
609812d3b68a77f35eb116682df3f844ab3a44c9 | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a3.py | 216 | 4.15625 | 4 | #Write function that converts a temperature from degrees Kelvin to degrees Fahrenheit
try:
k=int(input("Enter temp in Kelvin: "))
f=(k - 273.15) * 9/5 + 32
print("Temp in Fahrenheit: ",f)
except:
print("Error")
| true |
35c340635b063ecebc478a1ab8d7f527d6fe2f3f | Swapnil2095/Python | /8.Libraries and Functions/copy in Python (Deep Copy and Shallow Copy)/Shallow copy/shallow copy.py | 533 | 4.5625 | 5 | # Python code to demonstrate copy operations
# importing "copy" for copy operations
import copy
# initializing list 1
li1 = [1, 2, [3, 5], 4]
# using copy to shallow copy
li2 = copy.copy(li1)
# original elements of list
print("The original elements before shallow copying")
for i in range(0, len(li1)):
print(li1[i]... | true |
b91b8609d687dd362ac271c349fdc3c81ebfe0f3 | Swapnil2095/Python | /8.Libraries and Functions/Regular Expression/findall(d).py | 621 | 4.3125 | 4 | import re
# \d is equivalent to [0-9].
p = re.compile('\d')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
# \d+ will match a group on [0-9], group of one or greater size
p = re.compile('\d+')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
'''
\d Matches any decimal digit, this is e... | true |
2be154a4143a049477f827c9923ba19198f4a4e3 | Swapnil2095/Python | /8.Libraries and Functions/copyreg — Register pickle support functions/Example.py | 1,312 | 4.46875 | 4 | # Python 3 program to illustrate
# use of copyreg module
import copyreg
import copy
import pickle
class C(object):
def __init__(self, a):
self.a = a
def pickle_c(c):
print("pickling a C instance...")
return C, (c.a, )
copyreg.pickle(C, pickle_c)
c = C(1)
d = copy.copy(c)
print(d)
p = pickle.dumps(c)
print(p... | true |
3dc8226bfc786cf6bbea43a20a0cf5dbbdeeb72e | Swapnil2095/Python | /5. Modules/Mathematical Functions/sqrt.py | 336 | 4.5625 | 5 | # Python code to demonstrate the working of
# pow() and sqrt()
# importing "math" for mathematical operations
import math
# returning the value of 3**2
print("The value of 3 to the power 2 is : ", end="")
print(math.pow(3, 2))
# returning the square root of 25
print("The value of square root of 25 : ", end="")
print... | true |
1ca59efae74f5829e15ced1f428720e696867d9a | Swapnil2095/Python | /2.Operator/Inplace vs Standard/mutable_target.py | 849 | 4.28125 | 4 | # Python code to demonstrate difference between
# Inplace and Normal operators in mutable Targets
# importing operator to handle operator operations
import operator
# Initializing list
a = [1, 2, 4, 5]
# using add() to add the arguments passed
z = operator.add(a,[1, 2, 3])
# printing the modified value
print ("Va... | true |
7ffe6b1ac7437b0477a969498d66163e4c4e0584 | Swapnil2095/Python | /5. Modules/Time Functions/ctime.py | 450 | 4.15625 | 4 | # Python code to demonstrate the working of
# asctime() and ctime()
# importing "time" module for time operations
import time
# initializing time using gmtime()
ti = time.gmtime()
# using asctime() to display time acc. to time mentioned
print ("Time calculated using asctime() is : ",end="")
print (time.asctime(ti))
... | true |
9091de76643f812c44e1760f7d73e2a28c19bde6 | Swapnil2095/Python | /8.Libraries and Functions/enum/prop2.py | 724 | 4.59375 | 5 | '''
4. Enumerations are iterable. They can be iterated using loops
5. Enumerations support hashing. Enums can be used in dictionaries or sets.
'''
# Python code to demonstrate enumerations
# iterations and hashing
# importing enum for enumerations
import enum
# creating enumerations using class
class Animal(enum.... | true |
f0a0f758c7e274508da794d35c71c52f7da7e0f9 | Swapnil2095/Python | /5. Modules/Calendar Functions/firstweekday.py | 486 | 4.25 | 4 | # Python code to demonstrate the working of
# prmonth() and setfirstweekday()
# importing calendar module for calendar operations
import calendar
# using prmonth() to print calendar of 1997
print("The 4th month of 1997 is : ")
calendar.prmonth(1997, 4, 2, 1)
# using setfirstweekday() to set first week day number
ca... | true |
f60dcd5c7b7cc667b9e0155b722fd637570663ef | Swapnil2095/Python | /8.Libraries and Functions/Decimal Functions/logical.py | 1,341 | 4.65625 | 5 | # Python code to demonstrate the working of
# logical_and(), logical_or(), logical_xor()
# and logical_invert()
# importing "decimal" module to use decimal functions
import decimal
# Initializing decimal number
a = decimal.Decimal(1000)
# Initializing decimal number
b = decimal.Decimal(1110)
# printing logical_and... | true |
95a5a87944d4bff8b2e1b03a939d0277cd150fe1 | Swapnil2095/Python | /3.Control Flow/Using Iterations/unzip.py | 248 | 4.1875 | 4 | # Python program to demonstrate unzip (reverse
# of zip)using * with zip function
# Unzip lists
l1,l2 = zip(*[('Aston', 'GPS'),
('Audi', 'Car Repair'),
('McLaren', 'Dolby sound kit')
])
# Printing unzipped lists
print(l1)
print(l2)
| true |
9aebe2939010ff4b2eca5edf8f25dfc5362828c6 | Swapnil2095/Python | /5. Modules/Complex Numbers/sin.py | 593 | 4.21875 | 4 | # Python code to demonstrate the working of
# sin(), cos(), tan()
# importing "cmath" for complex number operations
import cmath
# Initializing real numbers
x = 1.0
y = 1.0
# converting x and y into complex number z
z = complex(x, y)
# printing sine of the complex number
print("The sine value of complex number is ... | true |
e7d09d8d38f4df4f2221ba3963b53467cef66cfb | bregman-arie/python-exercises | /solutions/lists/running_sum/solution.py | 659 | 4.25 | 4 | #!/usr/bin/env python
from typing import List
def running_sum(nums_li: List[int]) -> List[int]:
"""Returns the running sum of a given list of numbers
Args:
nums_li (list): a list of numbers.
Returns:
list: The running sum list of the given list
[1, 5, 6, 2] would return [1... | true |
9a3ecfad05a80abe490885249fb761a0ca77afb6 | milenamonteiro/learning-python | /exercises/radiuscircle.py | 225 | 4.28125 | 4 | """Write a Python program which accepts the radius of a circle from the user and compute the area."""
import math
RADIUS = float(input("What's the radius? "))
print("The area is {0}".format(math.pi * math.pow(RADIUS, 2)))
| true |
4ad91e1cd661f5b7ce3b6c0960cb022136275e0a | testergitgitowy/calendar-checker | /main.py | 2,618 | 4.15625 | 4 | import datetime
import calendar
def name(decision):
print("Type period of time (in years): ", end = "")
while True:
try:
period = abs(int(input()))
except:
print("Must be an integer (number). Try again: ", end = "")
else:
break
period *= 12
print("Type the day you want to check f... | true |
a57504d5e5dd34e53a3e30b2e0987ae6314d6077 | MattCoston/Python | /shoppinglist.py | 298 | 4.15625 | 4 | shopping_list = []
print ("What do you need to get at the store?")
print ("Enter 'DONE' to end the program")
while True:
new_item = input("> ")
shopping_list.append(new_item)
if new_item == 'DONE':
break
print("Here's the list:")
for item in shopping_list:
print(item)
| true |
7235257c51e5a1af67454306e76c5e58ffd2a31c | VeronikaA/user-signup | /crypto/helpers.py | 1,345 | 4.28125 | 4 | import string
# helper function 1, returns numerical key of letter input by user
def alphabet_position(letter):
""" Creates key by receiving a letter and returning the 0-based numerical position of that letter in the alphabet, regardless of case."""
alphabet = string.ascii_lowercase + string.ascii_uppercase
... | true |
f7c61b747436cfcd105a925edd695ac3c8d97279 | ksheetal/python-codes | /hanoi.py | 654 | 4.1875 | 4 |
def hanoi(n,source,spare,target):
'''
objective : To build tower of hanoi using n number of disks and 3 poles
input parameters :
n -> no of disks
source : starting position of disk
spare : auxillary position of the disk
target : end posit... | true |
de64db2e733e592558b5459e7fb4fcfd695abd1b | moogzy/MIT-6.00.1x-Files | /w2-pset1-alphabetic-strings.py | 1,220 | 4.125 | 4 | #!/usr/bin/python
"""
Find longest alphabetical order substring in a given string.
Author: Adrian Arumugam (apa@moogzy.net)
Date: 2018-01-27
MIT 6.00.1x
"""
s = 'azcbobobegghakl'
currloc = 0
substr = ''
sublist = []
strend = len(s)
# Process the string while the current slice location is less then the length of t... | true |
27ebcf2e51a5a9184d718ad14097aba5fb714d94 | tanawitpat/python-playground | /zhiwehu_programming_exercise/exercise/Q006.py | 1,421 | 4.28125 | 4 | import unittest
'''
Question 6
Level 2
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequ... | true |
a5d8b66c92ada51e44ca70d2596a30f0da6f7482 | jmlippincott/practice_python | /src/16_password_generator.py | 639 | 4.1875 | 4 | # Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main met... | true |
71fb6615811b40c8877b34456a98cdc34650dc92 | arvimal/DataStructures-and-Algorithms-in-Python | /04-selection_sort-1.py | 2,901 | 4.5 | 4 | #!/usr/bin/env python3
# Selection Sort
# Example 1
# Selection Sort is a sorting algorithm used to sort a data set either in
# incremental or decremental order.
# How does Selection sort work?
# 1. Iterate through the data set one element at a time.
# 2. Find the biggest element in the data set (Append it to anoth... | true |
7d2fe2f51f6759be77661c2037c7eb4de4326375 | rbrook22/otherOperators.py | /otherOperators.py | 717 | 4.375 | 4 | #File using other built in functions/operators
print('I will be printing the numbers from range 1-11')
for num in range(11):
print(num)
#Printing using range and start position
print("I will be printing the numbers from range 1-11 starting at 4")
for num in range(4,11):
print(num)
#Printing using range, start... | true |
b86322bff277a38ee7165c5637c72d781e9f6ee2 | Bbenard/python_assesment | /ceaser/ceaser.py | 678 | 4.34375 | 4 | # Using the Python,
# have the function CaesarCipher(str, num) take the str parameter and perform a Caesar Cipher num on it using the num parameter as the numing number.
# A Caesar Cipher works by numing all letters in the string N places down in the alphabetical order (in this case N will be num).
# Punctuation, space... | true |
5165e39c4ff20f645ed4d1d725a3a6becd002778 | ashishbansal27/DSA-Treehouse | /BinarySearch.py | 740 | 4.125 | 4 | #primary assumption for this binary search is that the
#list should be sorted already.
def binary_search (list, target):
first = 0
last = len(list)-1
while first <= last:
midpoint = (first + last)//2
if list[midpoint]== target:
return midpoint
elif list[midpoint] < ta... | true |
33c960afb411983482d2b30ed9037ee6017fbd34 | aggy07/Leetcode | /600-700q/673.py | 1,189 | 4.125 | 4 | '''
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing su... | true |
9ee533969bbce8aec40f6230d3bc01f1f83b5e96 | aggy07/Leetcode | /1000-1100q/1007.py | 1,391 | 4.125 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are th... | true |
8bdf3154382cf8cc63599d18b20372d16adbe403 | aggy07/Leetcode | /200-300q/210.py | 1,737 | 4.125 | 4 | '''
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you s... | true |
e9d57ebf9fe9beec2deb9654248f77541719e780 | aggy07/Leetcode | /100-200q/150.py | 1,602 | 4.21875 | 4 | '''
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression... | true |
8f83262573f48ba2f847993cc9ba7ffeb5fc1b17 | aggy07/Leetcode | /1000-1100q/1035.py | 1,872 | 4.15625 | 4 | '''
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw a straight line connecting two numbers A[i] and B[j] as long as A[i] == B[j], and the line we draw does not intersect any other connecting (non-horizontal) line.
Return the maximum number of connectin... | true |
64f7eb0fbb07236f5420f9005aedcbfefa25a457 | JATIN-RATHI/7am-nit-python-6thDec2018 | /variables.py | 730 | 4.15625 | 4 | #!/usr/bin/python
'''
Comments :
1. Single Comments : '', "", ''' ''', """ """ and #
2. Multiline Comments : ''' ''', and """ """
'''
# Creating Variables in Python
'Rule of Creating Variables in python'
"""
1. A-Z
2. a-z
3. A-Za-z
4. _
5. 0-9
6. Note : We can not create a variable name with numeric Value as a... | true |
356b0255a23c0a845df9c05b512ca7ccc681aa12 | JATIN-RATHI/7am-nit-python-6thDec2018 | /datatypes/list/List_pop.py | 781 | 4.21875 | 4 | #!/usr/bin/python
aCoolList = ["superman", "spiderman", 1947,1987,"Spiderman"]
oneMoreList = [22, 34, 56,34, 34, 78, 98]
print(aCoolList,list(enumerate(aCoolList)))
# deleting values
aCoolList.pop(2)
print("")
print(aCoolList,list(enumerate(aCoolList)))
# Without index using pop method:
aCoolList.pop()
print("")
... | true |
e23ca223aef575db942920729a53e52b1df2ed4d | JATIN-RATHI/7am-nit-python-6thDec2018 | /DecisionMaking/ConditionalStatements.py | 516 | 4.21875 | 4 | """
Decision Making
1. if
2. if else
3. elif
4. neasted elif
# Simple if statement
if "expression" :
statements
"""
course_name = "Python"
if course_name:
print("1 - Got a True Expression Value")
print("Course Name : Python")
print(course_name,type(course_name),id(course_name))
print("I am ou... | true |
47d9ba9ec790f0b9fde1a350cf8b240e5b8c886a | JATIN-RATHI/7am-nit-python-6thDec2018 | /OOPS/Encapsulation.py | 1,035 | 4.65625 | 5 | # Encapsulation :
"""
Using OOP in Python, we can restrict access to methods and variables.
This prevent data from direct modification which is called encapsulation.
In Python, we denote private attribute using underscore as prefix i.e single
“ _ “ or double “ __“.
"""
# Example-4: Data Encapsulation in Python
... | true |
9f6536e8d1970c519e84be0e7256f5b415e0cf3e | JATIN-RATHI/7am-nit-python-6thDec2018 | /loops/Password.py | 406 | 4.1875 | 4 |
passWord = ""
while passWord != "redhat":
passWord = input("Please enter the password: ")
if passWord == "redhat":
print("Correct password!")
elif passWord == "admin@123":
print("It was previously used password")
elif passWord == "Redhat@123":
print(f"{passWord} is your recent ... | true |
436120f034d541d70e2373de9c3a0c968b47f7ad | idubey-code/Data-Structures-and-Algorithms | /InsertionSort.py | 489 | 4.125 | 4 | def insertionSort(array):
for i in range(0,len(array)):
if array[i] < array[0]:
temp=array[i]
array.remove(array[i])
array.insert(0,temp)
else:
if array[i] < array[i-1]:
for j in range(1,i):
if array[i]>=array[j-1] a... | true |
9441cb892e44c9edd6371914b227a48f00f5d169 | hospogh/exam | /source_code.py | 1,956 | 4.21875 | 4 | #An alternade is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words. All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second let... | true |
fb745ae55b2759660a882d00b345ae0db70e60d2 | irfan-ansari-au28/Python-Pre | /Interview/DI _ALGO_CONCEPT/stack.py | 542 | 4.28125 | 4 | """
It's a list when it's follow stacks convention it becomes a stack.
"""
stack = list()
#stack = bottom[8,5,6,3,9]top
def isEmpty():
return len(stack) == 0
def peek():
if isEmpty():
return None
return stack[-1]
def push(x):
return stack.append(x)
def pop():
if isEmpty():
ret... | true |
6a34496d114bc6e67187e4bc12c8ff874d575de0 | BrightAdeGodson/submissions | /CS1101/bool.py | 1,767 | 4.28125 | 4 | #!/usr/bin/python3
'''
Simple compare script
'''
def validate(number: str) -> bool:
'''Validate entered number string is valid number'''
if number == '':
print('Error: number is empty')
return False
try:
int(number)
except ValueError as exp:
print('Error: ', exp)
... | true |
49b854f0322357dd2ff9f588fc8fb9c6f62fd360 | BowieSmith/project_euler | /python/p_004.py | 352 | 4.125 | 4 | # Find the largest palindrome made from the product of two 3-digit numbers.
def is_palindrome(n):
s = str(n)
for i in range(len(s) // 2):
if s[i] != s[-i - 1]:
return False
return True
if __name__ == "__main__":
ans = max(a*b for a in range(100,1000) for b in range(100,1000) if is_... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.