blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
302da1ed10202f3d7c8a421b47b0639b8d103745 | Brainchildtech/codes | /primenumber.py | 90 | 3.65625 | 4 | n=int(input("num"))
for i in range(1,n+1):
while n>0:
if i%2!=0:
print i
|
ba2e73fedd48f3cb0ccb0bd376899bda371833b6 | Oizys18/Algo | /preset/Python/BinarySearch.py | 1,365 | 3.828125 | 4 | # >> Most Generalized Binary Search
# Suppose we have a search space. It could be an array, a range, etc. Usually it's sorted in ascending order. For most tasks, we can transform the requirement into the following generalized form:
# Minimize k , s.t. condition(k) is True
# The following code is the most generalized binary search template:
def binary_search(array) -> int:
def condition(value) -> bool:
pass
# could be [0, n], [1, n] etc. Depends on problem
left, right = min(search_space), max(search_space)
while left < right:
mid = left + (right - left) // 2
if condition(mid):
right = mid
else:
left = mid + 1
return left
# What's really nice of this template is that, for most of the binary search problems, we only need to modify three parts after copy-pasting this template, and never need to worry about corner cases and bugs in code any more:
# Correctly initialize the boundary variables left and right to specify search space. Only one rule: set up the boundary to include all possible elements;
# Decide return value. Is it return left or return left - 1? Remember this: after exiting the while loop, left is the minimal k satisfying the condition function;
# Design the condition function. This is the most difficult and most beautiful part. Needs lots of practice.
|
28b99716f6d12fa73379f684fcebf4e0ed96214b | pierpaolo28/Algorithms | /Sorting/bubble_sort.py | 261 | 3.6875 | 4 | def bubble_sort(inp):
for i in range(len(inp)):
for j in range(len(inp)-i-1):
if inp[j] > inp[j+1]:
inp[j], inp[j+1] = inp[j+1], inp[j]
return inp
arr = [33, 55, 2, 7, 1, 1, 6778]
print(arr)
print(bubble_sort(arr))
|
5ae34e3821c1d3dd8476ad6bc319fefbd94aa08a | shiva-marupakula/Student-Management-System | /src/main/webapp/python/unit1/billpay.py | 444 | 3.953125 | 4 | # to calculate bill amount for item.
a=input("enter item name")
b=float(input("enter the quantity"))
p=float(input('enter price of item'))
d=float(input('enter the discount'))
tp=(b*p)
dis=tp*(d/100)
g=tp-dis
print ("*******************BILL**********************")
print ("item name\tquantity\tprice\tdiscount")
print ("{}\t {}\t {}\t {}".format(a,b,p,d))
print ('total price is ',g)
print('***************PLEASE VISIT AGAIN**************')
|
78081d048f66e57d2119cde2f81fd62b726a1c8a | gundam1996/pyWebCheck | /simple_client.py | 816 | 3.796875 | 4 | #/usr/lib/python2.7
from BeautifulSoup import BeautifulSoup
import re
import urllib, urllib2
str1 = raw_input("Please enter the network address: ")
if "https://" in str1:
try:
response = urllib2.urlopen(str(str1))
except URLError:
print "Cannot open website!"
response = None
elif "http://" in str1:
try:
response = urllib.urlopen(str(str1))
except URLError:
print "Cannot open website!"
response = None
else:
# Try HTTPS
str2 = "https://" + str1
try:
response = urllib2.urlopen(str(str2))
except URLError:
str2 = "http://" + str1
try:
response = urllib.urlopen(str(str1))
except URLError:
print "Cannot open website!"
response = None
if response == None:
print "URL invalid!"
else:
data = response.read()
soup = BeautifulSoup(''.join(data))
print soup.prettify()
|
1658d3f9ad7cb1ebb888c2cf415b08a85fe836f5 | bakliwalvaibhav1/Python-HackerRank | /01) Introduction/if_else.py | 266 | 3.71875 | 4 | """
TITLE: Python If-Else
INPUT:
12
OUTPUT:
Weird
"""
if __name__ == '__main__':
n = int(input().strip())
if(n%2 != 0):
print("Weird")
else:
if(n>=6 and n<= 20):
print("Weird")
else:
print("Not Weird")
|
7ea0a0c2eb86a91dc2cad331b1594baf67268300 | 01bui/Finding-Hidden-Messages-in-DNA | /patternCount.py | 671 | 3.578125 | 4 | import pdb
def patternCount(Text, Pattern):
count = 0
textList = list(Text)
patternList = list(Pattern)
print len(textList)
print len(patternList)
for i in range(0,len(textList)-len(patternList)+1,1):
if textList[i:i+len(patternList)] == patternList:
count += 1
return count
def readData(filename):
with open(filename, 'r') as f:
#f.readline() # Skip input line
Text = f.readline()
Pattern = f.readline()
return Text.strip(), Pattern.strip()
if __name__ == "__main__":
Text, Pattern = readData('dataset_2_6.txt')
resultCount = patternCount(Text, Pattern)
print resultCount |
75756eccac53bc1ac240762265ae5247e8b1df17 | pjp/KeyboardReader | /skid_steering/InputHandler.py | 17,060 | 4 | 4 | __author__ = 'Paul Pearce'
################################################################
# Logical input values to translate to motor speed and direction
#
# Use these so they logically match the numbers on the numeric keypad
STOP = 5
LEFT = 4
RIGHT = 6
FORWARD = 8
BACK = 2
import math
import logging
class InputHandler(object):
def __init__(self, min_motor_value, max_motor_value, step_value):
"""
Constructor
:param min_motor_value: The value to stop the motor turning.
:param max_motor_value: The value value to spin the motor at max. speed
:param step_value: How many increment each key press will move the motor value up or down. It is assumed that
the same range will be valid for reversing a motor.
:return:
Example ih = IH.InputHandler(0, 100, 20)
The logical motors can handle a range of -100 to +100 (full reverse to full forward), and 5 (100/20)
forward/back keypress's will move the motor from stopped to full speed in the relevant direction.
"""
self._logger = logging.getLogger("SkidSteering.InputHandler")
# Sanity checks
if min_motor_value > max_motor_value:
raise Exception("min value cannot be > max value")
if(min_motor_value == max_motor_value):
raise Exception("Cann have min == max")
if step_value < 1:
raise Exception("step value must be >= 1")
if (max_motor_value - min_motor_value) < step_value:
raise Exception("step is too big")
self._min_motor_value = min_motor_value
self._max_motor_value = max_motor_value
self._step_value = step_value
self._current_motor_left_value = 0
self._current_motor_right_value = 0
self._stop()
def move(self, input):
"""
Given the logical input movement key, determine the new left and right (logical) motor values.
:param input: A logical movement key value
Below are some of the actions performed when the vehicle is in various states
Vehicle State Key Action
============= === ======
ANY STOP Vehicle will stop
Stationary FORWARD Move forward (straight ahead) slowly
Stationary BACK Move back slowly
Stationary LEFT Spin left slowly
Stationary RIGHT Spin right slowly
Moving forward FORWARD Move forward (straight ahead) more quickly
Moving forward BACK Stop
Moving forward LEFT Turn to the left
Moving forward RIGHT Turn to the right
Moving forward and Turning left FORWARD Move forward (straight ahead) at the speed of the right (faster) track
Moving forward and Turning left BACK Move forward (straight ahead) at the speed of the left (slower) track
Moving forward and Turning left LEFT Turn left more quickly
Moving forward and Turning left RIGHT same as FORWARD
From the above, all the other states and actions can be inferred.
"""
initialMotorValues = "L/R" + str([self._current_motor_left_value, self._current_motor_right_value])
self._logger.info("Initial motor values: " + initialMotorValues)
self._logger.info("Input: [" + str(input) + "]")
################
# Generic action
if input == LEFT:
self._turn_left()
elif input == RIGHT:
self._turn_right()
elif input == FORWARD:
self._move_forward()
elif input == BACK:
self._move_back()
elif input == STOP:
self._stop()
else:
raise Exception("Invalid input: " + "[" + str(input) + "]")
currentMotorValues = "L/R" + str([self._current_motor_left_value, self._current_motor_right_value])
self._logger.info("Current motor values: " + currentMotorValues)
#############################################################################
# Sanity checks - cannot have one motor moving while another motor stationery
problem_left_motor_speed = self._current_motor_left_value == 0 and self._current_motor_right_value != 0
problem_right_motor_speed = self._current_motor_left_value != 0 and self._current_motor_right_value == 0
if problem_left_motor_speed or problem_right_motor_speed:
errorMessage = "Internal consistancy check failure - Motor values are invalid - one motor is stationery:"
errorMessage = errorMessage + " Initial motor values: " + initialMotorValues
errorMessage = errorMessage + " Input: " + "[" + str(input) + "]"
errorMessage = errorMessage + " Current motor values: " + currentMotorValues
raise Exception(errorMessage)
def left_motor_value(self):
"""
:return: The current left motor value
"""
self._logger.debug(self._current_motor_left_value)
return self._current_motor_left_value
def right_motor_value(self):
"""
:return: The current right motor value
"""
self._logger.debug(self._current_motor_right_value)
return self._current_motor_right_value
def _is_spinning(self):
"""
Determine if the vehicle is spinning on the spot
:return:
"""
moving = self._is_moving()
dM = math.fabs(self._current_motor_left_value + self._current_motor_right_value)
value = moving and dM == 0.0
self._logger.debug(str(value))
return value
def _is_turning(self):
"""
Determine if the vehicle should be turning based on the current motor values
:return: true if turning; else false
"""
moving = self._is_moving()
dM = (self._current_motor_left_value - self._current_motor_right_value)
value = moving and dM != 0.0
self._logger.debug(str(value))
return value
def _is_turning_left(self):
value = self._current_motor_left_value < self._current_motor_right_value
self._logger.debug(str(value))
return value
def _is_turning_right(self):
value = self._current_motor_right_value < self._current_motor_left_value
self._logger.debug(str(value))
return value
def _is_moving_forward(self):
"""
Determine if we are actually moving forward
:return:
"""
value = self._current_motor_left_value >= 0 and self._current_motor_right_value >= 0
self._logger.debug(str(value))
return value
def _is_moving_back(self):
value = self._current_motor_left_value < 0 and self._current_motor_right_value < 0
self._logger.debug(str(value))
return value
def _is_stopped(self):
"""
:return:
"""
value = self._current_motor_left_value == 0 and self._current_motor_right_value == 0
self._logger.debug(str(value))
return value
def _is_moving(self):
"""
:return:
"""
value = not self._is_stopped()
self._logger.debug(str(value))
return value
def _stop(self):
"""
Set motor value to stop the vehicle motors
:return:
"""
self._logger.info("Entering")
self._current_motor_left_value = self._min_motor_value
self._current_motor_right_value = self._min_motor_value
def _turn_left(self):
"""
Determine the motor values to turn the vehicle left
:return:
"""
self._logger.info("Entering")
if self._is_spinning() or self._is_stopped():
#########################################################
# Are we near the limits of max speed in either direction
target_left_value = self._current_motor_left_value - self._step_value
target_right_value = self._current_motor_right_value + self._step_value
###########################
# Slow left, speed up right
near_limit_left = target_left_value < (self._max_motor_value * -1)
near_limit_right = target_right_value >= self._max_motor_value
if near_limit_left and near_limit_right:
pass
else:
# speed up right motor
self._current_motor_right_value = self._current_motor_right_value + self._step_value
# slow down left motor
self._current_motor_left_value = self._current_motor_left_value - self._step_value
elif self._is_moving_forward():
#########################################################
# Are we near the limits of max speed in either direction
near_limit_left = (self._current_motor_left_value - self._step_value) <= 0
near_limit_right = (self._current_motor_right_value + self._step_value) > self._max_motor_value
if not near_limit_right :
# speed up right motor
self._current_motor_right_value = self._current_motor_right_value + self._step_value
elif not near_limit_left:
# slow down left motor
self._current_motor_left_value = self._current_motor_left_value - self._step_value
else:
pass
elif self._is_moving_back():
#########################################################
# Are we near the limits of max speed in either direction
near_limit_left = (self._current_motor_left_value + self._step_value) >= 0
near_limit_right = (self._current_motor_right_value - self._step_value) < (self._max_motor_value * -1)
if not near_limit_right :
# speed up right motor
self._current_motor_right_value = self._current_motor_right_value - self._step_value
elif not near_limit_left:
# slow down left motor
self._current_motor_left_value = self._current_motor_left_value + self._step_value
else:
pass
else:
raise Exception("Unknown state when turning Left")
def _turn_right(self):
"""
Determine the motor values to turn the vehicle right
:return:
"""
self._logger.info("Entering")
if self._is_spinning() or self._is_stopped():
#########################################################
# Are we near the limits of max speed in either direction
target_left_value = self._current_motor_left_value + self._step_value
target_right_value = self._current_motor_right_value - self._step_value
###########################
# Slow right, speed up left
near_limit_right = target_right_value < (self._max_motor_value * -1)
near_limit_left = target_left_value >= self._max_motor_value
if near_limit_left and near_limit_right:
pass
else:
# speed up left motor
self._current_motor_left_value = self._current_motor_left_value + self._step_value
# slow down right motor
self._current_motor_right_value = self._current_motor_right_value - self._step_value
elif self._is_moving_forward():
#########################################################
# Are we near the limits of max speed in either direction
near_limit_right = (self._current_motor_right_value - self._step_value) <= 0
near_limit_left = (self._current_motor_left_value + self._step_value) > self._max_motor_value
if not near_limit_left :
# speed up left motor
self._current_motor_left_value = self._current_motor_left_value + self._step_value
elif not near_limit_right:
# slow down right motor
self._current_motor_right_value = self._current_motor_right_value - self._step_value
else:
pass
elif self._is_moving_back():
#########################################################
# Are we near the limits of max speed in either direction
near_limit_right = (self._current_motor_right_value + self._step_value) >= 0
near_limit_left = (self._current_motor_left_value - self._step_value) < (self._max_motor_value * -1)
if not near_limit_left :
# speed up left motor
self._current_motor_left_value = self._current_motor_left_value - self._step_value
elif not near_limit_right:
# slow down right motor
self._current_motor_right_value = self._current_motor_right_value + self._step_value
else:
pass
else:
raise Exception("Unknown state when turning Right")
def _move_forward(self):
"""
Determine the motor values to move the vehicle forward
:return:
"""
self._logger.info("Entering")
#####################################
# Are we near the limits of max speed
near_limit_left = (self._current_motor_left_value + self._step_value) > self._max_motor_value
near_limit_right = (self._current_motor_right_value + self._step_value) > self._max_motor_value
near_limits = near_limit_left or near_limit_right
if self._is_spinning():
self._stop()
elif self._is_turning():
if self._is_moving_forward():
if(near_limits):
if(near_limit_left):
self._current_motor_right_value = self._current_motor_left_value
else:
self._current_motor_left_value = self._current_motor_right_value
else:
if self._is_turning_left():
self._current_motor_left_value = self._current_motor_right_value
else:
self._current_motor_right_value = self._current_motor_left_value
else:
if self._is_turning_left():
self._current_motor_left_value = self._current_motor_right_value
else:
self._current_motor_right_value = self._current_motor_left_value
else:
if(near_limits):
pass
else:
self._current_motor_left_value = self._current_motor_left_value + self._step_value
self._current_motor_right_value = self._current_motor_right_value + self._step_value
def _move_back(self):
"""
Determine the motor values to move the vehicle backwards
:return:
"""
self._logger.info("Entering")
#####################################
# Are we near the limits of max speed
near_limit_left = (self._current_motor_left_value - self._step_value) < (self._max_motor_value * -1)
near_limit_right = (self._current_motor_right_value - self._step_value) < (self._max_motor_value * -1)
near_limits = near_limit_left or near_limit_right
if self._is_spinning():
self._stop()
elif self._is_turning():
if self._is_moving_back():
if(near_limits):
if(near_limit_left):
self._current_motor_right_value = self._current_motor_left_value
else:
self._current_motor_left_value = self._current_motor_right_value
else:
if self._is_turning_left():
self._current_motor_right_value = self._current_motor_left_value
else:
self._current_motor_left_value = self._current_motor_right_value
else:
if self._is_turning_left():
self._current_motor_right_value = self._current_motor_left_value
else:
self._current_motor_left_value = self._current_motor_right_value
else:
if(near_limits):
pass
else:
self._current_motor_left_value = self._current_motor_left_value - self._step_value
self._current_motor_right_value = self._current_motor_right_value - self._step_value
|
cfac6a4cfa53ab57b0c46ffed668eeba9a690c5d | yj846272692/python-study | /Day1/year.py | 370 | 4 | 4 | # 输入年份,如果是闰年输出True,否则输出False
def is_leap_year():
year = int(input('请输入年份:'))
# 如果代码太长写成一行不便于阅读,可以使用 “\” 对代码进行折行
is_leap = (year % 4 == 0 and year % 100 != 0) or \
year % 400 == 0
print(is_leap)
if __name__ == '__main__':
is_leap_year()
|
61d63fbbd1eec1a5e783c5dfa4ce7dd9b31dd4ae | Par1Na/Twowaits | /day4-1.py | 380 | 3.875 | 4 | # Twowaits
Twowaits Problem
# Program to count the number of times an element
# Present in the list
# Count function is used
def Count(tup, en):
return tup.count(en)
# Driver Code
tup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
enq = 4
enq1 = 10
enq2 = 8
print(Count(tup, enq), "times")
print(Count(tup, enq1), "times")
print(Count(tup, enq2), "times")
|
1a524616a16c0aa619bff003c9fda9b0f84f0f67 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 4/Hash/Problems/Top K Frequent Elements in Array.py | 1,961 | 4.0625 | 4 | Top K Frequent Elements in Array - |
Given a non-empty array of integers, find the top K elements which have the highest frequency in the array. If two numbers have the same frequency then the larger number should be given preference.
Example 1:
Input:
N = 6
A[] = {1,1,1,2,2,3}
K = 2
Output: 1 2
Example 2:
Input:
N = 8
A[] = {1,1,2,2,3,3,3,4}
K = 2
Output: 3 2
Explanation: Elements 1 and 2 have the
same frequency ie. 2. Therefore, in this
case, the answer includes the element 2
as 2 > 1.
User Task:
The task is to complete the function TopK() that takes the array and integer K as input and returns a list of top K frequent elements.
Expected Time Complexity : O(NlogN)
Expected Auxilliary Space : O(N)
Constraints:
1 <= N <= 103
1<=A[i]<=104
Solution
#User function Template for python3
# arr[] : input list of size n
# k : as specified in the problem description
# Return a list that consists of the Top K most frequent elements in arr
def TopK(arr, n, k):
um = {}
for i in range(n):
if arr[i] in um:
um[arr[i]] += 1
else:
um[arr[i]] = 1
a = [0] * (len(um))
j = 0
for i in um:
a[j] = [i, um[i]]
j += 1
a = sorted(a, key = lambda x : x[0],
reverse = True)
a = sorted(a, key = lambda x : x[1],
reverse = True)
res = []
for i in range(k):
res.append (a[i][0])
return res
#{
# Driver Code Starts
#Initial Template for Python 3
t = int (input ())
for tc in range (t):
inp = list(map(int, input().split()))
n = inp[0]
arr = inp[1:]
k = int (input ())
res = TopK (arr, n, k)
for i in res:
print (i, end = " ")
print ()
# Contributed By : Pranay Bansal
# } Driver Code Ends
|
71118ba4f37754502c3e0b8124febf5bbeeb339d | tracietung/Python3 | /ex03_02pay.py | 578 | 4.09375 | 4 | # Exercise 3.2
hours = input('Enter Hours: ')
try:
h = int(hours)
except:
h = -1
if h == -1:
print('Error, please enter numeric input')
else:
rate = input('Enter Rate: ')
try:
r = int(rate)
except:
r = -1
if r == -1:
print('Error, please enter numeric input')
else:
if h > 40:
pay1 = 40 * float(rate)
pay2 = (h - 40) * 1.5 * float(rate)
pay = pay1 + pay2
print('Pay:', pay)
elif h <= 40:
pay3 = h * float(rate)
print('Pay:', pay3)
|
dfa70c585b7dd60f8076cd5656bec1efeb9485f4 | jyu197/comp_sci_101 | /apt7/GreenIndexes.py | 307 | 3.625 | 4 | '''
Created on Nov 4, 2015
@author: Jonathan
'''
def green(pixels):
greens = []
for pixel in pixels:
values = pixel.split(",")
if int(values[1]) > int(values[0]) + int(values[2]):
greens.append(pixels.index(pixel))
return greens
if __name__ == '__main__':
pass |
05a5bdf37911bccbb0b7bea498f090be24618c15 | prashanthr11/Leetcode | /practice/Trees/Balance a Binary Search Tree.py | 892 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# Time: O(N)
# Space: O(N)
def balanceBST(self, root):
def inorder(root):
nonlocal l
if not root:
return
inorder(root.left)
l.append(root.val)
inorder(root.right)
def buildbst(start, end):
if start > end:
return
mid = (end + start) // 2
root = TreeNode(l[mid])
root.left = buildbst(start, mid - 1)
root.right = buildbst(mid + 1, end)
return root
l = list()
inorder(root)
return buildbst(0, len(l) - 1)
|
2ba7dafa404a7d8f8bc71e004953cde395ce618c | zhenglaizhang/da-quest | /survey.py | 1,509 | 3.625 | 4 | import csv
import pprint
data_path = "./survey.csv"
def run():
male_set = {'male', 'm'}
female_set = {'female', 'f'}
# value is list with 2 elements, 1st element is result of female, 2nd element is the result of male's
result = {}
with open(data_path, newline='') as csv_file:
rows = csv.reader(csv_file)
for i, row in enumerate(rows):
if i == 0:
continue
if i % 50 == 0:
print("processing row {}".format(i))
# raw data
gender_val = row[2]
country_val = row[3]
# cleaning
gender_val = gender_val.lower().replace(' ', '')
country_val = country_val.lower()
if country_val not in result:
result[country_val] = [0, 0]
if gender_val in female_set:
result[country_val][0] += 1
elif gender_val in male_set:
result[country_val][1] += 1
else:
# noise data
# pass
print("unknown gender_val: {}", gender_val)
pprint.pprint(result)
with open('survey_result1.csv', 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(['Country', 'Male', 'Female'])
for k, v in list(result.items()):
writer.writerow([k, v[0], v[1]])
if __name__ == '__main__':
run()
|
079a9367fade3832a6a4f7046de7a50881992ee2 | apalat12/turtle_project | /turtle_race_multiple_instance.py | 1,352 | 4.09375 | 4 | from turtle import Turtle, Screen
from random import randint
t1 = Turtle()
t2 = Turtle()
t3 = Turtle()
t4 = Turtle()
t5 = Turtle()
t6= Turtle()
t6.penup()
t6.hideturtle()
t1.shape('turtle')
t2.shape('turtle')
t3.shape('turtle')
t4.shape('turtle')
t5.shape('turtle')
t1.color('red')
t2.color('green')
t3.color('blue')
t4.color('purple')
t5.color('orange')
screen = Screen()
obj_lst = [t1, t2, t3, t4, t5]
def turtle_racing(lst):
screen.setup(1000, 500)
user_input = screen.textinput("Who will win the race? ", 'Enter a color(red/green/blue/purple/orange):')
user_bet = user_input.lower()
for i in range(len(lst)):
lst[i].penup()
lst[i].setpos(-250, (i * 50) - 50)
lst[i].speed('slowest')
while (1):
for i in lst:
i.fd(randint(1, 5))
# print(user_bet,i.pos()[0],i.color()[0])
if int(i.pos()[0]) >= 480:
if i.color()[0] == user_bet:
t6.write("You win!", True, align="center",font=("Arial", 15, "normal"))
return "You win!"
else:
t6.write("You lose!{} is the winner".format(i.color()[0]), True, align="center",font=("Arial", 15, "normal"))
return "You lose!{} is the winner".format(i.color()[0])
print(turtle_racing(obj_lst))
screen.exitonclick()
|
23e02b22fe457cd3111ed0e558aba6c2e5709ae4 | shindeswapnil/46-Exercise | /39.py | 1,216 | 4 | 4 | '''
Write a program able to play the "Guess the number"-game, where the number to be guessed is randomly chosen between 1 and 20.
(Source: http://inventwithpython.com) This is how it should work when run in a terminal:
'''
'''
>> import guess_number
Hello! What is your name?
Torbjörn
Well, Torbjörn, I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
18
Good job, Torbjörn! You guessed my number in 3 guesses!
'''
from random import randrange
def guess_the_number():
print('|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||')
user_name=input('\nHello! What is your name ? : ')
print('\nWell, {} , I am thinking of a number between 1 and 20.\n'.format(user_name))
number=randrange(1,21)
tries=0
while True:
guess=int(input('Take a Guess : '))
tries+=1
if guess==number:
print('\nGood job, {} ! You guessed my number in {} guesses!\n'.format(user_name,tries))
print('|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||')
break
elif guess < number :
print('\nYour guess is too Low !\n')
elif guess > number :
print('\nYour guess is too High !\n')
guess_the_number()
|
d708b25adf102330ad54dfc7081fd1f9e5ceaf57 | gladydennyson/Artificial-Intelligence-CS411 | /15puzzlebfs.py | 4,421 | 3.734375 | 4 | from collections import deque
import timeit
import os
import psutil
from func_timeout import func_timeout, FunctionTimedOut
# Creating a node class to hold the state, corresponding action and its parent
class Node:
def __init__(self, state , action, parent):
self.state = state
self.action = action
self.parent = parent
# creating a movement function to move a node up, down, left, right
def movement(s):
output = list() # creating a list to store the output, which has all the movements in it
m = eval(s.state)
row = 0
# searching for element 0 in the 2d array
while 0 not in m[row]: row += 1
col = m[row].index(0);
if row > 0: #if the row index of the blank space is anything more than 0, move up
#swapping values
x = m[row][col]
m[row][col] = m[row-1][col]
m[row-1][col] = x
output.append(Node(str(m),1,s)) # adding the newstate, movement variable and parent state into the output
#putting back the swapped values
x = m[row][col]
m[row][col] = m[row-1][col]
m[row-1][col] = x
if row <3: #if the row index of the blank space is anything less than 3, move down
#swapping values
x = m[row][col]
m[row][col] = m[row+1][col]
m[row+1][col] = x
output.append(Node(str(m),2,s)) # adding the newstate, movement variable and parent state into the output
#putting back the swapped values
x = m[row][col]
m[row][col] = m[row+1][col]
m[row+1][col] = x
if col > 0: #if the column index of the blank space is anything more than 0, move left
#swapping values
x = m[row][col]
m[row][col] = m[row][col-1]
m[row][col-1] = x
output.append(Node(str(m),3,s)) # adding the newstate, movement variable and parent state into the output
#putting back the swapped value
x = m[row][col]
m[row][col] = m[row][col-1]
m[row][col-1] = x
if col < 3: #if the row index of the blank space is anything less than 3, move right
#swapping values
x = m[row][col]
m[row][col] = m[row][col+1]
m[row][col+1] = x
output.append(Node(str(m),4,s)) # adding the newstate, movement variable and parent state into the output
#putting back the swapped value
x = m[row][col]
m[row][col] = m[row][col+1]
m[row][col+1] = x
return (output)
def check_if_goal(s,goal): # checking if the state is the goal state or not
if s == goal:
return 1
else:
return 0
def bfs(s,goal):
queue = deque([s]) #adding the initial node in the queue
print(queue)
while queue: # till the queue has some elements
node = queue.popleft() #popping topmost element of the queue
check = check_if_goal(node.state,goal) #check if that element is the goal or not
if(check == 1):
goalnode = node
return goalnode
if node.state not in explored: # if not , check if that node is explored or not, if not explored proceed
explored.append(node.state) #add the node to explored
result = movement(node) # get children of node
for val in result: #for all the children append it to the queue
queue.append(val)
def path_finder(m,goalnode):
count = 0
temp = goalnode #storing goalnode in temp variable
while m != temp.state: #checking if that state is the end state or not,
#if not storing the action taken for that. Proceeding up to the parent node and doing the same
count += 1
temp = temp.parent
# moves.insert(0,movetaken) #insert movetaken into moves list
return count
if __name__ == '__main__':
goalnode = Node # making goalnode as an empty object of Node
explored = [] # creating an array named explored to store the explored nodes
moves = list() #creating a list to store the movements taken
m1 = []
m1 = [int(i) for i in input().split()] #taking input from user
m2 = [1, 2, 3, 4,5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0] #end state
a = []
b = []
a = [m1[i:i+4] for i in range(0, len(m1), 4)] #making into 2d array
b = [m2[i:i+4] for i in range(0, len(m2), 4)] #making into 2d array
initial = str(a)
final = str(b)
# print(initial)
#
start = timeit.default_timer() #starting timer
try:
finalgoal = func_timeout(30, bfs, args=(Node(initial,None,None),final)) #calling bfs function, if it exceeds 30s, go to exception
count = path_finder(initial, finalgoal) #backtracing to find the path
print("Moves:")
print(count) #printing the move values
except FunctionTimedOut: #exceeded time limit
print ("solution cannot be found")
|
2f20dd5873e30307eb8a848ab5bf14132b639546 | malea/hunt-the-wumpus | /grubbm_hw3.py | 12,598 | 3.546875 | 4 | import sys
from collections import namedtuple, defaultdict
from json import dump
GameState = namedtuple('GameState', ['board', 'location', 'orientation', 'arrow', 'alive', 'won', 'wumpus_dead'])
Point = namedtuple('Point', ['row', 'col'])
danger_map = {
'S': 'Wumpus',
'B': 'Pit',
}
def parse_board(string):
"""Returns initial grid that is created from the input file."""
lines = string.strip().split('\n')
return reorient([ line.replace(' ', '').split(',') for line in lines ])
def reorient(board):
# He wants the board to be indexed in a very stupid way.
# This makes that work.
return list(map(list, zip(*list(reversed(board)))))
def adjacent_points(board, point):
"""Returns a list of squares adjacent to a set of coordinates."""
offsets = [(0,1), (0, -1), (1, 0), (-1, 0)]
rows = len(board)
cols = len(board[0])
points = [
Point(point.row + row_offset, point.col + col_offset)
for row_offset, col_offset in offsets
]
return [
point for point in points
if 0 <= point.row < rows
and 0 <= point.col < cols
]
def adjacent_values(board, point):
"""Returns the values on the board that are adjacent to a point."""
return [board[p.row][p.col] for p in adjacent_points(board, point)]
def get_percepts(board, point):
"""Returns a tuple of the percepts present at a point"""
adj = adjacent_values(board, point)
percepts = []
if 'W' in adj:
percepts.append('S')
if 'P' in adj:
percepts.append('B')
if board[point.row][point.col] == 'G':
percepts.append('G')
return tuple(percepts)
def get_danger_percepts(board, point):
percepts = get_percepts(board, point)
return set(percepts) & set(danger_map.keys())
def convert_orientation(orientation):
"""Returns the long form of orientation for printing to console."""
mapping = { 'E':'EAST', 'W':'WEST', 'N':'NORTH', 'S':'SOUTH'}
return mapping[orientation]
def print_location(game):
"""Prints the location of the player to the console."""
print("You are in room ({},{}) of the cave. Facing {}.".format(
game.location.row+1, game.location.col+1,
convert_orientation(game.orientation)))
def print_percepts(game):
"""Prints the percepts of a location to the console."""
for percept in get_percepts(game.board, game.location):
if percept == 'S' and not game.wumpus_dead:
print("It's stinky in here!")
elif percept == 'B':
print("You feel a breeze in this room.")
elif percept == 'G':
print('Something glitters at your feet!')
def print_hints(game, kb):
certain_hints, maybe_hints = kb.get_hints()
for percept, points in certain_hints.items():
danger = danger_map[percept]
for point in points:
print("HINT: There is a {} at {},{}".format(danger,
point[0]+1, point[1]+1))
for percept, points in maybe_hints.items():
danger = danger_map[percept]
for point in points:
print("HINT: There may be a {} at {},{}".format(danger,
point[0]+1, point[1]+1))
def left_command(game):
"""Changes orientation by turning R."""
cycle = ['N','W','S','E','N']
return game._replace(
orientation=cycle[cycle.index(game.orientation) + 1])
def right_command(game):
"""Changes orientation by turning R."""
cycle = ['N','E','S','W','N']
return game._replace(
orientation=cycle[cycle.index(game.orientation) + 1])
def possible_moves(game):
"""Returns a list of moves that will not make the player bump into a wall."""
directions = ('N','S','E','W')
i,j = game.location.row, game.location.col
points = [Point(i,j+1), Point(i,j-1), Point(i+1,j), Point(i-1,j)]
return { direction:point for direction,point in zip(directions,points)
if 0 <= point.row < len(game.board) and
0 <= point.col < len(game.board[0]) }
def forward_command(game):
"""Goes one square forward."""
moves = possible_moves(game)
if game.orientation not in moves:
print('BUMP!!! You hit a wall!')
return game
else:
return move(game,moves)
def move(game, moves):
"""Move Forward Helper checks conditions and adjusts game status accordingly."""
i = moves[game.orientation].row
j = moves[game.orientation].col
game = game._replace(location=Point(i, j))
if game.board[i][j] == 'P':
print('You have fallen into the pit!!!')
return game._replace(alive=False)
elif game.board[i][j] == 'W':
if not game.wumpus_dead:
print('You have been eaten by the Wumpus!!!')
return game._replace(alive=False)
print('A dead wumpus lays at your feet. You hold your bow triumphantly aloft.')
return game
elif game.board[i][j] == 'G':
print('You have found the gold and won the game!!!')
return game._replace(won=True)
else:
return game
def shoot_arrow(game, kb):
"""Returns a T or F, depending on whether the player successfully kills the Wumpus."""
arrow_room = game.location
moving_game = game
while game.orientation in possible_moves(moving_game):
arrow_room = possible_moves(moving_game)[game.orientation]
if game.board[arrow_room.row][arrow_room.col] == 'W':
return True, arrow_room
moving_game = moving_game._replace(location=arrow_room)
# we missed, the wumpus is not here
moving_game = game
while game.orientation in possible_moves(moving_game):
kb.known_non_wumpus_points.add(tuple(moving_game.location))
arrow_room = possible_moves(moving_game)[game.orientation]
moving_game = moving_game._replace(location=arrow_room)
return False, None
def execute_command(command, game, kb):
"""Executes the command that the player has chosen."""
if command == 'R':
return right_command(game)
elif command == 'L':
return left_command(game)
elif command == 'F':
return forward_command(game)
else:
if game.arrow:
hit, loc = shoot_arrow(game, kb)
if hit:
print('You hear a loud scream!!! The Wumpus is dead!!!')
# update the knowledge base
danger_map['S'] = 'dead Wumpus'
kb.wumpus_dead = True
return game._replace(
wumpus_dead=True,
arrow=False)
else:
print('Your arrow did not hit the Wumpus!!!')
return game._replace(
arrow=False)
else:
print('You have already used your only arrow!!!')
return game
def main(filename):
# read the file in as a string and parse into a board
input_string = open(filename).read()
board = parse_board(input_string)
if len(board) == 0:
print('Invalid board! no rows')
return
if not all(len(row) == len(board[0]) for row in board):
print('Invalid board! all rows should have same length')
return
# Set up intial state of game
game = GameState(
board=board,
location=Point(0,0),
orientation='E',
arrow=True,
alive=True,
won=False,
wumpus_dead=False)
valid_commands = ('R','L','F','S')
# Prepare the knowledge base
rows = len(board)
cols = len(board[0])
kb = KnowledgeBase((rows, cols))
while game.alive and not game.won:
# Update the knowledge base.
percepts = get_danger_percepts(game.board, game.location)
kb.add_observation(tuple(game.location), percepts)
write_kb_to_file(kb, 'kb.dat')
print_location(game)
print_percepts(game)
print_hints(game, kb)
command = input("What would you like to do? Please enter command [R,L,F,S]:\n").strip().upper()
if command not in valid_commands:
print('Invalid command! Please choose from [R,L,F,S]!\n')
continue
game = execute_command(command, game, kb)
sys.exit('Thanks for playing Wumpus World!!!')
class KnowledgeBase:
"""Knowledge base for the Hunt of the Wumpus.
Set up the knowledge base by giving it the dimensions of your grid.
>>> kb = KnowledgeBase((4,4))
Add perceptions from each point you visit.
>>> kb.add_observation((0,0) {})
>>> kb.add_observation((1,0) {'Breezy'})
>>> kb.add_observation((0,1) {'Stinky'})
Then, you can get hints!
>>> certain_hints, maybe_hints = kb.get_hints()
>>> maybe_hints
{}
>>> certain_hints
{'Breezy': {(2, 0)}, 'Stinky': {(0, 2)}}
"""
def __init__(self, dimensions):
self.dimensions = dimensions
self.visited = {}
self.wumpus_dead = False
self.known_non_wumpus_points = set()
def add_observation(self, point, percepts):
"""Load an observation into the knowledge base.
Arguments:
point: a tuple with coordinates of the observed point
percepts: a set of percepts noted at this point
"""
self.visited[point] = percepts
def intersect_map(self):
intersect_map = defaultdict(set)
for percept_point, percepts in self.visited.items():
for point in self.get_adjacent(percept_point):
if point in self.visited:
continue
if point not in intersect_map:
intersect_map[point] = set(percepts)
else:
intersect_map[point] &= set(percepts)
for point in list(intersect_map.keys()):
if len(intersect_map[point]) == 0:
del intersect_map[point]
return dict(intersect_map)
def get_hints(self):
intersect_map = self.intersect_map()
certain_hints = defaultdict(set)
maybe_hints = defaultdict(set)
for percept_point, percepts in self.visited.items():
for percept in percepts:
if percept == 'S' and self.wumpus_dead:
continue
possible_points = set()
for point in self.get_adjacent(percept_point):
if percept == 'S' and point in self.known_non_wumpus_points:
continue
if percept in intersect_map.get(point, []):
possible_points.add(point)
assert len(possible_points) != 0, (
"percept {} at {} must have source"
.format(percept, percept_point))
if len(possible_points) == 1:
certain_hints[percept] |= possible_points
else:
maybe_hints[percept] |= possible_points
# If we're certain, there's no maybe about it.
for percept, points in certain_hints.items():
if percept in maybe_hints:
for point in points:
maybe_hints[percept].discard(point)
return dict(certain_hints), dict(maybe_hints)
def get_observations(self):
return self.visited
def get_adjacent(self, point):
return get_adjacent(point, self.dimensions)
def get_adjacent(point, dimensions=None):
if dimensions and len(dimensions) != len(point):
raise ValueError('invalid point')
adjacent = set()
for ii in range(len(point)):
coord = point[ii]
for modifier in (1, -1):
value = coord + modifier
if not dimensions or 0 <= value < dimensions[ii]:
adjacent.add(tuple(point[:ii] + (value,) + point[ii+1:]))
return adjacent
def write_kb_to_file(kb, filename):
tos = lambda d: {str(k):str(v) for k,v in d.items()}
certain_hints, maybe_hints = kb.get_hints()
obj = {
'observations': tos(kb.get_observations()),
'known_locations': dict((danger_map[k], str(v)) for k,v in certain_hints.items()),
'possible_locations': dict((danger_map[k], str(v)) for k,v in maybe_hints.items()),
'intersect_map': tos(kb.intersect_map()),
'known_non_wumpus_points_from_the_arrow': str(kb.known_non_wumpus_points),
'wumpus_alive': kb.wumpus_dead,
}
with open(filename, 'w') as fp:
dump(obj, fp)
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit('Please include a filename! We must have that to generate the board!')
filename = sys.argv[1]
main(filename)
|
a12b403af3c586ad62e1b143018206b420f32719 | nemac/fswms | /msconfig/ColorMap.py | 1,640 | 3.734375 | 4 | ###
### ColorMap class for loading color maps from CSV files
### and accessing their values.
###
### Mark Phillips <mphillip@unca.edu>
### Fri Sep 17 16:07:05 2010
###
class ColorMap:
###
### Create a new ColorMap object by loading it from a CSV file
###
def __init__(self, filename):
f = open(filename)
self.colors = []
try:
for line in f:
line = line.strip(" \t\n")
if line.startswith("#"): continue
fields = line.split(",")
values = []
self.colors.append(IndexedColor(int(fields[0]), int(fields[1]), int(fields[2]), int(fields[3])))
finally:
f.close()
###
### Return the color corresponding to value x, where x is a number between
### 0 and 1. x=0 corresponds to the first color in the ColorMap, x=1
### corresponds to the last, and numbers in between are interpolated
### accordingly.
###
def getColor(self,x):
v = float(x) * len(self.colors)-1
i = int(v+0.5)
if i >= len(self.colors): i = len(self.colors) - 1
if i <= 0: i = 0
return self.colors[i]
###
### Print out the entire color map, for debugging
###
def dump(self):
for color in self.colors:
print "(%3d,%3d,%3d,%3d)" % (color.i, color.r, color.g, color.b)
###
### A little utility class for storing indexed colors.
### (An "indexed color" is just an R,G,B color together with
### an index value 'i'.)
###
class IndexedColor:
def __init__(self, i,r,g,b):
self.i = i
self.r = r
self.g = g
self.b = b
|
0e078facda216da6b577e2298297edca074268fc | harshgujrati1/TOC | /stringEndingWith101.py | 92 | 3.90625 | 4 | string = str(input())
if string.endswith("101"):
print('true')
else:
print("false")
|
5897cdbdd3da6a8d56c64c88e6a3ffd80ea5e338 | carlos1500/Curso_Full-Stack_Blue | /Modulo 1/Exercícios de Aula/exercícios Aula 13.py | 313 | 3.6875 | 4 | def area(l1,l2):
resultado = l1 * l2
print(f"a área do seu retângulo é: {resultado}")
calculo = print("Insira o cumprimento dos lados do seu retângulo")
lado1 = int(input("Digite o primeiro lado "))
lado2 = int(input("Digite o segundo lado "))
resultado = area(lado1, lado2)
print(resultado)
|
c5167aaf0b17bc6b744043c389924270e3e235fe | nguyenlien1999/fundamental | /Session05/homework/exercise3.py | 408 | 4.625 | 5 | # 3 Write a Python function that draws a square, named draw_square, takes 2 arguments: length and color,
# where length is the length of its side and color is the color of its bound (line color)
import turtle
def draw_square(size,colors):
f = turtle.Pen()
f.color(colors)
# f.color(color)
for i in range(3):
f.forward(size)
f.right(90)
f.forward(size)
f.done()
draw_square(200,"blue")
|
ae5b8b7b55c6e078a69a93dd39628a3596b84f9d | jdleo/Leetcode-Solutions | /solutions/429/main.py | 1,038 | 3.859375 | 4 | from collections import deque
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def levelOrder(self, root: Node) -> list[list[int]]:
if not root: return []
# level by level array, and queue for bfs
res, queue = [], deque([root])
# keep going while there are nodes to search
while queue:
# get current size of queue and current level
size, curLevel = len(queue), []
# poll 'size' times from queue (because this is current level)
for _ in range(size):
# poll
cur = queue.popleft()
# add to current level
curLevel.append(cur.val)
# get children
for child in cur.children:
# add to queue
queue.append(child)
# add current level to result
res.append(curLevel)
return res |
b074fc975311a742c1dd01ad2544a6dc430bbbfe | PraghadeshManivannan/Python | /condition/even or odd using conditional operator.py | 92 | 4.21875 | 4 | a = int(input("Enter the number:"))
print(a,"is even") if a%2 == 0 else print(a,"is odd")
|
d20de2cc0f4edd230b3adb0ca062349bcdd9c91e | nahaza/pythonTraining | /ua/univer/HW04/ch08ProgTrain04.py | 1,056 | 4.3125 | 4 | # 4. Morse Code Converter
# Morse code is a code where each letter of the English alphabet, each digit, and various
# punctuation characters are represented by a series of dots and dashes. Table 8-4 shows part
# of the code.
# Write a program that asks the user to enter a string, then converts that string to Morse code
CODE = {'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..',
'0': '-----', '1': '.----', '2': '..---',
'3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..',
'9': '----.'
}
def main():
inputString = input('Enter a string: ')
for x in inputString:
print(CODE[x.upper()], end=' ')
if __name__ == "__main__":
main()
|
9a8c830d61d68a6725118f73446e2208c75fbcd5 | Gabogg07/Tarea2-1211091-1310625 | /Billetera.py | 1,754 | 3.515625 | 4 | '''
Created on Feb 1, 2017
@author: Gabriel Gutierrez 13-10625
@author: Alessandra Marrero 12-11091
'''
import datetime
class Registro:
def __init__(self, monto, fecha, idEstablecimiento):
self.monto = monto
self.fecha = fecha
self.idEstablecimiento = idEstablecimiento
def devMonto(self):
return self.monto
class BilleteraElectronica:
def __init__(self, nombre = None,apellido = None, ci = None,pin = None,id = None):
self.Nombre = nombre
self.Apellido = apellido
self.Cedula = ci
self.PIN = pin
self.id = id
self.regRecarga = []
self.regConsumo = []
self.saldoTotal = 0
def nombreValido(self):
if self.Nombre.isalpha() and self.Nombre is not None:
return True
else:
return False
def apellidoValido(self):
if self.Apellido.isalpha() and self.Apellido is not None:
return True
else:
return False
def saldo(self):
return self.saldoTotal
def recargar(self, registro):
if (registro.monto < 0):
print("El monto debe de ser positivo")
assert(registro.monto>=0)
self.regRecarga.append(registro)
self.saldoTotal+= registro.monto
def consumir(self, consumo, pin):
if (pin != self.PIN):
print( "El PIN no es valido")
assert(pin==self.PIN)
elif (self.saldoTotal < consumo.monto):
return "Su saldo no es suficiente"
elif (consumo.monto < 0):
return "El monto del consumo no puede ser negativo"
else:
self.regConsumo.append(consumo)
self.saldoTotal -= consumo.monto |
514c495bb7f9848b728518f4b0bd8de912c00d00 | MaoningGuan/LeetCode | /字节跳动测试开发工程师面试准备/decorator_test_3.py | 722 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
python装饰器实现函数运行时间统计
"""
import time
from functools import wraps
import random
# 装饰器函数
def print_info(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
duration_time = end_time - start_time
print("execute time running %s: %s seconds" % (func.__name__, duration_time))
return result
return wrapper
# 通过注解方式声明使用装饰器
@print_info
def random_sort_1(n):
time.sleep(3)
return sorted([random.random() for i in range(n)])
if __name__ == "__main__":
x = random_sort_1(100)
print(x)
|
3c2bbc3cf649d71fc0f2ebf6e311cfd9d2a5a05e | baichuan/Leetcode | /invert_binary_tree.py | 769 | 3.96875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# BFS solution
if root == None:
return None;
level = [root];
while level:
ls = [];
for node in level:
if node.left:
ls.append(node.left);
if node.right:
ls.append(node.right);
node.left, node.right = node.right, node.left;
level = ls;
return root;
|
cf8143123960eafc82e51df9a3c70a03cb31f422 | dgpshiva/PythonScripts | /Array_GroupAnagrams.py | 570 | 3.890625 | 4 | from collections import defaultdict
def groupAnagrams(input):
sortedWordAnagrams = defaultdict(list)
for item in input:
itemList = list(item)
itemList.sort()
key = ''.join(itemList)
sortedWordAnagrams[key].append(item)
output = []
for valuesList in sortedWordAnagrams.itervalues():
for value in valuesList:
output.append(value)
return output
if __name__ == '__main__':
input = ["shiva", "nivi", "vini", "hisav", "test", "etst", "sett", "first", "second"]
print groupAnagrams(input)
|
5760f09c016f910d32b4dc97b20e7697d9f77184 | Philip-Cant-Reid/Bright-Network-Tech-Internship-Experience-google-coding-challenge- | /src/video_player.py | 12,385 | 3.59375 | 4 | """A video player class."""
from .video_library import VideoLibrary
import random
import sys
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
self.playing = None
self.paused = False
self.playlists_names = []
self.playlists = {}
self.flagged_videos = {}
def number_of_videos(self):
num_videos = len(self._video_library.get_all_videos())
print(f"{num_videos} videos in the library")
def show_all_videos(self):
"""Returns all videos."""
print("Here's a list of all available videos:")
video_items_list = self._video_library.get_all_videos()
all_videos_list = []
for video_items in video_items_list:
all_videos_list.append(video_items.title + " (" + video_items.video_id + ") [" + ' '.join(video_items.tags) + "]")
all_videos_list.sort()
for item in all_videos_list:
print(" " + item)
def play_video(self, video_id):
"""Plays the respective video.
Args:
video_id: The video_id to be played.
"""
if self._video_library.get_video(video_id) in self._video_library.get_all_videos():
if self._video_library.get_video(video_id) in self.flagged_videos:
print("Cannot play video: Video is currently flagged (reason: " + self.flagged_videos[self._video_library.get_video(video_id)] + ")")
else:
self.paused = False
if self.playing:
print("Stopping video: " + self.playing.title)
print("Playing video: " + self._video_library.get_video(video_id).title)
self.playing = self._video_library.get_video(video_id)
else:
print("Cannot play video: Video does not exist")
def stop_video(self):
"""Stops the current video."""
if self.playing:
print("Stopping video: " + self.playing.title)
self.playing = None
else:
print("Cannot stop video: No video is currently playing")
def play_random_video(self):
"""Plays a random video from the video library."""
available_videos = list(set(self._video_library.get_all_videos()).difference(self.flagged_videos.keys()))
if len(available_videos) > 0:
self.play_video(random.choice(available_videos).video_id)
else:
print("No videos available")
#print("play_random_video needs implementation")
def pause_video(self):
"""Pauses the current video."""
if self.playing:
if self.paused:
print("Video already paused: " + self.playing.title)
else:
print("Pausing video: " + self.playing.title)
self.paused = True
else:
print("Cannot pause video: No video is currently playing")
def continue_video(self):
"""Resumes playing the current video."""
if self.playing:
if self.paused:
print("Continuing video: " + self.playing.title)
self.paused = False
else:
print("Cannot continue video: Video is not paused")
else:
print("Cannot continue video: No video is currently playing")
def show_playing(self):
"""Displays video currently playing."""
if self.playing:
print("Currently playing: " + self.playing.title + " (" + self.playing.video_id + ") [" + ' '.join(self.playing.tags) + "]" + (" - PAUSED" if self.paused else ""))
else:
print("No video is currently playing")
def create_playlist(self, playlist_name):
"""Creates a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name.lower() in self.playlists:
print("Cannot create playlist: A playlist with the same name already exists")
else:
self.playlists_names.append(playlist_name)
self.playlists[playlist_name.lower()] = []
print("Successfully created new playlist: " + playlist_name)
def add_to_playlist(self, playlist_name, video_id):
"""Adds a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be added.
"""
if playlist_name.lower() in self.playlists.keys():
if self._video_library.get_video(video_id) not in self._video_library.get_all_videos():
print("Cannot add video to " + playlist_name + ": Video does not exist")
elif video_id in self.playlists[playlist_name.lower()]:
print("Cannot add video to " + playlist_name + ": Video already added")
else:
self.playlists[playlist_name.lower()] += [video_id]
print("Added video to " + playlist_name + ": " + self._video_library.get_video(video_id).title)
else:
print("Cannot add video to " + playlist_name + ": Playlist does not exist")
def show_all_playlists(self):
"""Display all playlists."""
if len(self.playlists_names) == 0:
print("No playlists exist yet")
else:
print("Showing all playlists:")
playlist_names = self.playlists_names
playlist_names.sort()
for playlist_name in playlist_names:
print(playlist_name)
def show_playlist(self, playlist_name):
"""Display all videos in a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name.lower() in self.playlists.keys():
print("Showing playlist: " + playlist_name)
if(len(self.playlists[playlist_name.lower()]) == 0):
print("No videos here yet")
else:
for item in self.playlists[playlist_name.lower()]:
print(self._video_library.get_video(item).title + " (" + self._video_library.get_video(item).video_id + ") [" + ' '.join(self._video_library.get_video(item).tags) + "]")
else:
print("Cannot show playlist " + playlist_name + ": Playlist does not exist")
def remove_from_playlist(self, playlist_name, video_id):
"""Removes a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be removed.
"""
if playlist_name.lower() in self.playlists.keys():
if video_id in self.playlists[playlist_name.lower()]:
self.playlists[playlist_name.lower()].remove(video_id)
print("Removed video from " + playlist_name + ": " + self._video_library.get_video(video_id).title)
elif self._video_library.get_video(video_id) in self._video_library.get_all_videos():
print("Cannot remove video from " + playlist_name + ": Video is not in playlist")
else:
print("Cannot remove video from " + playlist_name + ": Video does not exist")
else:
print("Cannot remove video from " + playlist_name + ": Playlist does not exist")
def clear_playlist(self, playlist_name):
"""Removes all videos from a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name.lower() in self.playlists.keys():
self.playlists[playlist_name.lower()] = []
print("Successfully removed all videos from " + playlist_name)
else:
print("Cannot clear playlist " + playlist_name + ": Playlist does not exist" )
def delete_playlist(self, playlist_name):
"""Deletes a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name.lower() in self.playlists.keys():
print("Deleted playlist: " + playlist_name + "")
self.playlists.pop(playlist_name.lower(), None)
self.playlists_names.remove(playlist_name)
else:
print("Cannot delete playlist " + playlist_name + ": Playlist does not exist")
def search_videos(self, search_term):
"""Display all the videos whose titles contain the search_term.
Args:
search_term: The query to be used in search.
"""
video_items_list = self._video_library.get_all_videos()
all_videos_list = []
for video_items in video_items_list:
#print(video_items.title)
if(search_term in video_items.title.lower()):
all_videos_list.append(video_items.title + " (" + video_items.video_id + ") [" + ' '.join(video_items.tags) + "]")
if(len(all_videos_list) > 0):
all_videos_list.sort()
print("Here are the results for " + search_term + ":")
for i,item in enumerate(all_videos_list):
print(str(i+1) + ") " + item)
print("Would you like to play any of the above? If yes, "
"specify the number of the video.")
print("If your answer is not a valid number, we will assume it's a no.")
inp = input()
if inp != "No":
try:
if int(inp[0]) in range(1,len(all_videos_list)+1):
self.play_video(all_videos_list[int(inp[0])-1][all_videos_list[int(inp[0])-1].find("(")+1:all_videos_list[int(inp[0])-1].find(")")])
except:
pass
else:
print("No search results for " + search_term)
#for video_id in self._video_library.get_all_videos():
#print("search_videos needs implementation")
def search_videos_tag(self, video_tag):
"""Display all videos whose tags contains the provided tag.
Args:
video_tag: The video tag to be used in search.
"""
video_items_list = self._video_library.get_all_videos()
all_videos_list = []
for video_items in video_items_list:
#print(video_items.title)
if(video_tag.lower() in video_items.tags):
all_videos_list.append(video_items.title + " (" + video_items.video_id + ") [" + ' '.join(video_items.tags) + "]")
if(len(all_videos_list) > 0):
all_videos_list.sort()
print("Here are the results for " + video_tag + ":")
for i,item in enumerate(all_videos_list):
print(str(i+1) + ") " + item)
print("Would you like to play any of the above? If yes, "
"specify the number of the video.")
print("If your answer is not a valid number, we will assume it's a no.")
inp = input()
if inp != "No":
try:
if int(inp[0]) in range(1,len(all_videos_list)+1):
self.play_video(all_videos_list[int(inp[0])-1][all_videos_list[int(inp[0])-1].find("(")+1:all_videos_list[int(inp[0])-1].find(")")])
except:
pass
else:
print("No search results for " + video_tag)
def flag_video(self, video_id, flag_reason=""):
"""Mark a video as flagged.
Args:
video_id: The video_id to be flagged.
flag_reason: Reason for flagging the video.
"""
if self._video_library.get_video(video_id) in self._video_library.get_all_videos():
if(self._video_library.get_video(video_id) not in self.flagged_videos.keys()):
print("Successfully flagged video: "+ self._video_library.get_video(video_id).title + " (reason: "+(flag_reason if flag_reason!="" else "Not supplied")+")")
self.flagged_videos[self._video_library.get_video(video_id)] = (flag_reason if flag_reason!="" else "Not supplied")
else:
print("Cannot flag video: Video is already flagged")
else:
print("Cannot flag video: Video does not exist")
def allow_video(self, video_id):
"""Removes a flag from a video.
Args:
video_id: The video_id to be allowed again.
"""
print("allow_video needs implementation")
|
d26f03915c8e997b86a648f57868065071ba92c1 | kiansweeney11/ca117-programming2 | /If statements | 115 | 3.71875 | 4 | #!/usr/bin/env python
x = input()
y = input()
if x == y
print "square"
else:
print "rectangle"
|
25b47a125fe670f4c329cf77819dc852b4ff585d | alex-carvalho-data/hadoopFrankKane | /s04-spark/032-exercise-filterLowestRatedMovies10Times/LowestRatedMoviesRDD.py | 2,222 | 3.5 | 4 | from pyspark import SparkConf, SparkContext
# Run it in cluster with spark-submit
# spark-submit LowestRatedMoviesRDD.py
# This function just creates a Python "dictionary" we can later use to convert
# movie Id's to movie names while printing out the final results.
def load_movie_names():
movie_names = {}
with open('/home/maria_dev/ml-100k/u.item') as f:
for line in f:
fields = line.split('|')
movie_names[int(fields[0])] = fields[1]
return movie_names
# Take each line of u.data and convert it to (movieId, (rating, 1.0))
# This way we can then add up all the ratings for each movie, and the total of
# ratings for each movie (which lets us compute the average)
def parse_input(line):
fields = line.split()
return int(fields[1]), (float(fields[2]), 1.0)
if __name__ == '__main__':
# The main script - create ou SparkContext
conf = SparkConf().setAppName('WorstMovies')
sc = SparkContext(conf=conf)
# Load up out movie Id -> movie name lookup table
movieNames = load_movie_names()
# Load up the raw u.data file
linesRdd = sc.textFile('hdfs:///user/maria_dev/ml-100k/u.data')
# Convert to (movieId, (rating, 1.0))
movieRatingsRdd = linesRdd.map(parse_input)
# Reduce to (movieId, (sumOfRatings, totalRatings))
ratingTotalAndCount = \
movieRatingsRdd.reduceByKey(lambda accumulated_movie, current_movie:
(accumulated_movie[0] + current_movie[0],
accumulated_movie[1] + current_movie[1]))
# Filter movies rated at least 10 times
# Record format (movieId, (sumOfRatings, totalRatings))
filteredRatings = \
ratingTotalAndCount.filter(lambda record: record[1][1] >= 10)
# Map to (rating, averageRating)
averageRatings = \
filteredRatings.mapValues(lambda total_and_count:
total_and_count[0] / total_and_count[1])
# Sort by average rating
sortedMovies = averageRatings.sortBy(lambda x: x[1])
# Take the top 10 results
results = sortedMovies.take(10)
# Print them out
for result in results:
print(movieNames[result[0]], result[1])
|
a8ee2f667b95ed2391c8d61f14c98055c75bbd24 | iasminastana/PyLearn | /functii2.py | 1,340 | 3.90625 | 4 | # 1func:
# citim de la tastatura si returnam int
# 2func:
# 2 nr, le comparam
# daca n1 >= n2 => true daca nu false
# return,
# 3func:
# daca e true atunci cerem de la tastatura altul
# 4func
# daca e false
# sa il printui pe primul nr impar mai mic decat el
def cit_tast():
numarul = input('alege numarul : ') # LaMi - nu se returneaza int de numarul citit de la tastatura
return int(numarul)
def compar(): # numerele cu care se face compare are trebui trimise ca si parametrii la functia de compare si nu folosite variabile globale
if n1 >= n2:
return True
else:
return False
def if_false():
l = []
for num in range(2, int(n1)):
for i in range(2, num):
if (num % i) == 0:
break
else:
l.append(num)
return l[-1]
def if_true():
if r:
numarul_nou = input('alege numarul nou: ') # functia nu inlocuieste primul numar din cele citite initial ci citeste un numar nou si nu face nimic cu el, doar il printeaza la final
return numarul_nou
n1 = cit_tast()
n2 = cit_tast()
r = compar()
# urmatoarele 2 linii se executa oricum ... nu tin cont de output-ul de la compare
z = if_false()
nou = if_true()
print('asta e primul numar prim mai mic decat n1', z)
print('ai ales un alt numar nou: ', nou)
|
7c332a012a4fc5112396a0d382388d02372bae3e | pcwu/leetcode | /047-permutations-ii/permuteUnique.py | 892 | 3.578125 | 4 | class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def permuteIt(nums, current, results):
for i in range(len(nums)):
if len(nums) == 1:
results.append(current + nums)
elif not (i > 0 and nums[i] == nums[i - 1]):
permuteIt(nums[:i] + nums[i + 1:], current + [nums[i]], results)
results = []
permuteIt(sorted(nums), [], results)
return results
if __name__ == '__main__':
assert Solution().permuteUnique([1, 1, 1]) == [[1, 1, 1]]
assert Solution().permuteUnique([1, 1, 3, 4]) == \
[[1, 1, 3, 4], [1, 1, 4, 3], [1, 3, 1, 4], [1, 3, 4, 1],
[1, 4, 1, 3], [1, 4, 3, 1], [3, 1, 1, 4], [3, 1, 4, 1],
[3, 4, 1, 1], [4, 1, 1, 3], [4, 1, 3, 1], [4, 3, 1, 1]]
|
ae50b51b71ad1e2a2202324f407e44190581f251 | jhonangelmireles/openERP | /funcionVerificarUltimoDigito.py | 1,747 | 3.671875 | 4 | #Esta funcion aparentemente sirve para verificar que el ultimo digito del RIF es el correcto o no lo es
def calculoUltimoDigitoRif(RIF):
lista = RIF.split('-')
#posicion 0 Letra - pos 1 num_intermedio- pos 3 numero final
#rellena con 0 a la izq por ejemplo 123 -> 00000123
num_intermedio_rif = lista [1].rjust(8, '0')
#A continuacion se inician el vector de multiplicadores
array_multplicador = [ 4, 3, 2, 7, 6, 5, 4, 3, 2]
#Letra supongo que es el primer caracter dado del RIF,
#defino un segundo array llamado numeros
letra = lista[0]
numero = []
#Condiciones
if letra == 'V': #rif venezolano
numeros =[ 1 ]
elif letra == 'E': #rif extranjero
numeros =[ 2 ]
elif letra == 'J': #rif juridico
numeros =[ 3 ]
elif letra == 'P': #rif personal
numeros = [ 4 ]
elif letra == 'G': #rif organismo del estado
numeros = [ 5]
numeros.extend( [ int(i) for i in num_intermedio_rif])
#quedaria como lista de [ 1,1,9,5,9,8,6,0,6 ]
# Se inicia el vector de resultados y se efectuan las operacione
resultados = []
#multiplico los numeros * multiplicadores
for i in range(9):
resultados.append( array_multplicador[i] * numeros[i])
#se suman todos los numeros
suma = 0
for i in range(9):
suma=suma+resultados[i]
#le saco el modulo a la sumatoria
modulo_suma = suma%11
#saco el dato a retornar
retorno = 11 - modulo_suma
if (retorno > 9) or (retorno < 1):
retorno = 0
print RIF
print 'valor calculado',retorno
print 'valor introducido', lista[2]
numero_final = int(lista[2])
if(retorno!=numero_final):
print 'el valor introducido es falso'
return False
else:
print 'el valor introducido es verdadero'
return True
RIF = 'V-18545601-0'
print calculoUltimoDigitoRif(RIF)
|
ff23fc5933d57b4ff1d7f595a724a609f43933e7 | davecrob2/BallerBot | /player_scraper.py | 1,858 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 27 16:12:13 2017
@author: davecrob2
"""
import requests
from bs4 import BeautifulSoup
#Function to scrape an individual basketball reference page and combine all player names and player ids into a dictionary.
#Accepts the url to the page as an argument
def bb_scrape(link):
#Variable to store basketball reference player glossary
page = requests.get(link)
#Using BS4 to parse page
soup = BeautifulSoup(page.content,'html.parser')
#Finds "tbody" tag which contains the entire player table
tbody=soup.find('tbody')
#print(soup.find('tbody'))
#print(tbody.prettify())
#Finds "tr" tag in "tbody" tag
tr=tbody.find_all('tr')
fullnames=[]
links = []
zipper={}
#Iterates through page to pull all names and player ids
for i in tr:
#print(tr.prettify())
#Finds "th" tag in "tr" tag with class "Left"
th=i.find('th',class_='left')
#print(th)
#Finds "a" tag in "th" tag
a=th.find('a')
#print(a)
#Stores the player name
name =a.get_text()
#print(name)
#Stores all full names in a list
fullnames.append(name)
player_link=a['href']
#print(player_link)
#Splits the player_link for final extraction of player_id
id_extract=player_link.split(player_link[10])
id_split=id_extract[3]
final_extract=id_split.split(id_split[-5])
#Stores the entire player_id
player_id=final_extract[0]
#Stores player id in a list
links.append(player_id)
#print(fullnames)
#print(links)
#Combines two lists into dictionary
zipper=dict(zip(fullnames,links))
return zipper
|
7b07e6601854da0360a3199deb459e73ac1528ea | sicknick21/cmpt120siconolfi | /tictactoe.py | 5,458 | 4.15625 | 4 | # CMPT 120 Intro to Programming
# Lab #6 – Lists and Error Handling
# Author: Nicholas Siconolfi
# Created: 2018-10-23
import random
def printBoard(board):
# This function prints out the board and the rows.
# print the top border
# for each row in the board...
# print the row
# print the next border
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('+-----------+')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('+-----------+')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('+-----------+')
def inputSymbol():
# Lets the player type which symbol they want to be.
letter = ''
while not (letter == 'x' or letter == 'o'):
print('Do you want to be x or o?')
letter = input().lower()
if letter == 'x':
return ['x', 'o']
else:
return ['o', 'x']
def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'playertwo'
else:
return 'player'
def playAgain():
# This function sees if the player wants to play again.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def markBoard(board, letter, move):
# check to see whether the desired square is blank
board[move] = letter
def isWinner(bo, le):
#This function determines on how to be the winner of the game.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or
(bo[4] == le and bo[5] == le and bo[6] == le) or
(bo[1] == le and bo[2] == le and bo[3] == le) or
(bo[7] == le and bo[4] == le and bo[1] == le) or
(bo[8] == le and bo[5] == le and bo[2] == le) or
(bo[9] == le and bo[6] == le and bo[3] == le) or
(bo[7] == le and bo[5] == le and bo[3] == le) or
(bo[9] == le and bo[5] == le and bo[1] == le))
def getBoardCopy(board):
# This function makes a copy of the board for the next game.
copyBoard = []
for i in board:
copyBoard.append(i)
return copyBoard
def isSpaceFree(board, move):
# This function determines which space is free.
return board[move] == ' '
def getPlayerMove(board):
# This function lets the player type in his move.
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
print('What is your next move? (1-9)')
move = input()
return int(move)
def chooseRandomMoveFromList(board, movesList):
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
def getPlayerTwoMove(board, secondplayer):
# This function lets the second player type in his move.
if secondplayer == 'x':
Symbol = 'o'
else:
Symbol = 'x'
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
markBoard(copy, secondplayer, i)
if isWinner(copy, secondplayer):
return i
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
markBoard(copy, Symbol, i)
if isWinner(copy, Symbol):
return i
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move
if isSpaceFree(board, 5):
return 5
return chooseRandomMoveFromList(board, [2, 4, 6, 8])
def hasBlanks(board):
# for each row in the board...
# for each square in the row...
# check whether the square is blank
# if so, return True
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True
print('Tic Tac Toe Lab')
while True:
theBoard = [' '] * 10
Symbol, secondplayer = inputSymbol()
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
printBoard(theBoard)
move = getPlayerMove(theBoard)
markBoard(theBoard, Symbol, move)
if isWinner(theBoard, Symbol):
printBoard(theBoard)
print('You have won!')
gameIsPlaying = False
else:
if hasBlanks(theBoard):
printBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'playertwo'
else:
# Player two's turn.
move = getPlayerTwoMove(theBoard, secondplayer)
markBoard(theBoard, secondplayer, move)
if isWinner(theBoard, secondplayer):
printBoard(theBoard)
print('You lost.')
gameIsPlaying = False
else:
if hasBlanks(theBoard):
printBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'
if not playAgain():
break
|
df8cb1d8b7a6bab9e17bb64bd70ac59f0959f1a1 | rvsingh011/NitK_Assignments | /Sem1/Algorithm/closest_pair.py | 1,082 | 3.703125 | 4 | # with user Input
from math import sqrt
import time
def brute_force(points, n):
least = 100000
pos1, pos2 = 0, 0
for x in range(0, n):
x1, y1 = int(points[x][0]), int(points[x][1])
for y in range(0, n):
if x == y:
pass
else:
x2, y2 = int(points[y][0]), int(points[y][1])
distance = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
if distance < least:
least = distance
pos1 = x
pos2 = y
return pos1, pos2, least
def optimal_pair(points, n):
if n <= 3:
return brute_force(points, n)
else:
k = [x[1] for x in sorted(points.items(), key=lambda x: x[1])]
mid = int(n/2)
if __name__ == "__main__":
dic = {}
print("enter the number of points")
number = int(input())
for x in range(0, number):
dic[x] = input().strip().split(",")
t0 = time.time()
q, w, r = optimal_pair(dic, number)
t1 = time.time()
print(dic[q], dic[w], r, (t1-t0)/3600)
|
30d218417f115c77c08976801924d44e3b294a29 | VPoshelyuk/Python_DS_and_Algo | /Chapter1/C120.py | 250 | 3.53125 | 4 | import random
def shuffle(data):
for i in range(len(data)):
choice = random.randint(0, len(data)-1-i)
data[i], data[len(data)-1-choice] = data[len(data)-1-choice], data[i]
return data
print(shuffle([12,4,54,-3,14,12,76,22])) |
c0a6fb43da9259f457474ba7b396defed67101b9 | kunalsanwalka/bapsf_test_files | /wave_amplitude_lineplot.py | 5,970 | 3.59375 | 4 | """
@author: kunalsanwalka
This program plots the wave amplitude as a function of the z position
"""
###############################################################################
#############################User defined variables############################
###############################################################################
#Names of the read/write files
dataDir='C:/Users/kunalsanwalka/Documents/UCLA/BAPSF/Data/'
savepath='C:/Users/kunalsanwalka/Documents/UCLA/BAPSF/Plots_and_Animations/wave_amplitude.png'
###############################################################################
import h5py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy import ma
from scipy.interpolate import griddata
from matplotlib import ticker, cm
def dataArr(filename):
"""
This function takes the name of an hdf5 file and returns the relevant data arrays
Data in the hdf5 file is organized as-
Group 1- page1
There is no data in this group, we can ignore it
Group 2- page1.axes1.solid1
This group has the following subgroups-
Group 1- cdata
Contains the data for the slice
cdata has 2 subsequent subgroups-
Group 1- Imag
Stores the complex part of the number
Group 2- Real
Stores the real part of the number
Group 2- idxset
Do not know what data is stored here
Group 3- vertices
Contains the co-ordinates for the slice
Args:
filename: Name of the file (str)
Returns:
cdata: Complex valued solution of the problem (np.array)
xVals: x-coordinate of the data points (np.array)
yVals: y-coordinate of the data points (np.array)
"""
#Open the file
f=h5py.File(filename,'r')
#Initialize the data arrays
cdata=[]
idxset=[]
vertices=[]
#Open groups in the file
for group in f.keys():
# print('Group- '+group)
#Get the group
currGroup=f[group]
#Open keys in the group
for key in currGroup.keys():
# print('Key- '+key)
#Append the data to the respective arrays
if key=='cdata(Complex)':
cdataGroup=currGroup[key]
imag=[]
real=[]
#Open the keys in cdata
for subkey in cdataGroup.keys():
# print('Subkey- '+subkey)
#Get the real and imaginary parts of the array
if subkey=='Imag':
imag=cdataGroup[subkey][()]
elif subkey=='Real':
real=cdataGroup[subkey][()]
#Convert lists to numpy arrays
imag=np.array(imag)
real=np.array(real)
#Get the cdata value
cdata=real+1j*imag
elif key=='idxset':
idxset=currGroup[key][()]
elif key=='vertices':
vertices=currGroup[key][()]
#Remove the y component from the vertices
xVals=[]
yVals=[]
newVertices=[]
for vertex in vertices:
xVals.append(vertex[0])
yVals.append(vertex[2])
newVertices.append([vertex[0],vertex[1]])
vertices=newVertices
#Convert to numpy arrays
cdata=np.array(cdata)
xVals=np.array(xVals)
yVals=np.array(yVals)
#Close the file
f.close()
return cdata, xVals, yVals
def interpData(ampData,xVals,yVals):
"""
Interpolates the data into a regualar grid to allow for cleaner vector plots
Args:
ampData: The raw data
xVals,yVals: The co-ordinates of the data
Returns:
interpData: The interpolated data
xi,yi: Meshgrid to allow for the plotting of the data
"""
#Create the target grid of the interpolation
xi=np.linspace(-0.5,0.5,1001)
yi=np.linspace(-4,1.5,1001)
xi,yi=np.meshgrid(xi,yi)
#Interpolate the data
interpData=griddata((xVals,yVals),ampData,(xi,yi),method='linear')
return interpData,xi,yi
def linedata(filename):
"""
This function takes in the filename and gives the wave power along the z-axis
Args:
filename: The path where the data is stored
Returns:
BArr: The wave power as a function of z
zArr: The corresponding array with z-axis values
"""
#Get the data
By,X,Z=dataArr(filename)
#Take the absolute value squared
BAbs=np.abs(By)**2
#Take the real data
BAbs=np.real(By)
#Get the interpolated data
ByInterp,xi,zi=interpData(BAbs,X,Z)
#Transpose so getting slices across r is easier
BTrans=np.transpose(ByInterp)
xi=np.transpose(xi)
zi=np.transpose(zi)
#Integrate along the z axis
BArr=np.trapz(BTrans,axis=0)
#Get the z-axis values
zArr=zi[0]
return BArr,zArr
#Create an array with the filenames
localNameArr=['By_XZ_Plane_freq_100KHz_col_0000KHz.hdf','By_XZ_Plane_freq_100KHz_col_2500KHz.hdf','By_XZ_Plane_freq_100KHz_col_5000KHz.hdf']
#Create an array with the labels for each lineplot
labelArr=['0MHz','2.5MHz','5MHz']
#Plot the data
fig=plt.figure()
ax=fig.add_subplot(111)
ax.set_title('Effect of damping on wave amplitude')
for i in range(len(localNameArr)):
BArr,zArr=linedata(dataDir+localNameArr[i])
ax.plot(zArr,BArr,label=labelArr[i])
ax.set_yscale('symlog',linthreshy=1e-10)
ax.set_xlabel('Z [m]')
#ax.set_xlim(-1.5,1,5)
ax.set_ylabel('Wave Amplitude')
ax.legend()
ax.grid(True)
#plt.savefig(savepath,dpi=600)
plt.show()
plt.close() |
57ccce190fb2daff6e2e6145c0e27df9ad5da6f1 | adibsxion19/CS1114 | /Labs/lab3Pr5.py | 1,585 | 3.84375 | 4 | # Aadiba Haque
# CS - UY 1114
# 14 February 2020
#Lab 3 Problem 5
import turtle
import math
base_side = 100
base_angle = 72
side_triangle = (base_side / 2) / math.cos(math.radians(base_angle))
angle_star = 144
# Part 1
# turtle.forward(side_triangle)
# turtle.penup()
# turtle.forward(base_side)
# turtle.pendown()
# turtle.forward(side_triangle)
# turtle.right(angle_star)
# turtle.forward(side_triangle)
# turtle.penup()
# turtle.forward(base_side)
# turtle.pendown()
# turtle.forward(side_triangle)
# turtle.right(angle_star)
# turtle.forward(side_triangle)
# turtle.penup()
# turtle.forward(base_side)
# turtle.pendown()
# turtle.forward(side_triangle)
# turtle.right(angle_star)
# turtle.forward(side_triangle)
# turtle.penup()
# turtle.forward(base_side)
# turtle.pendown()
# turtle.forward(side_triangle)
# turtle.right(angle_star)
# turtle.forward(side_triangle)
# turtle.penup()
# turtle.forward(base_side)
# turtle.pendown()
# turtle.forward(side_triangle)
#Part 2
turtle.forward(side_triangle)
turtle.left(base_angle)
turtle.forward(side_triangle)
turtle.right(angle_star)
turtle.forward(side_triangle)
turtle.left(base_angle)
turtle.forward(side_triangle)
turtle.right(angle_star)
turtle.forward(side_triangle)
turtle.left(base_angle)
turtle.forward(side_triangle)
turtle.right(angle_star)
turtle.forward(side_triangle)
turtle.left(base_angle)
turtle.forward(side_triangle)
turtle.right(angle_star)
turtle.forward(side_triangle)
turtle.left(base_angle)
turtle.forward(side_triangle)
turtle.right(angle_star)
|
082d0e72957b748415f4e2f5fa1060b1852628eb | dieg00/pong_game_python | /scoreboard.py | 772 | 3.796875 | 4 | from turtle import Turtle
SEPARATION = 230
class Scoreboard(Turtle):
def __init__(self):
super(Scoreboard, self).__init__()
self.penup()
self.hideturtle()
self.sety(280)
self.color("white")
self.score = 0
def write_score(self):
self.write(arg=f"{self.score}", align="center", font =("Arial", 50, "bold"))
def set_left(self):
self.setx(-SEPARATION)
self.write_score()
def set_right(self):
self.setx(SEPARATION)
self.write_score()
def add_point(self):
self.clear()
self.score += 1
self.write_score()
def write_card(self):
self.setpos(0, -72)
self.write(arg="P O I N T !", align="center", font=("Arial", 90, "bold"))
|
be138a7cfc8f055f46a93612114193ca84788b41 | emrehaskilic/tekrar | /introduction/lesson3/kararYapilari1.py | 791 | 3.921875 | 4 | # KARAR YAPILARI
# Karsilastirma operatorleri
# == (esittir) sagdaki degerin soldaki degere esit olma durumu
# 1 == 1 => true - ıf
# 1 == 2 => false - else
# != (esit degildir) soldaki degerin sagdaki degere esit olmama durumu
# 1 != 1 => false - else
# 2 != 1 => true - if
# > (buyuktur)
# < (kucuktur)
# >= (buyuk esittir)
# <= (kucuk esittir)
username = input("Lutfen kullanici adinizi giriniz: ")
username = username.lower()\
.replace("ı","i")\
.replace("ç","c")\
.replace("ş","s")\
.replace("ö","o")\
.replace("ğ","g")\
.replace("ü","u") #replace("","") komutu soldaki karakter ve sağdaki karakterin yerini değiştirir
print(username)
if(username == "ozguc_tigmas"):
print("Tebrikler,giriş yaptiniz")
else:
print("Kullanici adiniz yanlis") |
b473e2eb316979e04483c26ebf34c3051c744e6e | daudras/Projet-Info-modelisation-d-une-file-d-automobiles | /IHM_new_code.py | 3,768 | 3.890625 | 4 | #!/usr/bin/python
# -*-coding:UTF-8 -*
#Circulation automobile d'une file de voiture
#Il est question de creer 10 cellules ayant chacune en elle trois fenetres, avec possibilite de modifier individuellement les couleurs des fenetres et cellules en faisant appel aux fonctions selon le besoin : couleur_fenetre, tte(), changecolor
from tkinter import *
class Application(Tk):
#---definition des fonctions gestionnaires des evenements, et creation du widget principal
def __init__(self, i = 0):
Tk.__init__(self) # constructeur de la classe parente
self.i = i
self.can =Canvas(self, width =1200, height =600, bg ="white")
self.can.pack(side =TOP, padx =5, pady =5)
Button(self, text ="File de voiture", command=self.ligne_suivante).pack(side =LEFT)
self.i = i
self.l1 = l1
l1 = Ligne_de_cellules(self.can)
l1.x = 0
l1.y = 0
l1.l = 90
l1.h = 60
def ligne_suivante(self):
"instanciation de 10 lignes de cellules dans le canevas"
if i < 10:
l1.h += 65
l1 = Ligne_de_cellules(self.can)
i += 1
class Cellule:
def __init__(self, cane, x=0, y=0, l = 90, h = 60, c = 0, an = 0, ds = 0, a = 0, v = 0, d = 0, coul = 'navy'):
#"dessin d'une cellule en <x,y> a la ligne lidans le canevas <cane>"
# mémorisation des paramètres dans des variables d'instance :
self.cane = cane
self.x = x
self.y = y
self.l = l
self.h = h
self.c = c
self.an = an
self.ds = ds
self.a = a
self.v = v
self.d = d
self.coul = coul
# rectangle de base : 95x60 pixels :
cane.create_rectangle(x, y, x+l, y+h, fill = coul)
# 3 fenêtres de 25x55 pixels, écartées de 5 pixels :
self.fen =[] # pour mémoriser les réf. des fenêtres
for xf in range(x + 2, x + l, 30):
self.fen.append(cane.create_rectangle(xf, y+2,
xf + cote - 2, y + h - 2, fill =changecolor()))
def changecolor(self):
"Pour determiner la couleur de la cellule et de chaque fenetre"
if (c = 0 & an = 0 & ds = 0 & a = -1 & v = 0 & d = -1)
if (c = 0 & an = 0 & ds = 0 & a = -1 & v = 1 & d = -1)
if c = 1:
if(an=1):
if(ds=1):
coul = "light green"
else: coul = "green"
elif (ds=1):
coul = "turquoise"
else: coul = "cyan"
elif (c = 2):
if (an = 1):
if (ds = 1): coul = "indigo"
else: coul = "purple"
elif(ds = 1): coul = "purple"
else: coul = "magenta"
else:
if(an=1):
if(ds=1):
coul = "orange-red"
else : coul = "orange"
elif (ds = 1): coul = "yellow+orange"
else: coul = "yellow"
if a = -3: color.self.fen[0]= "yellow"
if a = -2: color.self.fen[0]= "yellow+orange"
if a = -1: color.self.fen[0]= "orange"
if a = 0: color.self.fen[0]= "white"
if a = 1: color.self.fen[0]= "red+orange"
if a = 2: color.self.fen[0]= "magenta"
if a = 3: color.self.fen[0]= "purple"
if v = 0: color.self.fen[1]= "white"
if v = 1: color.self.fen[1]= "turquoise"
if v = 2: color.self.fen[1]= "cyan"
if v = 3: color.self.fen[1]= "indigo"
if d = 0: color.sefl.fen[2]= "black"
if d = 1: color.sefl.fen[2]= "red+orange"
if d = 2: color.sefl.fen[2]= "magenta"
if d = 3: color.sefl.fen[2]= "purple"
if d = 4: color.sefl.fen[2]= "purple"
if d = 5: color.sefl.fen[2]= "indigo"
if d = 6: color.sefl.fen[2]= "cyan"
if d = 7: color.sefl.fen[2]= "turquoise"
class Ligne_de_cellules(Cellule(cane [, x [, y [, l [, h [, c [, an [, ds [, a [, v [, d [, coul ]]]]]]]]]]]))
def __init__(self, cane, x, y, l , h, c, an, ds, a, v, d, coul , i = 10)
Cellule.__inti__(self, cane, x, y, l , h, c, an, ds, a, v, d, coul)
self.i = i
#ligne de cellules
self.ligne_de_cellules[]
for xi in range (x, x + 900, 95)
self.ligne_de_cellules.append(Cellule(cane, x, y))
Application().mainloop() |
2f720b6ede73e45103b04923f989774e3e609b6c | Lepajewski/PythonStudia | /Easy/comparetwonumbers.py | 251 | 3.953125 | 4 | t = int(input())
for i in range(t):
m, n = input().split()
m = int(m)
n = int(n)
if m > n:
print(m, " is greater than ", n)
elif m < n:
print(m, " is smaller than ", n)
else:
print("n is equal m: ", m)
|
5d7143b6e27936fbb44d65ef0fb511ccf8afc2f7 | Henry-Aybar/oop | /Users_with_bank_accounts/Users_with_bank_accounts.py | 2,289 | 4.21875 | 4 | class BankAccount:
bank_name = "First National Dojo"
all_accounts =[]
def __init__(self, int_rate, balance):
self.int_rate = int_rate
self.balance = balance
BankAccount.all_accounts.append(self)
def deposit(self, amount):
self.balance += amount
# print(f"{self.name} Deposited: ${amount}, curent balance is: ${balance}.")
print(f"deposited: ${amount}")
return self
def withdrawal(self, amount):
if User.can_withdrawal (self.account.balance, amount):
print (f"Withdrawal was succesful!Original Balance was ${self.account.balance} and you took ${amount} from your account.")
self.account.withdrawal(amount)
print (f"remaing account balance is now ${self.account.balance}.")
else:
print(f"Insufficient funds: Charging a $5 fee")
self.balance -= amount
return self
def display_account_info(self):
print(f"Bank account has ${self.account.balance} in it of and an intrest rate of ${self.int_rate}")
def yield_interest(self):
if self.balance > 0:
self.balance += self.balance * self.int_rate
print(f"balance after intrest is{self.balance}")
else:
print("balance is 0")
class User:
list_of_users=[]
def __init__(self , name, email_address):
User.list_of_users.append(self)
self.name = name
self.email = email_address
self.account= BankAccount(int_rate = 0.02, balance = 0)
# self.bank_name
def make_deposit(self, amount):
self.account.deposit(amount)
return self
def make_withdrawal(self, amount):
self.account.withdrawal(amount)
return self
def display_user_balance(self):
print(f"User: {self.name}, current Balance is: {self.account.balance}")
return self
def transfer_money(self, other_user, amount):
other_user.account += amount
######## Users ########
asta = User("Asta Staria", "asta.blackbull@clover.com")
yuno = User("Yuno Grinberryall", "yuno.goldendawn@clover.com")
yami = User("Yami Sukehiro", "yami.cpt.blackbulls@clover.com")
asta.make_deposit(1000)
yuno.make_deposit(1000)
yami.make_deposit(5000)
asta.display_user_balance()
yuno.display_user_balance()
yami.display_user_balance() |
5d2f9463451116bd3c0f8523dbf023d22d338cf3 | iffishells/Data-stucture- | /Assignment-solutions/Assignment_Number07 | 2,254 | 3.828125 | 4 | class Person:
def __init__(self,men,Age,queue_Number):
self.Men=men
self.Age=Age
self.queue_Number=queue_Number
def get_priority(self):
if self.Age>=40:
priority=100-self.queue_Number
return priority+100
else:
priority=100-self.queue_Number
return priority
def __str__(self):
return str(self.Men)+" "+str(self.get_priority())
def heap_sort(lst):
n=len(lst)
build_heap(lst)
for i in reversed(range(n)):
print(i)
lst[i] ,lst[0] =lst[0],lst[i]
heapify(lst,i,0)
def build_heap(lst):
n=len(lst) #1
for i in reversed(range(n//2)):
#print("loop count in buid heap")
#print( " value of i = ,",i)
#print( "value of n = ",n)
heapify(lst,n,i)
def heapify(lst,n,root):
largest=root
#1root=1
l=2*root+1 #3
r=2*root+2 #4 #198 #190
#print("lst[l].get_priority()", lst[l].get_priority())
#print("lst[largest].get_priority()" ,lst[largest].get_priority())
if l < n and lst[l].get_priority() < lst[largest].get_priority():
largest=l # 1
#193 #198
if r < n and lst[r].get_priority() < lst[largest].get_priority():
largest=r #2
if largest!=root:
lst[root],lst[largest]=lst[largest],lst[root]
heapify(lst,n,largest)
if __name__ == '__main__':
p = Person('A', 24, 1)
p.get_priority()
print(p) # should output: A 99
p = Person('A', 40, 1)
print(p) # should output: A 199
people = [
Person('A', 24, 1),
Person('B', 32, 2),
Person('C', 45, 3),
Person('D', 22, 4),
Person('E', 21, 5),
Person('F', 32, 6),
Person('G', 39, 7),
Person('H', 44, 8),
Person('I', 22, 9),
Person('J', 29, 10),
Person('K', 32, 11),
Person('L', 31, 12)
]
print(p)
print([str(p) for p in people])
heap_sort(people)
print([str(p) for p in people])
# sould output:
# ['C 197', 'H 192', 'A 99', 'B 98', 'D 96', 'E 95', 'F 94', 'G 93', 'I 91', 'J 90', 'K 89', 'L 88']
|
e22b3122cb0f76d6f36f65a57b67575e61b9dba9 | JeongYeonUk/Problem | /PS_Python/다음_큰_숫자.py | 385 | 3.75 | 4 | def int_to_bit(n):
n_bit = []
while n:
n_bit.append(n % 2)
n = n // 2
return n_bit.count(1)
def solution(n):
n_bit_count = int_to_bit(n)
n = n + 1
while True:
next_bit_count = int_to_bit(n)
if next_bit_count == n_bit_count:
break
n = n + 1
return n
if __name__ == "__main__":
print(solution(78))
|
49a6bdf834002fbaf455b1317bd6e44f0f0f1890 | Gokulraj210/python | /bubble sort using fun.py | 431 | 3.984375 | 4 | def bubble_sort(alist):
for i in range(len(alist)-1,0,-1):
no_swap=True
for j in range(0,i):
if alist[j+1] <alist[j]:
alist[j], alist[j + 1] = alist[j + 1],alist[j]
no_swap=False
if no_swap:
return
alist=input('enter the list of numbers:').split()
alist=[int(x) for x in alist]
bubble_sort(alist)
print('sorted list:',end='')
print(alist)
|
d9303728563354d0b86ebb464a5a2981cf190df4 | lamasumas/Machine_Learning | /ImageClassification/ImageClassificationLinearKernel.py | 2,367 | 3.546875 | 4 |
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
## Read the data
data_train = np.loadtxt("data_train1.txt")
label_train = np.loadtxt("labels_train1.txt")
data_test = np.loadtxt("data_test1.txt")
label_test = np.loadtxt("labels_test1.txt")
"""
## Testing the characters
plt.figure(figsize=(8,8))
for k in range(0,100):
plt.subplot(10,10,k+1)
## Each row is a character
imagen = data_train[k, ]
## Each character is 28x28 pixels
imagen = imagen.reshape(28, 28)
plt.imshow(imagen, cmap='gray')
plt.axis('off')
plt.show()
"""
## Parameter of regularization
c = 1
## Number of classes
number_of_classes = 10
## Number of rows in data array
n = data_train.shape[0]
## Number of rows in testing array
m = data_test.shape[0]
## Identity array n x n
I = np.identity(n)
## Is in a grey scale so we normalize the data (only 0 and 1)
H = data_train / 255
H_test = data_test / 255
## Array with the labels that we have
labels = np.zeros((n,number_of_classes))
for i in range(n):
labels[i,int(label_train[i])] = 1
## Linear kernel martrix
Omega = np.dot(H, H.T)
## Weights
W = np.linalg.solve((I/c) + Omega, labels)
Omega_test = np.dot(H_test, H.T)
## Make the predcition
actual_label_test = np.dot(Omega_test, W)
##The biggest value of the array is going to be the actual label
class_predicted = actual_label_test.argmax(axis=1)
guessed_porcentage = np.sum(class_predicted == label_test)/float(m) *100
print ('Guessed percentage = %.1f%%' % guessed_porcentage)
"""
## Show the matrix of prediction beside the actual solution
print('\nLabels predicted for testing samples')
for i in range(0,m):
if i%10 == 9:
print(np.argmax(actual_label_test[i])),
else:
print(np.argmax(actual_label_test[i]), end=" "),
print('\n')
print('Images corresponding to the above labels')
for k in range(0, 100):
plt.subplot(10, 10, k+1)
image = data_test[k, ]
image = image.reshape(28, 28)
plt.imshow(image, cmap="gray")
plt.axis('off')
plt.show()
"""
mytest = Image.open("MyTest.png")
myTestGray = mytest.convert("L")
myTestArray = np.asanyarray(myTestGray)
H_myTest = myTestArray / 255
y = []
for i in H_myTest:
for j in i:
y.append(j)
Omega_my_test = np.dot(y, H.T)
## Make the predcition
my_label_test = np.dot(Omega_my_test, W)
print(np.argmax(my_label_test))
|
8f9a94aa8fd30c8123d8989665471fd8a86ea3c6 | fulcorno/Settimane | /Settimana06/bisezione.py | 1,791 | 4.09375 | 4 | '''
Sia data una funzione reale di variabile reale y = f ( x ).
Si vuole trovare uno zero della funzione f nell'intervallo x ⋲ [a, b]
usando il metodo di bisezione (valido se f() è continua e f(a)f(b)<0)
'''
import math
EPSILON = 0.0000001
def main():
print("Inserisci gli estremi dell'intervallo [a, b]")
x1 = float(input("a="))
x2 = float(input("b="))
# zero = trovaZero(a=x1, b=x2)
# zero = trovaZero(b=x2, a=x1)
zero = trovaZero(x1, x2)
# zero = trovaZero(x1, x2, eps=0.01)
if zero is None:
print('La funzione non cambia segno nell\'intervallo')
else:
print(f'La soluzione è {zero}')
def trovaZero(a, b, eps=EPSILON):
"""
Ricerca di uno zero utilizzando il metodo di bisezione. Ricerca lo zero della funzione f(x)
nell'intervallo [a, b].
:param a: estremo sinistro dell'intervallo (compreso)
:param b: estremo destro dell'intervallo (compreso)
:param eps: (opzionale) precisione desiderata, l'algoritmo itera finché |a=b|<eps
:return: migliore approssimazione troata per la soluzione
"""
if f(a) * f(b) > 0:
# hanno lo stesso segno -> non si può applicare
return None # valore "sentinella" per indicare l'anomalia
# return "Errore"
elif f(a) == 0:
return a
elif f(b) == 0:
return b
else:
# devo cercare!
while abs(b - a) > eps:
m = (a + b) / 2
if f(m) == 0:
return m
elif f(m) * f(a) > 0:
# f(m) ha il segno di f(a)
a = m
else:
# f(m) ha il segno di f(b)
b = m
return m
def f(x):
"""
Funzione in cui ricercare gli zeri
"""
y = math.sin(x)
return y
main()
|
c0e9a88eb60a9e0f54d0f0313147a2ef2355c5f8 | statistics-exercises/t-tests-10 | /main.py | 1,275 | 3.78125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def sample_variance( data ) :
# Your code to compute the sample variance goes here
def common_variance( data1, data2 ) :
# Your code to compute the common variance using the formula in the
# description on the left goes here
# This code generates the graph -- you should not need to modify from here onwards
xvals, total_var, common_var = np.zeros(10), np.zeros(10), np.zeros(10)
for i in range(10) :
# This line generates 100 samples from two normal distribuions. The first of these
# distributions is centered on zero. the second is centered on the value of i.
# As we go through the loop the two distributions thus get progressively further and
# further appart.
samples1, samples2 = np.random.normal(0,1,size=100), np.random.normal(i,1, size=100)
xvals[i], common_var[i] = i, common_variance( samples1, samples2 )
# This line calculates the variance and assumes all the data points are from a
# single distribution
total_var[i] = sample_variance(np.concatenate([samples1, samples2]))
# This generates the graph.
plt.plot( xvals, total_var, 'ro' )
plt.plot( xvals, common_var, 'bo' )
plt.xlabel("Difference between means")
plt.ylabel("Variance")
plt.savefig("variance.png")
|
2ba18d4ca6bf2547477ffa4d2a28037dc81a2596 | sunnyyeti/Leetcode-solutions | /221 Maximal Square.py | 1,868 | 3.515625 | 4 | # Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
# Example 1:
# Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
# Output: 4
# Example 2:
# Input: matrix = [["0","1"],["1","0"]]
# Output: 1
# Example 3:
# Input: matrix = [["0"]]
# Output: 0
# Constraints:
# m == matrix.length
# n == matrix[i].length
# 1 <= m, n <= 300
# matrix[i][j] is '0' or '1'.
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
dp = [[None]*len(matrix[0]) for _ in matrix]
ans = 0
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if matrix[r][c]=='1':
if c==0 or matrix[r][c-1]=='0':
rdp = 1
else:
rdp = dp[r][c-1][0]+1
if r==0 or matrix[r-1][c]=='0':
cdp = 1
else:
cdp = dp[r-1][c][1]+1
dp[r][c] = [rdp,cdp]
else:
#print(r,c)
#print(dp)
dp[r][c] = [0,0]
square_dp = [[0]*len(matrix[0]) for _ in matrix]
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if matrix[r][c] == '0':
square_dp[r][c] = 0
else:
if r==0 or c==0:
square_dp[r][c] = 1
ans = max(ans,1)
else:
rdp,cdp = dp[r][c]
min_dp = min(rdp,cdp,square_dp[r-1][c-1]+1)
square_dp[r][c] = min_dp
ans = max(ans,min_dp)
return ans**2
|
c9dc46c39b7968e91a4d2bd847f44e32ebc9a335 | LimFangYong/DPL5211Tri2110 | /LAB 2.4.py | 688 | 3.96875 | 4 | # Student ID : 1201201544
# Student Name : LIM FANG YONG
BANANA = 1.5
GRAPES = 5.6
print("Invoice for fruits Purchase")
print("---------------------------------")
banana = int(input("Enter the quantity (comb) of bananas bought : "))
grapes = float(input("Enter the amount (kg) of grapes bought : "))
banana_price = banana * BANANA
grapes_price = grapes * GRAPES
total_price = banana_price + grapes_price
print("\nItem\t\t Qty\t Price\t Total")
print("Bananas (combs)\t {}\t RM {:.2f}\t RM {:.2f}".format(banana, BANANA, banana_price))
print("Graps (kg)\t {:.2f}\t RM {:.2f}\t RM {:.2f}".format(grapes, GRAPES, grapes_price))
print("Total : RM {:.2f}".format(total_price)) |
4d29ae324cec62811f08964cf62f0d1b2af1e156 | IamAamerAli/DataBaseConnectivity | /FirstProgram.py | 1,467 | 3.625 | 4 | import sqlite3
# Global Variable for Table Name to avoid mistakes in string
TABLE_STORE = "tbl_store"
COL_ITEM = "item"
COL_QUNTITY = "quantity"
COL_PRICE = "price"
def create_table():
conn = sqlite3.connect("lite.db")
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE IF NOT EXISTS {} ({} TEXT, {} INTEGER, {} REAL)".format(TABLE_STORE, COL_ITEM, COL_QUNTITY,
COL_PRICE))
conn.commit()
conn.close()
def insert_data(item, quntity, price):
conn = sqlite3.connect("lite.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO {} VALUES (?,?,?)".format(TABLE_STORE), (item, quntity, price))
conn.commit()
conn.close()
def view_data():
conn = sqlite3.connect("lite.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM {}".format(TABLE_STORE))
rows = cursor.fetchall()
conn.close()
return rows
def delete_data(item):
conn = sqlite3.connect("lite.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM {} WHERE {} = ?".format(TABLE_STORE, COL_ITEM), (item,))
conn.commit()
conn.close()
def update_date(item,quntity,price):
conn = sqlite3.connect("lite.db")
cursor = conn.cursor()
cursor.execute("UPDATE {} SET {} = ?,{} = ? WHERE {} = ?".format(TABLE_STORE, COL_QUNTITY, COL_PRICE, COL_ITEM),(quntity,price,item))
conn.commit()
conn.close()
print(view_data())
|
cd11702159d48bb1c0c683544c7d8cd4416bbed3 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/itprov/pancakes.py | 1,381 | 3.71875 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
import re
happy_sides_first_pattern = re.compile(r"^(\++)-+") # Pancakes starting with 1 or more +'s followed by at least 1 -
blank_sides_first_pattern = re.compile(r"^(-+)\++") # Pancakes starting with 1 or more -'s followed by at least 1 +
t = int(input()) # Number of test cases
for i in range(t):
pancakes = input() # Given test case string
j = 0 # Number of times of maneuvers
while "-" in pancakes: # Repeat while at least 1 - exists
match_found = happy_sides_first_pattern.match(pancakes) # Try first case - starting with +'s, e.g. ++--+-
if match_found:
matched_pancakes = match_found.group(1) # This is the first +'s that need to be flipped
pancakes = pancakes.replace(matched_pancakes, "-" * len(matched_pancakes), 1)
elif blank_sides_first_pattern.match(pancakes): # Try second case - starting with -'s, e.g. ---++-+
match_found = blank_sides_first_pattern.match(pancakes)
matched_pancakes = match_found.group(1) # This is the first -'s that need to be flipped
pancakes = pancakes.replace(matched_pancakes, "+" * len(matched_pancakes), 1)
else: # This last case means all pancakes are -'s
pancakes = pancakes.replace("-", "+")
j = j + 1
print("Case #{}: {}".format(i + 1, j))
|
ec4a9c95aabd204c737f214a61e11ce8e4441aaa | Rakeshmr1995/completed_task | /python/python_functions_2/ReverseList.py | 184 | 3.90625 | 4 | list1 = [100, 200, 300, 400, 500]
#list1 = list1[::-1]
#print(list1)
"""def Reverse(list1):
list1.reverse()
return list1
print(Reverse(list1))"""
list1.reverse()
print(list1) |
81c88b8e71cdc7f57da4970ba99d676f3836bb18 | RichaPrajapati1/HW06 | /HW06_ex09_02.py | 988 | 4.125 | 4 | #!/usr/bin/env python
# HW06_ex09_02.py
# (1)
# Write a function called has_no_e that returns True if the given word doesn't
# have the letter "e" in it.
# - write has_no_e
# (2)
# Modify your program from 9.1 to print only the words that have no "e" and
# compute the percentage of the words in the list have no "e."
# - print each approved word on new line, followed at the end by the %
##############################################################################
# Imports
# Body
def has_no_e(word):
for letter in word:
if letter == 'e':
return False
return True
##############################################################################
def main():
total = 0
counter = 0
fin = open('words.txt')
for line in fin:
total += 1
word = line.strip()
if has_no_e(word):
#print word
counter += 1
fin.close()
percentage = (float(counter)/total)*100
print "The percentage of words with no e are: %.2f" %(percentage)
if __name__ == '__main__':
main()
|
16ca117f07b6fb2576af2a4e74544ad64ce5c812 | aliyevmirzakhan/ABBTech-SWE-T1 | /problem1.py | 495 | 3.734375 | 4 |
def carParkingRoof(cars, k):
cars.sort()
# print(cars)
covers = []
for slice in range(0, len(cars)):
covers.append(cars[slice: slice + k]) if len(cars[slice: slice + k]) == k else None
differentials = [(cover[-1] - cover[0]) + 1 for cover in covers]
print(f"[Roof Length Canditates]: {differentials}")
return min(differentials)
if __name__ == "__main__":
test_list = [6,2,12,7]
min_roof_length = carParkingRoof(test_list, k = 3)
print(f"[Min Roof Length] - {min_roof_length}") |
8dab1cc403846956c1bf10383a64f27406cd2250 | AnonymousRandomPerson/TreeSearch | /data.py | 3,145 | 3.828125 | 4 | # coding: utf-8
import csv
pokemonFile = 'pokemonSS.csv'
trainersFile = 'trainersSS.csv'
class Data:
"""Stores data about Battle Tree Pokémon."""
def __init__(self):
"""Initializes the data storage."""
self.sets = {}
with open(pokemonFile, 'r') as csvFile:
pokemonReader = csv.reader(csvFile)
for row in pokemonReader:
set = Set(row)
self.sets[set.name] = set
self.trainers = {}
with open(trainersFile, 'r') as csvFile:
trainerReader = csv.reader(csvFile)
for row in trainerReader:
trainer = Trainer(self, row)
self.trainers[trainer.name.lower()] = trainer
def getTrainer(self, name):
"""
Gets a Trainer's data.
Args:
The name of the Trainer.
"""
name = name.lower()
if name in self.trainers:
return self.trainers[name]
return None
def getSet(self, name):
"""
Gets a set's data.
Args:
The name of the set.
"""
if name in self.sets:
return self.sets[name]
return None
class Set:
"""Data about a specific Pokémon set."""
def __init__(self, row):
"""
Initializes a set.
Args:
row: The CSV data for the set.
"""
self.name = row[0]
self.pokemon = row[0][:row[0].index('-')]
self.nature = row[1]
self.item = row[2]
self.moves = tuple(row[i] for i in range(3, 7))
self.evs = row[7]
def __repr__(self):
"""Returns the set's name."""
return self.name
class Trainer:
"""Data about a specific Trainer."""
def __init__(self, data, row):
"""
Initializes a Trainer.
Args:
data: The data object containing Pokémon data.
row: The CSV data for the Trainer.
"""
self.name = row[0]
allPokemon = row[1].split(',')
allPokemon.sort()
self.sets = []
self.dynamax = {}
for pokemon in allPokemon:
isDynamax = False
for dynamaxKeyword in ['-Dynamax', '-Gigantamax']:
if dynamaxKeyword in pokemon:
pokemon = pokemon.replace(dynamaxKeyword, '')
isDynamax = True
break
pokemonSet = data.getSet(pokemon)
self.sets.append(pokemonSet)
if isDynamax:
self.dynamax[pokemonSet.name] = dynamaxKeyword
def __repr__(self):
"""Returns the Trainer's name."""
return self.name
def getSets(self, name):
"""
Gets the possible Pokémon sets for the Trainer.
Args:
name: The name of the Pokémon to get possible sets for.
"""
sets = []
name = name.lower()
if name:
for pokemonSet in self.sets:
lowerName = pokemonSet.name.lower()
if lowerName.startswith(name):
sets.append(pokemonSet)
return sets |
e473e8e278a9505f977dced813612e0186d4b32a | lucmichea/leetcode | /Challenge_April_30_days_leetcoding_challenge-/day01.py | 1,042 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 14:51:20 2020
@author: Jinling Xing & Luc Michea
"""
'''
Problem :
Given a non-empty array of integers, every element appears twice except for one.
Find that single one.
Example 1:S
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = {}
for i in nums:
if i not in res:
res[i] = True
else:
res.pop(i)
return list(res.keys()).pop()
if __name__=='__main__':
sol = Solution()
inp = [2,2,1]
out = sol.singleNumber(inp)
print("The solution to {} is : {}".format(inp, out))
'''
We could have also used the XOR operator as : a XOR a = 0 and b XOR 0 = b
(Best answer from a friend)
Hence :
def singleNumber(self, nums: List[int]) -> int:
res = 0
for i in nums:
res = res ^ i
return res
'''
|
f41202d29d4c5ef5978208749e483c15f65ffce5 | QR10/PokemonChallenge | /pokemon.py | 4,775 | 3.765625 | 4 | def get_grid_size(ash_movement_sequence):
""" Returns the maximum used X and Y axis sizes for a movement sequence
as 2 integers.
Expects: A string with a sequence of movements
Modifies: Nothing
Returns: Two integers, X-axis value and Y-axis value
"""
list_of_ash_movements = list(ash_movement_sequence.lower())[::-1]
south_movements_count = 0
north_movements_count = 0
east_movements_count = 0
west_movements_count = 0
while list_of_ash_movements:
move_ash = list_of_ash_movements.pop()
if move_ash == "s":
south_movements_count += 1
elif move_ash == "n":
north_movements_count += 1
elif move_ash == "e":
east_movements_count +=1
elif move_ash == "o":
west_movements_count += 1
else:
print(f"{move_ash} não é um movimento valido!")
# Guardar maior numero de movimentos numa direcao
if east_movements_count > west_movements_count:
x_axis_movements = east_movements_count
else:
x_axis_movements = west_movements_count
if south_movements_count > north_movements_count:
y_axis_movements = south_movements_count
else:
y_axis_movements = north_movements_count
return x_axis_movements, y_axis_movements
def generate_grid(x, y) :
"""Returns a grid full of pokemons to catch, with the exception of the
starting pokemon/house.
Expects: X and Y axis max values as integers
Modifies: Nothing
Returns: A grid full of pokemons to catch
"""
world = []
for j in range(x*2+1):
column = []
for i in range(y*2+1):
column.append(1)
world.append(column)
# Ash starts here and gets starting Pokemon
world[x][y] = 0
return world
def catch_a_pokemon(grid_of_houses, x, y):
""" Returns an integer with the number of pokemons caught in Ash's
current position.
Expects: Grid with houses and x and y coordinates of ash's position
Modifies: Number of available pokemons in the current house
Returns: An integer with number of pokemons caught
"""
if grid_of_houses[x][y] == 1:
grid_of_houses[x][y] = 0
return 1
else:
return 0
def count_pokemons_caught(ash_movement_sequence, grid_of_houses, x_axis_pos,
y_axis_pos) :
""" Counts the number of pokemons caught by ash in a given move sequence
and returns the count as an integer
Expects: A string with a list of moves, a grid filled with pokemons to
catch, ash's x-axis and y-axis starting position'
Modifies: Nothing
Returns: A count of pokemons caught, as an integer
"""
list_of_ash_movements = list(ash_movement_sequence.lower())[::-1]
# Starting house pokemon acquired
pokemon_caught_count = 1
while list_of_ash_movements:
move_ash = list_of_ash_movements.pop()
if move_ash == "s":
y_axis_pos = y_axis_pos+1
pokemon_caught_count += catch_a_pokemon(grid_of_houses,
x_axis_pos, y_axis_pos)
elif move_ash == "n":
y_axis_pos = y_axis_pos-1
pokemon_caught_count += catch_a_pokemon(grid_of_houses,
x_axis_pos, y_axis_pos)
elif move_ash == "e":
x_axis_pos = x_axis_pos+1
pokemon_caught_count += catch_a_pokemon(grid_of_houses,
x_axis_pos, y_axis_pos)
elif move_ash == "o":
x_axis_pos = x_axis_pos-1
pokemon_caught_count += catch_a_pokemon(grid_of_houses,
x_axis_pos, y_axis_pos)
return pokemon_caught_count
def play_pokemon(ash_movement_sequence):
"""Prints the amount of pokemons caught by Ash in a user specified
movement sequence.
Expects: A string with Ash's movement sequence
Modifies: Nothing
Returns: Nothing
"""
x_axis_position, y_axis_position = get_grid_size(ash_movement_sequence)
grid_of_houses = generate_grid(x_axis_position, y_axis_position)
pokemons_caught_count = count_pokemons_caught(ash_movement_sequence,
grid_of_houses, x_axis_position,
y_axis_position)
print(f"O Ash apanhou {pokemons_caught_count} pokémons!")
def main():
user_move_sequence = input("Insira a sequência de movimentos do ash: ")
play_pokemon(user_move_sequence)
if __name__ == "__main__":
main()
|
9f6f65f0881047b13f79b91028d23f90405d7f33 | DawnEve/learngit | /Python3/pythonCodeGit/day6-OOP/op3_student.py | 1,060 | 4.0625 | 4 | #定义类
#class Student(object): #不写(object),直接(),也没有异常
class Student(): #不写(object),直接(),也没有异常
def __init__(self, name, score):
self.name = name
self.score = score
#和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。
def print_score(self):
print('%s: %s' % (self.name, self.score))
#添加新方法
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
#实例化对象: 实例(Instance)
#创建实例是通过类名+()实现的:
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
print(bart)
print(lisa)
#调用对象的方法
bart.print_score()
lisa.print_score()
#调用另一个方法
print( bart.get_grade() )
print( lisa.get_grade() )
#给类绑定对象
bart.age=25
print(bart.age)
#print(lisa.age)#没定义就没有值
|
57786ce68d50d8d8eb4339935865a62f22b7caef | Niranjan-10/DSA-Practice | /array/sub_array_with_0_sum.py | 351 | 3.78125 | 4 | def subArraaySum(arr):
n_sum = 0
s = set()
for i in arr:
n_sum += i
if n_sum == 0 or n_sum in s:
return True
s.add(n_sum)
return False
arr = [-3, 2, 3, 1, 6]
n = len(arr)
if subArraaySum(arr, n) == True:
print("Found a sunbarray with 0 sum")
else:
print("No Such sub array exits!") |
34317985a0d4b16d93a8e4a7c6325dbeedf365c8 | SoundNandu/Stack-1 | /DialyTemperature.py | 1,273 | 4.28125 | 4 | Daily Temperatures
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
Time complexity O(n) | Space complexity O(n)
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
stack,result = [] ,[0 for i in range(len(T))]
for index in range (len(T)):
#Monotonic stack we are comapring with the elements in the array with the stack element
while(len(stack) and T[stack[-1]] < T[index]):
# if its less than the stack element we are poping it
prorityIndex = stack.pop()
#calculating the index value
result[prorityIndex] = index - prorityIndex
#if the stack is empty keep adding
stack.append(index)
return result
|
30ade5d55a0168ee25b23da64f726bbb7d0bee07 | porrametict/learningSpace | /PythonWithChulalondkorn/set_demo1.py | 453 | 3.625 | 4 | def demo():
skills = {"Python","C","JAVA"}
print(skills)
print(type(skills))
a = {} # dict
b = set() # set
print(type(a))
print(type(b))
xy = {(5,2),(5,5)}
print(xy) #
# demo()
def basic_op():
a = {"mango", "banana", "coconut", "mango", "apple"}
b = {"cherry", "mango", "apple"}
m = a | b # union
print(m)
n = a & b
print(n)
p = a - b
q = a ^ b
print(p)
print(q)
basic_op() |
332f5cb57b123409ee56890fe44bc7bc7e9e3e88 | polinavolos/programming_practice | /week02/hw1/task4.py | 375 | 3.765625 | 4 | def where_is_Vasya(speed, hours):
if speed > 0:
distance = (speed * hours) % 109
return distance
v = int(input())
t = int(input())
vasyas_location = where_is_Vasya(v, t)
print(vasyas_location)
#я понимаю, что можно было в три строчки решить, но мне очень нравится составлять функции:)
|
598ff3f4b63a05ec01f9d45ed1923c32034ff371 | YBrady/pands-project | /dataInNumbers.py | 5,952 | 3.671875 | 4 |
# --------------------------------------------------------------
# Fischers Iris Dataset
#
# Written by Yvonne Brady
# GMIT ID: G00376355
#
# This python program looks after the data analysis / review
# of the actual numbers.
#---------------------------------------------------------------
# Import pandas library
import pandas
# Declaring and setting the dataset as a global variable - saves going back and forth all the time
data = pandas.read_csv("iris_csv.csv") # All Irises
dataVirg = data.loc[data["class"] == "Iris-virginica"] # Just the Iris-virginica
dataVers = data.loc[data["class"] == "Iris-versicolor"]# Just the Iris-versicolor
dataSeto = data.loc[data["class"] == "Iris-setosa"] # Just the Iris-setosa
# Displays the Data Menu
def display_num_menu():
print("")
# Creating the menu heading
print("=" * 20)
print("Raw Data Menu")
print("=" * 20)
print("1 - Display Raw Data ...")
print("2 - Display Data Shape and Size")
print("3 - Display Data Info")
print("4 - Display First x Rows")
print("5 - Display Last x Rows")
print("6 - Display Random x Rows")
print("7 - Display Statistical Summary Data ...")
print("8 - Display Statistical Data by Iris Class ...")
print("0 - Return to Main Menu")
# Allow the user a choice of what they want reported
print("")
choice = input("Enter choice: ")
print("")
# If the raw data is selected
if (choice == "1"):
# Calls a function where the user is asked which class they want to report on
iris = pick_iris_class()
# Prints the data related to Iris-Virginica class
if (iris == "1"):
print(dataVirg)
# Prints the data related to Iris-Setosa class
elif (iris =="2"):
print(dataSeto)
# Prints the data related to Iris-Versicolor class
elif (iris =="3"):
print(dataVers)
# Prints the all iris data
elif (iris == "4"):
print(data)
# Anything else return an error
else:
print("Invalid selection")
# Displays the menu again
display_num_menu()
# Displays the shape of the data
elif (choice == "2"):
print("The dataset has",data.shape[0], "rows each with", data.shape[1], "attributes.")
print("Altogether there are", data.size, "data values in the dataset.")
print("The Iris class breakdown is as follows:")
print(data.groupby("class").size())
# Returns to the numbers menu
display_num_menu()
# Displays the data info
elif (choice == "3"):
print("The following is information on the attributes in the dataset:")
print(data.info())
# Returns to the numbers menu
display_num_menu()
elif (choice =="4"):
num = int(input("How many rows do you wish to return? "))
print("The following are the first",num,"rows of the dataset:")
print(data.head(num))
# Returns to the numbers menu
display_num_menu()
elif (choice == "5"):
num = int(input("How many rows do you wish to return? "))
print("The following are the last",num,"rows of the dataset:")
print(data.tail(num))
# Returns to the numbers menu
display_num_menu()
elif (choice == "6"):
num = int(input("How many rows do you wish to return? "))
print("The following are",num,"random rows of the dataset:")
print(data.sample(num))
# Returns to the numbers menu
display_num_menu()
elif (choice == "7"):
iris = pick_iris_class()
if (iris == "1"):
print("The following is summary statistical data relating to the Iris-Virginica class of Iris:")
print(dataVirg.describe())
elif (iris == "2"):
print("The following is summary statistical data relating to the Iris-Setosa class of Iris:")
print(dataSeto.describe())
elif (iris == "3"):
print("The following is summary statistical data relating to the Iris-Versicolor class of Iris:")
print(dataVers.describe())
elif (iris == "4"):
print("The following is summary statistical data relating to all classes of Iris:")
print(data.describe())
else:
print("Invalid selection")
# Returns to the numbers menu
display_num_menu()
elif (choice == "8"):
print("Which of the following do you wish to see :")
stat = input("1 for Minimum; 2 for Maximum, 3 for Mean, 4 for Standard Deviation : ")
if (stat == "1"):
print("The following are the minimum values for each measurement by Iris class:")
print(data.groupby("class").min())
elif (stat == "2"):
print("The following are the maximum values for each measurement by Iris class:")
print(data.groupby("class").max())
elif (stat == "3"):
print("The following are the mean values for each measurement by Iris class:")
print(data.groupby("class").mean())
elif (stat == "4"):
print("The following are the standard deviation values for each measurement by Iris class:")
print(data.groupby("class").std())
else:
print("Invalid input")
# Returns to the numbers menu
display_num_menu()
elif (choice == "0"):
# Returns to main menu
return
else:
# Returns to the numbers menu
display_num_menu()
def pick_iris_class():
print("Which Iris class do you wish to report on?")
return input("Press 1 for Iris-virginica, 2 for Iris-Setosa or 3 for Iris-Versicolor or 4 for All Iris Classes: ")
# This part is used for testing only, or if not being called from the menus.py file
if __name__ == "__main__":
# execute only if run as a script
display_num_menu()
|
da7ff972317c6ecbb86f34bb4d58ffb47e736e9e | pyav/labs | /src/python/class.py | 397 | 3.578125 | 4 | #!/usr/bin/env python3
'''
__author__ = pyav
Output
------
first
Inside class C, first
'''
class A:
def first(self):
return "first"
class B:
def second(self):
print(A().first())
B().second()
class C():
def __init__(self):
self.objA = A()
def third(self):
print('Inside class C, ' + self.objA.first())
# __init__ gets into action
C().third()
|
3c105810de690287ed4bad50f8a6d655da43898f | npstar/HackBulgaria | /week0/1/biggest_difference.py | 223 | 3.78125 | 4 | def biggest_difference(arr):
min = arr[0]
max = arr[0]
for i in arr:
if i < min:
min = i
if i > max:
max = i
return min - max
print(biggest_difference([-10, -9, -1]))
|
7888cc1754014efe56907fd6a9cb5d81ca78e302 | PhebeJ/Knowledge-Engineering | /Sum first n num.py | 152 | 3.890625 | 4 | import sys
n=int(input("Enter the limit:"))
if(n < 0):
print("Enter a positive number!")
else:
i=0
while (i < n):
print("",i)
i = i + 1
|
6303711f20643e40bdb08e370a826f827abe700e | youthpasses/leetcode_python | /001_TwoSum.py | 1,001 | 3.875 | 4 | # coding:utf-8
# @sinner
# 16/6/4
'''
Total Accepted: 239594 Total Submissions: 1001231 Difficulty: Easy
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
'''
'''
思路:
x: 0 -> len(nums) - 1, y: x + 1 -> len(nums),遍历一遍,找到相加等于target即停止并返回x, y
'''
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# index1 = 0
# index2 = 0
count = len(nums)
for x in xrange(0, count - 1):
for y in xrange(x + 1, count):
print x, y
if (nums[x] + nums[y]) == target:
return [x, y]
solu = Solution()
print solu.twoSum([2, 4, 9, 0, 1], 5)
|
60f0fbdb28fe2716c9e79774e0c033ff6207b820 | friedlich/python | /19年7月/7.15/实例063:画椭圆.py | 398 | 4.03125 | 4 | # 题目 画椭圆。
# 程序分析 使用 tkinter
if __name__ == '__main__':
import tkinter
x = 360
y = 160
top = y - 30
bottom = y - 30
canvas = tkinter.Canvas(width=400,height=600,bg='white')
for i in range(20):
canvas.create_oval(250-top,250-bottom,
250+top,250+bottom)
top-=5
bottom+=5
canvas.pack()
canvas.mainloop()
|
b6037d21e5b6bea90bb12453f0d78fc053221028 | padamcs36/Introduction_to_Python_By_Daniel | /Chapter 4 Selections/Ex_18_CurrencyExchangeUStoChineseViceVersa.py | 755 | 4.09375 | 4 | #Program to covert Chinese RMB into the US Dollar and vice Versa
#When user enter 0 then covert dollar into the yuan
#when user enter 1 then convert RMB into the dollar
conversion = eval(input("Enter the exchange rate from dollars to RMB: "))
checkCondition = eval(input("Enter 0 to convert dollars to RMB and 1 Vice Versa: "))
if checkCondition == 0:
dollarAmount = eval(input("Enter dollar amount: "))
RMB = conversion * dollarAmount
print(f"{dollarAmount * 10 / 10.0} dollar is {RMB} yuan")
elif checkCondition == 1:
RMBAmount = eval(input("Enter the RMB amount: "))
dollar = RMBAmount / conversion
print(f"{RMBAmount * 10 / 10.0} yuan is {dollar * 100 / 100.0} dollars")
else:
print("Incorrect Input") |
8d7d8e151df6bc6636dae8d669f627fe8b93624b | tomobones/hort | /Code_Kinder/antonio_01.py | 214 | 3.671875 | 4 | import turtle
colors = ['red', 'blue']
t=turtle.Pen()
turtle.bgcolor('black')
for x in range(400):
t.pencolor(colors[x%2])
t.width(x/100+1)
t.forward(x)
t.left(90)
turtle.Screen().exitonclick()
|
82d3a6f1f904b5210d50779205639d0c77c3f55a | JWiryo/LearnAlgorithms | /MatrixTraversal.py | 3,402 | 3.671875 | 4 |
class MatrixTraversal:
# Up, Right, Down, Left
directions = [[-1,0], \
[0,1], \
[1,0], \
[0,-1]
]
# Udemy Implementation of BFS
def arrBFS(self, matrix):
rows = len(matrix)
cols = len(matrix[0])
# Setup visited and result list
seen = [[False for i in range(cols)] for j in range(rows)]
result = []
queue = [] #queue can get really large
queue.append([0,0]) # Start from node at Row 2 and Col 2
# Iterative loop
while queue:
# Pop item from queue
current = queue.pop(0)
curRow = current[0]
curCol = current[1]
if curRow < 0 or curCol < 0 or curRow >= len(matrix) or curCol >= len(matrix[0]) or seen[curRow][curCol]:
# If any of this happens, skip the next session within the while loop
continue
# Update Visited List
seen[curRow][curCol] = True
# Update Result List
result.append(matrix[curRow][curCol])
# Attempt all directions
for i in range(len(self.directions)):
# Get current direction
dir = self.directions[i]
queue.append([curRow + dir[0], curCol + dir[1]])
return result
def arrDFS(self, matrix):
rows = len(matrix)
cols = len(matrix[0])
# Setup visited and result list
seen = [[False for i in range(cols)] for j in range(rows)]
result = []
# Initialise Recursion from 0,0
self.__dfs(matrix, 0, 0, seen, result)
return result
## Private DFS Method
def __dfs(self, matrix, row, col, seen_arr, result_arr):
# Out of Bounds Condition and Seen == True Condition
if row < 0 or col < 0 or row >= len(matrix) or col >= len(matrix[0]) or seen_arr[row][col]:
return
# Update Results List
result_arr.append(matrix[row][col])
# Update Visited list
seen_arr[row][col] = True
# Recursive calls; attempt all directions
for i in range(len(self.directions)):
# Get current direction
dir = self.directions[i]
# Recursive
self.__dfs(matrix, row + dir[0], col + dir[1], seen_arr, result_arr)
# # Personal Implementation of BFS
def personalArrBFS(self, matrix):
rows = len(matrix)
cols = len(matrix[0])
# Setup visited and result list
seen = [[False for i in range(cols)] for j in range(rows)]
result = []
queue = [] #queue can get really large
queue.append([0,0]) # Start from node at Row 0 and Col 0
# Iterative loop
while queue:
# Pop item from queue
current = queue.pop(0)
curRow = current[0]
curCol = current[1]
# Add element to result
result.append(matrix[curRow][curCol])
# Change seen at current node to True
seen[curRow][curCol] = True
for i in range(len(self.directions)):
# Get current direction
dir = self.directions[i]
# Try all possible directions and add to queue
if (curRow + dir[0] >= 0 and curRow + dir[0] < len(matrix))\
and curCol + dir[1] >= 0 and curCol + dir[1] < len(matrix[0])\
and not seen[curRow + dir[0]][curCol + dir[1]]:
# Add node to queue
queue.append([curRow + dir[0], curCol + dir[1]])
# Change seen at next node to True
seen[curRow + dir[0]][curCol + dir[1]] = True
return result
|
81d71a9e4215977acde658c90afc4ad529216dad | dorajam/Algorithms | /permutation.py | 651 | 3.859375 | 4 | # Dora Jambor, dorajambor@gmail.com
# January 2016
'''
Implements a function that returns all permutations of string s
'''
result = []
# check if string is already in the list
def isIn(string1, string2):
if string1 in string2:
return True
return False
def permutation(s):
global result
if len(s) == 1 or len(s) == 0:
return result.append(s)
else:
while isIn(s, result) == False:
result.append(s)
print s, result
return permutation(s[0] + s[-1] + s[1:-1])
while isIn(s[1:] + s[0], result) == False:
return permutation(s[1:] + s[0])
permutation('dora') |
c81e61375b4a9a184137de5711a17dd649e519dc | H9574/python_test | /ProblemSolving.py | 3,345 | 4.1875 | 4 | #Räisänen Sanna 2.12.2016 klo 13:03
# Problem solving
# Create a function that solves the most suitable (with most power) link station
# for a device at given point [x,y]. Use any programming language of your choice.
#
# This problem can be solved in 2-dimensional space. Link stations have reach
# and power.
#
# A link station’s power can be calculated:
# power = (reach - device's distance from link station)^2
# if distance > reach, power = 0
#
# Function receives list of link stations and the point where the device is
# located.
#
# Function should output following line:
# “Best link station for point x,y is x,y with power z”
# Or:
# “No link station within reach for point x,y”
#
# Link stations are located at points (x, y) and have reach (r) ([x, y, r]):
# [[0, 0, 10],
# [20, 20, 5],
# [10, 0, 12]]
#
# Print out function output from points
# (x, y): (0,0), (100, 100), (15,10) and (18, 18).
import math
class station_power:
def __init__(self, point, stations):
self.point = point
self.stations = stations
def return_point(self):
return self.point
def return_stations(self):
return self.station
def find(self,lookfor, where):
for index, item in enumerate(where):
if lookfor in item:
return item
def calculate_distance_and_power(self,point,stations):
elements = len(stations)
helplist=[]
helppower=[]
i = 0
px = point[0]
py = point[1]
reach = stations[i][2]
while(i<elements):
sx = stations[i][0]
sy = stations[i][1]
#print("station ",sx,sy)
i = i+1
distance = math.sqrt(math.pow(px - sx,2)+math.pow(py - sy,2))
power = math.pow(reach - distance,2)
if distance > reach:
power = 0
helplist.append([point,i,power])
helppower.append(power)
#print("helplist ",helplist)
#print("all powers ",helppower)
max_power = max(helppower)
#print("maxpower ",max_power)
answerlist = station_power.find(self,max_power,helplist)
return answerlist
def answer(self,answerlist):
#print("answerlist ",answerlist)
point = answerlist[0]
station_index = answerlist[1]
station = stations[station_index]
power = answerlist[2]
if (power != 0):
print('Best link station for point ',point,' is ',station,' with power ', power)
else:
print('No link station within reach for point ', point)
stations = [[0, 0, 10], [20, 20, 5], [10, 0, 12]]
self = [[0,0],[[0, 0, 10], [20, 20, 5], [10, 0, 12]]]
#Test objects
piste1 = [0,0]
piste2 = [100,100]
piste3 = [15,10]
piste4 = (18,18)
eka = station_power.calculate_distance_and_power(self,piste1,stations,)
station_power.answer(self,eka)
toka = station_power.calculate_distance_and_power(self,piste2,stations)
station_power.answer(self,toka)
kolmas = station_power.calculate_distance_and_power(self,piste3,stations)
station_power.answer(self,kolmas)
neljas = station_power.calculate_distance_and_power(self,piste4,stations)
station_power.answer(self,neljas)
#koodaamisen lopetus klo 14:33
|
8f8db0fbe948c83e8b1167108ae33492e55e601a | yeml1/test | /day01.py | 638 | 4.15625 | 4 | # print 'helle word!!'
# print 输出
print('hello word!!!')
# 定义变量--python中直接定义,不需要表明是什么类型
# 定义变量:见名知意,尽量不要中文
name = 'yeml'
age ='26'
#字符串里面有单引号,则外面的用双引号
new_name1 ="let's go "
#字符串里面有双引号,则外面的用单引号
new_name2 ='小白,"好帅 "'
#字符串里面有双引号和单因哈,则外面的用三单引号
new_name3 =''''小白,"好帅",let's go '''
# 多行注释功能''' '''
'''
sdfsdfs
erwerwer
dsfsdfsdf
'''
# input 输入
name =input ('请输入你的名字:')
print('你的名字是',name)
|
0c945a3b034eb4d53b26d500ab152c962684d919 | abhinav318/Python-ProjectX | /EDX/Intro to python/Classes.py | 24,967 | 4.03125 | 4 | #############################################################################################################
# 5.1.8
# Write a class called "Burrito". A Burrito should have the
# following attributes (instance variables):
#
# - meat
# - to_go
# - rice
# - beans
# - extra_meat (default: False)
# - guacamole (default: False)
# - cheese (default: False)
# - pico (default: False)
# - corn (default: False)
#
# The constructor should let any of these attributes be
# changed when the object is instantiated. The attributes
# with a default value should be optional. Both positional
# and keyword attributes should be in the order shown above
#(for the autograder to work).
# Write your code here!
##############################################
# un-Comment From here
# class Burrito(object):
# """docstring for Burrito"""
# def __init__(self, meat, to_go, rice, beans, extra_meat=False, guacamole=False, cheese=False, pico=False, Corn=False):
# self.meat = meat
# self.to_go = to_go
# self.rice = rice
# self.beans = beans
# self.extra_meat = extra_meat
# self.guacamole = guacamole
# self.cheese = cheese
# self.pico = pico
# self.corn = Corn
# # The code below will test your class. If it is written
# # correctly, this will print True, then False. Note,
# # though, that we'll test your code against more complex
# # test cases when you submit.
# newBurrito = Burrito("Tofu", True, True, True)
# print(newBurrito.to_go)
# print(newBurrito.guacamole)
# un-Comment to here
###################################################
#################################################################################################################################
# 5.19
# Copy your Burrito class from the last exercise. Now,
# write a getter and a setter method for each attribute.
# Each setter should accept a value as an argument. If the
# value is a valid value, it should set the corresponding
# attribute to the given value. Otherwise, it should set the
# attribute to False.
#
# Edit the constructor to use these new setters and getters.
# In other words, if we were to call:
#
# new_burrito = Burrito("spaghetti", True, True, False)
#
# new_burrito.meat would be False because "spaghetti" is not
# one of the valid options. Note that you should NOT try to
# check if the new value is valid in both the constructor and
# the setter: instead, just call the setter from the
# constructor using something like self.set_meat(meat).
#
# Valid values for each setter are as follows:
#
# - set_meat: "chicken", "pork", "steak", "tofu", False
# - set_to_go: True, False
# - set_rice: "brown", "white", False
# - set_beans: "black", "pinto", False
# - set_extra_meat: True, False
# - set_guacamole: True, False
# - set_cheese: True, False
# - set_pico: True, False
# - set_corn: True, False
#
# Make sure you name each setter with the format:
#"set_some_attribute" and "get_some_attribute"
#
# For example, the getter for meat would be get_meat. The
# getter for to_go would be get_to_go.
#
# Hint: Your code is going to end up *very* long. This
# will be the longest program you've written so far, but
# it isn't the most complex. Complexity and length are
# often very different!
#
# Hint 2: Checking for valid values will be much easier
# if you make a list of valid values for each attribute
# and check the new value against that.
# Write your code here!
##############################################
# Uncomment from Here
# class Burrito(object):
# """docstring for Burrito"""
# def __init__(self, meat, to_go, rice, beans, extra_meat=False, guacamole=False, cheese=False, pico=False, Corn=False):
# self.set_meat(meat)
# self.set_to_go(to_go)
# self.set_rice(rice)
# self.set_beans(beans)
# self.set_extra_meat(extra_meat)
# self.set_guacamole(guacamole)
# self.set_cheese(cheese)
# self.set_pico(pico)
# self.set_corn(Corn)
# def set_meat(self, meat):
# if meat in ["chicken", "pork", "steak", "tofu"]:
# self.meat = meat
# else:
# self.meat = False
# def set_to_go(self, to_go):
# if type(to_go) == bool:
# self.to_go = to_go
# else:
# self.to_go = False
# def set_rice(self, rice):
# if rice in ["brown", "white"]:
# self.rice = rice
# def set_beans(self, beans):
# if beans in ["black", "pinto"]:
# self.beans = beans
# def set_extra_meat(self, extra_meat):
# if type(extra_meat) == bool:
# self.extra_meat = extra_meat
# else:
# self.extra_meat = False
# def set_guacamole(self, guacamole):
# if type(guacamole) == bool:
# self.guacamole = guacamole
# else:
# self.guacamole = guacamole
# def set_cheese(self, cheese):
# if type(cheese) == bool:
# self.cheese = cheese
# def set_pico(self, pico):
# if type(pico) == bool:
# self.pico = pico
# def set_corn(self, corn):
# if type(corn) == bool:
# self.corn = corn
# else:
# self.corn = False
# def get_meat(self):
# return (self.meat)
# def get_to_go(self):
# return (self.to_go)
# def get_rice(self):
# return (self.rice)
# def get_beans(self):
# return (self.beans)
# def get_extra_meat(self):
# return(self.extra_meat)
# def get_guacamole(self):
# return(self.guacamole)
# def get_cheese(self):
# return(self.cheese)
# def get_pico(self):
# return (self.pico)
# def get_corn(self):
# return (self.corn)
# # Feel free to add code below to test out the class that
# # you've written. It won't be used for grading.
# def get_cost(self):
# base_cost = 5.0
# if self.get_meat() in ["chicken", "pork", "tofu"]:
# base_cost += 1.0
# elif self.get_meat() == "steak":
# base_cost += 1.5
# if self.get_extra_meat() == True:
# base_cost += 1.0
# if self.get_guacamole() == True:
# base_cost += 0.76
# return (base_cost)
# # print: 7.75
# a_burrito = Burrito("pork", False, "white", "black", extra_meat=True, guacamole=True)
# print(a_burrito.get_cost())
# Un-Comment to here
#########################################
################################################################################################################
# 5.1.11
# Copy your Burrito class from the last exercise. Below,
# We've given you three additional classes named "Meat",
#"Rice" and "Beans." We've gone ahead and built getters
# and setters in these classes to check if the incoming
# values are valid, so you'll be able to remove those
# from your original code.
#
# First, edit the constructor of your Burrito class.
# Instead of calling setters to set the values of the
# attributes self.meat, self.rice, and self.beans, it
# should instead create new instances of Meat, Rice, and
# Beans. The arguments to these new instances should be
# the same as the arguments you were sending to the
# setters previously (e.g. self.rice = Rice("brown")
# instead of set_rice("brown")).
#
# Second, modify your getters and setters from your
# original code so that they still return the same value
# as before. get_rice(), for example, should still
# return "brown" for brown rice, False for no rice, etc.
# instead of returning the instance of Rice.
#
# Third, make sure that your get_cost function still
# works when you're done changing your code.
#
# Hint: When you're done, creating a new instance of
# Burrito with Burrito("pork", True, "brown", "pinto")
# should still work to create a new Burrito. The only
# thing changing is the internal reasoning of the
# Burrito class.
#
# Hint 2: Notice that the classes Meat, Beans, and Rice
# already contain the code to validate whether input is
# valid. So, your setters in the Burrito class no
# longer need to worry about that -- they can just pass
# their input to the set_value() methods for those
# classes.
#
# Hint 3: This exercise requires very little actual
# coding: you'll only write nine lines of new code, and
# those nine lines all replace existing lines of code
# in the constructor, getters, and setters of Burrito.
#
# You should not need to modify the code below.
# un-Comment from here
class Meat:
def __init__(self, value=False):
self.set_value(value)
def get_value(self):
return self.value
def set_value(self, value):
if value in ["chicken", "pork", "steak", "tofu"]:
self.value = value
else:
self.value = False
class Rice:
def __init__(self, value=False):
self.set_value(value)
def get_value(self):
return self.value
def set_value(self, value):
if value in ["brown", "white"]:
self.value = value
else:
self.value = False
class Beans:
def __init__(self, value=False):
self.set_value(value)
def get_value(self):
return self.value
def set_value(self, value):
if value in ["black", "pinto"]:
self.value = value
else:
self.value = False
# Add and modify your code here!
class Burrito(object):
"""docstring for Burrito"""
def __init__(self, meat, to_go, rice, beans, extra_meat=False, guacamole=False, cheese=False, pico=False, Corn=False):
self.set_meat(meat)
self.set_to_go(to_go)
self.set_rice(rice)
self.set_beans(beans)
self.set_extra_meat(extra_meat)
self.set_guacamole(guacamole)
self.set_cheese(cheese)
self.set_pico(pico)
self.set_corn(Corn)
def set_meat(self, meat):
# if meat in ["chicken", "pork", "steak", "tofu"]:
# self.meat = meat
# else:
# self.meat = False
meat_inst = Meat(meat)
def set_to_go(self, to_go):
if type(to_go) == bool:
self.to_go = to_go
else:
self.to_go = False
def set_rice(self, rice):
# if rice in ["brown", "white"]:
# self.rice = rice
rice_inst = Rice(rice)
def set_beans(self, beans):
# if beans in ["black", "pinto"]:
# self.beans = beans
beans_inst = Beans()
beans_inst.set_value(beans)
# 5.1.8
# Write a class called "Burrito". A Burrito should have the
# following attributes (instance variables):
#
# - meat
# - to_go
# - rice
# - beans
# - extra_meat (default: False)
# - guacamole (default: False)
# - cheese (default: False)
# - pico (default: False)
# - corn (default: False)
#
# The constructor should let any of these attributes be
# changed when the object is instantiated. The attributes
# with a default value should be optional. Both positional
# and keyword attributes should be in the order shown above
#(for the autograder to work).
# Write your code here!
##############################################
# un-Comment From here
# class Burrito(object):
# """docstring for Burrito"""
# def __init__(self, meat, to_go, rice, beans, extra_meat=False, guacamole=False, cheese=False, pico=False, Corn=False):
# self.meat = meat
# self.to_go = to_go
# self.rice = rice
# self.beans = beans
# self.extra_meat = extra_meat
# self.guacamole = guacamole
# self.cheese = cheese
# self.pico = pico
# self.corn = Corn
# # The code below will test your class. If it is written
# # correctly, this will print True, then False. Note,
# # though, that we'll test your code against more complex
# # test cases when you submit.
# newBurrito = Burrito("Tofu", True, True, True)
# print(newBurrito.to_go)
# print(newBurrito.guacamole)
# un-Comment to here
###################################################
#################################################################################################################################
# 5.19
# Copy your Burrito class from the last exercise. Now,
# write a getter and a setter method for each attribute.
# Each setter should accept a value as an argument. If the
# value is a valid value, it should set the corresponding
# attribute to the given value. Otherwise, it should set the
# attribute to False.
#
# Edit the constructor to use these new setters and getters.
# In other words, if we were to call:
#
# new_burrito = Burrito("spaghetti", True, True, False)
#
# new_burrito.meat would be False because "spaghetti" is not
# one of the valid options. Note that you should NOT try to
# check if the new value is valid in both the constructor and
# the setter: instead, just call the setter from the
# constructor using something like self.set_meat(meat).
#
# Valid values for each setter are as follows:
#
# - set_meat: "chicken", "pork", "steak", "tofu", False
# - set_to_go: True, False
# - set_rice: "brown", "white", False
# - set_beans: "black", "pinto", False
# - set_extra_meat: True, False
# - set_guacamole: True, False
# - set_cheese: True, False
# - set_pico: True, False
# - set_corn: True, False
#
# Make sure you name each setter with the format:
#"set_some_attribute" and "get_some_attribute"
#
# For example, the getter for meat would be get_meat. The
# getter for to_go would be get_to_go.
#
# Hint: Your code is going to end up *very* long. This
# will be the longest program you've written so far, but
# it isn't the most complex. Complexity and length are
# often very different!
#
# Hint 2: Checking for valid values will be much easier
# if you make a list of valid values for each attribute
# and check the new value against that.
# Write your code here!
##############################################
# Uncomment from Here
# class Burrito(object):
# """docstring for Burrito"""
# def __init__(self, meat, to_go, rice, beans, extra_meat=False, guacamole=False, cheese=False, pico=False, Corn=False):
# self.set_meat(meat)
# self.set_to_go(to_go)
# self.set_rice(rice)
# self.set_beans(beans)
# self.set_extra_meat(extra_meat)
# self.set_guacamole(guacamole)
# self.set_cheese(cheese)
# self.set_pico(pico)
# self.set_corn(Corn)
# def set_meat(self, meat):
# if meat in ["chicken", "pork", "steak", "tofu"]:
# self.meat = meat
# else:
# self.meat = False
# def set_to_go(self, to_go):
# if type(to_go) == bool:
# self.to_go = to_go
# else:
# self.to_go = False
# def set_rice(self, rice):
# if rice in ["brown", "white"]:
# self.rice = rice
# def set_beans(self, beans):
# if beans in ["black", "pinto"]:
# self.beans = beans
# def set_extra_meat(self, extra_meat):
# if type(extra_meat) == bool:
# self.extra_meat = extra_meat
# else:
# self.extra_meat = False
# def set_guacamole(self, guacamole):
# if type(guacamole) == bool:
# self.guacamole = guacamole
# else:
# self.guacamole = guacamole
# def set_cheese(self, cheese):
# if type(cheese) == bool:
# self.cheese = cheese
# def set_pico(self, pico):
# if type(pico) == bool:
# self.pico = pico
# def set_corn(self, corn):
# if type(corn) == bool:
# self.corn = corn
# else:
# self.corn = False
# def get_meat(self):
# return (self.meat)
# def get_to_go(self):
# return (self.to_go)
# def get_rice(self):
# return (self.rice)
# def get_beans(self):
# return (self.beans)
# def get_extra_meat(self):
# return(self.extra_meat)
# def get_guacamole(self):
# return(self.guacamole)
# def get_cheese(self):
# return(self.cheese)
# def get_pico(self):
# return (self.pico)
# def get_corn(self):
# return (self.corn)
# # Feel free to add code below to test out the class that
# # you've written. It won't be used for grading.
# def get_cost(self):
# base_cost = 5.0
# if self.get_meat() in ["chicken", "pork", "tofu"]:
# base_cost += 1.0
# elif self.get_meat() == "steak":
# base_cost += 1.5
# if self.get_extra_meat() == True:
# base_cost += 1.0
# if self.get_guacamole() == True:
# base_cost += 0.76
# return (base_cost)
# # print: 7.75
# a_burrito = Burrito("pork", False, "white", "black", extra_meat=True, guacamole=True)
# print(a_burrito.get_cost())
# Un-Comment to here
#########################################
################################################################################################################
# 5.1.11
# Copy your Burrito class from the last exercise. Below,
# We've given you three additional classes named "Meat",
#"Rice" and "Beans." We've gone ahead and built getters
# and setters in these classes to check if the incoming
# values are valid, so you'll be able to remove those
# from your original code.
#
# First, edit the constructor of your Burrito class.
# Instead of calling setters to set the values of the
# attributes self.meat, self.rice, and self.beans, it
# should instead create new instances of Meat, Rice, and
# Beans. The arguments to these new instances should be
# the same as the arguments you were sending to the
# setters previously (e.g. self.rice = Rice("brown")
# instead of set_rice("brown")).
#
# Second, modify your getters and setters from your
# original code so that they still return the same value
# as before. get_rice(), for example, should still
# return "brown" for brown rice, False for no rice, etc.
# instead of returning the instance of Rice.
#
# Third, make sure that your get_cost function still
# works when you're done changing your code.
#
# Hint: When you're done, creating a new instance of
# Burrito with Burrito("pork", True, "brown", "pinto")
# should still work to create a new Burrito. The only
# thing changing is the internal reasoning of the
# Burrito class.
#
# Hint 2: Notice that the classes Meat, Beans, and Rice
# already contain the code to validate whether input is
# valid. So, your setters in the Burrito class no
# longer need to worry about that -- they can just pass
# their input to the set_value() methods for those
# classes.
#
# Hint 3: This exercise requires very little actual
# coding: you'll only write nine lines of new code, and
# those nine lines all replace existing lines of code
# in the constructor, getters, and setters of Burrito.
#
# You should not need to modify the code below.
# un-Comment from here
class Meat:
def __init__(self, value=False):
self.set_value(value)
def get_value(self):
return self.value
def set_value(self, value):
if value in ["chicken", "pork", "steak", "tofu"]:
self.value = value
else:
self.value = False
class Rice:
def __init__(self, value=False):
self.set_value(value)
def get_value(self):
return self.value
def set_value(self, value):
if value in ["brown", "white"]:
self.value = value
else:
self.value = False
class Beans:
def __init__(self, value=False):
self.set_value(value)
def get_value(self):
return self.value
def set_value(self, value):
if value in ["black", "pinto"]:
self.value = value
else:
self.value = False
# Add and modify your code here!
class Burrito(object):
"""docstring for Burrito"""
def __init__(self, meat, to_go, rice, beans, extra_meat=False, guacamole=False, cheese=False, pico=False, Corn=False):
self.meat = Meat(meat)
self.set_to_go(to_go)
self.rice = Rice(rice)
self.beans = Beans(beans)
self.set_extra_meat(extra_meat)
self.set_guacamole(guacamole)
self.set_cheese(cheese)
self.set_pico(pico)
self.set_corn(Corn)
# def set_meat(self, meat):
# # if meat in ["chicken", "pork", "steak", "tofu"]:
# # self.meat = meat
# # else:
# # self.meat = False
# meat_inst = Meat(meat)
def set_to_go(self, to_go):
if type(to_go) == bool:
self.to_go = to_go
else:
self.to_go = False
# def set_rice(self, rice):
# # if rice in ["brown", "white"]:
# # self.rice = rice
# rice_inst = Rice(rice)
# def set_beans(self, beans):
# # if beans in ["black", "pinto"]:
# # self.beans = beans
# beans_inst = Beans(beans)
def set_extra_meat(self, extra_meat):
if type(extra_meat) == bool:
self.extra_meat = extra_meat
else:
self.extra_meat = False
def set_guacamole(self, guacamole):
if type(guacamole) == bool:
self.guacamole = guacamole
else:
self.guacamole = guacamole
def set_cheese(self, cheese):
if type(cheese) == bool:
self.cheese = cheese
def set_pico(self, pico):
if type(pico) == bool:
self.pico = pico
def set_corn(self, corn):
if type(corn) == bool:
self.corn = corn
else:
self.corn = False
def get_meat(self):
# meat_inst.get_value()
return (self.meat.get_value())
def get_to_go(self):
return (self.to_go)
def get_rice(self):
return (self.rice.get_value())
def get_beans(self):
return (self.beans.get_value())
def get_extra_meat(self):
return(self.extra_meat)
def get_guacamole(self):
return(self.guacamole)
def get_cheese(self):
return(self.cheese)
def get_pico(self):
return (self.pico)
def get_corn(self):
return (self.corn)
# Feel free to add code below to test out the class that
# you've written. It won't be used for grading.
def get_cost(self):
base_cost = 5.0
if self.get_meat() in ["chicken", "pork", "tofu"]:
base_cost += 1.0
elif self.get_meat() == "steak":
base_cost += 1.5
if self.get_extra_meat() == True:
base_cost += 1.0
if self.get_guacamole() == True:
base_cost += 0.75
return (base_cost)
# Below are some lines of code that will test your class.
# You can change the value of the variable(s) to test your
# class with different inputs. Remember though, the results
# of this code should be the same as the previous problem:
# what should be different is how it works behind the scenes.
#
# If your function works correctly, this will originally
# print: 7.75
a_burrito = Burrito("pork", False, "white", "black", extra_meat=True, guacamole=True)
print(a_burrito.get_cost())
# In this exercise, you won't edit any of your code from the
# Burrito class. Instead, you're just going to write a
# function to use instances of the Burrito class. You don't
# actually have to copy/paste your previous code here if you
# don't want to, although you'll need to if you want to write
# some test code at the bottom.
#
# Write a function called total_cost. total_cost should take
# as input a list of instances of Burrito, and return the
# total cost of all those burritos together as a float.
#
# Hint: Don't reinvent the wheel. Use the work that you've
# already done. The function can be written in only five
# lines, including the function declaration.
#
# Hint 2: The exercise here is to write a function, not a
# method. That means this function should *not* be part of
# the Burrito class.
# If you'd like to use the test code, paste your previous
# code here.
# Write your new function here.
def total_cost(multiple_burritos=[]):
Final_Cost = 0
for every_burrito in multiple_burritos:
Final_Cost += every_burrito.get_cost()
return(Final_Cost)
# Below are some lines of code that will test your function.
# You can change the value of the variable(s) to test your
# function with different inputs. Note that these lines
# will ONLY work if you copy/paste your Burrito, Meat,
# Beans, and Rice classes in.
#
# If your function works correctly, this will originally
# print: 27.0
burrito_1 = Burrito("tofu", True, "white", "black")
burrito_2 = Burrito("steak", True, "white", "pinto", extra_meat=True)
burrito_3 = Burrito("pork", True, "brown", "black", guacamole=True)
burrito_4 = Burrito("chicken", True, "brown", "pinto", extra_meat=True, guacamole=True)
burrito_list = [burrito_1, burrito_2, burrito_3, burrito_4]
print(total_cost(burrito_list))
|
81f23f2664a5deddc6c5ad3b2fa1b4c1821308e8 | kinzakasher/code-literacy | /Week2/story-sample.py | 1,673 | 4.34375 | 4 | # let the user know what's going on
print ("A Trip To The Beach!")
print ("Answer the questions below to play.")
print ("-----------------------------------")
# variables containing all of your story info
name1 = raw_input("Enter your name: ")
name2 = raw_input("Enter your friend's name: ")
adjective1 = raw_input("Enter an adjective: ")
food = raw_input("Your favorite food: ")
liquid = raw_input("Your favorite drink: ")
adjective2 = raw_input("Enter another adjective: ")
animal = raw_input("Your favorite animal: ")
adjective3 = raw_input("Enter one more adjective: ")
verb = raw_input("Enter a verb: ")
pluralnoun = raw_input("Name a pair of things you would buy at the beach: ")
food2 = raw_input("Your favorite fish food: ")
verb2 = raw_input("Enter a verb: ")
noun = raw_input("Enter a noun: ")
# this is the story. it is made up of strings and variables.
story = "One day, " + name1 + " and " + name2 + " decided to take a trip to the beach. " + name1 + " packed a bag full of " + adjective1 + " " + food + " " \
" and a big jug of " + liquid + ". " + name2 + " brought a towel that had a picture of a " + adjective2 + " " + animal + " on it." \
"The beach was crowded but there were a few " + adjective3 + " spots left. " + name1 + " and " + name2 + " wanted to learn how to " + verb + " " \
"so they rented a pair of " + pluralnoun + " and hopped into the water. " \
" Soon it was time for more snack so " + name1 + " went to a stand to buy fish " + food2 + ". " \
"The sun was " + verb2 + " and eventually the tide came too close so " + name1 + " and " + name2 + " packed their" \
" " + noun + " and went home. "
# finally we print the story
print (story)
|
35fdca75d02c9fdf8e26751a1364599a88c700ff | muratcavus/anagrams | /anagram_process.py | 1,576 | 4.0625 | 4 |
def get_word_list_from_file():
input_file = open('sample.txt', 'r')
word_list = input_file.read().splitlines()
input_file.close()
return word_list
def is_anagram(len_of_word1, sorted_word1, word2):
return len_of_word1 == len(word2) and sorted_word1 == sorted(word2)
def end_of(word_list):
return len(word_list) > 1
def get_first_word(word_list):
return word_list[0]
def get_anagram_list_for_word(word1, word_list):
sorted_word1 = sorted(word1)
len_of_word1 = len(word1)
anagram_list = []
i = 0
while len(word_list) > i:
word2 = word_list[i]
i += 1
if is_anagram(len_of_word1, sorted_word1, word2):
anagram_list.append(word2)
word_list.remove(word2)
i -= 1
return anagram_list
def print_anagram_list_for_word(anagram_list, word1):
if len(anagram_list) > 0:
anagram_list.insert(0, word1)
print(anagram_list)
anagram_list.clear()
def main():
word_list = get_word_list_from_file()
while end_of(word_list):
word1 = get_first_word(word_list)
word_list.remove(word1)
anagram_list = get_anagram_list_for_word(word1, word_list)
print_anagram_list_for_word(anagram_list, word1)
#get first element from word list and remove it from word list
#search word list one by one if it have any anagram macthes
#get matched word from word list and remove it from word list
#then add it anagram list, collect anagramlist while end of the word list
#and print anagram list to screen
main()
|
1e515107948be336a0332085be6629fcd672403a | LogankumarR/Logankumar | /OOPS/matrix.py | 578 | 3.609375 | 4 | class matrix():
def __init__(self,row,col):
self.row = m1
self.col = l1
self.matrix = []
def buildmatrix(self):
for col_idx in range(0,self.col):
temp_row = []
for row_idx in range (0,self.row):
ele = eval(input("enter a number in matrix col_num:" + str(col_idx)+ "row:"+str(row_idx))
temp_row.append(temp_row)
self.matrix.append(temp_row)
def prin(self):
print(self.matrix)
def main():
m1 = matrix(2,2)
m1.buildmatrix()
m1.prin()
main() |
0689eabb1ac0a00025ad1c4071e34db8c1295109 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/dsrkir001/boxes.py | 846 | 3.765625 | 4 | def print_square():
for i in range(5):
for j in range(5):
if (i==0 or i==4 or j==0 or j==4):
print("*",end='')
else:
print(" ",end='')
print()
def print_rectangle(wide,height):
for i in range(height):
for j in range(wide):
if (i==0 or i==(height-1) or j==0 or j==(wide-1)):
print("*",end='')
else:
print(" ",end='')
print()
def get_rectangle(wide,height):
a=""
for i in range(height):
for j in range(wide):
if (i==0 or i==(height-1) or j==0 or j==(wide-1)):
a+="*"
else:
a+=" "
a+="\n"
return a |
79c5cde4d08b3daf27e7e29b02150f828d07da9e | ayeshamujtaba/ICTPRG-Python | /stringwithinnotin.py | 415 | 3.953125 | 4 | string1 = 'one two three four five'
if 'four' in string1:
print("Found" + " four" + " in " + string1)
else:
print("The string four was not found")
print()
s1 = "123"
#Is it a digit
print(s1.isdigit())
#Is it a alpha numeric
print (s1.isalnum())
#Does it have space
print (s1.isspace())
#Is it upper case
print (s1.isupper())
#Is lower case
print (s1.islower())
#Split
print(s1.split())
|
91779ce7a83aae2f4da7e70bd6efbca664dd5833 | cmh1027/jugallersimulation | /matgoscore.py | 2,189 | 4.09375 | 4 | """
Calculate the player and computer's Score. And also when the game ends, it calcuates magnification
"""
# Calculate the player and computer's Score. And also when the game ends, it calcuates magnification
class Score:
def __init__(self, obj):
self.__obj=obj
def result(self):
score=0
if len(self.__obj.godori)==3:
score +=5
if len(self.__obj.godori)+len(self.__obj.animal)>=5:
score+=len(self.__obj.godori)+len(self.__obj.animal)-4
if len(self.__obj.reddan)==3:
score +=3
if len(self.__obj.bluedan)==3:
score +=3
if len(self.__obj.chodan)==3:
score +=3
if len(self.__obj.reddan)+len(self.__obj.bluedan)+len(self.__obj.chodan)+len(self.__obj.dan)>=5:
score += len(self.__obj.reddan)+len(self.__obj.bluedan)+len(self.__obj.chodan)+len(self.__obj.dan)-4
if len(self.__obj.beegwang)==1:
if len(self.__obj.beegwang)+len(self.__obj.gwang)==3:
score +=2
if len(self.__obj.beegwang)==0:
if len(self.__obj.gwang)==3:
score +=3
if len(self.__obj.beegwang)+len(self.__obj.gwang)==4:
score += 4
if len(self.__obj.beegwang)+len(self.__obj.gwang)==5:
score += 15
if len(self.__obj.pee)+2*len(self.__obj.doublepee)>=10:
score += len(self.__obj.pee)+2*len(self.__obj.doublepee)-9
return score
def result_end(self):
if self.__obj.go_display<=2:
return self.__obj.score+self.__obj.go_display
else:
return (self.__obj.score+2)*2**(self.__obj.go_display-2)
def multiple(self, enemyobj):
multiple=1
multiple_arr = []
if len(self.__obj.animal)+len(self.__obj.godori)>=7:
multiple=multiple*2
multiple_arr.append("멍따")
if len(self.__obj.gwang)+len(self.__obj.beegwang)>=3 and len(enemyobj.gwang)+len(enemyobj.beegwang)==0:
multiple=multiple*2
multiple_arr.append("광박")
if len(self.__obj.pee)+2*len(self.__obj.doublepee)>=10 and len(enemyobj.pee)+2*len(enemyobj.doublepee)<=7:
multiple=multiple*2
multiple_arr.append("피박")
if self.__obj.go_display>=0 and enemyobj.go_display>=1:
multiple=multiple*2
multiple=multiple*2**self.__obj.shake_display
if self.__obj.shake_display>0:
multiple_arr.append(str(self.__obj.shake_display)+"번 흔듦")
return (multiple,multiple_arr) |
d524f0efa90923ab587e554bfec88e5cbb2e4733 | daedalus/math | /sqrttest.py | 831 | 4.03125 | 4 | #!/usr/bin/env python
#
# Author Dario Clavijo 2015
# GPLv3
# implementation acording to whikipedia: https://es.wikipedia.org/wiki/C%C3%A1lculo_de_la_ra%C3%ADz_cuadrada
def sqrt(x):
r = x
t = 0
while t != r:
t = r
r = 0.5 * (x / r + r)
return r
# given the x**2-2=0 condition we bruteforce an aproximation to sqrt(2)
def sqrttest():
target = 2.0
x = 2.0
error = 1
step = 0.5
lower_error = 1
i = 0
c = 0
last_aprox = None
while error != 0:
i = i + 1
error = (x ** target) - target
x = x - (error * step)
if error < lower_error:
lower_error = abs(error)
print "Count: %d, Aprox: %s, Error: %s, LowerError: %s" % (
i,
x,
error,
lower_error,
)
sqrttest()
|
95366c674ffe0a032a7c947d4c4f59b11a8d883f | vitorsergiota/Python | /ex7.py | 123 | 3.921875 | 4 | # Nome e apelido
nome = str(input("Coloque seu nome: "))
apel = str(input("Coloque seu apelido "))
print (nome ,",", apel)
|
790958df3834bbd45218d3a8fa0f8ea633c3be0a | ZhangJiaQ/everything | /Python/Algorithm/LintCode/32. Minimum Window Substring.py | 1,942 | 3.890625 | 4 | """
32. 最小子串覆盖
中文English
给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的最短子串。
Example
例1:
输入:
""
""
输出:
""
例2:
输入:
"ADOBECODEBANC"
"ABC"
输出:
"BANC"
Challenge
要求时间复杂度为O(n)
Clarification
在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。
Noti
"""
class Solution:
"""
@param source : A string
@param target: A string
@return: A string denote the minimum window, return "" if there is no such a string
"""
def minWindow(self, source , target):
# write your code here
"""
使用collection.Counter()对target计数
然后双指针
右指针向右移动,直到满足子串长度要求
满足后左指针向右移动,直到不满足子串长度停止
在左指针移动时不停的更新最小长度与子串
"""
result = ""
left, tarLen, minLen = 0, 0, float('INF')
from collections import Counter
counter_target = Counter(target)
for index, value in enumerate(source):
counter_target[value] -= 1
if counter_target[value] >= 0:
tarLen += 1
while tarLen == len(target):
# 计算当前符合的子串长度
if minLen > index - left + 1:
minLen = index - left + 1
result = source[left: index+1]
# 判断Counter 将数据返回给Counter内的元素
counter_target[source[left]] += 1
if counter_target[source[left]] > 0:
# 目前子串不符合target,停止遍历
tarLen -= 1
left += 1
return result |
fa213d63095ea5678d591b3a5974bcd79321af37 | seema-sathyanarayana/Machine-Learning-Projects | /Lead_Scoring/Lead_Scoring_Case_Study.py | 30,176 | 3.984375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Lead Scoring Case Study
# ### Submitted By - Seema S B
# Problem Statement:
# 1. To build a model to find out the leads that are most likely to convert into paying customers.
# 2. To find the conversion rate of customers based on scoring of the leads.
# Solution Approach:
#
# The following approach has been carried out to arrive at the solution for the given problem:
# 1. Data Understanding
# 2. Data Cleaning
# 3. Data Visualization
# 4. Data Preparation
# 5. Modelling
# ### Data Understanding
# #### Import packages
# In[1]:
# Importing the required packages
import warnings
warnings.filterwarnings('ignore')
from math import log
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import seaborn as sns
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 250)
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import RFE
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn import metrics
from sklearn.metrics import precision_recall_curve
# #### Reading the Data
# In[2]:
# Reading the data from the given csv file
lead_df = pd.read_csv('Leads.csv')
# In[3]:
# Viewing the Data
lead_df.head()
# #### Shape of the dataframe
# In[4]:
# Finding out the no.of rows and columns in the dataset
initial = lead_df.shape
initial
# **Information of the dataframe**
# In[5]:
# To understand the datatypes of each columns and non-null records
lead_df.info()
# We could see that there are many columns which has got `null` values. Also there are various types of columns like `float`, `int64` and `categoricals`.
# ### Data Cleaning
# **Null percentage of columns**
# In[6]:
# Finding out the percentage of null records in each column
round(lead_df.isnull().sum()/len(lead_df) * 100, 2)
# The columns `'Lead Quality', 'Asymmetrique Activity Index', 'Asymmetrique Profile Index', 'Asymmetrique Activity Score', 'Asymmetrique Profile Score', 'Tags'` has the maximum percentage of null values in them, so it is better to drop these
# **Dropping the columns with high null percentage**
# In[7]:
# Dropping columns having more null values
lead_df.drop(['Lead Quality', 'Asymmetrique Activity Index', 'Asymmetrique Profile Index', 'Asymmetrique Activity Score',
'Asymmetrique Profile Score', 'Tags'], inplace=True, axis=1)
# **Value Counts of all the columns**
# In[8]:
# Finding the value counts for each columns
for col in lead_df:
if lead_df[col].dtype == 'O':
print(round(lead_df[col].value_counts()/len(lead_df) * 100, 2))
print('=====================================')
# Based on the value counts in each columns, we can infer and perform the below steps:
# 1. The column `Country` has the values mostly as 'India' and also there are null values too. So we should drop this column. The same applies for the column `City`, so dropping it as well
# 2. The columns `'Do Not Email', 'Do Not Call', 'Search', 'Magazine', 'Newspaper Article', 'X Education Forums', 'Newspaper', 'Digital Advertisement', 'Through Recommendations', 'Receive More Updates About Our Courses', 'Update me on Supply Chain Content', 'Get updates on DM Content', 'I agree to pay the amount through cheque'` are highly Skewed so dropping them
# 3. The column `What matters most to you in choosing a course` appears to be highly skewed towards the value `Better Career Prospects`, so it is better to drop the column
# 4. There are various categorical columns which has got the value `Select` as one of its level because it gets populated as default if no other option has been selected by the customer. So this is equivalent to null values
# 5. The columns `Lead Profile` and `How did you hear about X Education` has large number of `Select` which is equivalent to higher null percentage so dropping those columns
# 6. We can drop rows having null values in more than `five` coulmns as it will not impact the target variable
# 7. Though the column `What is your current occupation` has a high number of null records, it is advisable not to drop it because the enrollment of customers to an education platform may be highly impacted based on their occupation or field of work. So only the null records could be dropped while the column is retained
# **Dropping the columns which doesn't add any information to the data**
# In[9]:
# Dropping columns which doesn't add any information on the dataset
lead_df.drop(['Country', 'City'], axis=1, inplace=True)
round(lead_df.isnull().sum()/len(lead_df) * 100, 2)
# **Dropping the Highly Skewed Columns**
# In[10]:
# Dropping the Highly skewed columns
lead_df.drop(['Do Not Email', 'Do Not Call', 'Search', 'Magazine', 'Newspaper Article', 'X Education Forums', 'Newspaper',
'Digital Advertisement', 'Through Recommendations', 'Receive More Updates About Our Courses',
'Update me on Supply Chain Content', 'Get updates on DM Content', 'I agree to pay the amount through cheque',
'What matters most to you in choosing a course'],
axis=1, inplace=True)
# **Imputing `Select` with `np.nan`**
# In[11]:
# Replacing all the 'Select' values in the dataframe with NULL
lead_df.replace('Select', np.nan, inplace=True)
# **Dropping the columns with high null percentage**
# In[12]:
# Dropping columns with higher null percentage
lead_df.drop(['Lead Profile', 'How did you hear about X Education'], axis=1, inplace=True)
# **Dropping rows having more than five null values**
# In[13]:
# Dropping rows with >5 null values
lead_df.dropna(thresh=lead_df.shape[1]-5, inplace=True)
# **Dropping only null records from potential predictor variable**
# In[14]:
# Dropping only null records instead of the column
lead_df = lead_df[~lead_df['What is your current occupation'].isnull()]
# **Shape and Null Percentage of Columns**
# In[15]:
# Shape of the dataframe
lead_df.shape
# In[16]:
# Null Percentage in coulmns
round(lead_df.isnull().sum()/len(lead_df) * 100, 2)
# **Handling NULL Values in Categorical Columns**
# 1. In column `Lead Source`, the values having its count less than `1.0` are all combined under `Others` as they are less in percentage. The null values are handled by assigning them to `Others`
# 2. In column `Last Activity`, the values having its count less than `1.0` are all combined under `Others` as they are less in percentage. The null values are handled by assigning them to `Others`
# 3. In column `Specialization`, the null values are handled by replacing(imputing) them with `Others`
# In[17]:
# Handling nulls in Lead Source column
def combine(x):
if x in ('Google','Direct Traffic','Olark Chat', 'Organic Search', 'Reference', 'Welingak Website', 'Referral Sites'):
return x
else:
return 'Others'
lead_df['Lead Source'].replace('google', 'Google', inplace=True)
lead_df['Lead Source'] = lead_df['Lead Source'].apply(combine)
round(lead_df['Lead Source'].value_counts()/len(lead_df) * 100, 2)
# In[18]:
# Handling nulls in Last Activity column
def combine(x):
if x in ('Email Opened','SMS Sent','Olark Chat Conversation','Page Visited on Website','Converted to Lead','Email Bounced',
'Email Link Clicked','Form Submitted on Website','Unreachable'):
return x
else:
return 'Others'
lead_df['Last Activity'] = lead_df['Last Activity'].apply(combine)
round(lead_df['Last Activity'].value_counts()/len(lead_df) * 100, 2)
# In[19]:
# Handling nulls in Specialization column
lead_df['Specialization'].replace(np.nan, 'Others', inplace=True)
round(lead_df['Specialization'].value_counts()/len(lead_df) * 100, 2)
# **Shape and Null Percentage of Columns**
# In[20]:
lead_df.shape
# In[21]:
round(lead_df.isnull().sum()/len(lead_df)*100, 2)
# **Mapping 'Yes' and 'No' to 1 and 0 respectively in column `'A free copy of Mastering The Interview'`**
# In[22]:
# Converting the binomial categorical column to numerical
lead_df['A free copy of Mastering The Interview'] = lead_df['A free copy of Mastering The Interview'].map({'Yes': 1, 'No': 0})
# **Handling NULL Values in numerical variables**
# In[23]:
# Imputing the null values in Total Visits column with its median value
lead_df['TotalVisits'].replace(np.nan, lead_df['TotalVisits'].median(), inplace=True)
# Imputing the null values in Page Views Per Visit column with its median value
lead_df['Page Views Per Visit'].replace(np.nan, lead_df['Page Views Per Visit'].median(), inplace=True)
# In[24]:
# Dropping the unique id column too
lead_df.drop('Prospect ID', axis=1, inplace=True)
# **NULL Percentage after Data Cleaning**
# In[25]:
# Percentage of null values left after data cleaning
round(lead_df.isnull().sum()/len(lead_df)*100, 2)
# All the columns are now non-null
# In[26]:
# Viewing the top five rows
lead_df.head()
# In[27]:
# Shape of the dataframe
lead_df.shape
# In[28]:
# Information on the columns
lead_df.info()
# **Percentage of data retained**
# In[29]:
# The percentage of data retained from the initial dataset
len(lead_df)/initial[0]*100
# - We have 70.88% of rows which is quite enough for analysis
# ### Data Visualization
# #### Univariate Analysis
# In[30]:
# Plotting the numerical variables
plt.figure(figsize=(14,10))
plt.subplot(2,3,1)
sns.boxplot(lead_df['Total Time Spent on Website'])
plt.subplot(2,3,2)
sns.boxplot(lead_df['TotalVisits'])
plt.subplot(2,3,3)
sns.boxplot(lead_df['Page Views Per Visit'])
plt.show()
# The columns `TotalVisits` and `Page Views Per Visit` have outliers in it and needs to be treated
# **Handling the Outliers**
# In[31]:
# Capping the outliers to its 99th quantile value in Total Visits column
quant = lead_df['TotalVisits'].quantile([0.99])
lead_df['TotalVisits'] = np.clip(lead_df['TotalVisits'],
lead_df['TotalVisits'].quantile([0.01,0.99][0]),
lead_df['TotalVisits'].quantile([0.01,0.99][1]))
# In[32]:
sns.boxplot(lead_df['TotalVisits'])
# In[33]:
# Capping the outliers to its 99th quantile value in Page Views Per Visit column
quant = lead_df['Page Views Per Visit'].quantile([0.99])
lead_df['Page Views Per Visit'] = np.clip(lead_df['Page Views Per Visit'],
lead_df['Page Views Per Visit'].quantile([0.01,0.99][0]),
lead_df['Page Views Per Visit'].quantile([0.01,0.99][1]))
# In[34]:
sns.boxplot(lead_df['Page Views Per Visit'])
# In[35]:
# Correlation Matrix - Heatmap
sns.heatmap(lead_df.corr(), annot=True)
# From the heat map we can see that the columns `TotalVisits` and `Page Views Per Visit` are highly correlated.
# ### Data Preparation
# #### Dummy Variables Creation for Categorical variables
# In[36]:
# Creating dummy variables for the column Lead Origin
Lead_Origin = pd.get_dummies(lead_df['Lead Origin'], drop_first=True)
Lead_Origin.head()
# In[37]:
# Creating dummy variables for the column Lead Source
Lead_Source = pd.get_dummies(lead_df['Lead Source'])
Lead_Source.drop('Others', axis=1, inplace=True)
Lead_Source.head()
# In[38]:
# Creating dummy variables for the column Lead Activity
Last_Activity = pd.get_dummies(lead_df['Last Activity'], prefix='Last')
Last_Activity.drop('Last_Others', axis=1, inplace=True)
Last_Activity.head()
# In[39]:
# Creating dummy variables for the column Specialization
Specialization = pd.get_dummies(lead_df['Specialization'])
Specialization.drop('Others', axis=1, inplace=True)
Specialization.head()
# In[40]:
# Creating dummy variables for the column 'What is your current occupation'
occupation = pd.get_dummies(lead_df['What is your current occupation'])
occupation.drop('Other', axis=1, inplace=True)
occupation.head()
# In[41]:
# Creating dummy variables for the column 'Last Notable Activity'
activity = pd.get_dummies(lead_df['Last Notable Activity'])
activity.drop('Unsubscribed', axis=1, inplace=True)
activity.head()
# In[42]:
# Concatenating all the dummy variables created to the main dataframe
leads = pd.concat([lead_df,Lead_Origin,Lead_Source,occupation,Last_Activity,Specialization,activity], axis=1)
leads.head()
# In[43]:
# Dropping off the original columns
leads.drop(['Lead Origin','Lead Source','What is your current occupation','Last Activity','Specialization'
,'Last Notable Activity'], axis=1, inplace=True)
leads.head()
# In[44]:
# Number of rows and columns
leads.shape
# **Correlation Matrix [HeatMap]**
# In[45]:
# Plotting the correlation matrix for the dataset
plt.figure(figsize=(44,40))
sns.heatmap(round(leads.corr(),2), annot=True)
# In[46]:
# Top 10 highly correlated variables
leads.corr().unstack().sort_values(ascending=False).drop_duplicates().head(10)
# In[47]:
# Top 10 inversely correlated variables
leads.corr().unstack().sort_values(ascending=True).drop_duplicates().head(10)
# #### Train test split and scaling of data
# In[48]:
# Splitting the dataframe into train and test
np.random.seed(0)
df_train, df_test = train_test_split(leads, train_size=0.7, test_size=0.3, random_state=100)
# In[49]:
# Scaling the data to bring all in one scale
scaler = StandardScaler()
# In[50]:
# Apply the scaling metrics
num_vars = ['TotalVisits', 'Total Time Spent on Website', 'Page Views Per Visit']
df_train[num_vars] = scaler.fit_transform(df_train[num_vars])
# In[51]:
# Predictor and Target Variable Split
y_train = df_train.pop('Converted')
X_train = df_train.drop('Lead Number', axis=1)
# ### Modelling
# - Let's now move to model building. As you can see that there are a lot of variables present in the dataset which we cannot deal with. So the best way to approach this is to select a small set of features from this pool of variables using RFE.
# **RFE Approach**
# In[52]:
# Performing RFE approach for 15 variables
logreg = LogisticRegression()
rfe = RFE(logreg, 15) # running RFE with 15 variables as output
rfe = rfe.fit(X_train, y_train)
# In[53]:
# RFE result on all variables
list(zip(X_train.columns, rfe.support_, rfe.ranking_))
# In[54]:
# Selected 15
col = X_train.columns[rfe.support_]
col
# - Now you have all the variables selected by RFE and to check the statistics part, i.e. the p-values and the VIFs, let's use these variables to create a logistic regression model using statsmodels.
# **Logistic regression using statsmodels [Model 1]**
# In[55]:
# Performing logistic regression using stats models
X_train_sm = sm.add_constant(X_train[col])
logm1 = sm.GLM(y_train, X_train_sm, family = sm.families.Binomial()).fit()
logm1.summary()
# In[56]:
# Calculating the VIF values
VIF = pd.DataFrame()
VIF['Features'] = X_train[col].columns
VIF['VIF'] = [variance_inflation_factor(X_train[col].values, i) for i in range(X_train[col].shape[1])]
VIF['VIF'] = round(VIF['VIF'], 2)
VIF = VIF.sort_values(by = 'VIF', ascending = False)
VIF
# The VIF Value for all the columns are less than 5. But there are few columns which has high p-values. So based on high p-value, the column `Had a Phone Conversation` should be dropped.
# In[57]:
# Dropping the column with high p-value
col = col.drop('Had a Phone Conversation')
col
# **Logistic regression using statsmodels [Model 2]**
# In[58]:
# Performing logistic regression using stats models
X_train_sm = sm.add_constant(X_train[col])
logm2 = sm.GLM(y_train, X_train_sm, family = sm.families.Binomial()).fit()
logm2.summary()
# In[59]:
# Calculating the VIF values
VIF = pd.DataFrame()
VIF['Features'] = X_train[col].columns
VIF['VIF'] = [variance_inflation_factor(X_train[col].values, i) for i in range(X_train[col].shape[1])]
VIF['VIF'] = round(VIF['VIF'], 2)
VIF = VIF.sort_values(by = 'VIF', ascending = False)
VIF
# The VIF Value for all the columns are less than 5. But there are few columns which has high p-values. So based on high p-value, the column `Housewife` should be dropped.
# In[60]:
# Dropping the column with high p-value
col = col.drop('Housewife')
col
# **Logistic regression using statsmodels [Model 3]**
# In[61]:
# Performing logistic regression using stats models
X_train_sm = sm.add_constant(X_train[col])
logm3 = sm.GLM(y_train, X_train_sm, family = sm.families.Binomial()).fit()
logm3.summary()
# In[62]:
# Calculating the VIF values
VIF = pd.DataFrame()
VIF['Features'] = X_train[col].columns
VIF['VIF'] = [variance_inflation_factor(X_train[col].values, i) for i in range(X_train[col].shape[1])]
VIF['VIF'] = round(VIF['VIF'], 2)
VIF = VIF.sort_values(by = 'VIF', ascending = False)
VIF
# Since all the p-values and VIF values are low for all the columns, let's consider the `Model 3` as the final model
# ### Model Evaluation
# In[63]:
# Predicting the target values based on the predictor values using the final model
y_train_pred = logm3.predict(X_train_sm)
y_train_pred = y_train_pred.values.reshape(-1)
y_train_pred[:10]
# #### Actual vs Predicted
# In[64]:
# Creating a dataframe with the actual conversion flag and the predicted probabilities
y_train_pred_final = pd.DataFrame({'Converted':y_train.values, 'Converted_Prob':y_train_pred})
y_train_pred_final.head()
# #### Random Cut-off for Predicted
# In[65]:
# Creating new column 'Predicted' with 1 if Converted_Prob > 0.5 else 0
y_train_pred_final['Predicted'] = y_train_pred_final.Converted_Prob.map(lambda x: 1 if x > 0.5 else 0)
y_train_pred_final.head()
# #### Evaluate the model using Confusion Matrix
# In[66]:
# Plot the confusion matrix
confusion = metrics.confusion_matrix(y_train_pred_final.Converted, y_train_pred_final.Predicted)
confusion
# In[1]:
## Predicted Not Converted Converted
## Actual
## Not Converted 1983 395
## Converted 563 1644
# In[67]:
# Calculating the accuracy
metrics.accuracy_score(y_train_pred_final.Converted, y_train_pred_final.Predicted)
# In[68]:
# Let's evaluate the other metrics as well
TP = confusion[1,1] # true positive
TN = confusion[0,0] # true negatives
FP = confusion[0,1] # false positives
FN = confusion[1,0] # false negatives
# In[69]:
# Calculate the sensitivity
TP/(TP+FN)
# In[70]:
# Calculate the specificity
TN/(TN+FP)
# For the chosen random cut-off probability value, the Sensitivity is lower compared to specificity which clearly suggests that it's not the optimal cut-off. Let's check the ROC curve for the same.
# **ROC Curve**
# In[71]:
# ROC function
def draw_roc( actual, probs ):
fpr, tpr, thresholds = metrics.roc_curve( actual, probs,
drop_intermediate = False )
auc_score = metrics.roc_auc_score( actual, probs )
plt.figure(figsize=(5, 5))
plt.plot( fpr, tpr, label='ROC curve (area = %0.2f)' % auc_score )
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate or [1 - True Negative Rate]')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
# In[72]:
# Plotting the ROC Curve
fpr, tpr, thresholds = metrics.roc_curve(y_train_pred_final.Converted, y_train_pred_final.Converted_Prob,
drop_intermediate = False)
draw_roc(y_train_pred_final.Converted, y_train_pred_final.Converted_Prob)
# The area under the ROC curve is 0.87 which indicates that the chosen cut-off may not be optimal and some better cut-off could be used
# **Optimal Cut-Off Selection**
# In[73]:
# Creating columns with different probability cutoffs
numbers = [float(x)/10 for x in range(10)]
for i in numbers:
y_train_pred_final[i]= y_train_pred_final.Converted_Prob.map(lambda x: 1 if x > i else 0)
y_train_pred_final.head()
# In[74]:
# Creating a dataframe to see the values of accuracy, sensitivity, and specificity at different values of probabiity cutoffs
cutoff_df = pd.DataFrame(columns = ['prob','accuracy','sensi','speci'])
num = [float(x)/10 for x in range(10)]
for i in num:
cm1 = metrics.confusion_matrix(y_train_pred_final.Converted, y_train_pred_final[i] )
total1=sum(sum(cm1))
accuracy = (cm1[0,0]+cm1[1,1])/total1
speci = cm1[0,0]/(cm1[0,0]+cm1[0,1])
sensi = cm1[1,1]/(cm1[1,0]+cm1[1,1])
cutoff_df.loc[i] =[ i ,accuracy,sensi,speci]
print(cutoff_df)
# In[75]:
# Plotting the probability value across accuracy, sensitivity and specificity
cutoff_df.plot.line(x='prob', y=['accuracy','sensi','speci'])
plt.show()
# As you can see that around 0.38, you get the optimal values of the three metrics. So let's choose `0.38` as our cutoff now.
# **Predicting with the Optimal cut-off**
# In[76]:
# The predictions are done with the new optimal cut-off value
y_train_pred_final['Final_Predicted'] = y_train_pred_final.Converted_Prob.map(lambda x: 1 if x > 0.38 else 0)
y_train_pred_final.head()
# In[77]:
# Confusion Matrix
confusion_train = metrics.confusion_matrix(y_train_pred_final.Converted, y_train_pred_final.Final_Predicted)
confusion_train
# In[2]:
## Predicted Not Converted Converted
## Actual
## Not Converted 1691 687
## Converted 317 1890
# In[78]:
# Calculating the accuracy score
metrics.accuracy_score(y_train_pred_final.Converted, y_train_pred_final.Predicted)
# In[79]:
# Let's evaluate the other metrics as well
TP = confusion_train[1,1] # true positive
TN = confusion_train[0,0] # true negatives
FP = confusion_train[0,1] # false positives
FN = confusion_train[1,0] # false negatives
# In[80]:
# Calculate the sensitivity
TP/(TP+FN)
# In[81]:
# Calculate the specificity
TN/(TN+FP)
# In[82]:
# calculate precision
TP/(TP+FP)
# In[83]:
# calculate F1-Score
metrics.f1_score(y_train_pred_final.Converted, y_train_pred_final.Final_Predicted)
# With the chosen optimal cut-off, `0.38`:
# 1. Sensitivity is high compared to specificity
# 2. Precision is also high
# 3. The F1-Score is almost 79% which means the model has a better performance
# ### Making prediction on Test set
# #### Scaling the test dataset
# In[84]:
# Popping out the target variable from the test data
y_test = df_test.pop('Converted')
# Scaling the test using the same metrics used for train
df_test[num_vars] = scaler.transform(df_test[num_vars])
# In[85]:
# Scaled Test Predictor variables
X_test = df_test[col]
X_test.head()
# #### Predicting on the test dataset
# In[86]:
# Predicting on test dataset using the final model
X_test_sm = sm.add_constant(X_test)
y_test_pred = logm3.predict(X_test_sm)
y_test_pred.head()
# In[87]:
# Creating a dataframe with the predicted probabilities
y_test_pred = pd.DataFrame(y_test_pred, columns=['Converted_Prob'], dtype='float64')
y_test_pred.head()
# In[88]:
# Creating a dataframe with the target values
y_test = pd.DataFrame(y_test, columns=['Converted'], dtype='int64')
y_test.head()
# In[89]:
# Creating new datafram with target variable and predicted variable
y_test_final = pd.concat([y_test, y_test_pred], axis=1)
y_test_final.head()
# **Predicting the Test data using the optimal cut-off chosen**
# In[90]:
# Creating new column 'Predicted' with 1 if Converted_Prob > 0.38 else 0
y_test_final['Predicted'] = y_test_final.Converted_Prob.map(lambda x: 1 if x > 0.38 else 0)
y_test_final.head()
# #### Evaluate the model using Confusion Matrix
# In[91]:
# Confusion Matrix
confusion_test = metrics.confusion_matrix(y_test_final.Converted, y_test_final.Predicted)
confusion_test
# In[3]:
## Predicted Not Converted Converted
## Actual
## Not Converted 697 284
## Converted 160 824
# In[92]:
# Calculating the Accuracy
metrics.accuracy_score(y_test_final.Converted, y_test_final.Predicted)
# In[93]:
# Let's evaluate the other metrics as well
TP = confusion_test[1,1] # true positive
TN = confusion_test[0,0] # true negatives
FP = confusion_test[0,1] # false positives
FN = confusion_test[1,0] # false negatives
# In[94]:
# Calculate the sensitivity
TP/(TP+FN)
# In[95]:
# Calculate the specificity
TN/(TN+FP)
# In[96]:
# calculate precision
TP/(TP+FP)
# In[97]:
# calculate F1-Score
metrics.f1_score(y_test_final.Converted, y_test_final.Predicted)
# For the test data:
# 1. The Accuracy is high
# 2. Sensitivity is high compared to specificity
# 3. Precision is also pretty high
# 4. F1-score is about 78%
#
# Overall the final model looks good after evaluation
# ### Precision and Recall
# #### On train dataset
# In[98]:
# Confusion Matrix
confusion_train = metrics.confusion_matrix(y_train_pred_final.Converted, y_train_pred_final.Final_Predicted)
confusion_train
# In[4]:
## Predicted Not Converted Converted
## Actual
## Not Converted 1691 687
## Converted 317 1890
# In[99]:
# calculate precision
# TP/(TP+FP)
confusion_train[1,1]/(confusion_train[1,1] + confusion_train[0,1])
# In[100]:
# calculate recall
# TP/(TP+FN)
confusion_train[1,1]/(confusion_train[1,1] + confusion_train[1,0])
# Precision is less when compared to Recall
# #### Precision and Recall tradeoff
# In[101]:
p, r, thres = precision_recall_curve(y_train_pred_final.Converted, y_train_pred_final.Converted_Prob)
# In[102]:
plt.plot(thres, p[:-1], "g-")
plt.plot(thres, r[:-1], "r-")
plt.show()
# Based on the trade-off value 0.4 is chosen as the threshold for final prediction
# **Making Final Predictions using `0.4` as the cut-off value**
# In[103]:
# Creating new column 'Final_Pred_PR' with 1 if Converted_Prob > 0.4 else 0 and evaluating the model
y_train_pred_final['Final_Pred_PR'] = y_train_pred_final.Converted_Prob.map(lambda x: 1 if x > 0.4 else 0)
y_train_pred_final.head()
# In[104]:
# Confusion Matrix
confusion_pr = metrics.confusion_matrix(y_train_pred_final.Converted, y_train_pred_final.Final_Pred_PR)
confusion_pr
# In[105]:
# Calculating the accuracy
metrics.accuracy_score(y_train_pred_final.Converted, y_train_pred_final.Final_Pred_PR)
# In[106]:
# Let's evaluate the other metrics as well
TP = confusion_pr[1,1] # true positive
TN = confusion_pr[0,0] # true negatives
FP = confusion_pr[0,1] # false positives
FN = confusion_pr[1,0] # false negatives
# In[107]:
# Calculate the recall
TP/(TP+FN)
# In[108]:
# calculate precision
TP/(TP+FP)
# In[109]:
# calculate F1-Score
metrics.f1_score(y_test_final.Converted, y_test_final.Predicted)
# #### Prediction on the test dataset
# In[110]:
# Creating new column 'Predicted_PR' with 1 if Converted_Prob > 0.4 else 0 and evaluating the model
y_test_final['Predicted_PR'] = y_test_final.Converted_Prob.map(lambda x: 1 if x > 0.4 else 0)
y_test_final.head()
# In[111]:
# Confusion Matrix
confusion_test_pr = metrics.confusion_matrix(y_test_final.Converted, y_test_final.Predicted_PR)
confusion_test_pr
# In[5]:
## Predicted Not Converted Converted
## Actual
## Not Converted 751 230
## Converted 205 779
# In[112]:
# Calculating the accuracy
metrics.accuracy_score(y_test_final.Converted, y_test_final.Predicted_PR)
# In[113]:
# Let's evaluate the other metrics as well
TP = confusion_test_pr[1,1] # true positive
TN = confusion_test_pr[0,0] # true negatives
FP = confusion_test_pr[0,1] # false positives
FN = confusion_test_pr[1,0] # false negatives
# In[114]:
# Calculate the recall
TP/(TP+FN)
# In[115]:
# calculate precision
TP/(TP+FP)
# In[116]:
# calculate F1-Score
metrics.f1_score(y_test_final.Converted, y_test_final.Predicted)
# Based on the predictions:
# 1. Precision is low compared to the Recall
# 2. F1-Score is around 78%
# ### Assigning Lead Scores on test dataset
# In[117]:
# Lead Score function
def score(x):
return int(100-74+(7*log(x/(1-x))/log(2)))
y_test_final['Score'] = y_test_final.Converted_Prob.apply(score)
# In[118]:
y_test_final.head()
# In[119]:
# Assign the score to 0 for those having negative scores
y_test_final.Score[y_test_final.Score < 0] = 0
# In[120]:
# Top 5 Leads based on their lead score
y_test_final.sort_values(by='Score', ascending=False).head()
# In[121]:
# Concatenating X and y to find out the details about the leads using their lead scores
lead_score = pd.concat([X_test_sm, y_test_final], axis=1)
# In[122]:
# Top 5 Leads based on their lead score
lead_score.sort_values(by='Score', ascending=False).head()
# In[123]:
# Least 5 Leads based on their lead score
lead_score.sort_values(by='Score').head()
# **Hot Leads**
# In[124]:
# The leads with score greater than 70 will give us the hot leads
y_test_final[y_test_final.Score > 70].sort_values(by='Score').count()
# **Converted Leads even when they weren't reached on Phone**
# In[127]:
lead_score[lead_score.Unreachable == 1]
# **Summary**
# - The equation for Logistic Regression based on the final model `Model 3` is:
# $ Converted = 0.9303 \times const + 1.1188 \times Total Time Spent on Website + 3.2419 \times Lead Add Form
# -0.6192 \times Direct Traffic + 1.2087 \times Olark Chat + 2.5373 \times Welingak Website
# -1.5277 \times Student -1.5044 \times Unemployed + 1.0724 \times Working Professional
# -1.3279 \times Last\_Email Bounced -0.8449 \times Last\_Olark Chat Conversation
# +0.9830 \times Last\_SMS Sent -0.8698 \times Modified + 2.5536 \times Unreachable $
# - The Optimal cut-off chosen is `0.38`
#
# - Model Accuracy:`0.7740458015267175`
#
# - Sensitivty:`0.8373983739837398`
#
# - Specificity:`0.7104994903160041`
#
# - F1-Score:`0.7877629063097515`
# - After Precision-Recall Tradeoff, the cut-off for probability is `0.4`
#
# - Model Accuracy:`0.7786259541984732`
#
# - Precision:`0.7720515361744301`
#
# - Recall:`0.7916666666666666`
#
# - F1-Score:`0.7877629063097515`
|
7f612182ffb946c0ba196a5b71394e0d44d4d37c | blhwong/algos_py | /grokking_dp/unbounded_knapsack/minimum_coin_change/main.py | 1,240 | 4 | 4 | """
Introduction
Given an infinite supply of ‘n’ coin denominations and a total money amount, we are asked to find the minimum number of coins needed to make up that amount.
Example 1:
Denominations: {1,2,3}
Total amount: 5
Output: 2
Explanation: We need a minimum of two coins {2,3} to make a total of '5'
Example 2:
Denominations: {1,2,3}
Total amount: 11
Output: 4
Explanation: We need a minimum of four coins {2,3,3,3} to make a total of '11'
Problem Statement
Given a number array to represent different coin denominations and a total amount 'T', we need to find the minimum number of coins needed to make a change for 'T'. We can assume an infinite supply of coins, therefore, each coin can be chosen multiple times.
"""
def count_change(denominations, total):
dp = [[0] * (total + 1) for _ in range(len(denominations))]
for j in range(1, total + 1):
dp[0][j] = denominations[0] + dp[0][j - denominations[0]]
for i in range(1, len(denominations)):
for j in range(1, total + 1):
c1 = float('infinity')
if denominations[i] <= j:
c1 = dp[i][j - denominations[i]] + 1
c2 = dp[i - 1][j]
dp[i][j] = min(c1, c2)
return dp[-1][total]
|
9606f47a5a851699269c6b07e423cf97e736856b | yinhuax/leet_code | /datastructure/trie_tree/ReplaceWords.py | 3,106 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Mike
# @Contact : 597290963@qq.com
# @Time : 2021/2/12 13:40
# @File : ReplaceWords.py
from typing import List
"""
在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。
你需要输出替换之后的句子。
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/trie/x0cga2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
"""
from collections import defaultdict
class TrieTree(object):
def __init__(self):
self.is_word = False
self.children = defaultdict(TrieTree)
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
"""
前缀树
:param dictionary:
:param sentence:
:return:
"""
# 字典构建前缀树
root = TrieTree()
for word in dictionary:
cur_node = root
for s in word:
cur_node = cur_node.children[s]
cur_node.is_word = True
result = []
for word in sentence.split(" "):
cur_node = root
for i in range(len(word)):
if word[i] in cur_node.children:
cur_node = cur_node.children[word[i]]
if cur_node.is_word:
result.append(word[:i + 1])
break
else:
result.append(word)
break
else:
result.append(word)
return ' '.join(result)
if __name__ == '__main__':
print(Solution().replaceWords(
dictionary=["e", "k", "c", "harqp", "h", "gsafc", "vn", "lqp", "soy", "mr", "x", "iitgm", "sb", "oo", "spj",
"gwmly", "iu", "z", "f", "ha", "vds", "v", "vpx", "fir", "t", "xo", "apifm", "tlznm", "kkv",
"nxyud", "j", "qp", "omn", "zoxp", "mutu", "i", "nxth", "dwuer", "sadl", "pv", "w", "mding",
"mubem", "xsmwc", "vl", "farov", "twfmq", "ljhmr", "q", "bbzs", "kd", "kwc", "a", "buq", "sm", "yi",
"nypa", "xwz", "si", "amqx", "iy", "eb", "qvgt", "twy", "rf", "dc", "utt", "mxjfu", "hm", "trz",
"lzh", "lref", "qbx", "fmemr", "gil", "go", "qggh", "uud", "trnhf", "gels", "dfdq", "qzkx", "qxw"],
sentence="ikkbp miszkays wqjferqoxjwvbieyk gvcfldkiavww vhokchxz dvypwyb bxahfzcfanteibiltins ueebf lqhflvwxksi dco kddxmckhvqifbuzkhstp wc ytzzlm gximjuhzfdjuamhsu gdkbmhpnvy ifvifheoxqlbosfww mengfdydekwttkhbzenk wjhmmyltmeufqvcpcxg hthcuovils ldipovluo aiprogn nusquzpmnogtjkklfhta klxvvlvyh nxzgnrveghc mpppfhzjkbucv cqcft uwmahhqradjtf iaaasabqqzmbcig zcpvpyypsmodtoiif qjuiqtfhzcpnmtk yzfragcextvx ivnvgkaqs iplazv jurtsyh gzixfeugj rnukjgtjpim hscyhgoru aledyrmzwhsz xbahcwfwm hzd ygelddphxnbh rvjxtlqfnlmwdoezh zawfkko iwhkcddxgpqtdrjrcv bbfj mhs nenrqfkbf spfpazr wrkjiwyf cw dtd cqibzmuuhukwylrnld dtaxhddidfwqs bgnnoxgyynol hg dijhrrpnwjlju muzzrrsypzgwvblf zbugltrnyzbg hktdviastoireyiqf qvufxgcixvhrjqtna ipfzhuvgo daee r nlipyfszvxlwqw yoq dewpgtcrzausqwhh qzsaobsghgm ichlpsjlsrwzhbyfhm ksenb bqprarpgnyemzwifqzz oai pnqottd nygesjtlpala qmxixtooxtbrzyorn gyvukjpc s mxhlkdaycskj uvwmerplaibeknltuvd ocnn frotscysdyclrc ckcttaceuuxzcghw pxbd oklwhcppuziixpvihihp"))
|
63aa7376b684f17444a69772845c9e26677205e1 | vijaykm2/Tic-Tac-Toe | /Problems/Cat cafés/main.py | 315 | 3.984375 | 4 | inpt = ""
catCafes = []
while inpt != "MEOW":
inpt = input()
if inpt != "MEOW":
catCafes.append(inpt)
largest = ''
largestNum = -1
for cafe in catCafes:
cafeNum = int(cafe.split()[1])
if(cafeNum > largestNum):
largest = cafe.split()[0]
largestNum = cafeNum
print(largest)
|
79842a6278b9deddbbe9dcdd9efac467ff6cd753 | msadoghi/165a-winter-2021 | /template/index.py | 974 | 3.96875 | 4 | """
A data strucutre holding indices for various columns of a table. Key column should be indexd by default, other columns can be indexed through this object. Indices are usually B-Trees, but other data structures can be used as well.
"""
class Index:
def __init__(self, table):
# One index for each table. All our empty initially.
self.indices = [None] * table.num_columns
pass
"""
# returns the location of all records with the given value on column "column"
"""
def locate(self, column, value):
pass
"""
# Returns the RIDs of all records with values in column "column" between "begin" and "end"
"""
def locate_range(self, begin, end, column):
pass
"""
# optional: Create index on specific column
"""
def create_index(self, column_number):
pass
"""
# optional: Drop index of specific column
"""
def drop_index(self, column_number):
pass
|
2f31599a28c3bab0a12b3ab603c8e1fdd088747a | zhangbiqiong/hello-world | /d.py | 610 | 3.625 | 4 | # python notebook for Make Your Own Neural Network
# working with the MNIST data set
#
# (c) Tariq Rashid, 2016
# license is GPLv2
import numpy
import matplotlib.pyplot
data_file = open("mnist_train_100.csv", 'r')
data_list = data_file.readlines()
data_file.close()
print (len(data_list))
print (data_list[1])
# take the data from a record, rearrange it into a 28*28 array and plot it as an image
all_values = data_list[1].split(',')
image_array = numpy.asfarray(all_values[1:]).reshape((28,28))
matplotlib.pyplot.imshow(image_array, cmap='Greys', interpolation='None')
matplotlib.pyplot.savefig('001.png')
|
9e9ef72b4d4e394fba2a6090cae7e1fcceeefe49 | Selshy/Selshy | /NewPythonProject2/src/Kattis/Speedlimit.py | 259 | 3.515625 | 4 | for _ in range (10):
n = int(input())
if n == -1:
break
result = 0
c = 0
for _ in range(n):
a, b = input().split()
a = int(a)
b = int(b)
result += (a * (b-c))
c = b
print(result, "miles") |
ad3ee3f326184e57e4a70c7283170f7675693d36 | skshahriarahmedraka/DataStructurePractice-Python | /DFS.py | 3,489 | 3.921875 | 4 | class node:
def __init__(self,data):
self.visit=True
self.parentnode=None
self.nodedata=data
self.leftnode=None
self.rightnode=None
class binarytree:
def __init__(self):
self.root=None
def insert(self,data,extranode=None):
if extranode is None:
extranode=self.root
if self.root is None:
self.root=node(data)
return self.root
else:
if extranode.nodedata>=data:
if extranode.leftnode is None:
extranode.leftnode=node(data)
extranode.leftnode.parentnode=extranode
return extranode.leftnode
else:
return self.insert(data,extranode=extranode.leftnode)
else:
if extranode.rightnode is None:
extranode.rightnode=node(data)
extranode.rightnode.parentnode=extranode
return extranode.rightnode
else:
return self.insert(data,extranode=extranode.rightnode)
def showbinarytree(self,extranode=None):
if extranode==None:
extranode=self.root
if extranode==None:
print("binary tree is empty")
def DFS(self,data):
extranode=self.root
while True:
if extranode.nodedata == data:
print("data is found")
self._DFS()
return extranode
extranode.visit=False
if extranode.leftnode is not None and (extranode.leftnode.visit) :
extranode=extranode.leftnode
# print("leftnode")
continue
elif extranode.rightnode is not None and (extranode.rightnode.visit):
extranode=extranode.rightnode
# print("right")
continue
else:
if extranode.parentnode is not None:
extranode=extranode.parentnode
# print("parent")
continue
else:
print("data is not found")
self._DFS()
return
def _DFS(self):
extranode=self.root
while True:
extranode.visit=True
if extranode.leftnode is not None and (extranode.leftnode.visit) :
extranode=extranode.leftnode
# print("leftnode")
continue
elif extranode.rightnode is not None and (extranode.rightnode.visit):
extranode=extranode.rightnode
# print("right")
continue
else:
if extranode.parentnode is not None:
extranode=extranode.parentnode
# print("parent")
continue
else:
return
if __name__=="__main__":
n=int(input("how many imput you want to give : "))
bt=binarytree()
for i in range(n):
bt.insert(input())
bt.DFS(input("give a number for DFS search : "))
n=int(input("how many imput you want to give : "))
bt=binarytree()
for i in range(n):
bt.insert(input())
bt.DFS(input("give a number for DFS search : "))
|
9480a5c0f2878843bb6111a09339bebf302127cd | gusar/advsec | /caesar.py | 2,071 | 3.59375 | 4 | def caesar(s, k, decrypt_flag=False):
if decrypt_flag:
k = 26 - k
r = ""
for i in s:
if 65 <= ord(i) <= 90:
r += chr((ord(i) - 65 + k) % 26 + 65)
elif 97 <= ord(i) <= 122:
r += chr((ord(i) - 97 + k) % 26 + 97)
else:
r += i
return r
def encrypt(p, k):
return caesar(p, k)
def decrypt(c, k):
return caesar(c, k, True)
# Q1
KEY = -3
PLAINTEXT = """And I shall remain satisfied, and proud to have been the first who has ever enjoyed the fruit
of his writings as fully as he could desire; for my desire has been no other than to deliver
over to the detestation of mankind the false and foolish tales of the books of chivalry, which,
thanks to that of my true Don Quixote, are even now tottering, and doubtless doomed to fall
for ever. Farewell."""
caesar_encrypt_result_str = encrypt(PLAINTEXT, KEY)
print('Encrypting with key {}: {}'.format(str(KEY), caesar_encrypt_result_str))
# Answer
"""Xka F pexii objxfk pxqfpcfba, xka molra ql exsb ybbk qeb cfopq tel exp bsbo bkglvba qeb corfq
lc efp tofqfkdp xp criiv xp eb zlria abpfob; clo jv abpfob exp ybbk kl lqebo qexk ql abifsbo
lsbo ql qeb abqbpqxqflk lc jxkhfka qeb cxipb xka cllifpe qxibp lc qeb yllhp lc zefsxiov, tefze,
qexkhp ql qexq lc jv qorb Alk Nrfulqb, xob bsbk klt qlqqbofkd, xka alryqibpp alljba ql cxii
clo bsbo. Cxobtbii."""
# Q2
CIPHERTEXT = """Vg jbhyq frrz gung, nf ur rknzvarq gur frireny cbffvovyvgvrf, n fhfcvpvba pebffrq uvf zvaq: gur
zrzbel bs ubj ur uvzfrys unq orunirq va rneyvre qnlf znqr uvz nfx jurgure fbzrbar zvtug or
uvqvat ure sebz gur jbeyq"""
for key in range(1, 27):
decrypt_result_str = decrypt(CIPHERTEXT, key)
print("\nDecrypting using key {}:\n{}".format(str(key), decrypt_result_str))
# Answer: key 13
"""It would seem that, as he examined the several possibilities, a suspicion crossed his mind: the
memory of how he himself had behaved in earlier days made him ask whether someone might be
hiding her from the world""" |
2f4200453a55ec87867427345327c7a217879bb3 | tigerhub/Event-Simulator-Python | /code/System1.py | 11,413 | 3.578125 | 4 | from SimPy.Simulation import *
from numpy.random import seed, uniform, exponential, poisson
import numpy as np
import random
import argparse
import matplotlib.pyplot as plt
from itertools import chain
# First Name: Dan
# Last Name: Brown
# BU ID: U63795118
#You can add any extra helper methods to these classes as you see fit#.
#You must modify this class#
class Parameters:
'''In this class, you must just define the following variables of your distribution:
These variables will be hardcoded with values. Please refer to the assignment handout what
these values must be. You can use the values appropiately in your code by calling Parameters.NAME_OF_VARIABLE
--For Poisson Arrivals and Exponential Service Time
1) lambda for poisson arrivals
2) Ts for service time
--For Uniform Arrivals and Uniform Service Time
3) interarrivalTimeMin and interarrivalTimeMax for Uniform distribution.
4) serviceTimeMin and serviceTimeMax for Uniform distribution.
5. numberOfServers in your computing system
6. simulationTime in hrs. '''
# For Poisson Arrivals and Exponential Service Time:
interArrival = 0
TsCPU = 0.02
TsNet = 0.025
TsDisk = 0.1
# Other parameters:
numberOfServers = 1
simulationTime = 0 # in minutes (120 min = 2 hours)
RandomSeed = 123
steadyState = 0
#statistics
wLen = 0
wLength = []
wLengthMon = []
Tw = []
wait = 0
Arrivals_cpu = []
Arrivals_disk = []
Arrivals_net = []
exits = []
exitsAvgs = []
response_times = []
##### Processes #####
# Customer
class Packet(Process):
state = "cpu"
def behavior_of_single_packetExp(self, cpu, disk, net):
if self.state == "cpu":
#print("disk")
arriveCpu = now()
Parameters.Arrivals_cpu.append(arriveCpu) #add all times of arrival of packet to a list
Parameters.wLen += 1 # helps calculate length of queue; increment queue (number of packets waiting) length counter
#if not(self.name in chain(*Parameters.response_times)):
#Parameters.response_times.append((self.name, arriveCpu))
yield request,self,cpu
# wait before collecting data (wait for system to reach steady state):
#if now() > Parameters.steadyState:
#Parameters.wait = now()-arriveCpu
#wM.observe(wait)
Ts = exponential(Parameters.TsCPU)
yield hold,self,Ts
yield release,self,cpu
Parameters.wLen -= 1 # packet gets serviced, therefore, decrement number of packets waiting by one
#*** CONDITIONALS for cpu****
step_rnd = uniform(0,1)
#if ((step_rnd >= 0.4) and (step_rnd < 0.9)):
#packet exits system
if (step_rnd < 0.4):
#packet goes to network
#print("cpu to network")
p = Packet(name = self.name)
p.state = "net"
activate(p,p.behavior_of_single_packetExp(cpu, disk, net))
elif ((step_rnd >= 0.4) and (step_rnd < 0.9)):
#packet exits system
Parameters.exits.append(now())
elif step_rnd >= 0.9:
#packet goes to disk
#print("cpu to disk")
p = Packet(name = self.name)
p.state = "disk"
activate(p,p.behavior_of_single_packetExp(cpu, disk, net))
elif self.state == "disk":
#print("disk")
#arriveDisk = now()
Parameters.Arrivals_disk.append(now())
yield request,self,disk
#wait = now()-arriveDisk
#wM.observe(wait)
Ts = exponential(Parameters.TsDisk)
yield hold,self,Ts
yield release,self,disk
#*** CONDITIONALS for disk****
step_rnd = uniform(0,1)
if step_rnd >= 0.5:
#packet goes to cpu
#print("disk to cpu")
p = Packet(name = self.name)
p.state = "cpu"
activate(p,p.behavior_of_single_packetExp(cpu, disk, net))
else:
#packet goes to network
#print("disk to network")
p = Packet(name = self.name)
p.state = "net"
activate(p,p.behavior_of_single_packetExp(cpu, disk, net))
elif self.state == "net":
#print("net")
#arriveNet = now()
Parameters.Arrivals_net.append(now())
yield request,self,net
#wait = now()-arrive
#wM.observe(wait)
Ts = exponential(Parameters.TsNet)
yield hold,self,Ts
yield release,self,net
#*** CONDITIONALS for netowrk****
# In this case, network packets have 100% chance to (automatically) go back to cpu
#packet goes to cpu
#print("network to cpu")
p = Packet(name = self.name)
p.state = "cpu"
activate(p,p.behavior_of_single_packetExp(cpu, disk, net))
# Packet Generator class.
class PacketGenerator(Process):
# for experimental dist arrival rate
def createPacketsExp(self, cpu, disk, net):
i = 0
while True:
#creates new packet
rnd = exponential(Parameters.interArrival)
yield hold, self, rnd
p = Packet(name = "Packet " + str(i))
activate(p,p.behavior_of_single_packetExp(cpu, disk, net)) # behavior for packet using exponential dist
i+= 1
# Monitor Generator class.
class MonitorGen(Process):
def createMon(self,cpu, disk, net):
i = 0
# create poisson distribution (with lambda = 1, for 100 seconds)
rnd_list = poisson(1,Parameters.simulationTime - Parameters.steadyState)
#print "rnd list" , len(rnd_list)
#print rnd_list
for x in rnd_list:
yield hold, self, x
#print(Parameters.wLen)
Parameters.wLength.append(Parameters.wLen)
#using monitoring object:
Parameters.wLengthMon.append(len(cpu.waitQ))
# this is for getting exit rate for the system
if (len(Parameters.exits) > 0):
diff_exits = np.diff(Parameters.exits)
exitAvgTime = (sum(diff_exits) / float(len(diff_exits)))
exitAvg = (1.0/exitAvgTime)
else:
exitAvg = 0
Parameters.exitsAvgs.append(exitAvg)
Parameters.exits = [] #reset for next average calculation
i+= 1
#You do not need to modify this class.
class ComputingSystem(Resource):
pass
def modelMM2():
global f
f = open('data.txt', 'w')
#print "Creating experiment for MM2"
#Parameters.numberOfServers = 2
seed(Parameters.RandomSeed)
#cs = Resource(capacity=Parameters.numberOfServers,monitored=True, monitorType=Monitor)
cpu=ComputingSystem(capacity=2,monitored=True, monitorType=Monitor)
disk=ComputingSystem(capacity=1,monitored=True, monitorType=Monitor)
net=ComputingSystem(capacity=1,monitored=True, monitorType=Monitor)
global wM
wM = Monitor()
initialize()
s = PacketGenerator('Process')
activate(s, s.createPacketsExp(cpu, disk, net), at=0.0)
Mon = MonitorGen('Process') # create instance of monitor class
activate(Mon, Mon.createMon(cpu, disk, net), at= Parameters.steadyState)
simulate(until= Parameters.simulationTime)
# print "Wlength" , Parameters.wLength
#print (len(Parameters.wLength))
#avg_wLength = (sum(Parameters.wLength) / float(len(Parameters.wLength)))
#print "Average length of queue (w) is: ", avg_wLength
avg_wLength2 = (sum(Parameters.wLengthMon) / float(len(Parameters.wLengthMon)))
print "Average length of CPU queue with Monitor (w) is: ", avg_wLength2
sample_deviation_Cpu = np.std(Parameters.wLengthMon)
print "sample deviation for cpu requests waiting (w) is " , sample_deviation_Cpu
#------ lambdas for subsystems
# difference between time of arrivals of a packet and next packet
time_diff_cpu = np.diff(Parameters.Arrivals_cpu)
time_diff_disk = np.diff(Parameters.Arrivals_disk)
time_diff_net = np.diff(Parameters.Arrivals_net)
# avg of the time-differences will give us the average time between packets;
# So, in order to get lambda (the rate of arrivals per second), we need to divide
# 1 by the avg of the time-differences
avg_cpu_times = (sum(time_diff_cpu) / float(len(time_diff_cpu)))
avg_disk_times = (sum(time_diff_disk) / float(len(time_diff_disk)))
avg_net_times = (sum(time_diff_net) / float(len(time_diff_net)))
lambda_cpu = (1.0/avg_cpu_times)
lambda_disk = (1.0/avg_disk_times)
lambda_net = (1.0/avg_net_times)
#print "time list for cpu" , time_diff_cpu
print "lambda for cpu: " , lambda_cpu
print "lambda for disk: " , lambda_disk
print "lambda for net: " , lambda_net
#plotting code:
# just uncomment out one of these to run and see the corresponding graphs
'''
# for Hw4 part 2a
# for this one, set Parameters.simulationTime to 100, and Parameters.steadyState = 0
x = [z+1 for z in range(0,Parameters.simulationTime)]
y = Parameters.wLengthMon
plt.scatter(x, y)
plt.xlabel('Time (in seconds)')
plt.ylabel('Number of requests waiting in CPU (w)')
plt.show()
# for Hw4 part 2b
# for this one, set Parameters.steadyState = 0 in the model() function, and set Parameters.steadyState to something larger than 100
x = [z+1 for z in range(Parameters.steadyState,Parameters.simulationTime)]
y = Parameters.exitsAvgs
plt.scatter(x, y)
plt.xlabel('Time (in seconds)')
plt.ylabel('Exiting rate for the system')
plt.show()
'''
f.close()
#return w
#You can modify this model method#.
# *This is the experiment (where we initialize everything and run it; this is not the same as a model for MVC
# (Model View Controller) )
def model():
Parameters.simulationTime = 140 #higher simulation times => better aproximation to analytical
Parameters.steadyState = 40 # change this to 0 when testing out my plotting code for graphing
Parameters.RandomSeed = 123 # just to make sure
Lambda = 40 # 40 times per second
Parameters.interArrival = 1.0/Lambda
Parameters.TsCPU = .02
Parameters.TsDisk = .1
Parameters.TsNet = .025
modelMM2()
#Change the below, as per the requirements of the assignment.
if __name__ == "__main__":
model()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.