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.exit(0)
print("The characters in the given string are unique.")
| 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 from one to one million, use min() and max() to check that it starts at 1 and ends at 1000000 and then sum all of the elements from the list together.
onemillion = list(range(1,1000001))
print(min(onemillion))
print(max(onemillion))
print(sum(onemillion))
# 4.6 Odd numbers
# Make a list of the odd numbers from 1 to 20 and use a for loop to print each number.
odd_numbers = list(range(1,21,2))
for odd in odd_numbers:
print(odd)
print('\n')
# 4.7 Threes
# Make a list of the multiples of 3 from 3 to 30 and then print it.
threes =list(range(3,31,3))
for number in threes:
print(number)
# 4.8 Cubes
# Make a list of the first 10 cubes.
cubes = list(range(1,11))
for cube in cubes:
print(cube**3)
# 4.9 Cube comprehension
# Use a list comprehension to generate a list of the first 10 cubes.
cubes =[cube**3 for cube in range(1,11)]
| 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://www.udacity.com/course/viewer#!/c-nd000/l-4185678656/m-1013629057
# class: a blueprint for objects that can include data and methods
# instance: multiple objects based on a class
# constructor: the __init__ inside the class to create the object
# self: Python common practice for referring back to the object
# instance methods: functions within a class that refers to itself
import webbrowser
class Movie():
"""This class provides a way to store movie related information."""
def __init__(self, movie_title, rating, duration, release_date, movie_storyline, poster_image, trailer_youtube):
# Initializes instance of class Movie
self.title = movie_title
self.rating = rating
self.duration = duration
self.release_date = release_date
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
# Opens a browser window with the movie trailer from YouTube
webbrowser.open(self.trailer_youtube_url)
| 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".format(div))
| 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 Solution:
# def longestPalindrome(self, s):
# # Fill this in.
# # Test program
# s = "tracecars"
# print(str(Solution().longestPalindrome(s)))
# # racecar
class Solution:
def checkPalindrome(str):
# reversing a string in python to get the reversed string
# This is extended slice syntax.
# It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1,
# it reverses a string.
reversedString = str[::-1]
if (str == reversedString):
return true
else:
return false
def longestPalindrome(str):
while (index > str.length):
while ():
pass
| 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 depth = 3.
"""
import Queue as queue
class TreeNode(object):
def __init__(self,x):
self.val= x
self.left= None
self.right= None
class Solution(object):
def createTree(self, treelist):
root= TreeNode(treelist[0])
q= queue.Queue(maxsize= len(treelist))
q.put(root)
i = 1
while True:
if i>= len(treelist): break
node= q.get()
if treelist[i] != "null":
node.left= TreeNode(treelist[i])
q.put(node.left)
i+=1
if i>= len(treelist): break
if treelist[i] != "null":
node.right= TreeNode(treelist[i])
q.put(node.right)
i+=1
return root
def maxDepth(self, root):
if root==None: return 0
return max( self.maxDepth(root.left)+1, self.maxDepth(root.right)+1 )
if __name__=="__main__":
testcases= [[3,9,20,"null","null",15,7, 1, 1, 3], [1], [1,"null", 3]]
obj= Solution()
for test in testcases:
root= obj.createTree(test)
print test, " -> ", obj.maxDepth(root)
| 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 the tree is at most 1000.
The total number of nodes is at most 5000.
"""
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children #list of nodes
class Solution(object):
def helper(self, root, res, level):
if root==None:
return
if len(res)<= level+1 and len(root.children)>0:
res.append([])
for eachNode in root.children:
res[level+1].append(eachNode.val)
self.helper(eachNode, res, level+1)
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root==None:
return []
res= [[root.val]]
self.helper(root, res, 0)
return res
| 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_number) | 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 plot
OUTPUT:
plot with the top number of countries with the var scores
'''
# Initialize the matplotlib figure
f, ax = plt.subplots(figsize=(6, 15))
# Choose only the top 50 countries with higher score
y=df.sort_values(var, ascending=False)
y_top = y['Country or region'][:top_num]
# Plot the GDP per capita per country
sns.set_color_codes("pastel")
g=sns.barplot(x=var, y=y_top, data=df,
label=var, color="y")
# Add a legend and informative axis label
ax.legend(ncol=3, loc="lower right", frameon=True)
ax.set(xlim=(0, 10), ylabel="",
xlabel=var)
sns.despine(left=True, bottom=True)
return g | 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 withdraw exceeds your balance. Try again.")
withdrawSum = float(input("How much money do you need? "))
print ("You have successfully withdrawn " + str(withdrawSum) + "PLN. Your current balance is " + str(round((balance-withdrawSum), 2)) + "PLN.")
| 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') + wrap)
codedWord = codedWord + newChar
print("Your word in code is: ", codedWord)
| 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: ' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self,vert):
return self.connectedTo[vert]
class Graph():
"""Graph"""
def __init__(self):
# A dictionary to map Vertex-keys and object vertex class.
self.vertlist = {}
self.vertexNum = 0
def addVertex(self, key):
self.vertlist[key] = Vertex(key)
self.vertexNum += 1
return self.vertlist[key]
def getVertex(self, key):
if key in self.vertlist:
return self.vertlist[key]
else:
return None
def addEdge(self, h, t, weight=0):
# If any of vertex not in list create them
if h not in self.vertlist:
nv = self.addVertex(h)
if t not in self.vertlist:
nv = self.addVertex(t)
# Add edge from head to tail
self.vertlist[h].addEdge(self.vertlist[t], weight)
def getVertices(self):
return self.vertlist.keys()
def __iter__(self):
return iter(self.vertlist.values())
# create a graph
g = Graph()
# add some vertex
for i in range(6):
g.addVertex(i)
print (g.vertlist)
# Some Egdes
g.addEdge(0,1,5)
g.addEdge(0,5,2)
g.addEdge(1,2,4)
g.addEdge(2,3,9)
g.addEdge(3,4,7)
g.addEdge(3,5,3)
g.addEdge(4,0,1)
g.addEdge(5,4,8)
g.addEdge(5,2,1)
# View them
for v in g:
for w in v.getConnections():
print("( %s , %s )" % (v.getId(), w.getId()))
| 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__(self):
"""
Prints the details of a time block.
"""
return self.start_time.strftime("%c") + " " + self.end_time.strftime("%c")
def get_json(self):
"""
returns a json format of a Time Block
"""
time_dict=dict()
time_dict["start"]=self.start_time
time_dict["end"] = self.end_time
return time_dict
def get_start_time(self):
"""
return TimeBlock's end_time
"""
return self.start_time
def get_end_time(self):
"""
return TimeBlock's end_time
"""
return self.end_time
def set_start_time(self, start_time):
"""
set start_time
"""
self.start_time = start_time
return True
def set_end_time(self, end_time):
"""
set end_time
"""
self.end_time = end_time
return True | 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')
#4. Combine the name of their city and pet and show them their band name.
print('Band Name: ' + city_grew_user + " " + pet_of_user)
| 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(color_set)
color_set.update(["Blue","Green"])
print(color_set)
# Write a Python program to remove item(s) from set.
num_set = set([0, 1, 3, 4, 5])
num_set.pop()
print(num_set)
num_set.pop()
print(num_set)
# Write a Python program to create an intersection of sets.
#Intersection
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx & sety
print(setz)
# Write a Python program to create a union of sets.
seta = setx | sety
print(seta)
# Write a Python program to create set difference.
setn = setx - sety
print(setn)
# Write a Python program to create a symmetric difference.
seto = setx^sety
print(setn)
# Write a Python program to test whether every element in s is in t and every element in t is in s.
setz = set(["mango"])
issubset = setx <= sety
print(issubset)
issuperset = setx >= sety
print(issuperset)
issubset = setz <= sety
print(issubset)
issuperset = sety >= setz
print(issuperset)
# Write a Python program to create a shallow copy of sets.
setp = set(["Red", "Green"])
setq = set(["Green", "Red"])
#A shallow copy
setr = setp.copy()
print(setr)
# Write a Python program to clear a set.
setq.clear()
print(setq)
# Write a Python program to use of frozensets.
x = frozenset([1, 2, 3, 4, 5])
y = frozenset([3, 4, 5, 6, 7])
#use isdisjoint(). Return True if the set has no elements in common with other.
print(x.isdisjoint(y))
#use difference(). Return a new set with elements in the set that are not in the others.
print(x.difference(y))
#new set with elements from both x and y
print(x | y)
# Write a Python program to find maximum and the minimum value in a set.
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta))
| 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 = {'c1':'Churchgate', 'c5':'Marine Drive', 'c4':'Vile Parle', 'c3':"Bandra", 'c2':'Dadar', 'c6':'Andheri'}
dic2 = {'w3':'Wadala', 'c5':'Chowpatty', 'w4':'Kurla', 'w5':"Thane", 'c2':'Dadar', 'w7':'Andheri'}
# Printing dictionary
print dic1
# Print all keys
print dic1.keys()
# Print all values
print dic1.values()
# Printing a particular value using key
print 'Value of key c4 is: ' + dic1["c4"]
print "Value of key c4 is: " + dic1.get("c4")
# Print all keys and values
print dic1.items()
print "--------------------------------"
# Add value in dictionalry
dic1['w1']='Victoria Terminus'
dic1['w2']=10001
dic1[20]='Byculla'
print dic1
print "--------------------------------"
# Finding data type of key
print [type(i) for i in dic1.keys()]
print "--------------------------------"
print "Length of dictionary is:",
print len(dic1)
print "--------------------------------"
# "in" used to test whether a key is present in the dictionary
print dic1
print 20 in dic1
print "c6" in dic1
print "c6" not in dic1
print "--------------------------------"
# Adding values in dictionary using another dictionary
# If same key exist in both the dictionaries then it will update the value of the key available from dic2 in dic1
# If both dictionaries have same key + value then it will only keep the original value from dic1
dic1.update(dic2)
print dic1
print "--------------------------------"
# Remove value from dictionary
dic1.pop('w4')
print dic1
print "--------------------------------"
# Looping through dictionary
for key, value in dic2.items():
print key, value
print "--------------------------------"
dic1.clear()
print "Total number of elements in dic1 after using the clear function: ",
print len(dic1)
print "-------------THE END-------------------" | 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 instance of the class Edureka
# obj2 = Edureka()
#
# print obj1.domain
# print obj2.domain
#
# obj1.SetCourse('Python') # Calling the method
# obj2.SetCourse('Hadoop')
#
# print obj1.name
# print obj2.name
########################################################
# Program to understand more about constructor or distructor
class Edureka:
def __init__(self, name):
self.name = name
def __del__(self): # Called when an instance is about to be destroyed
print 'Destructor started'
obj1 = Edureka('Python')
obj2 = obj1
# Calling the __del__ function
del obj1
obj1 = obj2
print obj2.name
print obj1.name
del obj1, obj2 | 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 statement is used to modify existing records in the database. Its syntax is as follows:
'''
UPDATE table_name
SET column1 = value1, column2 = value2, column3 = value3, …, columnN = valueN
WHERE condition;
'''
# If we'd like to set the priority to 20 for a task with idequal to 1, we can use the following query:
'''
UPDATE tasks SET priority = 20 WHERE id = 1;
'''
# IMPORTANT NOTE: If you forget about the WHERE clause, all data in the table will be updated.
import sqlite3
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute('UPDATE tasks SET priority = ? WHERE id = ?', (20, 1))
conn.commit()
conn.close()
# DELETING DATA #
# After completing a task, we would like to remove it from our database. To do this, we must use the SQL statement called DELETE
'''
DELETE FROM table_name WHERE condition;
DELETE FROM tasks WHERE id = 1;
'''
# NOTE: If you forget about the WHERE clause, all data in the table will be deleted.
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute('DELETE FROM tasks WHERE id = ?', (1,)) # Tuple here? Not sure why, could be required...
conn.commit()
conn.close() | 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 longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
def get_tel_num_max_time(calls):
"""
Function for finding the telephone number that spent the longest time on the phone.
Args:
calls(list): list containing call records
Return:
max_len(tuple): tuple containing the telephone number and the time spend on
the phone from the telephone number that spent the longest time on the phone.
"""
# dictionary for keeping track of the time of every tel number
tel_nums = {}
# loop all records
for record in calls:
# loop both columns
for i in range(2):
# if key already exists summ values
if record[i] in tel_nums:
tel_nums[record[i]] += int(record[3])
# key does not exist create key with value
else:
tel_nums[record[i]] = int(record[3])
# find tel number with max length
max_len = ("0",0)
for tel_num, length in tel_nums.items():
if length > max_len[1]:
max_len = (tel_num, length)
return max_len
tel_num, lenght = get_tel_num_max_time(calls)
print("{} spent the longest time, {} seconds, on the phone during September 2016."\
.format(tel_num, lenght))
| 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 generated. """
def __init__(self):
""" Initialize the Agent """
self.__history = []
self.__x = -1
self.__y = -1
self.__destination_x = -1
self.__destination_y = -1
# ---------
# TO DO
# ---------
def make_decision(self):
""" make decision where agent have to go """
pass
# ---------
# TO DO
# ---------
def move(self, way: int):
""" Move the agent in a given direction """
pass
def add_to_history(self, env_vector: list[int], decision: int):
""" Add new pair of environment vector and decision to history """
self.__history.append((env_vector, decision))
def __str__(self):
""" define how agent should be shown as string """
string_agent = "{"
string_agent += "position: (" + str(self.__x) + ", " + str(self.__y) + ")"
string_agent += " | "
string_agent += "destination: (" + str(self.__destination_x) + ", " + str(self.__destination_y) + ")"
string_agent += "}"
return string_agent
def set_position(self, x: int, y: int):
""" Set new agent position """
self.__x = x
self.__y = y
def clear_history(self):
""" clear agent history """
self.__history.clear()
def get_history(self):
""" Return agent history """
return self.__history
def get_position(self):
""" Return agent position as a tuple (x, y) """
return self.__x, self.__y
if __name__ == '__main__':
agent = Agent()
print(agent)
agent.add_to_history([1, 0, 0, 1, 0, 1], 5)
agent.add_to_history([1, 0, 2, 3, 5, 6], 5)
agent.add_to_history([1, 1, 0, 3, 6, 5], 5)
print(agent.get_history())
agent.clear_history()
print(agent.get_history())
| 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 you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Example:
Given n = 5, and version = 4 is the first bad version.
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
同样是二分法 这个例子带边界值
"""
def isBadVersion(version):
return True if version >= 6 else False
class first_bad_version:
def firstBadVersion(self, n):
return self.findBadVersion(0, n)
def findBadVersion(self, left, right):
if right - left == 1:
if not isBadVersion(left) and isBadVersion(right):
return right
else:
middleVersion = (right + left) // 2
if isBadVersion(middleVersion):
return self.findBadVersion(left, middleVersion)
else:
return self.findBadVersion(middleVersion, right)
instance = first_bad_version()
print(instance.firstBadVersion(7)) | 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 unordered sequence of data of key-value pair form.
# It is similar to Map or hash table type.
# Dictionaries are written within curly braces in the form key:value
countries = {"India": "New Delhi", "China": "Beijing", "USA": "Washington", "Australia": "Canberra"}
print(countries["India"])
# adding entry to dictionary
countries["UK"] = "London"
print(countries)
# A set is an unordered collection of items. Every element is unique (no duplicates).
# In Python sets are written with curly brackets.
set1 = {1, 2, 3, 3, 4, 5, 6, 7}
print(set1)
set1.add(10)
# remove & discard does the same thing. removes the element.
# difference is discard doesn't raise error while remove raise error if element doesn't exist in set
set1.remove(6)
set1.discard(7)
print(set1)
| 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 condition in ()
if (1 == 1 and 2 + 2 > 3):
print('true')
else:
print('false')
# Or Operator
age = 15
money = 500
if age > 18 or money > 100:
print('Welcome')
# Not Operator
# print(not 1 == 1) # False
# print(not 1 > 7) # True
if not True:
print('1')
elif not (1 + 1 == 3):
print("2")
else:
print("3")
| 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(filename, 'a', encoding="UTF8") as f:
out = f.write(text)
f.closed
return (out)
| 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 integer")
elif size < 0:
raise ValueError("size must be >= 0")
for _i in range(size):
print('#' * size)
| 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(argv) == 2:
print("{:d} argument:".format(len(sys.argv) - 1))
else:
print("{:d} arguments:".format(len(sys.argv) - 1))
# range start in 1 because range start counting at 0
for i in range(1, len(argv)):
print("{:d}: {:s}".format(i, argv[i]))
| 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 % 3 == 0:
print '%d --> Fizz' % x
if x % 5 == 0:
print '%d --> Buzz' % x
if x % 3 == 0 and x % 5 == 0:
print '%d --> FizzBuzz' % x
def main():
fizzbuzz(randint(1, 100))
if __name__ == '__main__':
main()
| 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”
s1 = “silent”
Output:
True
Example 2:
Input:
s0 = “bedroom”
s1 = “bathroom”
Output:
False
Write your code here
"""
# my own code with new functions
def isanagram(x,s1):
if(s1.find(x)==-1):
return 0
else:
return 1
def anagram(s0,s1):
length = len(s0)
count=0
for x in s0:
if(isanagram(x,s1)==1):
count = count+1
if(count==length):
print('TRUE')
else:
print('FALSE')
s0 = input()
s1 = input()
anagram(s0,s1)
#using counter
from collections import Counter
def anagram1(input1, input2):
return Counter(input1) == Counter(input2)
input1 = 'abcd'
input2 = 'dcab'
print(anagram1(input1, input2)) | 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 plaintext:
if c.isalpha()==True:
if c.isupper()==True:
p = chr((ord(c) - ord('A') + key)%26 + ord('A'))
else:
p = chr((ord(c) - ord('a') + key)%26 + ord('a'))
else:
p=c
ciphertext+=p
print()
# 4. print ciphertext
print("Ciphertext: " + ciphertext) | 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
#Overriding
class Add:
def result(self,x,y):
print('addition', x+y)
class mult(Add):
def result(self,x,y):
print('multiplication', x*y)
obj= mult()
obj.result(5,6)
#Using superclass method we can modify the parent class method and call it in child class
class Add:
def result(self,x,y):
print('addition', x+y)
class mult(Add):
def result(self,a,b):
super().result(10,11)
print('multiplication', a*b)
obj= mult()
obj.result(10,20)
#Overloading: we can define a method in such a way that it can be called in different ways
class intro():
def greeting(self,name=None):
if name is not None:
print('Hello ', name)
if name is None:
print('no input given')
else:
print('Hello Alien')
obj1= intro()
obj1.greeting('Umasankar')
obj1.greeting(None)
#Ex2
class calculator:
def number(self,a=None,b=None,c=None):
if a!=None and b!=None and c!=None:
s=a+b+c
elif a!=None and b!= None:
s=a+b
else:
s= 'enter atlest two number'
return s
ob=calculator()
print(ob.number(10,)) | 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(process). Each independent part is called thread.
Thread: is a separate flow of execution. Every thread has a task
Multithreading: Using multiple thread in a prhram
once a thread is created, it should be started by calling start method: t= Thread(target=fun, args=()) then t.start()
'''
from threading import Thread
def display(user):
print('hello', user)
th=Thread(target=display, args=('uma',))
th.start()
#Example: thread in loop
def show(a,b):
print('hello number', a,b)
for i in range(3):
t=Thread(target=show, args=(10,20))
print('hey')
t.start() | 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 second complex number, enter real number"))
b1 = int(input("For second complex number, enter imaginary number"))
c1 = complex(a,b)
print(c1)
c2 = complex(a1,b1)
print(c2)
print("Addition of two complex number =", c1 + c2)
#Subtraction
print("Subtraction of two complex number =", c1 - c2)
#Multiplication
print("Multiplication of two complex number =", c1 * c2)
#Division
print("Division of two complex number =", c1 / c2)
c = (3 + 6j)
print('Complex Number: Real Part is = ', c. real)
print('Complex Number: Imaginary Part is = ', c. imag)
print('Complex Number: conjugate Part = ', c. conjugate())
| 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, int
float, True, False
None
'''
data = {"Name": "Girish",
"Shares": 100,
"Price": 540}
# convert into JSON:
json_str = json.dumps(data)
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
# the result is a JSON string:
print(json_str)
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann", "Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
# Use the indent parameter to define the numbers of indents:
print(json.dumps(x, indent=4)) # Very useful.
# Use the separators parameter to change the default separator:
print(json.dumps(x, indent=4, separators=("|| ", " = ")))
# Order the Result
# Use the sort_keys parameter to specify if the result should be sorted or not:
print("New Dict = ", json.dumps(x, indent=4, sort_keys=True))
# ==============================================================
# Parse JSON - Convert from JSON to Python
# If you have a JSON string, you can parse it by using the json.loads() method.
# The result will be a Python dictionary.
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
| 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 earned
points = int(input('How many quality points do you have? ')) # asks user for amount of quality points
gpa = points / hours # calculates GPA
gpa = round(gpa, 2) #rounds gpa 2 decimal places
print ('Hi ' + str(name) + '. ' + 'Your grade point average is ' + str(gpa) + '.') # displays users name and GPA
time.sleep(5)
| 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 efficient code, refactor the code.
"""
import random
import string
def StringGenerator():
a = int(input('Minimum length: '))
b = int(input('Maximum length: '))
n = int(input('How many strings do you want? '))
list_of_strings = []
for i in range(0,n):
length = random.randrange(a,b)
char = string.ascii_lowercase + string.digits
list_of_strings.append(''.join(random.choice (char) for i in range(length)))
print(list_of_strings)
StringGenerator() | 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:"))
labScores.append(score)
i += 1
print("Lab scores:", labScores)
numberOfTests = int(input("How many tests are you entering?"))
while numberOfTests <= 0:
print("Invalid input")
numberOfTests = int(input("How many tests are you entering?"))
testScores = []
i = 0
while i < numberOfTests:
score = float(input("Enter a test score:"))
testScores.append(score)
i += 1
print("Test scores:", testScores)
print("The default weight for scores is 50% labs and 50% tests.")
weightSelection = input("To change weight scale enter C, to use default weights, enter D:").lower()
while weightSelection != "c" and weightSelection != "d":
print("Invalid input.")
weightSelection = input("To change weight scale enter C, to use default weights, enter D:").lower()
if weightSelection == "c":
labWeight = float(input("What % weight do you want labs to count for? (Do not use % sign):"))
while labWeight < 0:
print("Invalid input.")
labWeight = float(input("What % weight do you want labs to count for? (Do not use % sign):"))
testWeight = float(input("What % weight do you want tests to count for? (Do not use % sign):"))
while testWeight < 0:
print("Invalid input.")
testWeight = float(input("What % weight do you want tests to count for? (Do not use % sign):"))
grade_calculator(labScores, testScores, labWeight, testWeight)
else:
grade_calculator(labScores, testScores)
def grade_calculator(labScores, testScores, labWeight = 50, testWeight = 50):
labAverage = sum(labScores) / len(labScores)
print("Lab Average:", labAverage)
testAverage = sum(testScores) / len(testScores)
print("Test Average:", testAverage)
courseGrade = (labAverage * (labWeight/100)) + (testAverage * (testWeight/100))
print("Course Grade:", courseGrade)
main()
| 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 hoursSinceMidnight >= 12:
meridiem = "PM"
hours = hoursSinceMidnight - 12
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
elif hoursSinceMidnight < 12:
meridiem = "AM"
hours = hoursSinceMidnight
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
else:
print("The input seconds exceeds the number of seconds in a single day.")
| 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 bytes
3) object type -- 8 bytes
4) object value -- 8 bytes
since numpy uses less bytes of memory it is faster than lists.
Another reason for numpy is faster than list is it uses contiguous memory. contiguous memory -- continues memory.
benefits :
->SIMD Vector processing
SIMD-Single Instruction Multiple Data.
->Effective cache utilization
lists | numpy
|
-> List can perform |-> Numpy can perforn insertion Deletion
insertion,delection | , appending , concatenation etc. we can perform lot more actions here.
appending,concatenation |
ex : | ex :
a=[1,3,5] | import numpy as np
b=[1,2,3] | a=np.array([1,3,5])
a*b = ERROR | b=np.array([1,2,3])
| c=a*b
| print(c)
|
| o/p : [1,6,15]
Applications of Numpy?
-> we can do maths with numpy. (MATLAB Replacement)
-> Plotting (Matplotlib)
-> Backend ( Pandas , Connect4 , Digital Photography)
-> Machine Learing.
Codes.
1) input
import numpy as np
a=np.array([1,2,3])
print(a)
1) o/p
[1 2 3] (one dimentional array)
2) input
b=np.array([[9.0,3.9,4],[6.0,5.0,4.0]])
print(b)
2) 0/p
[[9. 3.9 4. ] ( both the array inside must be equal or else it will give error )
[6. 5. 4. ]] --> Two dimentional array.
3) input
#To get dimension.
->print(a.ndim)
n-number,dim-dimention
3) o/p
1
4) input
# To get shape.
print(b.shape)
print(a.shape)
4) o/p
(2, 3) # { 2 rows and 3 columns }
(3,) # { 1 row and 3 columns }
5) input
# to get type.
print(a.dtype)
d-data,type
5) o/p
int32
6) input
to get size.
print(a.itemsize)
6) o/p
4 ( because 4 * 8 = 32 ) 8 - bytes
7) input
note :
we can specify the dtype in the beginning itself ex:
a=np.array([2,3,4],dtype='int16')
print(a.itemsize)
7) o/p
2 (because 2 * 8 = 16 ) 8 - bytes
8) input
# to get total size.
a=np.array([[2,5,4],[3,5,4]])
print(a.nbytes) # gets total size.
print(a.size * a.itemsize) # gets the total size.
8) o/p
24
24
9) input
#to get specific element [row,column]
print(a)
print(a[1,2]) or print(a[-1,-1]) '-' Refers to reverse indexing.
o/p
[[2 5 4]
[3 5 4]]
( indexing strats from 0 so a[1,2] means 2st row and 3rd column which is 4. )
4
input
#to get specific row only.
print(a[0:1])
o/p
[2 5 4]
input
#to get specific column.
print(a[:,2])
o/p
[4 4]
| 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 * If the number is not divisible by 3 or 5, just print the number.
# MAGIC
# MAGIC HINT: Look at the modulo (`%`) operator.
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def fizzBuzz(i):
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
# COMMAND ----------
# MAGIC %md
# MAGIC This function expects a numeric type. If it receives a different type, it will throw an error.
# MAGIC
# MAGIC * Add a check so that if the input to the function is not numeric (either `float` or `int`) print `Not a number`.
# MAGIC
# MAGIC HINT: Use the `type()` function.
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def typeCheckFizzBuzz(i):
if type(i) == int or type(i) == float:
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
else:
print("Not a number")
# COMMAND ----------
# MAGIC %md But what if the argument passed to the function were a list of values? Write a function that accepts a list of inputs, and applies the function to each element in the list.
# MAGIC
# MAGIC A sample list is provided below to test your function.
# COMMAND ----------
my_list = [1, 1.56, 3, 5, 15, 30, 50, 77, "Hello"]
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def listFizzBuzz(my_list):
for i in my_list:
if (type(i) == int) or (type(i) == float):
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
else:
print("Not a number")
listFizzBuzz(my_list)
| 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)
print("the asubstraction of two numbers is", num1 - num2)
print("enter the valid input")
| 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 counter
# counter = counter + 1
| 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+............
# end = " " means print will show with ount line break
sumVal = sumVal + x #this line will calculate sum 1+2+3+............
else:
print(str(x) + " = ", end=" ")#this line will show last value of series 5 = ............
sumVal = sumVal + x
print(sumVal) #this line will show final sum result of series............
| 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 from right to left | 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")
quit()
elif (guess > secret):
print("Your guess is high, try again")
else:
print("Your guess is low, try again")
| 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) # set to list
# add data
s.add(4)
s.add(10)
print(s)
# remove method
s.remove(1) #key not present in set,it will show error && IF ONE KEY IS PRESENT SEVERAL TIME,IT WILL NOT REMOVE
print(s)
# discard method
s.discard(4) # key not present in set,it will not set error
print(s)
# copy method
s1=s.copy()
print(s1)
#we cant store list tuple dictionary , we can store float,string
# we can use loop
for item in s:
print(item)
# we can use if else
if 'a' in s:
print('present')
else:
print('false')
# union && intersection
s1={1,2,3}
s2={4,5,6}
union_set=s1|s2 # union |
print(union_set)
intersection_set=s1&s2 # intersection using &
print(intersection_set)
| 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: use bayes theorem flip the coins twice, if HH or TT then p(HH) == 0.49, p(TT) = 0.09, p(HT) = p(TH) = 0.21
1) flip two coins
2) if HH or TT repeat 1)
3) if different then heads if HT and tails if TH
Bayes' Theorem:
p(head on the first flip / diff results) = p(diff results / head on the first flip)*p(head on the first flip) / p(diff results)
p(diff results / head on the first flip) = p(tails/heads) = 0.3
p(heads on first flip) = 0.7
p(diff results) = p(HT)+p(TH) = 0.21*2
p(head on the first flip / diff results) = 0.3*0.7/0.42 = 0.5 ---answer for a fair coin flip!
"""
"""
1: heads
0: tails
"""
def unfair_coin():
p_heads = random.randint(0, 100)/100
if p_heads > 0.5:
return 1
else:
return 0
def unfair_to_fair(a,b):
p, q = unfair_coin()
print(b*p, a*q)
if __name__ == '__main__':
a = unfair_coin()
b = unfair_coin()
if a==b:
unfair_coin()
if a == 1:
print("heads")
else:
print("tails")
| 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) #set thickness of line
tim.shape('turtle')
tim.forward(100) #turtle moves 100 pixels forward
tim.left(90) #turtle turns left 90 degrees
tim.forward(100)
tim.right(90)
tim.forward(100)
tim.penup() #lifts the pen up - turtle is moving but line is not drawn
tim.left(90)
tim.forward(100)
tim.right(90)
tim.pendown() #puts the pen back down
tim.forward(100)
tim.left(90)
tim.penup()
tim.forward(50)
tim.left(90)
tim.pendown()
tim.color('green') #changes the colour of the line to green
tim.forward(100)
#Making a new object named dave
dave = turtle.Turtle()
dave.color('blue')
dave.pensize(10)
dave.shape('arrow')
dave.backward(100)
dave.speed(1)
| 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_num = start_num+1
| 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.route('/frog')
def my_favorite_animal():
"""shows user my favorite animal"""
return f'Frogs are cute!'
@app.route('/dessert/<users_dessert>')
def favorite_dessert(users_dessert):
return f'How did you know I liked {users_dessert}'
@app.route('/madlibs/<adjective>/<noun>')
def mad_libs(adjective, noun):
return f'That is one {adjective} {noun}'
@app.route('/multiply/<number1>/<number2>')
def multiply(number1, number2):
if (number1.isdigit() == True) & (number2.isdigit() == True):
answer = int(number1) * int(number2)
return answer
else:
return "Invalid inputs. Please try again by entering 2 numbers!"
@app.route('/sayntimes/<word>/<number>')
def sayntimes(word, number):
if number.isdigit() == True:
string = ""
for word in range(int(number)):
string += str(word)
return
else:
return f"Invalid input. Please try again by entering a word and a number!"
if __name__ == '__main__':
app.run(debug=True)
| 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
current = node
count = 1
sqrt_index = 1
crossedthrough = []
result = None
while current != None:
if count == sqrt_index * sqrt_index:
crossedthrough.append(current.get_data())
result = current.get_data()
print "Checking if current count = sq( "+str(sqrt_index)+" )"
sqrt_index = sqrt_index + 1
count = count + 1
current = current.get_next()
print "We have crossed through: (sqrt(n))== 0 for :"+str(crossedthrough)
return result
head = ListNode.ListNode(1)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(2)
n2 = ListNode.ListNode(3)
n3 = ListNode.ListNode(4)
n4 = ListNode.ListNode(5)
n5 = ListNode.ListNode(6)
n6 = ListNode.ListNode(7)
n7 = ListNode.ListNode(8)
n8 = ListNode.ListNode(9)
n9 = ListNode.ListNode(10)
n10 = ListNode.ListNode(11)
n11 = ListNode.ListNode(12)
n12 = ListNode.ListNode(13)
n13 = ListNode.ListNode(14)
n14 = ListNode.ListNode(15)
#orig_head = ListNode.ListNode(1)
#orig_head.set_next(n1)
head.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
n6.set_next(n7)
n7.set_next(n8)
n9.set_next(n10)
n10.set_next(n11)
n11.set_next(n12)
n12.set_next(n13)
n13.set_next(n14)
print "Sqrt node (last from beginning): "+str(sqrtNthNode(head))
| 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:
result.append(char)
else:
if hash_table[char] != 1:
result.append(char)
result = ''.join(result)
print result
remove_chars("hello","he")
| 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):
if self.head is None:
print "Nothing to pop. Stack is empty!"
return -1
toremove = self.head
self.head = self.head.get_next()
self.size = self.size - 1
return toremove
def peek(self):
if self.head is None:
print "Nothing to peek!. Stack is empty!"
return -1
return self.head.get_data()
def print_stack(self):
current = self.head
while current != None:
print current.get_data(),
current = current.get_next()
print
'''
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
stack.push(6)
stack.print_stack()
stack.pop()
stack.print_stack()
print stack.size
print "top: "+str(stack.peek())
print stack.size
''' | 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
if top of stack has higher precedence
pop from stack and append to result
push the current operator to stack
else
push the current operator to stack
'''
# Time Complexity : O(n)
# Space Complexity : O(n)
import Stack
def get_precedence_map():
prec_map = {}
prec_map["*"] = 3
prec_map["/"] = 3
prec_map["+"] = 2
prec_map["-"] = 2
prec_map["("] = 1
return prec_map
def convert_infix_to_postfix(infix):
if infix is None:
return None
prec_map = get_precedence_map()
#print prec_map
opstack = Stack.Stack()
result_postfix = []
for item in infix:
print "--------------------------item: "+str(item)
# if operand just add it to result
if item in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or item in "0123456789":
print "appending: "+str(item)
result_postfix.append(item)
opstack.print_stack()
# if "(" just push it to stack
elif item == "(":
opstack.push(item)
opstack.print_stack()
# add to result upto open brace
elif item == ")":
top_elem = opstack.pop()
while top_elem.get_data() != "(" and opstack.size > 0:
print "appending: "+str(top_elem.get_data())
result_postfix.append(top_elem.get_data())
top_elem = opstack.pop()
opstack.print_stack()
#result_postfix.append(top_elem) # no need to append paranthesis in result.
else:
# should be an operator
while opstack.size > 0 and prec_map[opstack.peek()] >= prec_map[item]:
temp = opstack.pop()
print "appending: "+str(temp.get_data())
result_postfix.append(temp.get_data())
opstack.push(item) # after popping existing operator , push the current one. (or) without popping just push. based on the precedence check.
opstack.print_stack()
#print result_postfix
while opstack.size != 0:
result_postfix.append(opstack.pop().get_data())
return result_postfix
infixstring = "A*B-(C+D)+E"
infix = list(infixstring)
postfix = convert_infix_to_postfix(infix)
postfix = "".join(postfix)
print "Postfix for :"+str(infixstring)+" is : "+str(postfix)
| 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 (year2-month2-day2).
If either date is invalid, the function should return 0. Notice that you already wrote a
function to determine if a date is valid or not! If the second date is earlier than the first date,
the function should also return 0.
'''
import datetime
from is_valid_date import is_valid_date
def days_between(year1,month1,day1,year2,month2,day2):
if is_valid_date(year1,month1,day1):
date1 = datetime.date(year1,month1,day1)
else:
return 0
if is_valid_date(year2,month2,day2):
date2 = datetime.date(year2,month2,day2)
else:
return 0
delta = date2 - date1
if delta.days <= 0:
return 0
else:
return delta.days
# Testing
#print(days_between(1988,7,19,2018,7,3))
| 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 Enter: ")
c = input("Type in a value for 'c' and press Enter: ")
d = (b**2.0 - (4.0 * a * c))
if d < 0:
print "No real roots"
else:
root_1 = (-b + d**0.5) / (2.0 * a)
root_2 = (-b - d**0.5) / (2.0 * a)
print "The answers are:", root_1, "and", root_2
raw_input("Press Enter to exit.")
main()
| 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 guesses a number until he/she gets it right
number = 10
while True:
try:
inum = int(input("Enter a number: "))
if inum < number:
raise ValueTooSmallError
elif inum > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
except ValueTooLargeError:
print("This value is too large, try again!")
print("Congratulations! You guessed it correctly.") | 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], end=" ")
print("\r")
# adding and element to new list
li2[2][0] = 7
# checking if change is reflected
print("The original elements after shallow copying")
for i in range(0, len(li1)):
print(li1[i], end=" ")
| 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 equivalent
to the set class [0-9].
\D Matches any non-digit character.
\s Matches any whitespace character.
\S Matches any non-whitespace character
\w Matches any alphanumeric character, this is
equivalent to the class [a-zA-Z0-9_].
\W Matches any non-alphanumeric character.
'''
| 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)
'''
The copyreg module defines functions which are used by pickling specific objects
while pickling or copying. This module provides configuration information
about object constructors(may be factory functions or class instances)
which are not classes.
copyreg.constructor(object)
This function is used for declaring object as a valid constructor.
An object is not considered as a valid constructor if it is not callable.
This function raises TypeError if the object is not callable.
copyreg.pickle(type, function, constructor=None)
This is used to declare function as a “reduction” function for objects of type type.
function should return either a string or a tuple containing two or three elements.
The constructor parameter is optional. It is a callable object which can be used
to reconstruct the object when called with the tuple of arguments returned by
function at pickling time. TypeError is raised if object is a class or
constructor is not callable.
''' | 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(math.sqrt(25))
| 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 ("Value after adding using normal operator : ",end="")
print (z)
# printing value of first argument
# value is unchanged
print ("Value of first argument using normal operator : ",end="")
print (a)
# using iadd() to add the arguments passed
# performs a+=[1, 2, 3]
p = operator.iadd(a,[1, 2, 3])
# printing the modified value
print ("Value after adding using Inplace operator : ",end="")
print (p)
# printing value of first argument
# value is changed
print ("Value of first argument using Inplace operator : ",end="")
print (a)
| 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))
# using ctime() to diplay time string using seconds
print ("Time calculated using ctime() is : ", end="")
print (time.ctime())
| 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.Enum):
dog = 1
cat = 2
lion = 3
# printing all enum members using loop
print("All the enum values are : ")
for Anim in (Animal):
print(Anim)
# Hashing enum member as dictionary
di = {}
di[Animal.dog] = 'bark'
di[Animal.lion] = 'roar'
# checking if enum values are hashed successfully
if di == {Animal.dog: 'bark', Animal.lion: 'roar'}:
print("Enum is hashed")
else:
print("Enum is not hashed")
| 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
calendar.setfirstweekday(4)
print("\r")
# using firstweekday() to check the changed day
print("The new week day number is : ", end="")
print(calendar.firstweekday())
| 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 of two numbers
print ("The logical_and() of two numbers is : ",end="")
print (a.logical_and(b))
# printing logical_or of two numbers
print ("The logical_or() of two numbers is : ",end="")
print (a.logical_or(b))
# printing exclusive or of two numbers
print ("The exclusive or of two numbers is : ",end="")
print (a.logical_xor(b))
# printing logical inversion of number
print ("The logical inversion of number is : ",end="")
print (a.logical_invert())
'''
1. logical_and() :- This function computes digit-wise logical “and” operation of the number. Digits can only have the values 0 or 1.
2. logical_or() :- This function computes digit-wise logical “or” operation of the number. Digits can only have the values 0 or 1.
3. logical_xor() :- This function computes digit-wise logical “xor” operation of the number. Digits can only have the values 0 or 1.
4. logical_invert() :- This function computes digit-wise logical “invert” operation of the number. Digits can only have the values 0 or 1.
''' | 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 : ", end="")
print(cmath.sin(z))
# printing cosine of the complex number
print("The cosine value of complex number is : ", end="")
print(cmath.cos(z))
# printing tangent of the complex number
print("The tangent value of complex number is : ", end="")
print(cmath.tan(z))
| 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, 6, 12, 14]
Time Complexity: O(n)
Space Complexity: O(n)
"""
for i in range(1, len(nums_li)):
nums_li[i] += nums_li[i - 1]
return nums_li
if __name__ == '__main__':
nums_str = input("Insert numbers (e.g. 1 5 1 6): ")
nums_li = [int(i) for i in nums_str.split()]
print(running_sum(list(nums_li)))
| 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 for (1-Monday, 7-Sunday")
while True:
try:
choosed_day = int(input())
if 1 <= choosed_day <= 7:
break
else:
print("Wrong number. Pass an integer in range (1-7): ", end = "")
except:
print("Must be an integer in range (1-7). Type again: ", end = "")
day = datetime.date.today().day
month = datetime.date.today().month
year = datetime.date.today().year
startdate=datetime.datetime(year, month, day)
d = startdate
match_amount = 0
month_amount = 0
control = 0
while(period > 0):
period -= 1
if d.weekday() == choosed_day - 1:
if control == 0 and decision == 1:
print("Month's found: ")
control = 1
if control == 0 and decision == 0:
control = 1
match_amount += 1
if decision == 1:
print(calendar.month(d.year,d.month))
if d.month != 1:
month1 = d.month - 1
d = d.replace (month = month1)
month_amount += 1
else:
year1 = d.year - 1
d = d.replace (month = 12, year = year1)
month_amount += 1
diff = abs(d - startdate)
elif d.month != 1:
month1 = d.month - 1
d = d.replace (month = month1)
month_amount += 1
else:
year1 = d.year - 1
month1 = 12
d = d.replace (month = month1, year = year1)
month_amount += 1
if control == 0:
print("No matching were found.\nProbability: 0\nProbability expected: ", 1/7)
else:
print("Number of months found: ", match_amount)
print("Number of months checked: ", month_amount)
print("Number of days: ", diff.days)
print("Probability found: ", match_amount/month_amount)
print("Probability expected: ", 1/7)
if decision == 1:
print("Range of research:\nStarting month:")
print(calendar.month(startdate.year, startdate.month))
print("Final month:",)
print(calendar.month(d.year, d.month))
print("Do you want to print out all of founded months?: [1/y][n/0]", end = " ")
true = ['1','y','Y','yes','YES','YEs','YeS','Yes','ye','Ye','YE']
false = ['0','no','NO','nO','No','n','N']
while True:
decision = input()
if decision in true:
decision = 1
break
elif decision in false:
decision = 0
break
else:
print("Wrong input. Try again: ")
name(decision) | 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
alphabet1 = string.ascii_lowercase
alphabet2 = string.ascii_uppercase
i = 0
for c in alphabet:
key = 0
c = letter
if c in alphabet1:
ascii_value = ord(c)
c = ascii_value
key = (c - 97) % 26
elif c in alphabet2:
ascii_value = ord(c)
c = ascii_value
key = (c - 65) % 26
elif c not in alphabet:
key = ord(c)
return key
# helper funtion 2
def rotate_character(char, rot):
"""Receives a character 'char', and an integer 'rot'.
Returns a new char, the result of rotating char by rot number of places to the right."""
a = char
a = alphabet_position(a)
rotation = (a + rot) % 26
if char in string.ascii_lowercase:
new_char = rotation + 97
rotation = chr(new_char)
elif char in string.ascii_uppercase:
new_char = rotation + 65
rotation = chr(new_char)
elif char == char:
rotation = char
return rotation
| 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 position of the disk
'''
#approach : call hanoi function recursively to move disk from one pole to another
assert n>0
if n==1:
print('Move disk from ',source,' to ',target)
else:
hanoi(n-1,source,target,spare)
print('Move disk from ',source,' to ',target)
hanoi(n-1,spare,source,target)
| 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 the string.
while currloc < strend:
# Append the character from the current location to the substring.
substr += s[currloc]
# Our base case to ensure we don't try to access invalid string slice locations.
# If current location is equal to the actual length of the string then increment
# the current location counter and append the substring to our list.
if currloc == strend - 1:
currloc += 1
sublist.append(substr)
# Continute processing the substring as we've still got slices in alphabetical order.
elif s[currloc+1] >= s[currloc]:
currloc += 1
# Current slice location broken the alphabetical order requirement.
# Append the current substring to our list, reset to an empty substring and increment the current location.
else:
sublist.append(substr)
substr = ''
currloc += 1
print("Longest substring in alphabetical order is: {}".format(max(sublist, key=len)))
| 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 sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
def logic(input_string):
c = 50
h = 30
input_list = input_string.split(",")
output_list = []
output_string = ""
for d in input_list:
output_list.append(str(int((2*c*int(d)/h)**0.5)))
for i in range(len(output_list)):
if i == 0:
output_string = output_string+output_list[i]
else:
output_string = output_string+","+output_list[i]
return output_string
class TestLogic(unittest.TestCase):
def test_logic(self):
self.assertEqual(
logic("100,150,180"),
"18,22,24",
"Should be `18,22,24`")
if __name__ == '__main__':
unittest.main() | 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 method.
import random, string
chars = string.ascii_letters + string.digits + string.punctuation
def generate(length):
psswd = "".join(random.choice(chars) for i in range(length))
return psswd
while True:
num = input("How long would you like your new password? ")
num = int(num)
print(generate(num)) | 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 another if needed)
# 3. Reduce the sample space to `n - 1` by the biggest element just found.
# 4. Start the iteration over again, on the reduced sample space.
# 5. Continue till we have a sorted data set, either incremental or decremental
# How does the data sample reduces in each iteration?
# [10, 4, 9, 3, 6, 19, 8] - Data set
# [10, 4, 9, 3, 6, 8] - [19] - After Iteration 1
# [4, 9, 3, 6, 8] - [10, 19] - After Iteration 2
# [4, 3, 6, 8] - [9, 10, 19] - After Iteration 3
# [4, 3, 6] - [8, 9, 10, 19] - After Iteration 4
# [4, 3] - [6, 8, 9, 10, 19] - After Iteration 5
# [3] - [4, 6, 8, 9, 10, 19] - After Iteration 6
# [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set
# Let's check what the Selection Sort algorithm has to go through in each
# iteration
# [10, 4, 9, 3, 6, 19, 8] - Data set
# [10, 4, 9, 3, 6, 8] - After Iteration 1
# [4, 9, 3, 6, 8] - After Iteration 2
# [4, 3, 6, 8] - After Iteration 3
# [4, 3, 6] - After Iteration 4
# [4, 3] - After Iteration 5
# [3] - After Iteration 6
# [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set
# Observations:
# 1. It takes `n` iterations in each step to find the biggest element.
# 2. The next iteration has to run on a data set of `n - 1` elements.
# 3. Hence the total number of overall iterations would be:
# n + (n - 1) + (n - 2) + (n - 3) + ..... 3 + 2 + 1
# Since `Selection Sort` takes in `n` elements while starting, and goes through
# the data set `n` times (each step reducing the data set size by 1 member),
# the iterations would be:
# n + [ (n - 1) + (n - 2) + (n - 3) + (n - 4) + ... + 2 + 1 ]
# Efficiency:
# We are interested in the worse-case scenario.
# In a very large data set, an `n - 1`, `n - 2` etc.. won't make a difference.
# Hence, we can re-write the above iterations as:
# n + [n + n + n + n ..... n]
# Or also as:
# n x n = n**2
# O(n**2)
# Final thoughts:
# Selection Sort is an algorithm to sort a data set, but it is not particularly
# fast. For `n` elements in a sample space, Selection Sort takes `n x n`
# iterations to sort the data set.
def find_smallest(my_list):
smallest = my_list[0]
smallest_index = 0
for i in range(1, len(my_list)):
if my_list(i) < smallest:
smallest = my_list(i)
smallest_index = i
return smallest_index
def selection_sort(my_list):
new_list = []
for i in range(len(my_list)):
smallest = find_smallest(my_list)
new_list.append(my_list.pop(smallest))
return new_list
print(selection_sort([10, 12, 9, 4, 3, 6, 100]))
| 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, and step position
print("I'll print the numbers in range to 11, starting at 2, with a step size of 2")
for num in range(2,11,2):
print(num)
#Using the min built in function
print('This is the minimum age of someone in my family:')
myList = [30, 33, 60, 62]
print(min(myList))
#Using the max built in function
print('This is the maximum age of someone in my family:')
print(max(myList))
| 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, spaces, and capitalization should remain intact.
# For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt".
# more on cipher visit http://practicalcryptography.com/ciphers/caesar-cipher/
# happy coding :-)
def CaesarCipher(string, num):
# Your code goes here
print "Cipertext:", CaesarCipher("A Crazy fool Z", 1)
| 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] < target :
first = midpoint + 1
else :
last = midpoint - 1
return None
#summary of above code :
#two variables named first and last to indicate the starting and ending point
#of the list.
# the while loop would run till the first value is less than or equal to last
# then we update the values of first and last.
a= [x for x in range(1,11)]
print(a)
print(binary_search(a,1))
| 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 subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.
'''
class Solution(object):
def findNumberOfLIS(self, nums):
length = [1]*len(nums)
count = [1]*len(nums)
result = 0
for end, num in enumerate(nums):
for start in range(end):
if num > nums[start]:
if length[start] >= length[end]:
length[end] = 1+length[start]
count[end] = count[start]
elif length[start] + 1 == length[end]:
count[end] += count[start]
for index, max_subs in enumerate(count):
if length[index] == max(length):
result += max_subs
return result
| 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 the same, or all the values in B are the same.
If it cannot be done, return -1.
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
'''
class Solution(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
if len(A) != len(B):
return -1
if len(A) == 0:
return 0
for possibility in set([A[0], B[0]]):
top_rotation, bottom_rotation =0, 0
for a_num, b_num in zip(A, B):
if possibility not in [a_num, b_num]:
break
top_rotation += int(b_num != possibility)
bottom_rotation += int(a_num != possibility)
else:
return min(top_rotation, bottom_rotation)
return -1
| 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 should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1] .
'''
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = [[] for _ in range(numCourses)]
visited = [False for _ in range(numCourses)]
stack = [False for _ in range(numCourses)]
for pair in prerequisites:
x, y = pair
graph[x].append(y)
result = []
for course in range(numCourses):
if visited[course] == False:
if self.dfs(graph, visited, stack, course, result):
return []
return result
def dfs(self, graph, visited, stack, course, result):
visited[course] = True
stack[course] = True
for neigh in graph[course]:
if visited[neigh] == False:
if self.dfs(graph, visited, stack, neigh, result):
return True
elif stack[neigh]:
return True
stack[course] = False
result.append(course)
return False | 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 would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
'''
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
if not tokens:
return 0
stack = []
for val in tokens:
if val == '+':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val1 + val2)
elif val == '-':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2-val1)
elif val == '*':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2*val1)
elif val == '/':
val1 = stack.pop()
val2 = stack.pop()
if val1*val2 < 0:
stack.append(-(-val2/val1))
else:
stack.append(val2/val1)
else:
stack.append(int(val))
return stack[0] | 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 connecting lines we can draw in this way.
Example 1:
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
Example 2:
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
Note:
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
'''
class Solution(object):
def maxUncrossedLines(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
dp = [[0]*len(A) for _ in range(len(B))]
dp[0][0] = 1 if A[0] == B[0] else 0
for index_i in range(1, len(dp)):
dp[index_i][0] = dp[index_i-1][0]
if A[0] == B[index_i]:
dp[index_i][0] = 1
for index_j in range(1, len(dp[0])):
dp[0][index_j] = dp[0][index_j-1]
if B[0] == A[index_j]:
dp[0][index_j] = 1
for index_i in range(1, len(dp)):
for index_j in range(1, len(dp[0])):
if A[index_j] == B[index_i]:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1] + 1, max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
else:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1], max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
return dp[len(B)-1][len(A)-1]
| 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 prefix
"""
'''left operand = right operand
left operand : Name of the Variable
right operand : Value of the Variable'''
"Creating variables in Python"
FIRSTNAME = 'Guido'
middlename = "Van"
LASTname = '''Rossum'''
_python_lang = """Python Programming Language"""
"Accessing Variables in Python"
print(FIRSTNAME)
print("")
print(middlename)
print("")
print(LASTname)
print("")
print(_python_lang)
| 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("")
print(aCoolList,list(enumerate(aCoolList)))
'''
5. list.pop([i]) : list.pop()
Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last item in the list.
(The square brackets around the i in the method signature denote that the
parameter is optional,
not that you should type square brackets at that position.
You will see this notation frequently in the Python Library Reference.)
'''
| 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 outside of if condition")
var = 100
var1 = 50
if var == var1:
print("Yes, Condition is met")
print("Goodbye!")
if (var == var1):
print("Yes, Condition is met")
print("Goodbye!")
| 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
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
"""
In the above program, we defined a class Computer.
We use __init__() method to store the maximum selling price of computer.
We tried to modify the price.
However, we can’t change it because Python treats the __maxprice as private attributes.
To change the value, we used a setter function i.e setMaxPrice() which takes price as parameter.
""" | 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 changed password")
else:
print("Incorrect Password- try again!")
| 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] and array[i]<array[j]:
temp=array[i]
array.remove(array[i])
array.insert(j,temp)
return array
| 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 letter is used will produce a four-letter word and a three-letter word. Here are two examples:
# "board": makes "bad" and "or".
# "waists": makes "wit" and "ass".
#
#
#Using the word list at unixdict.txt, write a program that goes through each word in the list and tries to make two smaller words using every second letter. The smaller words must also be members of the list. Print the words to the screen in the above fashion.
#max_leng_of_word = 14
with open("unixdict.txt", "r") as f:
words = f.readlines()
f.closed
words = [s.strip("\n") for s in words]
#creating a dict with a member after each word which contains an empty list
potential_words = {str(word): ["evennumberword", "oddnumberword"] for word in words}
#adding to the dict member of each word it's even number and odd number chars made words, in total: 2 words as
for word in words:
even_number_word = ""
odd_number_word = ""
try:
for i in range(14):
if i % 2 == 0:
even_number_word = "".join([even_number_word, word[i]])
elif not i % 2 == 0:
odd_number_word = "".join([odd_number_word, word[i]])
except IndexError:
potential_words[str(word)][0] = even_number_word
potential_words[str(word)][0] = odd_number_word
print(word, "evennumber is", even_number_word, "and oddnumber is", odd_number_word)
if even_number_word in set(words) and odd_number_word in set(words):
print(word, "is an alternade")
else:
print(word, "is not an alternade")
#didn't take out dict creation part cause it might be used to write this info in another file
| 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():
return None
else:
return stack.pop()
if __name__ == '__main__':
push(8)
push(5)
push(6)
push(3)
push(9)
print(isEmpty())
print(peek())
x = pop()
print(x,'pop')
print(stack) | 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)
return False
return True
def read_number(prefix: str) -> int:
'''Read number from the prompt'''
while True:
prompt = 'Enter ' + prefix + ' > '
resp = input(prompt)
if not validate(resp):
continue
number = int(resp)
break
return number
def compare(a, b: int) -> (str, int):
'''
Compare two numbers
It returns 1 if a > b,
returns 0 if a == b,
returns -1 if a < b,
returns 255 if unknown error
'''
if a > b:
return '>', 1
elif a == b:
return '==', 0
elif a < b:
return '<', -1
return 'Unknown error', 255
def introduction():
'''Display introduction with example'''
_, example1 = compare(5, 2)
_, example2 = compare(2, 5)
_, example3 = compare(3, 3)
print('''
Please input two numbers. They will be compared and return a number.
Example:
a > b is {}
a < b is {}
a == b is {}
'''.format(example1, example2, example3))
def main():
'''Read numbers from user input, then compare them, and return result'''
introduction()
first = read_number('a')
second = read_number('b')
result_str, result_int = compare(first, second)
if result_int == 255:
print(result_str)
return
print('Result: {} {} {} is {}'.format(first, result_str, second,
result_int))
if __name__ == "__main__":
main()
| 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_palindrome(a*b))
print(ans)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.