blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2e80109811c17a80fea98d970307850d64edd302 | Dragonriser/DSA_Practice | /LinkedLists/LinkedListCycle.py | 454 | 3.859375 | 4 | #QUESTION:
#Detect if a linked list has a cycle.
#Using 2 pointers- fast and slow. In a circle they will eventually meet each other, hence cycle is detected.
#CODE:
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
|
9ef0a45a11579a6bb459fbf54bf0092c7c020b7e | Dragonriser/DSA_Practice | /Dynamic Programming/UniquePaths.py | 1,961 | 3.9375 | 4 | #QUESTION:
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
#CODE: TC: O(2^(m+n)) SC: O(m+n)
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m == 0 or n == 0:
return 0
if m == 1 and n == 1:
return 1
right = self.uniquePaths(m, n-1)
down = self.uniquePaths(m - 1, n)
return right + down
#This is the recursive solution, which works perfectly, but isn't optimised. Fails at a 23 x 12 matrix grid since there are too many recursive calls in the stack.
#So we optimise the code by memoizing the solution.
#MEMOIZED SOLUTION: TC: O(mn) SC: O(m+n)
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
memo = {}
def helperUniquePaths(m, n, memo):
if (m, n) in memo:
return memo[(m, n)]
elif m == 1 and n == 1:
return 1
elif m == 0 or n == 0:
return 0
memo[(m, n)] = helperUniquePaths(m, n - 1, memo) + helperUniquePaths(m - 1, n, memo)
return memo[(m,n)]
return helperUniquePaths(m, n, memo)
#TABULATED (iterative) SOLUTION: TC: O(mn) SC: O(mn)
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
memo = [[0] * (n + 1) for j in range(m + 1)]
memo[1][1] = 1
print(memo)
for r in range(m + 1):
for c in range(n + 1):
if r + 1 <= m:
memo[r + 1][c] += memo[r][c]
if c + 1 <= n:
memo[r][c + 1] += memo[r][c]
return memo[m][n]
|
75b4292c4e85d8edd136e7bf469c60e9222e383f | Dragonriser/DSA_Practice | /Binary Search/OrderAgnostic.py | 847 | 4.125 | 4 | """
Given a sorted array of numbers, find if a given number ‘key’ is present in the array. Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order. You should assume that the array can have duplicates.
Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1.
Example 1:
Input: [4, 6, 10], key = 10
Output: 2
"""
#CODE:
def orderAgnostic(arr, target):
length = len(arr)
ascending = False
if arr[0] < arr[length - 1]:
ascending = True
lo, hi = 0, length - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] == target:
return mid
else:
if ascending:
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
else:
if arr[mid] < target:
hi = mid - 1
else:
lo = mid + 1
return -1
|
cace5ce20518d3711b51f563ba7741437f5f6a8f | Dragonriser/DSA_Practice | /LinkedLists/MiddleOfList.py | 485 | 4.09375 | 4 | #QUESTION:
#Find the middle of the Linked List.
#Method 1:
#Just traverse the entire list, to find length. Then return node at length / 2
#Method 2:
#Have 2 pointers. One traverses 2 nodes at once, while the other traverses one. By the time the faster one reaches the end, the slower one will reach the middle.
#CODE:
def findMid(head):
fast = slow = head #head points to list.
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.val
|
d6b9c248126e6027e39f3f61d17d8a1a73f687b0 | Dragonriser/DSA_Practice | /LinkedLists/MergeSortedLists.py | 877 | 4.1875 | 4 | #QUESTION:
#Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
#APPROACH:
#Naive: Merge the linked Lists and sort them.
#Optimised: Traverse through lists and add elements to new list according to value, since both lists are in increasing order. Time & Space complexity: O(n + m)
#CODE:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2:
return None
merged = cur = ListNode()
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
elif l2.val <= l2.val:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return merged.next
|
ce4647c1adbd85de6d94d35e511f81a44c8c351f | Dragonriser/DSA_Practice | /Bit Manipulation/MissingNumber.py | 985 | 3.546875 | 4 | #QUESTION:
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
#Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
#CODE:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
total = 0
actual = 0
for i, n in enumerate(nums):
total += n
actual += i + 1
return actual - total
#More readable version, using Gauss' Formula:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
total = sum(nums)
n = len(nums)
actual = n * (n + 1) // 2 #Gauss' Formula
return actual - total
#Using Bit manipulation for even faster results:
#CODE:
class Solution:
def missingNumber(self, nums):
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missing
|
17855bcea6c00238e952b01112236d4a0bebda6d | CodecoolBP20161/python-pair-programming-exercises-2nd-tw-mikloci | /listoverlap/listoverlap_module.py | 418 | 4.09375 | 4 | def listoverlap(list1, list2):
c = []
for i in list1:
for j in list2:
if i == j:
if j not in c:
c.append(j)
return c
def main():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = listoverlap(a, b) # other c than in listoverlap
print(c)
return
if __name__ == '__main__':
main()
|
80c2632c8dc49c71fe182f7f83344830abb797e6 | 343829084/python_practice | /OrderedDict.py | 544 | 3.875 | 4 | from collections import OrderedDict
class FILOOrderDict(OrderedDict):
def __init__(self, capacity):
super(FILOOrderDict, self).__init__()
self.capacity = capacity
def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
OrderedDict.__setitem__(self, key, value)
if (len(self) > self.capacity) :
first = self.popitem(last=True)
print("remove item ", first)
d = FILOOrderDict(3)
d['A'] = 100
d['B'] = 200
d['C'] = 300
d['D'] = 400
d['E'] = 500
print(d) |
ba947707a49493ec0f39d013704c18e49f2aa857 | julianje/Bishop | /build/lib/bishop/Agent.py | 10,234 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Stores information about agent and comes with supporting methods to sample random agents.
"""
import random
import numpy as np
class Agent(object):
def __init__(self, Map, CostPrior, RewardPrior, CostParams, RewardParams, Capacity=-1, Minimum=0, SoftmaxChoice=True, SoftmaxAction=True, choiceTau=1, actionTau=0.01, CNull=0, RNull=0, Restrict=False):
"""
Agent class.
Create an agent with a set of costs and rewards.
If sampling parameters are numbers rather than lists the constructor fixes this automatically.
Args:
Map (Map): A map object.
CostPrior (str): String indicating prior's name. Run Agent.Priors() to see list
RewardPrior (str): String indicating Reward prior's name. Run Agent.Priors() to see list
CostParams (list): List of parameters for sampling costs.
RewardParams (list): List of parameters for sampling rewards.
Capacity (int): Number of objects agent can carry. If set to -1 Planner adjusts
it to the total number of objects in the map.
Minimum (int): Minimum number of objects must take before leaving.
SoftmaxChoice (bool): Does the agent select goals optimally?
SoftmaxAction (bool): Does the agent act upong goals optimally?
choiceTau (float): Softmax parameter for goal selection.
actionTau (float): Softmax parameter for action planning.
CNull (float): Probability that a terrain has no cost.
RNull (float): Probability that an object has no reward
Restrict (bool): When set to true the cost samples make the first terrain
always less costly than the rest.
"""
# Check that priors exist.
Priors = self.Priors(False)
if CostPrior in Priors:
self.CostPrior = CostPrior
else:
print("WARNING: Cost prior not found! Setting to uniform")
self.CostPrior = "ScaledUniform"
if RewardPrior in Priors:
self.RewardPrior = RewardPrior
else:
print("WARNING; Reward prior not found! Setting to uniform")
self.RewardPrior = "ScaledUniform"
self.Restrict = Restrict
self.CostDimensions = len(np.unique(Map.StateTypes))
# Get dimensions over which you'll build your simplex
self.RewardDimensions = len(set(Map.ObjectTypes))
self.Capacity = Capacity
self.Minimum = Minimum
self.SoftmaxChoice = SoftmaxChoice
self.SoftmaxAction = SoftmaxAction
if SoftmaxAction:
self.actionTau = actionTau
else:
self.actionTau = None
if SoftmaxChoice:
self.choiceTau = choiceTau
else:
self.choiceTau = None
if self.RewardDimensions == 0:
print("WARNING: No rewards on map. AGENT-001")
if isinstance(CostParams, list):
self.CostParams = CostParams
else:
self.CostParams = [CostParams]
if isinstance(RewardParams, list):
self.RewardParams = RewardParams
else:
self.RewardParams = [RewardParams]
self.CNull = CNull
self.RNull = RNull
self.ResampleCosts() # Generate random cost of map
self.ResampleRewards() # Generate random rewards for objects
def ResampleAgent(self):
"""
Reset agent with random costs and rewards.
Args:
Restrict (bool): If true, first terrain is always the least costly
Returns:
None
"""
self.ResampleCosts()
self.ResampleRewards()
if self.Restrict:
temp = self.costs[0]
new = self.costs.argmin()
minval = self.costs[new]
self.costs[new] = temp
self.costs[0] = minval
def ResampleCosts(self):
"""
Reset agent's costs.
"""
# Resample the agent's competence
self.costs = self.Sample(
self.CostDimensions, self.CostParams, Kind=self.CostPrior)
self.costs = [
0 if random.random() <= self.CNull else i for i in self.costs]
def ResampleRewards(self):
"""
Reset agent's rewards.
Returns:
None
"""
# Resample the agent's preferences
self.rewards = self.Sample(
self.RewardDimensions, self.RewardParams, Kind=self.RewardPrior)
if self.rewards is not None:
self.rewards = [
0 if random.random() <= self.RNull else i for i in self.rewards]
def Sample(self, dimensions, SamplingParam, Kind):
"""
Generate a sample from some distribution
Args:
dimensions (int): Number of dimensions
SamplingParam (list): Parameter to use on distribution
Kind (str): Name of distribution
Returns:
None
"""
if dimensions == 0:
return None
if (Kind == "Simplex"):
# Output: Simplex sample of length 'dimensions' (Adds to 1)
sample = -np.log(np.random.rand(dimensions))
return sample / sum(sample)
if (Kind == "IntegerUniform"):
return np.round(np.random.rand(dimensions) * SamplingParam[0])
if (Kind == "ScaledUniform"):
return np.random.rand(dimensions) * SamplingParam[0]
if (Kind == "Gaussian"):
return np.random.normal(SamplingParam[0], SamplingParam[1], dimensions)
if (Kind == "Exponential"):
return [np.random.exponential(SamplingParam[0]) for j in range(dimensions)]
if (Kind == "Constant"):
return [0.5 * SamplingParam[0]] * dimensions
if (Kind == "Beta"):
return [np.random.beta(SamplingParam[0], SamplingParam[1]) for i in range(dimensions)]
if (Kind == "Empirical"):
return [random.choice(SamplingParam) for i in range(dimensions)]
if (Kind == "PartialUniform"):
# Generate random samples and scale them by the first parameter.
samples = np.random.rand(dimensions) * SamplingParam[0]
# Now iterate over the sampling parameters and push in static
# values.
for i in range(1, len(SamplingParam)):
if SamplingParam[i] != -1:
samples[i - 1] = SamplingParam[i]
return samples
if (Kind == "PartialGaussian"):
# Generate random gaussian samples.
samples = np.random.normal(
SamplingParam[0], SamplingParam[1], dimensions)
# Now iterate over the sampling parameters and push in static
# values.
for i in range(2, len(SamplingParam)):
if SamplingParam[i] != -1:
samples[i - 2] = SamplingParam[i]
samples = [0 if i < 0 else i for i in samples]
return samples
def Priors(self, human=True):
"""
Print list of supported priors.
PRIORS:
Simplex: No arguments needed.
IntegerUniform: argument is one real/int that scales the vector
ScaledUniform: argument is one real/int that scales the vector
Gaussian: First argument is the mean and second argument is the standard deviation.
PartialGaussian: First two arguments are the same as Gaussian. Next there should be N arguments
with N = number of terrains. When Nth value after the main to is -1, the terrain cost gets sampled
from the gaussian distribution, when the value is different it is held constant. See also PartialUniform.
Exponential: First parameter is lambda
Constant: First parameter is the constant value.
Beta: First parameter is alpha and second is beta.
PartialUniform: First parameter as a real/int that scales the vector. This argument should be followed by a list of numbers
that matches the number of terrains. If the entry for terrain i is -1 that terrain get resampled and scaled, if it contains any value
then the terrain is left constant at that value. E.g., a two terrain world with a PartialUniform prior and parameters 10 -1 0.25
generates priors where the first terrain is uniform between 0 and 10, and the second paramter is always 0.25
Args:
human (bool): If true function prints names, otherwise it returns a list.
"""
Priors = ['Simplex', 'IntegerUniform', 'ScaledUniform', 'Beta',
'Gaussian', 'PartialGaussian', 'Exponential', 'Constant', 'Empirical', 'PartialUniform']
if human:
for Prior in Priors:
print(Prior)
else:
return Priors
def GetSamplingParameters(self):
"""
Return cost and reward sampling parameters, respectively
"""
return [self.CostParams, self.RewardParams]
def SetCostSamplingParams(self, samplingparams):
"""
Set sampling parameters for costs
"""
if len(samplingparams) != len(self.CostParams):
print("Vector of parameters is not the right size")
else:
self.CostParams = samplingparams
def SetRewardSamplingParams(self, samplingparams):
"""
Set sampling parameters for costs
"""
if len(samplingparams) != len(self.RewardParams):
print("Vector of parameters is not the right size")
else:
self.RewardParams = samplingparams
def Display(self, Full=True):
"""
Print object attributes.
.. Warning::
This function is for internal use only.
Args:
Full (bool): When set to False, function only prints attribute names. Otherwise, it also prints its values.
Returns:
standard output summary
"""
if Full:
for (property, value) in vars(self).items():
print((property, ': ', value))
else:
for (property, value) in vars(self).items():
print(property)
|
bc8483b86c4d416130f367249ffe0df98a5d07e6 | julianje/Bishop | /Bishop/Map.py | 18,887 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Map class. Maps are a essentially an abstraction on top of MDPs that make it move intuitive to interact with the planner.
"""
import numpy as np
import sys
import math
class Map(object):
def __init__(self, ObjectLocations=[], ObjectTypes=[], Organic=[], SurvivalProb=1, ObjectNames=[], S=[], StateTypes=[], StateNames=[], A=[], ActionNames=[], diagonal=None, T=[], ExitState=None, StartingPoint=None):
"""
This class stores the environments states (S) and the terrain type (StateTypes), the possible actions (A), the transition matrix (T), and reward locations (ObjectLocations).
It also stores human-readable information: StateNames, ActionNames, and LocationNames.
If no arguments are provided the structures are just initialized.
.. Warning::
The constructor is designed to only initialize variables. Objects should be built through BuildGridWorld method.
Args:
ObjectLocations (list): List of object locations.
ObjectTypes (list): List indicating the object type in each location.
Organic (list): List indicating which object types are organic (i.e. might die at any point and thus have a future discount adjustment).
SurvivalProb (float): Probability that organic objects survive in each time step.
ObjectNames (list): List with object names.
S (list): List of states.
StateTypes (list): List indicating the terrain type of each state.
StateNames (list): List of strings indicating the names of states.
A (list): List of actions available.
ActionNames (list): List of action names.
diagonal (boolean): Determines if agents can travel diagonally.
T (matrix): Transition matrix. T[SO,A,SF] contains the probability that agent will go from SO to SF after taking action A.
ExitState (int): Exit state
StartingPoint (int): Map's starting point
"""
self.diagonal = diagonal
self.S = S
self.A = A
self.T = T
self.ActionNames = ActionNames
self.ObjectLocations = ObjectLocations
self.ObjectTypes = ObjectTypes
self.Organic = Organic
self.SurvivalProb = SurvivalProb
self.ObjectNames = ObjectNames
self.StateNames = StateNames
self.StateTypes = StateTypes
self.ExitState = ExitState
self.StartingPoint = StartingPoint
# Helps detect errors if other functions are called when Map isn't
# ready.
self.mapwidth = -1
self.mapheight = -1
def Validate(self):
"""
Check if Map object has everything it needs.
"""
Success = True
Tshape = self.T.shape
if Tshape[0] != Tshape[2]:
print("ERROR: Transition matrix has wrong dimensions. MAP-001")
Success = False
if Tshape[0] != len(self.S) + 1: # 1 for the dead state!
print("ERROR: Transition matrix does not match number of states. MAP-002")
Success = False
if Tshape[1] != len(self.A):
print("ERROR: Transition matrix does not match number of actions. MAP-003")
Success = False
# Check that location and locationtype match
if len(self.ObjectLocations) == 0 or len(self.ObjectTypes) == 0:
print("ERROR: Missing object locations. MAP-004")
Success = False
if len(self.ObjectLocations) != len(self.ObjectTypes):
print(
"ERROR: List of locations and list of location types are of different length. MAP-005")
Success = False
# Check that location types are ordered
# from 0 to len(self.ObjectTypes).
LocTypes = list(set(self.ObjectTypes))
if list(range(max(LocTypes) + 1)) != LocTypes:
print("ERROR: Location types are not ordered correctly (They should be ordered from 0 to N, consecutively). Look at your .ini file in the [Objects] section and the \"ObjectTypes\" entry. MAP-018")
Success = False
# Check that objectnames match number of objects
if self.ObjectNames is not None:
if len(self.ObjectNames) != len(set(self.ObjectTypes)):
print("ERROR: Object names do not match number of objects. MAP-006")
Success = False
# Check that starting point and exit state are in map
if self.StartingPoint is not None:
if self.StartingPoint < 0 or self.StartingPoint >= len(self.S):
print("ERROR: Starting point is not a state number. MAP-007")
Success = False
else:
print("ERROR: Missing starting point. MAP-008")
Success = False
if self.ExitState is not None:
if self.ExitState < 0 or self.ExitState >= len(self.S):
print("ERROR: Exit state is not a state number. MAP-009")
Success = False
else:
print("ERROR: Missing exit states. MAP-010")
Success = False
# Check that there are no object in exit state.
if self.ExitState in self.ObjectLocations:
print("ERROR: Cannot have object on exit state. MAP-022")
# Check that transition matrix makes sense
if sum([np.all(np.sum(self.T[:, i, :], axis=1) == 1) for i in range(len(self.A))]) != len(self.A):
print("ERROR: Transition matrix is not well formed. MAP-011")
Success = False
return Success
def BuildGridWorld(self, x, y, diagonal=True):
"""
Build a simple grid world with a noiseless transition matrix and an unreachable dead.
Planner objects take advantage of the dead state to build MDPs that converge faster.
Args:
x (int): Map's length
y (int): Map's height
diagonal (bool): Can the agent travel diagonally?
"""
self.mapwidth = x
self.mapheight = y
self.diagonal = diagonal
WorldSize = x * y
self.S = list(range(WorldSize))
self.StateTypes = [0] * len(self.S)
if diagonal:
self.A = list(range(8))
self.ActionNames = ["L", "R", "U", "D", "UL", "UR", "DL", "DR"]
else:
self.A = list(range(4))
self.ActionNames = ["L", "R", "U", "D"]
if self.ObjectNames == []:
self.ObjectNames = [
"Object " + str(i) for i in set(self.ObjectTypes)]
# From, With, To. Add one for the dead state
self.T = np.zeros((len(self.S) + 1, len(self.A), len(self.S) + 1))
# First create dead state structure. All actions leave agent in same
# place.
self.T[len(self.S), :, len(self.S)] = 1
# Make all states of the same type
self.StateTypes = [0] * (len(self.S))
for i in range(len(self.S)):
# Moving left
if (i % x == 0):
self.T[i, 0, i] = 1
else:
self.T[i, 0, i - 1] = 1
# Moving right
if (i % x == x - 1):
self.T[i, 1, i] = 1
else:
self.T[i, 1, i + 1] = 1
# Moving up
if (i < x):
self.T[i, 2, i] = 1
else:
self.T[i, 2, i - x] = 1
# Moving down
if (i + x >= WorldSize):
self.T[i, 3, i] = 1
else:
self.T[i, 3, i + x] = 1
if diagonal: # Add diagonal transitions.
if ((i % x == 0) or (i < x)): # Left and top edges
self.T[i, 4, i] = 1
else:
self.T[i, 4, i - x - 1] = 1
if ((i < x) or (i % x == x - 1)): # Top and right edges
self.T[i, 5, i] = 1
else:
self.T[i, 5, i - x + 1] = 1
# Bottom and left edges
if ((i % x == 0) or (i + x >= WorldSize)):
self.T[i, 6, i] = 1
else:
self.T[i, 6, i + x - 1] = 1
# Bottom and right edges
if ((i % x == x - 1) or (i + x >= WorldSize)):
self.T[i, 7, i] = 1
else:
self.T[i, 7, i + x + 1] = 1
def InsertSquare(self, topleftx, toplefty, width, height, value):
"""
Insert a square of some type of terrain. This function rewrites old terrains.
MAPS are numbered from left to right and from top to bottom, with the first state numbered 1 (not 0).
Args:
topleftx (int): x coordinate of top left corner of square (counting from left to right)
toplefty (int): y coordinate of top left corner of square (counting from top to bottom)
width (int): Square's width
height (int): Square's height
"""
if ((topleftx + width - 1) > self.mapwidth) or ((toplefty + height - 1) > self.mapheight):
print("ERROR: Square doesn't fit in map. MAP-012")
return None
TopLeftState = (toplefty - 1) * self.mapwidth + (topleftx) - 1
for i in range(height):
initial = TopLeftState + self.mapwidth * i
end = TopLeftState + width + 1
self.StateTypes[initial:end] = [value] * width
def GetActionList(self, Actions):
"""
Transform a list of action names into a list of action indices.
Args:
Actions (list): List of action names
Returns
Actions (list): List of actions in numerical value
"""
ActionList = [0] * len(Actions)
for i in range(len(Actions)):
ActionList[i] = self.ActionNames.index(Actions[i])
return ActionList
def GetWorldSize(self):
"""
Get size of world
Args:
None
Returns:
Size (int)
"""
return len(self.S)
def NumberOfActions(self):
"""
Get number of actions
Args:
None
Returns:
Number of actions (int)
"""
return len(self.A)
def GetActionNames(self, Actions):
"""
Get names of actions
Args:
Actions (list): List of actions in numerical value
Returns
Actions (list): List of action names
"""
ActionNames = [0] * len(Actions)
for i in range(len(Actions)):
ActionNames[i] = self.ActionNames[Actions[i]]
return ActionNames
def GetRawStateNumber(self, Coordinates):
"""
Transform coordinate into raw state number
Args:
Coordinates (list): with the x and y coordinate.
Returns
State (int)
"""
# Transform coordinates to raw state numbers.
xval = Coordinates[0]
yval = Coordinates[1]
if (xval <= 0) or (xval > self.mapwidth):
print("ERROR: x-coordinate out of bounds (Numbering starts at 1). MAP-013")
return None
if (yval <= 0) or (yval > self.mapheight):
print("EROOR: y-coordinate out of bounds (Numbering starts at 1). MAP-014")
return (yval - 1) * self.mapwidth + xval - 1
def GetCoordinates(self, State):
"""
Transform raw state number into coordinates
Args:
State (int): State id
Returns
Coordinates (list): x and y coordinates ([x,y])
"""
if (State >= len(self.S)):
print("ERROR: State out of bound. MAP-015")
return None
yval = int(math.floor(State * 1.0 / self.mapwidth)) + 1
xval = State - self.mapwidth * (yval - 1) + 1
return [xval, yval]
def InsertObjects(self, Locations, ObjectTypes, Organic, ObjectNames=None, SurvivalProb=1):
"""
Add objects to map.
Args:
Locations (list): List of state numbers where objects should be placed
ObjectTypes (list): List of identifiers about object id
Organic (list)L List identifyng if objects are organic (organic objects have a future discount on the reward as a function of path length)
ObjectNames (list): List of names for the objects
SurvivalProb (float): Probability of organic objects surviving.
Returns:
None
Example: Add five objects on first five states. First two and last three objects are of the same kind, respectively.
>> InsertTargets([0,1,2,3,4],[0,0,1,1,1],["Object A","Object B"],[False,False])
>> InsertTargets([22,30],[0,1],["Agent","Object"],[True,False], 0.95)
"""
# Check that location and locationtype match
if len(Locations) != len(ObjectTypes):
print(
"ERROR: List of locations and list of location types are of different length. MAP-016")
return None
# Check that object names match number of objects
if ObjectNames is not None:
if len(ObjectNames) != len(set(ObjectTypes)):
print("ERROR: Object names do not match number of objects. MAP-017")
return None
# Not useful to validate object types because user might add targets in more than one step.
# That can be checked later through the validate() method
self.ObjectLocations = Locations
self.ObjectTypes = ObjectTypes
self.Organic = Organic
self.ObjectNames = ObjectNames
self.SurvivalProb = SurvivalProb
def PullObjectStates(self, Coordinates=True):
"""
Returns a list of states that have an object in them.
Args:
Coordinates (bool): Return raw state numbers or coordinates?
"""
if not Coordinates:
return self.ObjectLocations
else:
return [self.GetCoordinates(item) for item in self.ObjectLocations]
def AddTerrainNames(self, StateNames):
"""
Add names to the states depending on the terrain.
Args:
StateNames (list): List of strings with state names
"""
if len(StateNames) != len(set(self.StateTypes)):
print(
"ERROR: List of state names does not match number of state types. MAP-018")
return None
self.StateNames = StateNames
def AddExitState(self, ExitState):
"""
Add exit state to map
"""
if ExitState < 0 or ExitState >= len(self.S):
print("ERROR: Exit state is not a state in the map. MAP-019")
return None
self.ExitState = ExitState
def AddStartingPoint(self, StartingPoint):
"""
Add starting point to map
"""
if StartingPoint < 0 or StartingPoint >= len(self.S):
print("ERROR: Starting point is not a state in the map. MAP-020")
return None
self.StartingPoint = StartingPoint
def PrintMap(self, terrain='*'):
"""
Print map in ascii
Args:
terrain (Character): Character to mark terrains.
>> MyMap.PrintMap()
"""
#if not self.Validate():
# print("WARNING: Map isn't well formed. May fail to print. MAP-021")
colors = ['\033[94m', '\033[92m', '\033[93m',
'\033[91m', '\033[1m', '\033[4m', '\033[95m']
endcolor = '\033[0m'
sys.stdout.write("Action space: " + str(self.ActionNames) + "\n")
sys.stdout.write("Targets: ")
if self.ObjectLocations != []:
sys.stdout.write(str(self.PullObjectStates(True)) + "\n")
else:
sys.stdout.write("None\n")
sys.stdout.write("Exit state: ")
if self.ExitState is not None:
sys.stdout.write(str(self.GetCoordinates(self.ExitState)) + "\n\n")
else:
sys.stdout.write("None\n")
# Print color keys
terrains = list(set(self.StateTypes))
sys.stdout.write("Terrains: ")
if self.StateNames == []:
for i in range(len(terrains)):
sys.stdout.write(
colors[i] + "Terrain " + str(i) + endcolor + " ")
else:
for i in range(len(terrains)):
sys.stdout.write(
colors[i] + str(self.StateNames[i]) + endcolor + " ")
sys.stdout.write("\nItems: ")
if self.ObjectNames == []:
for i in range(len(self.ObjectTypes)):
sys.stdout.write(
"Object " + str(i) + " ")
if self.Organic[i]:
sys.stdout.write("(Organic) ")
else:
for i in self.ObjectTypes:
sys.stdout.write(
str(self.ObjectNames[i]) + " ")
if self.Organic[i]:
sys.stdout.write("(Organic) ")
sys.stdout.write("\n")
if sum(self.Organic) > 0:
sys.stdout.write("Surirval probability: " +
str(self.SurvivalProb) + "\n")
sys.stdout.write("Map labels: Exit state (E), starting point (S)")
for i in range(len(self.ObjectNames)):
sys.stdout.write(", " + self.ObjectNames[i] + "(" + str(i) + ")")
sys.stdout.write("\n\n")
ObjectStates = self.PullObjectStates(False) # Get raw object states
currstate = 0
begincolor = endcolor
for i in range(self.mapheight):
for j in range(self.mapwidth):
# Check if state being printed has an object
character = terrain
if currstate == self.ExitState:
character = 'E'
if currstate == self.StartingPoint:
character = 'S'
if currstate in ObjectStates:
index = ObjectStates.index(currstate)
character = self.ObjectTypes[index]
begincolor = colors[self.StateTypes[self.mapwidth * i + j]]
sys.stdout.write(begincolor + str(character) + endcolor)
currstate += 1
sys.stdout.write("\n")
sys.stdout.write("\n")
def Display(self, Full=False):
"""
Print object attributes.
.. Internal function::
This function is for internal use only.
Args:
Full (bool): When set to False, function only prints attribute names. Otherwise, it also prints its values.
Returns:
standard output summary
"""
if Full:
for (property, value) in vars(self).items():
print((property, ': ', value))
else:
for (property, value) in vars(self).items():
print(property)
|
f0438d1379df6974702dc34ef108073385a3877e | Nightzxfx/Pyton | /function.py | 1,069 | 4.1875 | 4 | def square(n):
"""Returns the square of a number."""
squared = n ** 2
print "%d squared is %d." % (n, squared) <--%d because is comming from def (function)
return squared
# Call the square function on line 10! Make sure to
# include the number 10 between the parentheses.
square(10)
--------------------------
def power(base, exponent): # Add your parameters here!
result = base ** exponent
print "%d to the power of %d is %d." % (base, exponent, result)
power(37, 4) # Add your arguments here!
-------------------------------
def one_good_turn(n):
return n + 1
def deserves_another(m):
return one_good_turn(m) + 2 <0 use the result of the frist funciton to apply in the second
---------------------------
def cube(number):
return number * number * number
def by_three(number):
if number % 3 == 0: <-- if the number is devided by 3
return cube(number)
else:
return False
-----------------
def distance_from_zero(p):
if type(p) == int or type(p) == float:
return abs(p)
else:
return "Nope"
|
2677119db01d3fd1d41347277081543c738d20b3 | sad786/Python-Practice-Programs | /Python/Palindrome.py | 334 | 4.09375 | 4 | '''
palindrome number is the number if we reverse the sequence of the digits then we will get the same number
'''
x = int(input("Enter any number = "))
n = x
res = 0
while n>0:
t = int(n%10)
n = int(n/10)
res = res*10+t
if res==x:
print(x,"is palindrome number")
else:
print(x,"is not palindrome number") |
8b5cfaf02f500a4eab9704acd41d533236095ef3 | maelys/Images_downloader | /database_manager.py | 1,303 | 3.734375 | 4 | import sqlite3
class DatabaseManager:
CREATE_TABLE = "CREATE TABLE IF NOT EXISTS photos (photo_id PRIMARY KEY, user_name text, tags text, upload_date text, vote text, avg text);"
INSERT_QUERY = "INSERT INTO photos (photo_id, user_name, tags, upload_date, vote, avg) VALUES (?, ?, ?, ?, ?, ?);"
conn = ''
c = ''
def connect(self):
self.conn = sqlite3.connect('database.sqlite')
self.c = self.conn.cursor()
# Create table
self.c.execute(self.CREATE_TABLE)
self.conn.commit()
def insert(self,insert_values):
# Insert into table
self.c.execute(self.INSERT_QUERY, insert_values)
# Commit the changes
self.conn.commit()
def photo_exist(self, photo_id):
# Check if a photo is already in the database
self.c.execute('SELECT COUNT (*) FROM photos WHERE photo_id = %s' % photo_id)
result = self.c.fetchone()
count = result[0]
print count
if (count == 0):
return False
else:
return True
def print_db(self):
# Select all
self.c.execute('SELECT* FROM photos')
for row in self.c:
print row
def close(self):
# Close the cursor
self.conn.close()
|
17dddfaf05ed5f17df5de99738bea1c8f0b3c6cb | ludwigflo/ml_utils | /src/ml_utils/data_utils/data_split.py | 2,981 | 4.03125 | 4 | import random
def data_split(num_data: int, train_data: float, val_data: float, shuffle: bool = True) -> tuple:
"""
Computes the indices for a training, validation and test split, based on the total number of data. The test data are
the remaining data, which have not been assigned to training or validation data.
Parameters
----------
num_data: Total number of available data.
train_data: Fraction of data, which should be used for training.
val_data: Fraction of data, which should be used for validation.
shuffle: Boolean, which indicates whether to shuffle the data or not.
Returns
-------
split: tuple, in which lists of indices according to the splits are stored.
"""
assert train_data + val_data <= 1, "The amount of training and validation data needs to be smaller ot equal to 1!"
# create the indices, corresponding to the data points, and shuffle them, if required
indices = list(range(num_data))
if shuffle:
random.shuffle(indices)
# compute the amount of indices
num_train_indices = int(train_data * num_data)
num_val_indices = int(num_data * val_data)
# split the indices into their corresponding lists
train_indices = indices[:num_train_indices]
val_indices = indices[num_train_indices:num_train_indices+num_val_indices]
# if there are remaining data points, assign them to the test set
if num_train_indices + num_val_indices < num_data:
test_indices = indices[num_train_indices+num_val_indices:]
split = (train_indices, val_indices, test_indices)
else:
split = (train_indices, val_indices)
return split
def k_fold_cross_validation(k: int, num_data: int, shuffle: bool = True) -> tuple:
"""
Splits a number of training data into k folds, which can be used for k-fold-cross-validation.
Parameters
----------
k: number of folds for cross validation.
num_data: Total amount of data values.
shuffle: Boolean variable, which indicates whether to shuffle the data or not.
Returns
-------
split: tuple, in which lists of indices according to the splits are stored.
"""
assert num_data >= k, "Total amount of data needs to be larger or equal to the number of folds!"
# create indices, corresponding to the data points, and shuffle them, if required
indices = list(range(num_data))
if shuffle:
random.shuffle(indices)
# compute the sizes of the folds and the remaining number of data
fold_size = int(num_data / k)
remaining_data = num_data % k
# compute the splits
fold_list = []
for i in range(k):
fold_list.append(indices[i*fold_size:(i+1)*fold_size])
# append the remaining data points to the folds
for i in range(remaining_data):
fold_list[i].append(indices[k*fold_size+i])
split = tuple(fold_list)
return split
|
087d90c8f10870f8efa7882d4341501eeb4c9f57 | Wasylus/lessons | /lesson22.py | 1,053 | 3.734375 | 4 | # test.assert_equals(nth_fib(3), 1, "3-rd Fibo")
# test.assert_equals(nth_fib(4), 2, "4-th Fibo")
# test.assert_equals(nth_fib(5), 3, "5-th Fibo")
# test.assert_equals(nth_fib(6), 5, "6-th Fibo")
# test.assert_equals(nth_fib(7), 8, "7-th Fibo")
# def fib(n):
# pass
# def fib(n):
# raise NotImplementedError
# test.assert_equals(fib(1), 0, "1-st Fibo")
# test.assert_equals(fib(2), 1, "2-nd Fibo")
# F(1) F(2) F(3) F(4) F(5)
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
# def nth_fib(n: int) -> int:
# if n == 1:
# return 0
# elif n == 2:
# return 1
# print(n)
# return nth_fib(n-1) + nth_fib(n-2)
# def nth_fib(n: int) -> int:
# if n == 1 or n == 2:
# return n - 1
# return nth_fib(n-1) + nth_fib(n-2)
def nth_fib(n: int) -> int:
if n < 1:
raise ValueError
if n <= 2:
return n - 1
print(n)
return nth_fib(n-1) + nth_fib(n-2)
# n = int(input("Give me some n:"))
nth_result = nth_fib(2)
print(nth_result) |
12188e81219abc09fc9e995f00ec54a52b605166 | Wasylus/lessons | /lesson12.py | 1,117 | 4.4375 | 4 |
# print(int(bmi))
# # 1. What if bmi is 13
# # 2. What if bmi is 33
# if bmi <= 18:
# print("Your BMI is 18, you are underweight.")
# elif bmi >= 22:
# print("Your BMI is 22, you have a normal weight.")
# elif bmi >= 28:
# print("Your BMI is 28, you are slightly overweight.")
# elif bmi >= 33:
# print("Your BMI is 33, you are obese.")
# print("Your BMI is 40, you are clinically obese.")
# result = int(bmi)
# print(result)
def calculate_bmi(weight: float, height: float) -> float:
return weight / height ** 2
def bmi_to_str(bmi: int) -> str:
if bmi < 18:
return "underweight"
elif bmi < 25:
return "normal weight"
elif bmi < 30:
return "overweight"
elif bmi < 35:
return "obese"
else:
return "clinically obese"
# Homework: check math.ceil, math.floor, math.round
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
bmi = calculate_bmi(weight, height)
bmi_repr = bmi_to_str(bmi)
msg = f"Your bmi is {int(bmi)}, you are {bmi_repr}"
print(msg) |
698acc83f10059e5905a491a162a63e6ab518c07 | Wasylus/lessons | /lesson27.py | 1,233 | 3.90625 | 4 |
# TODO: This method needs to be called multiple times for the same person (my_name).
# It would be nice if we didnt have to always pass in my_name every time we needed to great someone.
class Person:
def __init__(self, my_name):
self.name = my_name
def greet(self, your_name: str) -> str:
msg = f"Hello {your_name}, my name is {self.name}"
print(msg)
return msg
def greet_long_names(self,name: str):
if len(name) >= 4:
return f"You have a long name: {name}"
return f"Hello, you have a short name {name}"
# Exact same behavior can be achieved by:
# else:
# return f"Hello, you have a short name {name}"
person_one = Person("Jill")
person_two = Person("Jack")
assert person_two.greet("Jill") == "Hello Jill, my name is Jack"
assert person_two.greet("Mary") == "Hello Mary, my name is Jack"
assert person_one.greet("Jack") == "Hello Jack, my name is Jill"
assert person_one.name == "Jill", "Person's name could not be retrieved"
# This is how "assert" keyword works under the hood
# if not (jill.name == "Jill"):
# raise AssertionError("Person's name could not be retrieved")
|
8a2d42da1ecc91edeb91370f73cc4cf75137df54 | kokowhen/my_Learning_Notes | /Python/Codes/list_pra.py | 2,104 | 3.953125 | 4 | namelists=[1,2,3,"小明","k"] #数据的操作:增、删、改、查、排、反
i=0
for namelist in namelists:
while i<5:
namelists.append("jeffery") #append是在列表的末尾增加元素,默认把增加的对象当作一个元素
i+=1
b=[90,100]
namelists.append(b)
print(namelists)
print(namelists[2:8:3])
namelists.extend(b) #extend是把a列表里的元素逐一增加到b列表的末尾
namelists.insert(4,"jacky") #insert是指定增加元素位置的方式增加
print(namelists)
songNames=["手写的从前","简单爱","以父之名","牛仔很忙","彩虹","最长的电影"]
for songName in songNames:
print(songName)
del songNames[2] #del删除指定位置元素
print(songNames)
songNames.pop() #pop删除列表末尾最后一个元素
print(songNames)
songNames.remove("手写的从前") #remove删除列表中特意指定的元素
print(songNames)
bookNames=["小狗钱钱","时间简史","解读基金","1984","老人与海","炼金术士","时间简史","解读基金","1984","老人与海","炼金术士"]
for bookName in bookNames:
print(bookName)
bookNames[2]="j1's story" #直接修改,比较简单
print(bookNames)
i="j1's story"
if i in bookNames: #if in查找,返回判断的结果
print("yes")
else:
print("no")
a=bookNames.index("小狗钱钱")
print(a)
a=bookNames.index("小狗钱钱",0,5) #index可以指定查找的区间,但是要确定查找的内容在区间内,不然会报错,返回对应元素被的下标
#注意区间是左闭右开的
a=bookNames.count("shijianjianshi")
print(a)
a=bookNames.count("时间简史") #count查找某个元素在列表中出现的个数,返回指定元素在列表中出现的个数
print(a)
bookNames.reverse() #自身只是None值,反转列表里的元素排序位置
print(bookNames)
bookNames.sort() #sort排序,注意升序和降序怎么用
print(bookNames)
bookNames.sort(reverse=True) #T一定要大写
print(bookNames)
a=[["A","B","C","D"],["E","F"],["G"]]
for i in a:
print(i) |
b4f6c409b78ec37ec8d0848556502085b9059111 | kokowhen/my_Learning_Notes | /Python/Codes/pra_729.py | 953 | 3.734375 | 4 | #向函数传递列表
def greet_users(names):
for name in names:
msg = "Hello,"+ name +"!"
print(msg)
usernames = ["hannah","ty","margot","Jeffery"]
greet_users(usernames)
#在函数中修改列表
#传递任意数量的实参
#1.结合使用位置实参和任意数量实参
def song(author,*songname):
print("{}'s song :\n{}".format(author,songname))
song("zhoujielun","J","K","l")#所有值会存储在元组songname中
#2.使用任意数量的关键字实参
def build_profile(first_name,last_nmae,**user_info):
profile = {}
profile["first_name"] = first_name
profile["last_nmae"]= last_nmae
for key,value in user_info.items():
profile[key] = value #将实参键值对传入到形参空字典user_info中,并将字典user_info里的键值对传入到字典profile中
return profile
user_profile = build_profile("Jeffery","SHI",location="Chendu",field="CS",hobby="guitar")
print(user_profile)
#将函数存储在模块中 |
553e1903b680207d1c0e956b7b881692609834a3 | OJ13/Python | /Udemy/Iniciantes/condicionais.py | 400 | 4.1875 | 4 | numero = 1
if(numero == 1):
print("Numero é igual a um")
if(numero == 2) :
print("Número é igual a Dois")
numero = 3
if(numero == 1):
print("Numero é igual a um")
else:
print("Número não é igual a um")
nome = "Junior"
if("z" in nome) :
print("Contém 'Z' no nome")
elif("o" in nome) :
print("Contém 'o' no nome")
else:
print("Não contém nem Z nem O")
|
79a5a20c451782ce716bc8e2ec9ab797d4fed101 | OJ13/Python | /Udemy/python&MySql/exercicios.py | 1,236 | 3.890625 | 4 | #Baskara
#a2 + bx + c
#(-b +- sqtr(b2-4ac))/2
from math import sqrt
a = int(input("Digite o valor de a: "))
b = int(input("Digite o valor de b: "))
c = int(input("Digite o valor de c: "))
delta = b**2 - 4*a*c
raiz_delta = sqrt(delta)
x1 = (-b + raiz_delta)/(2*a)
x2 = (-b - raiz_delta)/(2*a)
print("x1 = %f" %x1)
print("x2 = %f" %x2)
##Ordenar Listas
lista = [5, 9, 3, 2, 1, 8, 0]
#print(sorted(lista)) #função já para isso
#select sort
for i in range(len(lista)):
menor = i
for j in range(i+1, len(lista)):
if lista[j] < lista[menor]:
menor = j
if lista[i] != lista[menor]:
aux = lista[i]
lista[i] = lista[menor]
lista[menor] = aux
print(lista)
num1 = int(input("Digite o primeiro número: "))
operador = input("Digite o operador: ")
num2 = int(input("Digite o segundo número: "))
resultado = -1
if operador == "+":
resultado = num1 + num2
elif operador == "-":
resultado = num1 - num2
elif operador == "*":
resultado = num1 * num2
elif operador == "/":
resultado = num1 / num2
elif operador == "%":
resultado = num1 % num2
elif operador == "**":
resultado = num1 ** num2
else:
print("Operador não encontrado")
print(resultado) |
4b7f9a4c23369576bb69b8dc891165bb07802736 | Rohitkumar3796/PYTHON_CODES | /PYTHON_CODES.py | 32,095 | 3.9375 | 4 | # HOW CAN WE CONVERT STRING VALUE TO INT
str1="Hello World!"
int_=''.join(map(str,map(ord,str1)))
print(int(int_))
# --------------------------------------------------------------------
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 3) #here 3 means how much time "one is repeated in the string"
print(x)
# ------------------------------------------------
a,b=(input("enter")).split()#here i se split function to split input
print(int(a)+int(b))
# -----------------------------------------------------------------------------
# from tkinter import *
# from tkinter.ttk import *
# from time import strftime
# root=Tk()
# root.title("Clock")
# def time():
# string=strftime('%H:%M:%S %p')
# label.config(text=string)
# label.after(1000,time)
#
# label=Label(root,font=("ARIAL" ,20),bg="GREY",fg="WHITE")
# label.pack(anchor="center")
# time()
# root.mainloop()
# =================================================================
string="one two three\nfour\tfive" #\n and \t means space so split function is used to split from space
print(string.split())
# ------------------------------
string="one,two,three,four,five" #here i separated the string from comma and use spllit function and
#number also so it splits the 3 starting string separated by string and left of the string is printed in a single string separated by comma
print(string.split(",",3))
# ----------------------------------------------------
string="one\ntwo\nthree\nfour"
print(string.split('\n',2)[2]) #it print like nested list of string here i use slicing from different type
# --------------------------------------------------
s="one,two,three,four" #here we can also split from right side
print(s.rsplit(',',2)[-1])
# ---------------------------------------------------
s_lines_multi = '1 one\n2 two\r\n3 three\n'
print(s_lines_multi.split()) #['1', 'one', '2', 'two', '3', 'three']
print(s_lines_multi.split("\n"))#['1 one', '2 two\r', '3 three', '']
print(s_lines_multi.splitlines())#['1 one', '2 two', '3 three'](splits at various newline characters but not at other whitespace.not include)
# ------------------------------------------------------------------------------
# string="rrrrohit"
# a=string.lower()
# b=input("char")
# v=a.count(b)
# for i in range(v):
# a=a.replace(b,'*')
# print(a.capitalize())
# ----------------------------------------------
# list_of_numbers=list(range(10))
# print(list_of_numbers)
# ------------------------------------------/
# list=[1,2,3,4,5,13,7,8]
# print(list[list[4]]) #here list of index of 4, the value is 5 but another list 0f 5 as a index number for another list so it prints 13, index of
# ----------------------------------------------------
# list=[]
# for i in range(4):
# if len(list)==i:
# list.insert(i,int(input('num')))
# print(list)
# ------------------------------------
# squares and sum of natural number
n=int(input("num"))
m=0
for i in range(1,n+1):
a=i**2
print(a)
m=a+m
print(m)
# ------------------------------------------------------------
# recursive fuction to calculate sum of square of natural numbers
def sq_num(n):
if n==1:
return n
else:
r=sq_num(n-1)
return r+n**2
n=int(input("number"))
print(sq_num(n))
# ---------------------------------
# use return keyword omly to return the value
def print_nums(x):
for i in range(x):
print(i)
return
print_nums(10)
# ------------------------------------
# Celsius = (Fahrenheit – 32) * 5/9
# Fahrenheit = (Celsius * 9/5) + 32
celsius = int(input())
def conv(c):
return (c * 9 / 5) + 32
fahrenheit = conv(celsius)
print(fahrenheit)
# ---------------------------------------------
# nums = {1, 2, 3, 4, 5, 6}
# nums = {0, 1, 2, 3} & nums #here i use and oerator, so it's comparing the value in both sets
#
# nums = filter(lambda x: x > 1, nums)
# print(len(list(nums)))
# --------------------------------------------------
foo=print()
if foo==None:
print(1)
else:
print(2)
# ------------------------------------------------
# def deliver(houses):
# if len(houses) == 1:
# house = houses[0]
# print("DELIVER", house)
# else:
# res = len(houses) // 2
# first_half = houses[:res]
# second_half = houses[res:]
# return first_half, second_half
#
# print(deliver(["Eric's houses", "Rohit houses", "Amit houses", "Pooja houses"]))
# ----------------------------------------------------------------------------------
def fun(func,arg):
return func(func(arg))
def mult(x):
return x+x
v=fun(mult,3) #what happened here when will pass mult function to fun function as an argument in func parameter
print(v) #In second line of fun function there is return so there we call mult fucntion and pass value args as a value to mult function
# -----------------------------------------------------------------
# PRIME OR NOT
n=30
for i in range(2,n):
for j in range(2,i):
if(i%j==0):
break
else:
print(i,'prime')
# ==========================================
# def power(x, y):
# if y == 0:
# return 1
# else:
# return x * power(x, y - 1)
#
# print(power(2, 3))=
# ---------------------------------------------
# from itertools import accumulate, takewhile
#
# nums = list(accumulate(range(8)))
# print(nums)
# print(list(takewhile(lambda x: x<= 6, nums)))
# -----------------------------------------------
# def fib(n):
# if n==1 or n==0:
# return 1
# else:
# fibo= fib(n-1) +fib(n-2)
# return fibo
# print(fib(int(input('num'))))
#
# ---------------------------------------
# from functools import reduce
# number=[1,2,3,4,5]
# sum of list of numbers by reduce function
# c=reduce(lambda x,y:x+y,number)
# print(c)
# ----------------------------------------------
# import re
# c=re.findall(r'\w','http://www.hackerrank.com/')
# print(c)
#
# c=re.finditer(r'\w','http://www.hackerrank.com/')
#
# v=list(map(lambda x: x.group(),c))
# print(v)
#
# string="rabcdeefgyYhFjkIoomnpOeorteeeeet"
# -------------------------------------------------------------
# nums=[1,2,3,4,5,6,7]
# res=list(filter(lambda x:x%2==0,nums))
# print(res)
# ------------------------------------------
# def spell(txt):
# if txt=="":
# return txt
# else:
# a=spell(txt[1:])
# return a+txt[0]
#
# txt = input()
# print(spell(txt)) #INPUT=HELLO, OUTPUT=OLLEH
# ---------------------------------------------------------------------------------------
# squares numbers with function
# def sq(n):
# if n == 1:
# return n
# else:
# return n**2 + sq(n-1)
#
# print(sq(5))
# # squares number from lambda
# sq=lambda n: n if n==1 else n**2 + sq(n-1)
# print(sq(5))
# --------------------------------------------/
# a=int(input("enter the number"))
# b=int(input("enter the 2nd number"))
# c=int(input("enter the 3rd number"))
# if a>b and a>c:
# if b>c:
# print("a is greater")
# else:
# print("c is greater")
# else:
# print("b is greater")
#-----------------------------------------
# a=int(input("enter the number"))
# if a>5 and a<10:
# if a==7:
# if a<=8:
# print("yes it is less than 8")
# else:
# print("enter the number again")
# else:
# print(" ** enter the number again")
# elif a>=12:
# print("number is greater ")
# else:
# print("enter the number again")
#----------------------------------------------
#list1=[["rohit",24],["shubham",23],["dhruv",24],["vishal",24],["amartya",24],["vishwajit",23]]
# set1=set()
# set1.add("rohit")
# set1.add("kumar")
# print(set1)
# set2=list(set1)
# print(set2)
# set1={"apple","mango",["banana"],["cherry"]}
# print(set1)
#===============================================
# list1=[ 1,4,3,5,2,24,3,55,23,54,6]
# for item in list1:
# if str(item).isnumeric() and item>6:
# print(item)
i=0
while(i<45):
i+=1
if i < 4:
print("yes it is less than",i, end=" ")
else:
print("get out ",i, end=" ")
# ===================================================================
# list1=[1,23,4,4,5,5]
# for number in list1:
# print(number,end=" ")
# i=0
# while(True):
# print(i+1)
# if(i==10):
# break
# i+=1
# c=lambda a,b:a+b
# print(c(4,6))
# z=lambda x,y:\
# x+y
# print(z(3,5))
# class student:
# x=5
# print(x)
#
# s1=student
# y=s1.x
# print(y)
# a="7"
# b="8"
# print(int(a)+int(b))
# print("enter the number")
# num=input()
# print(int(num)+10)
# tuple1=tuple()
# tuple1="rohit","kumar","amit"
# print(tuple1)
# list1=tuple1
# list1=list()
# print(list1)
# list1="rohit","amit","amit"
# print(list1)
# a=7
# b=8
# temp=a
# a=b
# b=temp
# print(a,b)
# dict1=dict
# dict1={"name":"rohit"}
# dict1.update({"name2":"amit"})
# dict1["name3"]="poja"
# dict1["name4"]="kusum"
# print(dict1)
# string1="red black blue maroon"
# print(string1.split())
# def add(**name): #key= value
# print(name)
#
# add(name="rohit",surname="kumar")
# add(android="samsung",book="python")
# i=0
# while(True):
#
# if(i<10):
# i=i+1
# print(i)
# continue
# print(i)
# if i==20:
# break
# i=i+1
#continue= stop the current iteration and run the next, break = when condition is true the its stop execution
# while True:
# num = int(input("enter the number\n"))
# if num>50:
# print("yes you entered the right number")
# break
# elif num==50:
# print("both are equal")
#
# else:
# print(num,"\n enter the number again")
# continue
# ==========================================================================
#Arithmetic operation
# print("2+4",2+4)
# print("2-4",2-4)
# print("2*4",2*4)
# print("2/4",2/4)
# print("2%4",2%4)
# print("2**4",2**4)
# print("2//25",2//25)
#Assignment operator
#Coomparison operator
#Identity operators
#Membership operators
#Logical operators
# a=True
# b=False
# print(not(a or b))
# c=False
# d=False
# print(not(c or d))
# x=True
# y=True
# print(not(x or y))
# p=False
# q=True
# print(not(p or q))
# Bitwise operator
# print(bool(1&2))
# print(bool(3|2))
# a=int(input("enter the number"))
# b=int(input("enter the number"))
# print("a is greater than b") if a>b else print("b is greater than a")
# a=9
# b=7
# try:
# print(a + b)
# except Exception as e:
# print(e,"this is important line")
# print("ok i got the error")
# else:
# print("i got no error in try block")
# =======================================
# try:
# print("a is greater then b") if a>b else print("b is greater than a")
# except Exception as e:
# print("NOT DEFINED")
# print("hello")
# else:
# print("if no error found then will execute else statement")
# finally:
# print("main nahi rukunga meri marzi")
# --------------------------------------------------------------
# def is_inverse(word,word1):
# if len(word) != len(word1):
# return False
# i=0
# j=len(word1)-1
# while j>0:
# if word[i]==word1[j]:
# return False
#
# i = i + 1
# j = j - 1
#
# return True
#
# z=is_inverse("rohit","sphit")
# print(z)
# ==============================================================
# lis = []
# s=input("Enter String")
# for ch in s:
# if ch in lis:
# lis.append('$')
# else:
# lis.append (ch)
# print(''.join(str(i) for i in lis))
# ==================================================
# def is_even(striing):
# print(striing)
#
# x=map(is_even,("r","o","h"))
# print(x)
###################################################
# Write a Python program to count the number of characters (character frequency) in a string. Go to the editor
# Sample String : google.com' Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1} By dictionary
# def count(string):
# dict={}
# for n in string:
# keys=dict.keys()
# if n in keys:
# dict[n]=dict[n]+1
# else:
# dict[n]=1
# return dict
#
# a=count("google")
# print(a)
#############################################################
# Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string.
# If the string length is less than 2, return instead of the empty string
# def first_last(string):
# string2=string[0:2] + string[-2:]
# print(string2)
# if len(string2)<2:
# return "empty"
# else:
# return "is greater"
# z=first_last("google")
# print(z)
#####################################################################
# Write a Python program to get a string from a given string where all occurrences of its first char have been
# changed to '$', except the first char itself.
# def special(string):
#
# char=string[1]
# string2=string.replace(char,"$")
# print(string2)
# string1=string[0]+char+string2[2:]
# return string1
#
# x=special("google")
# print(x)
######################################################################
# Write a Python program to get a single string from two given strings, separated by a space and swap
# the first two characters of each string. Example=abc,xyz: xyc:abz
# def new_String(a,b):
# char=b[0:2]+a[-1]
# char1=a[0:2]+b[-1]
# return char+" "+char1
#
# d=new_String("abc","xyz")
# print(d)
####################################################
# Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string,
# if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string
# Sample String : 'The lyrics is not that poor!'The lyrics is poor!'
# Expected Result : 'The lyrics is good!'The lyrics is poor!'
# def appearance(str):
# char="good"
# string=str.find("not")
# string1=str.find("poor")
# if string1>string:
# string2=str.replace(str[string:string1+4],char)
# print(string2)
#
# appearance("The lyrics is not that poor! The lyrics is poor!'")
###############################################################
# Write a Python program to remove the nth index character from a nonempty string
# def strings(string,n):
# first_part=string[:n]
# second_part=string[n+1:]
# main_string=first_part+second_part
# print(main_string)
# if __name__ == '__main__':
# strings("python",4)
####################################################
# Write a Python program to change a given string to a new string where the first and last chars have been exchanged
# def string(word):
# print(word)
# return word[-1:]+word[1:-1]+word[0:1]
#
# exchanged=input("enter the word, want to exchanged")
# a=string(exchanged)
# print(a)
##############################################
# Write a Python function that takes a list of words and returns the length of the longest one.
# def length(list1):
# list=[]
# for i in list1:
# list.append((len(i),i))
# list.sort()
# print(list[-1])
#
# length(["apple","pineapple","mango"])
# ====================================================
# Write a Python program to remove the characters which have odd index values of a given string.
# def string(word):
# for i in range(len(word)):
# if i%2==0:
# result=word[i]
# print(result,end="")
# a=input("enter the word")
# string(a)
# ========================================================
# Write a Python program to count the occurrences of each word in a given sentence
# def count(word):
# dict={}
# for i in word.split():
# keys=dict.keys()
# if i in keys:
# dict[i]=dict[i]+1
# else:
# dict[i]=1
# return dict
# b=input("enter the string:")
# a=count(b)
# print(a)
# =============================================================
# Write a Python script that takes input from the user and displays that input back in upper and lower cases.
# string=input("enter the string")
# print(string.upper())
# print(string.lower())
# +++++++++++++++++++++++++++==========================+++++++++++++++
# Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in
# sorted form (alphanumerically).Sample Words:red, white, black, red, green, black,Expected Result : black, green, red,
# white,red==here, we have taken a list from user and prints it in alphabatically
# def sep_comma(num):
# list=[]
# for i in range(num):
# list.append(input("enter the item"))
# for i in list:
# list.sort()
# print(list)
#
# a=int(input("enter the count"))
# sep_comma(a)
# ===============================================================/
# Write a Python function to insert a string in the middle of a string.
# def insert_word(string,number,word1):
# string=string.split()
# string.insert(number,word1)
# print(string)
#
# sentense=input("enter the word")
# index=int(input("enter the index"))
# word=input("enter the word")
# insert_word(sentense,index,word)
# ====================================================
# Write a Python function to get a string made of 4 copies of the last two characters of a specified string (
# length must be at least 2). Go to the editor. Sample function and result :insert_end('Python') -> onononon
# insert_end('Exercises') -> eseseses
# def four_copies(str):
# char=str[-2:]
# # space=""
# i=0
# while i < 4:
# main=char+""
# print(main,end="")
# i=i+1
# string = input("enter the word")
# four_copies(string)
# =================================================
# Write a Python function to get a string made of its first three characters of a specified string. If the length of
# the string is less than 3 then return the original string. Go to the editor.
# Sample function and result :first_three('ipy') -> ipy//first_three('python') -> pyt
# def return_original(str):
# if len(str)>3:
# return str
# else:
# return str
#
# word=input("enter the word")
# a=return_original(word)
# print(a)
# =================================================
# word="geeksforgeeks"
# char=word[0:3]
# space=""
# a=word.replace(char,space)
# b=space+word[3:]
# print(b)
# =============================================================
# 19. Write a Python program to get the last part of a string before a specified character.
# https://www.w3resource.com/python-exercises=https://www.w3resource.com/python
# def link(string):
# a=string.split("-")
# b=a[-1]
# string=string.replace(b,"")
# return string
#
# f=link("https://www.w3resource.com/python-exercises")
# print(f) #OUTPUT=https://www.w3resource.com/python-
# ======================================================================/
# 20. Write a Python function to reverses a string if it's length is a multiple of 4
# def reverse(string):
# a = len(string)
# if a % 4 == 0:
# while a >0 :
# b = string[a-1]
# print(b)
# a=a-1
# else:
# print("u enter the word is not a multiples of 4")
# word=input("enter the word")
# reverse(word)
# 2nd way use of join
# def reverse1(word1):
# if len(word1)%4==0:
# return "".join(reversed(word1))
# return word1
#
# a=reverse1("amit")
# print(a)
# =================================================================================//
# 21. Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase
# characters in the first 4 characters
# def string_IN_uppercase(string):
# Count_UpperCase=0
# for i in string[:4]: #for i in string[0:]
# if i.upper()==i:
# Count_UpperCase=Count_UpperCase+1
# if Count_UpperCase>=2:
# return string.upper()
# return string
# word=input("enter the word")
# a=string_IN_uppercase(word)
# print(a)
# ===================================================/
# Write a Python program to sort a string lexicographically. sort the string
# def lexicographically(string):
# a=list(string)
# a.sort()
# return a
# b=lexicographically("python3")
# print(b)
# =====================================================================/
# 23. Write a Python program to remove a newline in Python.
# string="Python Exercise\n"
# print(string.strip())
# ==================================================================
# 38. Write a Python program to count occurrences of a substring in a string
# string="is available at the bottom of the page to write and execute"
# print(string.count("the"))
# 39. Write a Python program to reverse a string.
# string="javascript"
#1st method
# print(string[::-1])
# 2nd method
# print("".join(sorted(string)))
# 3rd method
# string="rohit"
# i=5
# while i>0:
# print(string[i-1])
# i=i-1
# ====================================================================
# 40. Write a Python program to reverse words in a string
# string="means start at the end of the string and end "
# string=string.split()
# print(string[::-1])
# ===================================================================================
# 41. Write a Python program to strip a set of characters from a string
# remove vowels from string
# def remove_strip(str,vowel):
# for i in str:
# if i not in vowels:
# str=i
# print(str,end="")
#
# string="the quick brown fox"
# vowels="aeiou"
# remove_strip(string,vowels)
# remove vowels from string by join method
# def remove_strip(str,char):
# print("".join(c for c in str if c not in char))
#
# string="the quick brown fox"
# character="aeiou"
# remove_strip(string,character)
# ================================================================/
# 42. Write a Python program to count repeated characters in a string.
# Sample string: 'thequickbrownfoxjumpsoverthelazydog' by dict function
# def repeated_string(str):
# dict1 = dict()
# for x in string:
# if x in dict1:
# dict1[x]=dict1[x]+1
# else:
# dict1[x]=1
# return dict1
#
# string="thequickbrownfoxjumpsoverthelazydog"
# a=repeated_string(string)
# print(a)
# 2nd way by dict
# def repeated_string(str):
# dict={}
# for i in str:
# if i in dict:
# dict[i]=dict[i]+1
# else:
# dict[i]=1
# return dict
#
# string="the quick brown fox jumps over the lazy dog"
# a=repeated_string(string)
# print(a)
# ===============================================
element="rohit"
for i in reversed(element):
print(i)
=============================================
# REVERSER STRING/
# a='rohit'
# strg=''
# for i in a:
# strg=i+strg
# print(strg)
# # ===========================
# # RECURSION REVERSER STRING
# def reverse(string):
# if len(string)==0:
# return string
# else:
# return reverse(string[1:]) + string[0]
#
# print(reverse('point'))
# ==========================================
# string=input(("Enter a string:"))
# if(string==string[::-1]): #it return True because it is same from front and back side(front:madam=reverse:madam)
# print("The string is a palindrome")
# else:
# print("Not a palindrome")
# ------------------------------------
# num=int(input("Enter a number:"))
# temp=num
# rev=0
# while(num>0):
# a=num%10
# rev=rev*10+a
# num=num//10
#
# if(temp==rev):
# print("The number is palindrome!")
# else:
# print("Not a palindrome!")
# ------------------------------------
# num=int(input("Enter a number:"))
# temp=num
# rev=0
# while(num>0):
# a=num%10
# rev=rev*10+a
# num=num//10
#
# if(temp==rev):
# print("The number is palindrome!")
# else:
# print("Not a palindrome!")
# ===================================================
# def sum1(a,b):
# if a==0:
# return b
# else:
# return sum1(a-1,a+b)
# print(sum1(3,0)) output:6
# ========================================
# seed use with random.random() and from seed function we can hold or print the same value till the value are not change of seed
# import random
# random.seed(5)
# print(random.random())
# ===========================================
# literals in python
# String literals
# Numeric literals
# Boolean literals
# Literal Collections
# Special literals
# =======================================
# Q=Which code can be used as an input dialog named ''Is this a character? ''
# Ans=Tkinter.messagebox.askyesno(''askyesno'' , ''Is this a character? '')
# ============================================================================
# st='oro'
# string=''
# ind_=st.find('o')
# # print(ind_)
# char=st[ind_]
# # print(char)
# st1=st.replace(st[ind_],'@')
# st=st1[0:ind_+1]+st[ind_+1:]
# print(st)
# ============================================
# def dictionary_(string):
# dict1 = {}
# for i in string:
# if i not in dict1:
# dict1[i]=1
# else:
# dict1[i]=dict1[i]+1
# print(dict1)
#
# string='google'
# dictionary_(string)
# ==================================================
# a=34.6000
# print('{:.0f}'.format(a)) # if you give 0 so you got inter value
# print('{:.4%}'.format(0.33))
# =====================================================
# class Count:
# def __init__(self,count=0):
# self.__count=count
# a=Count(2)
# b=Count(2)
# print(id(a)==id(b))#as we know that different variable have same value so the ids(address) will be same but objects id(address) are not same
#
# c= " hello "
# d= " hello "
# print(id(c)==id(d))#here the same happening we have different variable have same value so the id will be same
# ==========================================================
# print('hello world'.istitle())#it identify as per the first character should be capital
# print('Hello World'.istitle())#it identify as per the first character should be capital
# =========================================================
# num=20
# def fun(x):
# global num
# num=num+x
# def fun1(x):
# num=x
# fun(x)
# print(num)
#
# fun1(10)
# print(pow(2,4,5)) #output how to write this 2**4%5
# ================================================================
# def out(original_func):
# message='Hi'
# def inner():
# print(message)
# return original_func()
# return inner
#
# @out
# def display():
# print("display")
#
# display()
# ====================class Bird: #PARENT CLASS
#
# def __init__(self,name,color):
# self.name=name
# self.color=color
# def whoisThis(self):
# print("Bird")
# def swim(self):
# print("swim faster")
# class Penguin(Bird): #CHILD CLASS
# no='rohit'
# def __init__(self,name,color):
# super().__init__(name,color)
# print("bird is ready")
#
# def whoisThis(self):
# print("Bird")
# def swim(self):
# print("swim faster")
#
# peggy=Penguin('rohit','black')
# peggy.whoisThis()
# print(peggy.name)
# -======================
# file=open('words.txt')
# print(file)
# word_dict=dict()
# for line in file:
# wordList=line.split('.')
# for word in wordList:
# word_dict[word]=word
#
# print(word_dict)
# ==================================
# num=eval(input("enter the number"))
# print("the result is: %d" %num)
# ====================================
import random
# lower="abcdefghijklmnopqrstuvwxyz"
# upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# specials="@#$%^"
# number="1234567890"
# length=16
# addup=upper+lower+specials+number
# password=''.join(random.sample(addup,length))
# print(password)
# ============================================
# REVERSE STRING
# string="rohit"
# for i in range((len(string)-1),-1,-1):
# print(string[i])
# ===========================================
# a=[1,2,3]
# b=[4,5,6]
# v=map(lambda x,y:x+y,a,b)
# print(list(v))
# ========================================================
from string import ascii_lowercase
from functools import reduce
# LIST TO DICTIONARY
a=[1, 2, 3, 4, 5, 6]
# print(dict.fromkeys(a))
# print(dict.fromkeys(a,'a')) #a is for value
print({n:n for n in a})
# p=[1,2,3]
# q=[4,5,6]
# print({i:j for i,j in zip(p,q)})
# print({i:i*i for i in a})
# MERGE TWO LIST
# a=[1,2,3]
# b=[1,2,3]
# a.extend(b)
# print(a)
# print(a+b)
# a.append(b)
# print(a)
# add to list
# print([i+j for i,j in zip(a,b)])
# DICTIONARY COMPREHENSION
# f={1: 1, 2: 2, 3: 3}
# print({i:j for i,j in f.items()})
# print({i:j for i,j in zip(a,b) if i<5})
# print({i:j for i,j in enumerate(ascii_lowercase) if i<5})
# l1 = ["eat","sleep","repeat"]
# print(list(enumerate(l1,1)))
# d1={'a': 0, 'b': 1}
# d2={'c': 2, 'd': 3, 'e': 4}
# d1.update(d2)
# print(d1)
# print(dict(d1,**d2))
# print({**d1, **d2})
# print(d1.pop('a')) #here i have poped the ath element from dictionary
# print(d1)
# ======================================================
# RETURN MULTIPLE VALUES FROM FUNCTION
# def x():
# return 1,2,3,4,5
# z=x()
# print(list(z)) #default the output comes in tuple
# def y():
# return 1,2,3
# p,q,r=y()
# print(p,q,r)
# ======================================================
# from functools import partial
# # A normal function
# def f(a, b, c, x):
# return 1000 * a + 100 * b + 10 * c + x
# # A partial function that calls f with
# # a as 3, b as 1 and c as 4.
# g = partial(f, 3, 1, 4,4)
# print(g())
# =================================================================
# count how many times 8 in the list
count=0
def find_occurence(lst,x):
global count
for i in lst:
if i==x:
count=count+1
return count
x=8
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
print(find_occurence(lst,x))
# ==========================================================
# Dict = {"1": 'Geeks', "2": 'For', "3": 'Geeks'}
# Dict1 = {"4": 'Geeks', "5": 'For', '6': 'Geeks'}
# print({**Dict,**Dict1})
# dict2={**Dict,**Dict1}
# print(dict2)
# ==========================================================
# MAKE SUBSTRING FROM STRING
# s="BANANA"
# res=[s[i:j] for i in range(len(s))for j in range(i+1,len(s)+1)]
# print(res)
# # _______________
# MAKE SUBSTRING FROM STRING YOU CAN FROM LIST ALSO TO APPEND
s="BANANA"
for i in range(len(s)):
for j in range(i+1,len(s)+1):
print(s[i:j],end=',')
# =========================================================
# print MAX
# a=[1,5,4,6,8]
# mx=0
# for i in range(len(a)):
# if a[i]>=mx:
# mx=a[i]
# else:
# mx=a[i]-1
#
# print(mx)
# ==========================================================
# import sys
# def print_to_stderr(a):
# print(a, file=sys.stderr) #here we genereate an erorr from stderr
# print(a, file=sys.stdout) #here we have printing the output
#
# print_to_stderr("Hello World")
# ==========================================================
# sum of all subarrays
# def sumofSubArray(arr,n):
# sum=0
# for i in range(0,len(arr)):
# sum+=(arr[i] * (i+1) * (n-i))
# return sum
#
# arr=[1,2,3]
# n=len(arr)
# res=sumofSubArray(arr,n)
# print(res)
# ==========================================================
|
c7eed0a9bee1a87a3164f81700d282d1370cebdb | philuu12/PYTHON_4_NTWK_ENGRS | /wk1_hw/Solution_wk1/ex7_yaml_json_read.py | 835 | 4.3125 | 4 | #!/usr/bin/env python
'''
Write a Python program that reads both the YAML file and the JSON file created
in exercise6 and pretty prints the data structure that is returned.
'''
import yaml
import json
from pprint import pprint
def output_format(my_list, my_str):
'''
Make the output format easier to read
'''
print '\n\n'
print '#' * 3
print '#' * 3 + my_str
print '#' * 3
pprint(my_list)
def main():
'''
Read YAML and JSON files. Pretty print to standard out
'''
yaml_file = 'my_test.yml'
json_file = 'my_test.json'
with open(yaml_file) as f:
yaml_list = yaml.load(f)
with open(json_file) as f:
json_list = json.load(f)
output_format(yaml_list, ' YAML')
output_format(json_list, ' JSON')
print '\n'
if __name__ == "__main__":
main()
|
411a705b9688e6d9ff0e46ed66546ab0fe8184f6 | PeteCoward/teach-python | /easy_crypto/lesson1/test_task3.py | 561 | 3.515625 | 4 | from .task3 import get_next_letter
def test_get_next_letter():
''' get the next letter in the alphabet cycling from Z to A '''
assert get_next_letter('A') == 'B', "the next letter after A should be B"
assert get_next_letter('M') == 'N', "the next letter after M should be N"
assert get_next_letter('Z') == 'A', "the next letter after Z should be A"
def test_get_next_letter_does_not_change_nonletters():
''' get_next_letter should not change non letter characters '''
assert get_next_letter(' ') == ' ', "spaces should be unchanged"
|
98ca62e618892837f9750bbbb16b0aec2128672b | PeteCoward/teach-python | /easy_crypto/lesson2/task3.py | 227 | 3.984375 | 4 | '''
# TASK 3 - write a function to shift an array of bytes by caesar shift
'''
def shift_byte_array(byte_array, shift):
table = bytearray([(i + shift) % 256 for i in range(0, 256)])
return byte_array.translate(table)
|
201923fe72c91c891a2b8f7b0a05a7be55fe6fb5 | Sharpeon/Tic-Tac-Toe-Online | /game.py | 2,092 | 3.671875 | 4 | import random
class Game:
def __init__(self, id) -> None:
self.id = id
self.turnP1 = random.choice([True, False])
self.rows = 3
self.cols = 3
self.grid = [[-1 for i in range(self.cols)] for j in range(self.rows)] # 2d arrays are weird in python...
self.last_winner = None
def resetGame(self):
self.turnP1 = random.choice([True, False])
self.grid = [[-1 for i in range(self.cols)] for j in range(self.rows)]
def placeSymbol(self, pos:int, symbol:str):
finalPos = 0
for x in range(self.rows):
for y in range(self.cols):
if finalPos == pos:
self.grid[x][y] = symbol
return
else:
finalPos += 1
self.switchTurn()
def switchTurn(self):
self.turn1 = not self.turnP1
def checkWin(self, symbol:str) -> bool:
count = 0
# Check Horizontal wins
for x in range(self.rows):
for y in range(self.cols):
if self.grid[y][x] == symbol:
count += 1
if count == self.cols:
count = 0
return True
else:
count = 0
# Check Vertical wins
for x in range(self.cols):
for y in range(self.rows):
if self.grid[x][y] == symbol:
count += 1
if count == self.rows:
count = 0
return True
else:
count = 0
# Check win diagonal like \
for i in range(self.cols):
if self.grid[i][i] == symbol:
count += 1
if count == self.cols:
return True
else:
count = 0
# Check win diagonal like /
row = 0
for i in reversed(range(self.cols)):
if self.grid[i][row] == symbol:
count += 1
row += 1
if count == self.cols:
return True
return False
game = Game(1)
|
ebc2bad584302fc5e3dd0a5993619f8c0c50e1c8 | kirkbroadbelt/Python | /homework8.py | 4,004 | 4.09375 | 4 | # ST114: Homework 8
# Name: Kirk Broadbelt
# Instructions:
# In this assignment, we will practice using sorting and list comprehensions.
#
# A Python file homework8.py has been provided for you. You will need to
# edit it and push it to your ncsu repo:
# 'https://github.ncsu.edu/your-Unity-ID/you-Unity-IDST114/HW8/homework8.py'.
import math
# Problem 1.
def my_median(x):
""" (list) -> number
Returns the median of a list of numbers
>>> my_median([9,2,7,5,3])
5
>>> my_median([1,2,3,4])
2.5
"""
x.sort()
y = x
n = len(x)
if n % 2 == 1:
return y[(n + 1)// 2 - 1]
elif n % 2 == 0:
return (y[n // 2 - 1] + y[n // 2] ) / 2
#print(my_median([9,2,7,5,3]) )
#print(my_median([1,2,3,4]))
# Problem 2
def mad_for(x):
""" (list) -> number
Returns the MAD of a list
>>> mad_for([1,2,3,4,5])
1
>>> mad_for([1,2,3,4])
1.0
"""
d = [0]*len(x)
medianx = my_median(x)
for i in range(len(x)):
d[i] = abs(x[i] - medianx)
return my_median(d)
#print(mad_for([1,2,3,4,5]))
# Problem 3
def mad_lc(x):
""" (list) -> number
Returns the MAD of a list
>>> mad_lc([1,2,3,4,5])
1
>>> mad_lc([1,2,3,4])
1.0
"""
d = [0] * len(x)
medianx = my_median(x)
d = [abs(x[i]-medianx) for i in range(len(x))]
return my_median(d)
#print(mad_lc([1,2,3,4,5]))
# Problem 4
def log_transform(x):
""" (list) -> list
It returns a list y containing the log-transformed values of x
>>> log_transform([1,2])
[0.0, 0.6931471805599453]
>>> log_transform([1,2,-1,0])
[0.0, 0.6931471805599453, nan, nan]
"""
y = [math.log(x[i]) if x[i] > 0 else math.nan for i in range(len(x)) ]
return y
#print(log_transform([1,2]))
#print(log_transform([1,2,-1,0]))
# Problem 5
def apply_for(x, f):
"""(list,function) -> list
Returns a list obtained by applying f to each list of numbers in x
>>> apply_for([[1,2,3,4,5],[1,2],[1,5,7]],my_median)
[3, 1.5, 5]
>>> apply_for([[1,2,3,4,5],[1,2],[1,5,7]],mad_for)
[1, 0.5, 2]
>>> apply_for([[1,2,3,4,5],[1,2],[1,5,7]],mad_lc)
[1, 0.5, 2]
>>> apply_for([[1,2,3,4,5],[1,2],[1,5,7]],log_transform)
[[0.0, 0.6931471805599453, 1.0986122886681098, 1.3862943611198906, 1.6094379124341003], [0.0, 0.6931471805599453], [0.0, 1.6094379124341003, 1.9459101490553132]]
>>> apply_for([[-1,2],[-1,-5,7]],log_transform)
[[nan, 0.6931471805599453], [nan, nan, 1.9459101490553132]]
"""
y = x[:]
for i in range(len(x)):
y[i] = f(x[i])
return y
#print(apply_for([[1,2,3,4,5],[1,2],[1,5,7]],my_median))
#print(apply_for([[1,2,3,4,5],[1,2],[1,5,7]],mad_for))
#print(apply_for([[1,2,3,4,5],[1,2],[1,5,7]],mad_lc))
#print(apply_for([[1,2,3,4,5],[1,2],[1,5,7]],log_transform))
# Problem 6
def apply_lc(x, f):
"""(list,function) -> list
Returns a list obtained by applying f to each list of numbers in x
>>> apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],my_median)
[3, 1.5, 5]
>>> apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],mad_for)
[1, 0.5, 2]
>>> apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],mad_lc)
[1, 0.5, 2]
>>> apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],log_transform)
[[0.0, 0.6931471805599453, 1.0986122886681098, 1.3862943611198906, 1.6094379124341003], [0.0, 0.6931471805599453], [0.0, 1.6094379124341003, 1.9459101490553132]]
>>> apply_lc([[-1,2],[-1,-5,7]],log_transform)
[[nan, 0.6931471805599453], [nan, nan, 1.9459101490553132]]
"""
y = x[:]
y = [f(x[i]) for i in range(len(x))]
return y
#print(apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],my_median))
#print(apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],mad_for))
#print(apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],mad_lc))
#print(apply_lc([[1,2,3,4,5],[1,2],[1,5,7]],log_transform))
if __name__ == "__main__":
import doctest
doctest.testmod()
|
9868eb19f13a3590ef0592456a1f4da332eda4ea | kirkbroadbelt/Python | /Final For Statistical Programming/linear_regression.py | 5,269 | 3.640625 | 4 | import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from math import nan
class SLR:
def __init__(self, data):
""" (SLR, Data) -> NoneType
Create a new simple linear regression object from data,
with data data, intercept beta0, and slope beta1.
"""
self.data = data
self.beta0 , self.beta1 = data.compute_least_squares_fit()
def predict(self, x_new):
""" (SLR, number) -> number
Return predicted value at x_new.
"""
return self.beta0 + self.beta1 * x_new
def compute_residuals(self):
""" (SLR) -> list
Return the residuals in a list of numbers.
"""
residual_list = []
for i in range(self.data.num_obs()):
residual_list.append(self.data.y[i] - self.predict(self.data.x[i]))
return residual_list
def compute_SSResid(self):
""" (SLR) -> number
Return the sum of square residuals (SSResid).
"""
SSResid = 0
resids = self.compute_residuals()
for i in range(len(resids)):
SSResid = SSResid + (resids[i] ** 2)
return SSResid
def compute_residual_sd(self):
""" (SLR) -> number
Return the residual standard deviation.
"""
return (self.compute_SSResid() / (self.data.num_obs() - 2) ) ** 0.5
def compute_rsquared(self):
""" (SLR) -> number
Return the R-squared of the SLR fit.
"""
#return (self.data.compute_SST() - self.compute_SSresid() ) / self.data.computeSST()
a = self.compute_SSResid()
c = self.data.compute_SST()
return((c-a)/(c))
def __str__(self):
""" (SLR) -> str
Return a string representation of an SLR in this format:
Least squares fit on 10 data points.
Intercept = 45.584331
Slope = 3.465523
Residual standard deviation = 13.051139
R-squared = 0.731364
"""
#output_text = 'Least squares fit on {} data points.\n'.format(self.data.num_obs())
#output_text += 'Intercept = {}\n'.format(self.beta0)
#output_text += 'Slope = {}\n'.format(self.beta1)
#output_text += 'Residual standard deviation = {}\n'.format(self.compute_residual_sd() )
#output_text += 'R-squared = {}\n'.format(self.compute_rsquared())
return 'Least squares fit on {} data points.\nIntercept = {:.6f}\nSlope = {:.6f}\nResidual standard deviation = {:.6f}\nR-squared = {:.6f}'.format(self.data.num_obs(),self.beta0,self.beta1,self.compute_residual_sd(),self.compute_rsquared())
def plot(self):
""" (SLR) -> None
Produce a scatter plot of the data and
the simple linear regression model.
"""
plt.plot(self.data.x, self.data.y, marker = '^', color = 'b', linewidth = 0)
xMax = max(self.data.x)
xMin = min(self.data.x)
xRange = np.arange(xMin, xMax, .1)
plt.plot(xRange, self.beta0 + self.beta1 * xRange, color = 'k')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
def compute_test_statistic(self):
""" (SLR) -> float
Returns the t-statistic for the slope parameter.
"""
try:
x_sample_mean , y_sample_mean = self.data.compute_sample_means()
Sxx = 0
for i in range(len(self.data.x)):
Sxx += (self.data.x[i] - x_sample_mean) ** 2
return self.beta1 / (self.compute_residual_sd() / (Sxx ** 0.5))
except ZeroDivisionError:
print('Standard error of the slope is zero.')
return nan
def compute_p_value(self):
""" (SLR) -> float
Returns the p-value for the slope parameter.
"""
return stats.t.cdf(self.compute_test_statistic(), self.data.numobs() - 2)
def t_test_two_tailed(self, alpha):
""" (SLR, float) -> str
Performs a two-tailed t-test on the slope parameter.
"""
p_value = self.compute_p_value()
try:
if alpha > 0 and alpha < 1:
pass
else:
raise ValueError('Inputed significance level is not supported.')
if p_value <= alpha:
print('There is a statistically significant association at the alpha level of {}.'.format(alpha))
return 'There is a statistically significant association at the alpha level of {}.'.format(alpha)
else:
print('There is not a statistically significant association at the alpha level of {}.'.format(alpha))
return('There is not a statistically significant association at the alpha level of {}.'.format(alpha))
except ZeroDivisionError:
print('Standard error of the slope is zero.')
print('Test statistic cannot be computed.')
return('Test statistic cannot be computed.')
except ValueError as excpt:
print(excpt)
return 'Inputed significance level is not supported.' |
96d7d761a9593d39c6d389de8c1dc506d61ef9b4 | AASHMAN111/Addition-using-python | /Development/to_run_module.py | 1,800 | 4.125 | 4 | #This module takes two input from the user. The input can be numbers between 0 and 255.
#This module keeps on executing until the user wishes.
#This module can also be called as a main module.
#addition_module.py is imported in this module for the addition
#conversion_module.py is imported in this module for the conversion
#user_input_moduoe.py is imported in this module for taking the inputs from them and to handle exceptions.
#Aashman Uprety, 26th May, 2020
import addition_module
import conversion_module
import user_input_module
def list_to_string(lst):
"""Function to convert the list 'lst' to string."""
string = ""
for i in lst:
i = str(i)
string = string + i
return string
check = "yes"
while check != "no":
if check == "yes":
lst = user_input_module.user_input_module()
fbinary = conversion_module.decimal_to_binary(lst[0])
sbinary = conversion_module.decimal_to_binary(lst[1])
bit_addition = addition_module.bit_addition(fbinary, sbinary)
bitwise_add = addition_module.bitwise_addition(lst[0],lst[1])
print("First inputted number in binary is: ", list_to_string(fbinary))
print("Second inputted number in binary is: ", list_to_string(sbinary))
print("Sum of the two inputted numbers in binary is: ", list_to_string(bit_addition))
print("Sum of the two inputted numbers in decimal is: ",bitwise_add)
else:
print("please only enter yes or no.")
check = input("Are you willing for another addition? If yes just type yes than you can else just type no, the program will terminate : ")
check = check.lower()
if check == "no":
print("The program is terminating. BYYEEEEEEEE.")
|
3e1b22ddeeea67da7f853215adaad5fc1490f157 | ashish-bisht/leetcode_solutions | /57InsertInterval.py | 649 | 3.921875 | 4 | def insert_interval(intervals, new_interval):
intervals.append(new_interval)
intervals.sort()
last_interval = intervals[0]
res = []
for cur_interval in intervals[1:]:
if cur_interval[0] <= last_interval[1]:
last_interval[1] = max(cur_interval[1], last_interval[1])
else:
res.append(last_interval)
last_interval = cur_interval
res.append(last_interval)
return res
print(insert_interval([[1, 3], [6, 9]], [2, 5]))
print(insert_interval([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))
print(insert_interval([], [5, 7]))
print(insert_interval([[1, 5]], [2, 3]))
|
da7678263f8f702a94c4ac8931943eee3436643e | ashish-bisht/leetcode_solutions | /5_longest_palindromic_substring.py | 546 | 3.984375 | 4 | def longest_palindromic_substring(string):
ans = ""
for i in range(len(string)):
even = helper(string, i, i+1)
odd = helper(string, i, i)
ans = max(ans, even, odd, key=len)
return ans
def helper(string, left, right):
while left >= 0 and right < len(string):
if string[left] == string[right]:
left -= 1
right += 1
else:
break
return string[left+1:right]
print(longest_palindromic_substring("babad"))
print(longest_palindromic_substring("cbbd"))
|
ea93293c04c9cfd10a89bafde61c2453d4a035ab | ashish-bisht/leetcode_solutions | /1047remove_adjacent.py | 236 | 3.984375 | 4 | def remove_adjacent(string):
stack = []
for ch in string:
if stack and stack[-1] == ch:
stack.pop()
else:
stack.append(ch)
return ("").join(stack)
print(remove_adjacent("abbaca"))
|
afa94a2794f02b1d8e55ea839a118a8de33276fa | ashish-bisht/leetcode_solutions | /394_decode_strings.py | 721 | 3.71875 | 4 | def decode_strings(string):
cur_num = 0
cur_string = ""
stack = []
for ch in string:
if ch == "[":
stack.append(cur_string)
stack.append(cur_num)
cur_string = ""
cur_num = 0
elif ch.isnumeric():
cur_num = cur_num*10 + int(ch)
elif ch == "]":
num = stack.pop()
last_string = stack.pop()
cur_string = last_string + num * cur_string
else:
cur_string += ch
return cur_string
print(decode_strings("3[a]2[bc]"))
print(decode_strings("3[a2[c]]"))
print(decode_strings("2[abc]3[cd]ef"))
print(decode_strings("abc3[cd]xyz"))
print(decode_strings("100[leetcode]"))
|
e4f00a45ffcd90311ef055f9aeac82db427e6f11 | ashish-bisht/leetcode_solutions | /767.py | 808 | 3.703125 | 4 | def reorganise_string(string):
import heapq
from collections import Counter
temp = list(string)
count = Counter(temp)
heap = []
for key, val in count.items():
heapq.heappush(heap, (-val, key))
res = []
val2 = -1
while heap:
val1, key1 = heapq.heappop(heap)
if res and res[-1] == key1:
return ""
res.append(key1)
val1 = -val1 - 1
if heap:
val2, key2 = heapq.heappop(heap)
res.append(key2)
val2 = -val2 - 1
if val1 > 0:
heapq.heappush(heap, (-val1, key1))
if val2 > 0:
heapq.heappush(heap, (-val2, key2))
return ("").join(res)
print(reorganise_string("aaab"))
print(reorganise_string("aab"))
print(reorganise_string("bbbbbbbb"))
|
5ba0d99e2b4c267c6e12a807b432825e465f8d57 | ashish-bisht/leetcode_solutions | /389find_diffrence.py | 256 | 3.84375 | 4 |
def find_diffrence(str1, str2):
ans = 0
for ch in str1 + str2:
ans ^= ord(ch)
return chr(ans)
print(find_diffrence("abcd", "abcde"))
print(find_diffrence("", "y"))
print(find_diffrence("a", "aa"))
print(find_diffrence("ae", "aea"))
|
6e612e12a95e18c856a114f4602f9f49621bdf82 | ashish-bisht/leetcode_solutions | /1209remove_adjacent.py | 628 | 3.796875 | 4 | def remove_adjacent(string, k):
stack = []
for ch in string:
print(stack)
if len(stack) >= k and stack[-1] == ch:
temp = ""
for _ in range(k):
if stack[-1] != ch:
break
cur = stack.pop()
temp += cur
if len(temp) < k:
for _ in range(len(temp)):
stack.append(ch)
else:
stack.append(ch)
return ("").join(stack)
print(remove_adjacent("abcd", 2))
print(remove_adjacent("deeedbbcccbdaa", 3))
print(remove_adjacent("pbbcggttciiippooaais", 2))
|
07de9ce5b5a0797592990f74153cc04296cc3547 | jj1993/comp-sys | /smallnetwork.py | 8,059 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import random
import copy
class Car(object):
def __init__(self, edge, route, speed):
self.edge = edge
self.route = route
self.pos = 0
self.speed=speed
self.age = 0
self.aveSpeed = 0
# Visualisation point
x, y = edge.getStart()
self.vis = plt.plot(x, y, 's', markersize=4)[0]
def getPos(self):
return self.pos
def getEdge(self):
return self.edge
# The three speed rules
def accelerationRule(self):
if self.speed <= maxSpeed - maxSpeed/steps:
self.speed+=maxSpeed/steps
def randomizationRule(self):
var=np.random.uniform(0,1)
if self.speed > maxSpeed/steps:
if var<p:
self.speed-=maxSpeed/(steps)
def distanceRule(self, frontCar):
hisEdge = frontCar.getEdge()
if hisEdge == self.edge:
difference = frontCar.getPos() - self.pos
else:
difference = (
self.edge.getLength() - self.pos
+ frontCar.getPos()
)
if difference + 2 < self.speed:
self.speed = difference
if self.speed < 0:
self.speed = 0
# Updating locations and moving to new edges
def setNewEdge(self):
del self.route[0]
if len(self.route) != 0:
self.edge = route[0]
else: self.edge = False
def update(self, timestep):
self.aveSpeed = (self.aveSpeed*self.age + self.speed)/(self.age + 1)
self.age += 1
distance = self.speed*timestep
if self.pos + distance < self.edge.getLength():
# Updating visualisation information
self.pos += distance
x, y = self.edge.getXY(self.pos)
self.vis.set_data(x, y)
return True
else:
if len(self.route) == 0:
self.vis.remove()
self.pos += distance
self.edge.removeCar(self)
return False
else:
distance -= self.edge.getLength() - self.pos
self.pos = distance
self.edge.removeCar(self)
self.edge = self.route[0]
self.edge.addCar(self)
del self.route[0]
x, y = self.edge.getXY(self.pos)
self.vis.set_data(x, y)
return True
def getFrontCar(self):
cars = self.edge.getCars()
print(cars)
for n, car in enumerate(cars):
if car == self:
if n > 0:
return cars[n-1]
break
if len(self.route) != 0:
nextCarList = self.route[0].getCars()
if len(nextCarList) != 0:
return nextCarList[-1]
return False
def activate(self):
self.edge.addCar(self)
updateSpeed(self)
def getAverageSpeed(self):
return self.aveSpeed
class Edge(object):
def __init__(self, node1, node2):
x1, y1 = node1
x2, y2 = node2
plt.plot((x1,x2),(y1,y2))
self.length = np.sqrt((x2-x1)**2 + (y2-y1)**2)
self.angle = np.pi + np.arctan((y2-y1)/(x2-x1))
self.x1, self.y1 = x1, y1
self.x2, self.y2 = x2, y2
self.cars = []
self.newCars = []
def getLength(self):
return self.length
def getStart(self):
return (self.x1, self.y1)
def getXY(self, pos):
x = self.x1 + np.cos(self.angle)*pos
y = self.y1 + np.sin(self.angle)*pos
return (x, y)
def addCar(self, car):
self.newCars.append(car)
def update(self):
if len(self.newCars) != 0:
# Makes sure the cars are ordered correctly on the new edge
enteringCars = sorted(self.newCars, key=lambda car: car.getPos())
self.cars += reversed(enteringCars)
self.newCars = []
def removeCar(self, car):
for n, myCar in enumerate(self.cars):
if myCar == car:
del self.cars[n]
return
def getCars(self):
return self.cars
# ==============
# Some constants
# ==============
totCars = 100 #number of cars initiated in simulation
maxSpeed = 5 #maximum speed (m/s)
p = 0.1 #change of slowing down every speed update
interval = .5 # time steps between cars
steps = 5.0 #number of speed steps as interpreted from the CA model
def chooseRandomRoute(edges, startNode, numEdges):
route = []
lastx, lasty = startNode
while True:
options = []
for edge in edges:
thisx, thisy = edge[0]
if thisx == lastx and thisy == lasty:
options.append(edge)
route.append(random.choice(options))
lastx, lasty = route[-1][1]
if (lastx, lasty) == (0, 0): break
return [Edge(start, end) for start, end in route]
def addNewCars(totCars, edges):
# Generate all agents
cars = []
for c in range(totCars):
startNode = random.choice(random.choice(edges))
numEdges = random.choice(range(4))+1
route = chooseRandomRoute(edges, startNode, numEdges)
if c%100 == 0: print('Routing car ',c)
speed = maxSpeed
cars.append(Car(route[0], route[1:], speed))
return cars
def updatePositions(cars, timestep):
newCars = []
# Locations are updated on every timestep
for car in cars:
onEdge = car.update(timestep)
if onEdge:
newCars.append(car)
[edge.update() for edge in network]
return newCars
def updateSpeed(car):
car.accelerationRule()
car.randomizationRule()
frontCar = car.getFrontCar()
if frontCar: car.distanceRule(frontCar)
else: print("NO FRONT CAR")
return
def runSimulation(cars, vis=True):
if vis: plt.ion()
# Activate interactive visualisation
activeCars = []
t = 0
while len(cars) > 0 or len(activeCars) > 0:
# Speeds are updated on the end of every second!
timeToNewCar = round(interval - t%interval, 2)
if timeToNewCar < 1e-2: timeToNewCar = round(interval, 2)
timeToSpeedUpdate = round(1 - t%1, 2)
if timeToSpeedUpdate < 1e-2: timeToSpeedUpdate = 1
if timeToSpeedUpdate <= timeToNewCar:
# First travel remaining distance
timestep = timeToSpeedUpdate
t += timestep
activeCars = updatePositions(activeCars, timestep)
# Then update speeds
[updateSpeed(car) for car in activeCars]
if timeToSpeedUpdate == timeToNewCar and len(cars) != 0:
# Sometimes speed is updated while new car is added!
activeCars.append(cars[0])
cars[0].activate()
del cars[0]
else:
# First travel remaining distance
timestep = timeToNewCar
t += timestep
activeCars = updatePositions(activeCars, timestep)
# Then add new car
if len(cars) != 0:
activeCars.append(cars[0])
cars[0].activate()
del cars[0]
t = round(t, 2)
if vis: plt.pause(0.01)
return
if __name__ == '__main__':
# Initialise network, for now only one road
edges = [
[(0,0),(100,30)],
[(0,0),(100,-30)],
[(0,0),(150,0)],
[(100,30),(200,30)],
[(100,-30),(200,-30)],
[(200,30),(300,0)],
[(200,-30),(300,0)],
[(100,-30),(150,0)],
[(100,30),(150,0)],
[(150,0),(200,-30)],
[(150,0),(200,30)],
[(150,0),(300,0)],
[(300,0),(400,0)],
]
edges += [(end, start) for start, end in edges]
network = [Edge(start, end) for start, end in edges]
# Generate all agents
cars = addNewCars(totCars, edges)
runSimulation(copy.copy(cars), vis=True)
averageSpeed = sum([car.getAverageSpeed() for car in cars])/len(cars)
print(averageSpeed)
|
1b188ae6f0a2d386265e42f72dac95089d02761f | ivy12138/driving | /driving.py | 326 | 4.09375 | 4 | country=input('where are you from?')
age=int(input('how old are you?'))
if country=='Taiwan':
if age>=18:
print('Yes,you can')
else:
print('No')
elif country=='America':
if age>=16:
print('Yes,you can')
else:
print('No')
else:
print('you can only enter Taiwan or America')
|
22b14040226a8e15bf326b88b673be6ada073258 | yelinjo18/2021_PL_HW | /2021_PL_HW1/hw1_3.py | 948 | 3.875 | 4 | '''
과제 3
/ 리스트를 Merge Sort로 정렬하라
- 입력은 input()을 통해 받을 것
- 입력은 리스트의 요소들이다
Input : 100 23 31 123 435 642 1
Output : [1, 23, 31, 100, 123, 435, 642]
'''
#Merge Sort
def MergeSort(list):
if len(list)<=1:
return list
else:
m_i=int(len(list)/2)
# Recursion
pre=MergeSort(list[:m_i])
post=MergeSort(list[m_i:])
return Merge(pre, post)
# Merge
def Merge(pre, post):
t_list=[]
i=0
j=0
while i<len(pre) and j<len(post):
if pre[i]<=post[j]:
t_list.append(pre[i])
i+=1
else:
t_list.append(post[j])
j+=1
if i>=len(pre):
t_list.extend(post[j:])
elif j>=len(post):
t_list.extend(pre[i:])
return t_list
# Input to List
list = list(map(int,input().split()))
print(MergeSort(list)) |
868ad4369cd64f877f4ea35f1a85c941aa9c7409 | SaketJNU/software_engineering | /rcdu_2750_practicals/rcdu_2750_strings.py | 2,923 | 4.40625 | 4 | """
Strings are amongst the most popular types in Python.
We can create them simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
"""
import string
name = "shubham"
print("Data in upper case : ",name.upper()) # upper() for UPPER case strings conversion
lower = "PRAJAPATI"
print("Data in lower case : ",lower.lower()) # lower() for lower case strings conversion
takeData = input("Please enter any data : ")
print("Here is the user input data : ",takeData) # input() for taking data from user
# NOTE -> input() takes data in string if you want to do some functionality with numeric please
# convert that data in your dataType like : int float etc.
# Let's take a look of some in-built string functions
print(string.ascii_uppercase) # ascii_uppercase gives A-Z
print(string.digits) # it gives 0-9
# string formatter
"""
% c -> character
% s -> string
% i ,d-> signed integer deciaml integer
% u -> unsigned decimal integer
% x -> hex decimal integer (lowercase)
% X -> hex decimal integer (UPPERCASE)
% o -> octal decimal integers
% e -> exponantial notation (lowercase, e^3)
% E -> exponantial notation (10^3)
% f -> floating point numbers
"""
print("hexa decimal : ",string.hexdigits) # string.hexdigits gives hexadecimal number
print("only printable no : ",string.printable ) # printable characters only
print("Octa decimal no : ",string.octdigits) # Octa decimal no's
print(type(name.isalnum()),name.isalnum()) # checks alphanumeric
print(type(name.isnumeric()),name.isnumeric()) # checks numeric
print(type(name.isdigit()),name.isdigit()) # checks digit
print("Split func : ",name.split()) # Splits stings
print("Starts With ",name.startswith('s')) # Checks starting char of string return boolean
number = " my number is 97748826478"
print(number.split()) # Basically returns list
print(number.strip()) # removes unprintable charaters from both side left and right
print(number.rstrip()) # removes unprintable charaters right side only
splitn= number.split()
for onew in splitn:
if (onew.strip()).isdigit():
if len(onew.strip())== 11:
print("No", onew.strip())
str1 = "abcdxyzabc"
print(str1.replace('a','k')) # occurance of 'a' by 'k'
str2 = str1.replace('a','k')
print(str2.replace('acd','shu'))
print(str1.capitalize()) # Capitalize capital only first char of an string
# Method 1st
newName = "shubham kumar prajapati"
splitName = newName.split()
print(splitName)
print(splitName[0][0].upper() + ". "+ splitName[1][0].upper() + ". "+ splitName[2].capitalize())
wordlen = len(splitName)
print("Length of list : ",wordlen)
# Method 2nd
count = 0
newname = ""
for aw in splitName:
count +=1
if count < wordlen:
newname += aw[0].upper()+ ". "
else :
newname += aw[0].upper()+aw[1:]
print("By method 2nd : ",newname) |
12b2d25976624a786d7879b8895192d940e57f55 | SaketJNU/software_engineering | /rcdu_2750_practicals/rcdu_2750_Calculater.py | 1,381 | 3.9375 | 4 | class Calculator():
def __init__(self):
pass
def addition(sefl,number, number2):
return number+number2
def mult(self, number, number2):
return number*number2
def sub(self, number, number2):
return number-number2
def div(self, number, number2):
return number/number2
def mathOps(self):
test = 'Y'
while test=='Y' or test=='y':
number = int(input("Enter First No = "))
number2 = int(input("Enter Second No = "))
print("Choice of Operations : \n 1. For Addition \n 2. For Multi \n 3. For Sub \n 4 For Division \n")
choice = int(input("Enter Your Choice : "))
output = 0.0
if choice == 1 :
output = self.addition(number,number2)
elif choice == 2 :
output = self.mult(number,number2)
elif choice == 3 :
output = self.sub(number,number2)
elif choice == 4 :
output = self.div(number,number2)
else :
output = "Invailid Input"
print("Output is ", output)
test = input(" Do you want to continue ? \n Press 'Y' for Yes \n Enter Your choice : ")
if __name__ == "__main__" :
matho = Calculator()
matho.mathOps() |
8e238c386f0ef9c942d41fd5dfa79f245b6789e2 | SaketJNU/software_engineering | /data_cleaning/read_all_json_new.py | 579 | 3.546875 | 4 | import json
from clean_csv_data import list_all_files
def read_json(file_name):
with open(file_name) as f:
file_data = json.load(f)
print("_______________________ For file {} Data are following".format(file_name))
for k, v in file_data.items():
print("For Date {}, Price is {}".format(k, v))
if __name__ == "__main__":
folder_name = "processed_data"
file_list = list_all_files(folder_name)
print("File list is {}".format(file_list))
for file in file_list:
file_name = folder_name + "/" + file
read_json(file_name)
|
0c41a027ed056aa70174f751ceb64314525af0fe | yhesper/PyniverseText | /tp2/planetClass.py | 1,901 | 3.546875 | 4 |
import math
#################################################
# Helper functions
#################################################
import random
class Planet(object):
def __init__(self,x,y,r,l2):
#x and y may changes
self.x=x
self.y=y+15
#r , l and never changes
self.r=r
self.l2=l2# l is the square of distance
#speed may changes
self.speed=1
self.num=random.randint(0,1)
def __eq__(self,other):
return isinstance(other,Planet) and abs(self.l2-other.l2)<8
def move(self,data):
dx=self.speed*self.y/(self.l2)**0.5
dy=self.speed*(data.width-self.x)/(self.l2)**0.5
self.x += dx
self.y += dy
def __hash__(self):
return hash(self.l2)
#different stars
#def s0(self,canvas,data)
#def s1(self,canvas,data)
#def m0(self,canvas,data)
#def m1(self,canvas,data)
#def l0(self,canvas,data)
#def l1(self,canvas,data)
#s=[s0,s1]#character length 0-4
#m=[m0,m1]#character length 5-10
#l=[l0,l1]#11 or more
def draw(self,canvas,data,i):
mycolor=data.colorMap[i]
if self.x-self.r*2<data.width and self.y-self.r/2<data.height :
l=((self.y-data.menuHeight)**2+(data.width-self.x)**2)**0.5
canvas.create_oval(data.width-l,data.menuHeight-l,data.width+l,data.menuHeight+l,outline='steelblue')
canvas.create_oval(self.x-self.r,self.y-self.r,self.x+self.r,self.y+self.r,fill=mycolor,width=0)
canvas.create_oval(self.x-self.r*2,self.y-self.r/2,self.x+self.r*2,self.y+self.r/2,width=self.r/8,outline=mycolor)
rSmall=self.r/4
xSmall=self.x+self.r*3/2
ySmall=self.y+self.r*3/8
canvas.create_oval(xSmall-rSmall,ySmall-rSmall,xSmall+rSmall,ySmall+rSmall,fill=mycolor,width=0)
|
5aa142cf5cd874b3b1fd1b9f1b497354b99ecda7 | echen67/Computer-Graphics | /p2a_object/p2a_object/p2a_object.pyde | 10,163 | 3.640625 | 4 | # Animation Example
#Emily Chen
time = 0 # use time to move objects from one frame to the next
def setup():
size (800, 800, P3D)
perspective (60 * PI / 180, 1, 0.1, 1000) # 60 degree field of view
def draw():
global time
time += 0.01
camera (0, 0, 100, 0, 0, 0, 0, 1, 0) # position the virtual camera
background (255, 255, 255) # clear screen and set background to white
# create a directional light source
ambientLight(50, 50, 50);
lightSpecular(255, 255, 255)
directionalLight (100, 100, 100, -0.3, 0.5, -1)
noStroke()
specular (100, 100, 100)
#ambient (100, 100, 100)
emissive (20, 20, 20)
shininess (10.0)
# draw piano
translate(0,10,-10)
rotateY(-time/2)
rotateX(radians(-45))
scale(.8)
piano()
# piano
def piano():
pushMatrix()
rotateY(radians(180))
translate(-50,0,0)
keyboard()
popMatrix()
fill(100,100,100)
#bottom
pushMatrix()
rotateX(radians(90))
translate(-2,-8,-2)
box(90,20,5)
popMatrix()
#cover
pushMatrix()
rotateX(radians(-70))
translate(-2,9,-13)
box(89,2,15)
popMatrix()
#under cover
pushMatrix()
translate(-2,0,-11)
box(89,5,5)
popMatrix()
#high left
pushMatrix()
rotateX(radians(90))
translate(-48,-6,0.5)
box(3,21,10)
popMatrix()
#high right
pushMatrix()
rotateX(radians(90))
translate(44,-6,0.5)
box(3,21,10)
popMatrix()
#left leg
pushMatrix()
translate(-48,20,0)
box(2,35,4)
popMatrix()
#right leg
pushMatrix()
translate(44,20,0)
box(2,35,4)
popMatrix()
#left
pushMatrix()
translate(-48,20,-13)
box(3,35,7)
popMatrix()
#right
pushMatrix()
translate(44,20,-13)
box(3,35,7)
popMatrix()
#low left
pushMatrix()
translate(-48,40,-6)
box(3,5,22)
popMatrix()
#low right
pushMatrix()
translate(44,40,-6)
box(3,5,22)
popMatrix()
#pedal bar
pushMatrix()
translate(0-2,40,-18)
box(93,5,5)
popMatrix()
#back
pushMatrix()
translate(-2,5,-25)
box(95,75,17)
popMatrix()
#right pedal
pushMatrix()
scale(1.5)
translate(2,27,-6.5)
rotateX(radians(-90))
rightPedal()
popMatrix()
#left pedal
pushMatrix()
scale(-1.5,1.5,1.5)
translate(2,27,-6.5)
rotateX(radians(-90))
rightPedal()
popMatrix()
#middle pedal
pushMatrix()
scale(1.5)
translate(0,27.5,-9)
box(1.5,1,5)
popMatrix()
# keyboard
def keyboard():
for i in range(7):
translate(11.2,0,0)
octave()
translate(11.2,0,0)
rotateX(radians(90))
rightKey()
translate(1.6,0,0)
leftKey()
translate(-0.5,3,1)
blackKey()
# octave
def octave():
#black keys
pushMatrix()
rotateX(radians(90))
translate(1.05,3,1)
blackKey()
translate(1.6,0,0)
blackKey()
translate(3.2,0,0)
blackKey()
translate(1.6,0,0)
blackKey()
translate(1.6,0,0)
blackKey()
popMatrix()
#white keys
pushMatrix()
rotateX(radians(90))
translate(0,0,0)
rightKey()
translate(1.6,0,0)
middleKey()
translate(1.6,0,0)
leftKey()
translate(1.6,0,0)
rightKey()
translate(1.6,0,0)
middleKey()
translate(1.6,0,0)
middleKey()
translate(1.6,0,0)
leftKey()
popMatrix()
# cylinder with radius = 1, z range in [-1,1]
def cylinder(sides = 64):
# first endcap
beginShape()
for i in range(sides):
theta = i * 2 * PI / sides
x = cos(theta)
y = sin(theta)
vertex ( x, y, -1)
endShape(CLOSE)
# second endcap
beginShape()
for i in range(sides):
theta = i * 2 * PI / sides
x = cos(theta)
y = sin(theta)
vertex ( x, y, 1)
endShape(CLOSE)
# sides
x1 = 1
y1 = 0
for i in range(sides):
theta = (i + 1) * 2 * PI / sides
x2 = cos(theta)
y2 = sin(theta)
beginShape()
normal (x1, y1, 0)
vertex (x1, y1, 1)
vertex (x1, y1, -1)
normal (x2, y2, 0)
vertex (x2, y2, -1)
vertex (x2, y2, 1)
endShape(CLOSE)
x1 = x2
y1 = y2
#right pedal
def rightPedal():
fill(255,255,0)
#top
beginShape()
vertex(0,0,1)
vertex(0,5,1)
vertex(1,5,1)
vertex(1.5,2,1)
vertex(1.5,0,1)
endShape()
#bottom
beginShape()
vertex(0,0,0)
vertex(0,5,0)
vertex(1,5,0)
vertex(1.5,2,0)
vertex(1.5,0,0)
endShape()
#largest side
beginShape()
vertex(0,0,0)
vertex(0,0,1)
vertex(0,5,1)
vertex(0,5,0)
endShape()
#bottom side
beginShape()
vertex(0,0,0)
vertex(0,0,1)
vertex(1.5,0,1)
vertex(1.5,0,0)
endShape()
#top side
beginShape()
vertex(0,5,0)
vertex(0,5,1)
vertex(1,5,1)
vertex(1,5,0)
endShape()
#top slant side
beginShape()
vertex(1,5,0)
vertex(1,5,1)
vertex(1.5,2,1)
vertex(1.5,2,0)
endShape()
#bottom slant side
beginShape()
vertex(1.5,2,0)
vertex(1.5,2,1)
vertex(1.5,0,1)
vertex(1.5,0,0)
endShape()
# right white key
def rightKey():
fill(255,255,255)
#top
beginShape()
vertex(0,0,2)
vertex(0,8,2)
vertex(1,8,2)
vertex(1,3,2)
vertex(1.5,3,2)
vertex(1.5,0,2)
endShape(CLOSE)
#bottom
beginShape()
vertex(0,0,0)
vertex(0,8,0)
vertex(1,8,0)
vertex(1,3,0)
vertex(1.5,3,0)
vertex(1.5,0,0)
endShape(CLOSE)
#largest side
beginShape()
vertex(0,0,0)
vertex(0,0,2)
vertex(0,8,2)
vertex(0,8,0)
endShape(CLOSE)
#bottom side
beginShape()
vertex(0,0,0)
vertex(0,0,2)
vertex(1.5,0,2)
vertex(1.5,0,0)
endShape(CLOSE)
#top side
beginShape()
vertex(0,8,0)
vertex(0,8,2)
vertex(1,8,2)
vertex(1,8,0)
endShape(CLOSE)
#top half side
beginShape()
vertex(1,8,0)
vertex(1,8,2)
vertex(1,3,2)
vertex(1,3,0)
endShape(CLOSE)
#bottom half side
beginShape()
vertex(1.5,0,0)
vertex(1.5,0,2)
vertex(1.5,3,2)
vertex(1.5,3,0)
endShape(CLOSE)
#smallest side
beginShape()
vertex(1,3,0)
vertex(1,3,2)
vertex(1.5,3,2)
vertex(1.5,3,0)
endShape(CLOSE)
# left white key
def leftKey():
fill(255,255,255)
#top
beginShape()
vertex(0,0,2)
vertex(0,3,2)
vertex(0.5,3,2)
vertex(0.5,8,2)
vertex(1.5,8,2)
vertex(1.5,0,2)
endShape()
#bottom
beginShape()
vertex(0,0,0)
vertex(0,3,0)
vertex(0.5,3,0)
vertex(0.5,8,0)
vertex(1.5,8,0)
vertex(1.5,0,0)
endShape()
#top side
beginShape()
vertex(0.5,8,0)
vertex(0.5,8,2)
vertex(1.5,8,2)
vertex(1.5,8,0)
endShape()
#bottom side
beginShape()
vertex(0,0,0)
vertex(0,0,2)
vertex(1.5,0,2)
vertex(1.5,0,0)
endShape()
#largest side
beginShape()
vertex(1.5,0,0)
vertex(1.5,0,2)
vertex(1.5,8,2)
vertex(1.5,8,0)
endShape()
#top half side
beginShape()
vertex(0.5,3,0)
vertex(0.5,3,2)
vertex(0.5,8,2)
vertex(0.5,8,0)
endShape()
#smallest side
beginShape()
vertex(0,3,0)
vertex(0,3,2)
vertex(0.5,3,2)
vertex(0.5,3,0)
endShape()
#bottom half side
beginShape()
vertex(0,0,0)
vertex(0,0,2)
vertex(0,3,2)
vertex(0,3,0)
endShape()
# middle white key
def middleKey():
fill(255,255,255)
#top
beginShape()
vertex(0,0,2)
vertex(0,3,2)
vertex(0.5,3,2)
vertex(0.5,8,2)
vertex(1,8,2)
vertex(1,3,2)
vertex(1.5,3,2)
vertex(1.5,0,2)
endShape(CLOSE)
#bottom
beginShape()
vertex(0,0,0)
vertex(0,3,0)
vertex(0.5,3,0)
vertex(0.5,8,0)
vertex(1,8,0)
vertex(1,3,0)
vertex(1.5,3,0)
vertex(1.5,0,0)
endShape(CLOSE)
#bottom side
beginShape()
vertex(0,0,0)
vertex(0,0,2)
vertex(1.5,0,2)
vertex(1.5,0,0)
endShape(CLOSE)
#top side
beginShape()
vertex(0.5,8,0)
vertex(0.5,8,2)
vertex(1,8,2)
vertex(1,8,0)
endShape()
#left bottom half
beginShape()
vertex(0,0,0)
vertex(0,0,2)
vertex(0,3,2)
vertex(0,3,0)
endShape()
#left smallest
beginShape()
vertex(0,3,0)
vertex(0,3,2)
vertex(0.5,3,2)
vertex(0.5,3,0)
endShape(CLOSE)
#left top half
beginShape()
vertex(0.5,3,0)
vertex(0.5,3,2)
vertex(0.5,8,2)
vertex(0.5,8,0)
endShape()
#right top half
beginShape()
vertex(1,3,0)
vertex(1,3,2)
vertex(1,8,2)
vertex(1,8,0)
endShape()
#right smallest
beginShape()
vertex(1,3,0)
vertex(1,3,2)
vertex(1.5,3,2)
vertex(1.5,3,0)
endShape()
#right bottom half
beginShape()
vertex(1.5,0,0)
vertex(1.5,0,2)
vertex(1.5,3,2)
vertex(1.5,3,0)
endShape()
# black piano key
def blackKey():
fill(100,100,100)
#bottom
beginShape()
normal(0,0,-1)
vertex(0,0,0)
vertex(1,0,0)
vertex(1,5,0)
vertex(0,5,0)
endShape(CLOSE)
#top
beginShape()
normal(0,0,1)
vertex(0,1,2)
vertex(1,1,2)
vertex(1,5,2)
vertex(0,5,2)
endShape(CLOSE)
#leftside
beginShape()
vertex(0,5,2)
vertex(0,5,0)
vertex(0,0,0)
vertex(0,0,1)
vertex(0,1,2)
endShape(CLOSE)
#rightside
beginShape()
vertex(1,5,2)
vertex(1,5,0)
vertex(1,0,0)
vertex(1,0,1)
vertex(1,1,2)
endShape(CLOSE)
#slanttop
beginShape()
vertex(0,1,2)
vertex(1,1,2)
vertex(1,0,1)
vertex(0,0,1)
endShape(CLOSE)
#slantbottom
beginShape()
vertex(0,0,0)
vertex(1,0,0)
vertex(1,0,1)
vertex(0,0,1)
endShape(CLOSE)
#back
beginShape()
vertex(0,5,0)
vertex(1,5,0)
vertex(1,5,2)
vertex(0,5,2)
endShape(CLOSE) |
a458281c5714e31e1b00a3b6bc9dc68fa9ca25f8 | BME-AI-STUDY/BME_AI_STUDY-21_1 | /3주차/answer3.py | 3,026 | 3.6875 | 4 | def check1():
ans = input("정답을 입력하시오")
if ans == 'max,index':
print('무야호~')
else:
print('오답')
def check2():
ans = input("정답을 입력하시오")
if ans == "OXXO":
print("무야호~")
else:
print("떙!")
def check3():
ans = input("정답을 입력하시오")
if ans == "교차엔트로피" or ans == "교차 엔트로피" or ans == "cross entropy" or ans == "crossentropy":
print("무야호~")
else:
print("떙!")
def check4():
ans1 = input("odd =")
ans2 = input("logit =")
if ans1 == y/1-y and ans2 == log(y/1-y):
print("무야호~")
else:
print("떙!")
def check5():
print('토론해 봅시다!')
def check6(answer_1, answer_2, answer_3, answer_4, answer_5):
answers = [answer_1, answer_2, answer_3, answer_4, answer_5]
labels = ['(N,b)', '(N,b)', '(1)', '(1)', '(N,b)']
print()
for n in range(5):
if answers[n] == labels[n]:
print('answer_{} : 정답'.format(n+1))
else:
print('answer_{} : 오답'.format(n+1))
def check7(answer1, answer2, answer3):
if answer1 == "4e^(-3)" and answer2 == "4e^(-3)" and answer3 == "e^(-3)":
print("정답")
else:
print("땡")
def check8():
print("단순히 한차례 선택분류를 할 것이 아닌 이후의 데이터를 가지고 학습을 시켜 새로운 데이터가 들어와도 제대로 분류할 수 있게끔 해야하기 때문이다.")
print("따라서 확률값으로 변환시켜 확률값을 토대로 weight를 조정하여 학습을 시키는 과정이 이후에 이루어진다")
"""Quiz 9"""
def check9_1(answer1):
if answer1 == 4:
print('정답입니다.')
else:
print('오답입니다.')
def check9_2(answer2):
if answer2 == 'chain rule':
print('정답입니다.')
elif answer2 == 'chainrule':
print('정답입니다.')
else:
print('오답입니다.')
def check10(answer) :
if answer == (1024, [1024,1024], 1024):
print("딩동댕")
else :
print("땡")
def check11(answer):
if answer[0]!=-0.05:
print('ㄱ 오답')
if answer[1]!=0.05:
print('ㄴ 오답')
if answer[2]!=-0.05:
print('ㄷ 오답')
if answer[3]!=0:
print('ㄹ 오답')
else:
print('정답')
def check12(input_vector, logits_vector, probability, num_of_perceptron):
if input_vector == ['n',7] and logits_vector == ['n',3] and probability == ['n',3] and number_of_perceptron ==3 :
return True
else :
return False
def check13(ans):
print("정답입니다!") if (ans == "2") else print("오답입니다")
def check14(answer) :
if answer == 3:
print('정답')
else :
print('오답')
def check15(answer):
if answer == "OOXOX":
print("정답입니다.")
else:
print("오답입니다") |
682b42e3089a87c4b24c8ee528e663bdfb466fd5 | shubham3000/python_turtle | /circle/circle.py | 335 | 3.90625 | 4 | import turtle
turtle.bgcolor("black")
turtle.pensize(1.5)
turtle.speed(0)
for i in range(6):
for colours in ["red","blue","yellow","orange","green","purple","cyan"]:
turtle.color(colours)
turtle.circle(100) #radius of circle
turtle.left(10) #angle shift for each circle
turtle.hideturtle()
turtle.done() |
7bbe18daf81dabb7aa2ddb7f20bca261734a17d8 | dodooh/python | /Sine_Cosine_Plot.py | 858 | 4.3125 | 4 | # Generating a sine vs cosine curve
# For this project, you will have a generate a sine vs cosine curve.
# You will need to use the numpy library to access the sine and cosine functions.
# You will also need to use the matplotlib library to draw the curve.
# To make this more difficult, make the graph go from -360° to 360°,
# with there being a 180° difference between each point on the x-axis
import numpy as np
import matplotlib.pylab as plt
plt.show()
# values from -4pi to 4pi
x=np.arange(-4*np.pi,4*np.pi,0.05)
y_sin=np.sin(x)
y_cos=np.cos(x)
#Drawing sin and cos functions
plt.plot(x,y_sin,color='red',linewidth=1.5, label="Sin(x)")
plt.plot(x,y_cos,color='blue', label="Cos(x)")
plt.title("Sin vs Cos graph")
plt.xlabel('Angles in radian')
plt.ylabel('sin(x) and cos(x)')
plt.legend(['sin(x)','cos(x)'])
plt.show() |
572da56c0611e09c0e3c8d00ad81f8780e457ec9 | ta100rik/HU-Huiswerk | /canvas/8/Py8.4_dictenfiles.py | 633 | 3.671875 | 4 | def ticker(filename):
File = open(filename)
ticker = {}
for line in File:
line = line.split(':')
totalname = line[0]
shortname = line[1].rstrip()
ticker[shortname] = totalname
return ticker
def searchticker(searchvalue,filename):
tickersdic = ticker(filename)
res = 'You search is not found'
for shortname, name in tickersdic.items():
if searchvalue == name:
res = shortname
elif searchvalue == shortname:
res = name
return res
uservalue = input('Give us your ticker or Companynae')
print(searchticker(uservalue,'tickers.txt'))
|
347c9b8ad2d52b3262a628fc960dce056171a85c | ta100rik/HU-Huiswerk | /canvas/7/py7.3_list&number.py | 1,095 | 3.84375 | 4 | invoer = "5-9-7-1-7-8-3-2-4-8-7-9"
# making a list of the input
list = invoer.split('-')
# sorting the list to make it readable
list.sort()
# defining templates for later on
template = "gesorteede lijst van ints = {}"
template2 = "Grootste getal: {} en Kleinste getal: {}"
template3 = "Aantal getallen: {} en som van de getallen: {}"
template4 = "Gemiddelde: {}"
def totallist(list):
'function to get the total of the list because sum function doesn\'t work in type list'
# defining default var
total = 0
# looping every list item
for number in list:
# counting the current total with the new list item
total = int(number) + total
return total
def averagelist(list):
# grabbing totallist from other function
total = totallist(list)
# counting the total listitems
total_items = len(list)
# calculating the average price
average = total / total_items
return average
print(template.format(list),'\n',template2.format(max(list),min(list)),'\n',template3.format(len(list),totallist(list)),'\n',template4.format(averagelist(list))) |
efa8e8bad596287953e1afdc8a4afb2b7bb5a1ce | ta100rik/HU-Huiswerk | /canvas/6/py6.4_filesschrijven.py | 1,130 | 3.9375 | 4 | # unlimited loop
import datetime
while True:
#
userfunctioncall = int(input('\nWhat do you want to see?\n1. insert a new runner\n2. Show all runners\n Insert the number of choose\n'))#asking the user for the function
# looking if the user has the right number else it will print that it is not
if userfunctioncall == 1:
# asking the name of the users
runner = input('What is the runnes his/her/its name: ')
#grabbing the current date full like all the paramaters
today = datetime.datetime.today()
# formatting the time to a nice format
currenttime = today.strftime("%a %d %b %Y, %H:%M:%S")
# opening the file with append permissions
file = open("Runnerlijst.txt", "a")
# making template
template = '{}, {}\n'
file.write(template.format(currenttime,runner))
file.close()
elif userfunctioncall == 2:
file = open('Runnerlijst.txt', 'r')
for line in file:
template = '{}'
print(template.format(line.rstrip()))
file.close()
else:
print('That is not a option') |
477830aa55a40a28ccd67afb831cf387bf567537 | ta100rik/HU-Huiswerk | /canvas/9/Py9.3_ASCI.py | 372 | 4.03125 | 4 | def code(string):
word = ''
for char in string:
dec = ord(char) + 3
new_value = chr(dec)
word = word + new_value
return word
gebruiker = input('Give me your name plz: ')
Startstation = input('Where do the user starts: ')
endstation = input('Where do the users stops: ')
combine = gebruiker+Startstation+endstation
print(code(combine)) |
cbb9ba081b16f0e1be200044b62eb1905b85e63a | matvey-mtn/advent-of-code | /python/day_2/password_validator_pt2.py | 671 | 3.90625 | 4 | f = open("test_input.txt", "r")
def validate(input_line):
chunked = input_line.split()
# get min and max
first_and_last = chunked[0].split("-")
first_occur = int(first_and_last[0]) - 1
last_occur = int(first_and_last[1]) - 1
# get char
char = chunked[1].replace(":", "")
# get password
password = chunked[2]
is_valid = (password[first_occur] == char) != (password[last_occur] == char)
answer = "valid" if is_valid else "invalid"
print(input_line.replace("\n", "") + " is " + answer)
return is_valid
valid_count = 0
for line in f.readlines():
if validate(line):
valid_count += 1
print(valid_count)
|
590f50b1aa83ab13a28949a109a004acca0b1ab7 | VerleysenNiels/Project_Computervisie | /label_images.py | 1,970 | 3.5 | 4 | """ Utility script for labeling painting corners.
Run this with the right settings for the folder to read and the csv to write
and it will show every image in turn. When it shows an image, click the four corners
(only the first four are recorded, so do it right) and then press any button to go
to the next image. Make sure you exit clean, or nothing will be saved in the csv.
Also, don't overwrite existing files.
Corner coordinates are in the images scaled to 1080
"""
import csv
import cv2
import numpy as np
import src.utils.io as io
scale = 1.0
def draw_point(event, x, y, flags, corners):
if event == cv2.EVENT_LBUTTONDOWN:
corners.append(int(x*scale))
corners.append(int(y*scale))
cv2.circle(img_scaled, (x, y), 3, (0, 255, 0), thickness=-1)
cv2.imshow(imname, img_scaled)
with open("corners_11.csv", mode="w") as pandc:
corner_writer = csv.writer(
pandc, delimiter=";", quotechar="\"", quoting=csv.QUOTE_MINIMAL)
for path, img in io.imread_folder("images\zalen\zaal_11"):
path2 = path.split("\\")
imname = path2[len(path2) - 1]
print(imname)
height, width, depth = img.shape
if (height > 700):
scale = height/700
img_scaled = cv2.resize(
img, (int(width / scale), int(height / scale))) # width height
else:
scale = 1
print(scale)
cv2.namedWindow(imname)
corners = []
cv2.setMouseCallback(imname, draw_point, corners)
cv2.imshow(imname, img_scaled)
cv2.moveWindow(imname, 100, 0)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(corners)
print(len(corners))
if(len(corners) >= 7):
print("writing")
corner_writer.writerow([imname, corners[0], corners[1], corners[2], corners[3],
corners[4], corners[5], corners[6], corners[7]])
|
68d606253d377862c11b0eaf52f942f6b6155f56 | DimaSapsay/py_shift | /shift.py | 349 | 4.15625 | 4 | """"
function to perform a circular shift of a list to the left by a given number of elements
"""
from typing import List
def shift(final_list: List[int], num: int) -> List[int]:
"""perform a circular shift"""
if len(final_list) < num:
raise ValueError
final_list = final_list[num:] + final_list[:num]
return final_list
|
630d6de3258bef33cfb9b4a79a276d002d56c39c | VictoryWekwa/program-gig | /Victory/PythonTask1.py | 205 | 4.53125 | 5 | # A PROGRAM TO COMPUTE THE AREA OF A CIRCLE
##
#
import math
radius=float(input("Enter the Radius of the Circle= "))
area_of_circle=math.pi*(radius**2)
print("The Area of the circle is", area_of_circle)
|
6e173ae8b17ac4af50fdebb3fb48e857fa3159da | KiemNguyen/data-science | /data-analysis-and-visualization /data-cleaning/Challenge - Cleaning Data.py | 1,056 | 4 | 4 | ## 3. Exploring the Data ##
import pandas as pd
avengers = pd.read_csv("avengers.csv")
avengers.head(5)
## 4. Filtering Out Bad Data ##
import matplotlib.pyplot as plt
true_avengers = pd.DataFrame()
avengers['Year'].hist()
true_avengers = avengers[avengers["Year"] > 1960]
## 5. Consolidating Deaths ##
def calculate_death(row):
columns = ["Death1", "Death2", "Death3", "Death4", "Death5"]
death_count = 0
for column in columns:
death = row[column]
if pd.isnull(death) or death == 'NO':
continue
elif death == 'YES':
death_count += 1
return death_count
true_avengers["Deaths"] = true_avengers.apply(calculate_death, axis=1)
print(true_avengers["Deaths"])
## 6. Verifying Years Since Joining ##
joined_accuracy_count = int()
# Calculate the number of rows where Years since joining is accurate
years_diff = 2015 - true_avengers["Year"]
correct_joined_year = true_avengers[true_avengers["Years since joining"] == years_diff]
joined_accuracy_count = len(correct_joined_year)
|
9ff86358248bb89b4c5390a3c8e8b0bb3bc2bb45 | KiemNguyen/data-science | /summarizing-job-data/Summarizing Job Data.py | 1,392 | 3.640625 | 4 | ## 2. Introduction to the Data ##
import pandas as pd
all_ages = pd.read_csv("all-ages.csv")
recent_grads = pd.read_csv("recent-grads.csv")
print(all_ages.head(5))
print(recent_grads.head(5))
## 3. Summarizing Major Categories ##
import numpy as np
# Unique values in Major_category column.
print(all_ages['Major_category'].unique())
#aa_cat_counts = dict()
#rg_cat_counts = dict()
aa_cat_counts = all_ages.pivot_table(index = "Major_category", values = "Total", aggfunc = np.sum)
rg_cat_counts = recent_grads.pivot_table(index = "Major_category", values = "Total", aggfunc = np.sum)
print(aa_cat_counts)
print("")
print(rg_cat_counts)
## 4. Low-Wage Job Rates ##
low_wage_percent = 0.0
low_wage_jobs_sum = recent_grads['Low_wage_jobs'].sum()
recent_grads_sum = recent_grads['Total'].sum()
low_wage_percent = low_wage_jobs_sum / recent_grads_sum
print(low_wage_percent)
## 5. Comparing Data Sets ##
# All majors, common to both DataFrames
majors = recent_grads['Major'].unique()
rg_lower_count = 0
for major in majors:
recent_grads_row = recent_grads[recent_grads["Major"] == major]
all_ages_row = all_ages[all_ages["Major"] == major]
rg_unemp_rate = recent_grads_row.iloc[0]["Unemployment_rate"]
aa_unemp_rate = all_ages_row.iloc[0]["Unemployment_rate"]
if rg_unemp_rate < aa_unemp_rate:
rg_lower_count += 1
print(rg_lower_count ) |
377634aaf2e80aba479808236f2b49f2fbea6845 | rockomatthews/Dojo | /Python/scoresAndGrades.py | 476 | 3.890625 | 4 | import random
def grades(students):
for x in range(0, students):
score = random.randint(60, 100)
if score >= 60 and score < 70:
print "Score: ", score,"; Your grade is D"
elif score >= 70 and score < 80:
print "Score: ", score,"; Your grade is C"
elif score >= 80 and score < 90:
print "Score: ", score,"; Your grade is B"
else:
print "Score: ", score,"; Your grade is A"
grades(10) |
30f766189335d229a23333fc40acb3df39f6e509 | rockomatthews/Dojo | /Python/multiplesSumAverage.py | 287 | 4.09375 | 4 | for count in range(1, 1000, 2):
print count
for count in range(5, 1000000, 5):
print count
sum = 0
a = [1, 2, 5, 10, 255, 3];
for element in a:
sum += element
print sum
sum = 0
a = [1, 2, 5, 10, 255, 3];
for element in a:
sum += element
avg = sum/len(a)
print avg |
a47e1bea7cd89173b07847f8b6ba3309e8a5a341 | chessleensingh/sudoku_solver | /sudoku_solver_1.py | 6,554 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import time
class Sudoku_node:
data = None
center = None
val_avail = None
def __init__(self, data):
self.data = data
puzzle_1d = [0,6,0,8,0,0,0,5,4,0,0,0,0,0,0,0,3,0,0,2,4,0,9,0,8,0,6,0,0,6,0,1,3,0,0,0,0,0,0,5,0,9,0,0,0,0,0,0,6,4,0,1,0,0,3,0,5,0,6,0,9,8,0,0,7,0,0,0,0,0,0,0,6,1,0,0,0,5,0,2,0]
np_puzzle = np.array(puzzle_1d)
np_puzzle = np_puzzle.reshape(9,9)
print(np_puzzle)
def allocate_centers(arr):
for i in range(9):
for j in range(9):
dist = []
#finding the distance to all centers
for center in centers:
dist_1 = (np.array([i,j]) - np.array(center[1]))**2
dist_1 = np.sum(dist_1)
dist_1 = np.sqrt(dist_1)
dist.append(dist_1)
center_apt = np.argmin(dist)
arr[i][j].center = int(center_apt)
return arr
def update_val_available(arr):
val_avail_9by9 = []
for i in range(9):
for j in range(9):
things_to_eliminate = set()
center_allocated = arr[i][j].center
if (arr[i][j].data != None):
arr[i][j].val_avail = [11,12,13,14,15,16,17,18,19,10]
val_avail_9by9.append([11,12,13,14,15,16,17,18,19,10])
continue
else:
columns = []
rows = []
for k in range(9):
columns.append(arr[k][j].data)
rows.append(arr[i][k].data)
things_to_eliminate = things_to_eliminate.union(rows, columns)
val_avail_from_box = (values_avail_for_centers[arr[i][j].center])
temp = set([1,2,3,4,5,6,7,8,9]).difference(things_to_eliminate)
temp_1 = (temp).intersection(set(val_avail_from_box))
arr[i][j].val_avail = list(temp_1)
val_avail_9by9.append(list(temp_1))
val_avail_9by9 = np.array(val_avail_9by9)
val_avail_9by9 = val_avail_9by9.reshape(9,9)
#trying to check if there's a unique value in a row,col
for i in range(9):
row_data = val_avail_9by9[i,:]
col_data = val_avail_9by9[:,i]
for k in range(1,10): #numbers
check_in_rows = [0,0,0,0,0,0,0,0,0]
check_in_cols = [0,0,0,0,0,0,0,0,0]
for indices in range(9):
if k in row_data[indices]:
check_in_rows[indices] = 1
if k in col_data[indices]:
check_in_cols[indices] = 1
if(sum(check_in_rows) == 1):
j_to_update = check_in_rows.index(1)
arr[i][j_to_update].val_avail = [k]
if(sum(check_in_cols) == 1):
i_to_update = check_in_cols.index(1)
arr[i_to_update][i].val_avail = [k]
return arr, val_avail_9by9
def update_centers(arr):
for i in range(9):
for j in range(9):
if (arr[i][j].data != None):
center_allocated = arr[i][j].center
values_avail_for_centers[center_allocated][(arr[i][j].data)-1] = None
else:
continue
return arr
def every_cell_has_data(arr):
for i in range(9):
for j in range(9):
if (arr[i][j].data == None):
return True
else:
continue
return False
def cell_w_lowest_options(arr):
min_cell = []
for i in range(9):
for j in range(9):
if (len(arr[i][j].val_avail) == 1):
min_cell.append((arr[i][j], i, j))
return (min_cell)
def set_data_to_data_structure():
arr = [None]*81
arr = np.array(arr)
arr = arr.reshape(9,9)
for i in range(9):
for j in range(9):
if (np_puzzle[i][j] == 0):
arr[i][j] = Sudoku_node(None)
else:
arr[i][j] = Sudoku_node(np_puzzle[i][j])
return arr
def Solver():
arr = set_data_to_data_structure()
arr = allocate_centers(arr)
arr = update_centers(arr)
np_puzzle_1 = np_puzzle.copy()
iteration = 0
while(every_cell_has_data(arr)):
arr = update_centers(arr)
arr, val_avail_9by9 = update_val_available(arr)
cell_list = cell_w_lowest_options(arr)
if (not cell_list):
values_avail_in_a_box = [[]]
for i in range(9):
temp_list = []
for j in range(9):
center = arr[i][j].center
if (not values_avail_in_a_box[center]):
values_avail_in_a_box.insert(center,[[(i,j), arr[i][j].val_avail]])
else:
values_avail_in_a_box[center].append([(i,j), arr[i][j].val_avail])
for box in range(9):
for k in range(1,10):
occurence_counter = [0,0,0,0,0,0,0,0,0]
for cell_values in range(9):
if (k in values_avail_in_a_box[box][cell_values][1]):
occurence_counter[cell_values] = 1
if (sum(occurence_counter) == 1):
index_of_cell = occurence_counter.index(1)
i_,j_ = values_avail_in_a_box[box][index_of_cell][0]
arr[i_][j_].val_avail = [k]
cell_list = cell_w_lowest_options(arr)
for cell, i, j in cell_list:
temp_arr = arr[i][j]
arr[i][j] = Sudoku_node(cell.val_avail[0])
arr[i][j].center = temp_arr.center
iteration+=1
for i in range(9):
for j in range(9):
np_puzzle_1[i][j] = arr[i][j].data
print(np_puzzle)
print("\n\n............solved.........\n\n")
print(np_puzzle_1)
centers = [(0,[1,1]), (1,[1,4]), (2,[1,7]), (3,[4,1]), (4,[4,4]), (5,[4,7]), (6,[7,1]), (7,[7,4]), (8,[7,7])]
values_avail_for_centers = [[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9]]
start_time = time.time()
Solver()
print(time.time()- start_time)
|
776435c8431a83db3aca92842ca6b11c9554be56 | mohammed-qureshi/Bank | /bank.py | 934 | 3.875 | 4 | class User:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"name = {self.name}, age = {self.age}"
class Bank(User):
def __init__(self, name, age, balance):
super().__init__(name, age)
self.balance = balance
def deposit(self, amount):
self.balance += amount
return f"{self.name}'s account balance is ${self.balance}"
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return f"{self.name}'s account balance is ${self.balance}"
else:
print(f'Insufficent funds, Account Balance: ${self.balance}')
if __name__ == "__main__":
mo = Bank('Mohammed Qureshi', 21, 1382)
adnan = Bank('Adnan Khan', 35, 545)
print(mo.deposit(12))
print(adnan.withdraw(75))
print(adnan.withdraw(1000))
|
ee08f2ee20612f5f5911065803f2824beb11d1c9 | NagaTaku/atcoder_abc_edition | /ABC044/b.py | 143 | 3.5 | 4 | s = input()
res = 'Yes'
for i in range(len(s)):
hantei = s.count(s[i])
if hantei%2 == 1:
res = 'No'
break
print(res) |
8e89064e68022c83a38a3811b70e784a126debcd | NagaTaku/atcoder_abc_edition | /ABC168/a.py | 195 | 3.75 | 4 | n = int(input())
if n%10 == 2 or n%10 == 4 or n%10 == 5 or n%10 == 7 or n%10 == 9:
print('hon')
elif n%10 == 0 or n%10 == 1 or n%10 == 6 or n%10 == 8:
print('pon')
else:
print('bon') |
e527a551b17d706c206afc1285fe6c319aabbeda | NagaTaku/atcoder_abc_edition | /ABC066/b.py | 197 | 3.546875 | 4 | s = input()
s_len = len(s)
for i in range(1, int(s_len/2)+1):
s = s[:-2]
half = int(len(s)/2)
s_mae = s[:half]
s_ato = s[half:]
if s_mae == s_ato:
break
print(len(s)) |
50d3c9773fbeca17dfae09df2f46b57cd507275c | NagaTaku/atcoder_abc_edition | /ABC062/b.py | 324 | 3.53125 | 4 | h, w = map(int, input().split())
a = []
for i in range(h):
a.append(input())
ans = []
topdown = ""
for i in range(w+2):
topdown = topdown + "#"
for i in range(h):
a[i] = "#" + a[i] + "#"
ans.append(topdown)
for i in range(h):
ans.append(a[i])
ans.append(topdown)
for i in range(h+2):
print(ans[i])
|
212bd26c0ebb4139eab60ea9d64ddf542e8368fd | NagaTaku/atcoder_abc_edition | /ABC046/a.py | 217 | 3.765625 | 4 | a,b,c = map(int, input().split())
if a == b and b == c:
print(str(1))
elif (a == b and a != c) or (a == c and a != b) or (a != b and b == c):
print(str(2))
elif a != b and b != c and a != c:
print(str(3)) |
5503ffdae3e28c9bc81f7b536fc986bf46913d34 | jocogum10/learning_data_structures_and_algorithms | /doubly_linkedlist.py | 1,940 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next_node = None
self.previous_node = None
class DoublyLinkedList:
def __init__(self, first_node=None, last_node=None):
self.first_node = first_node
self.last_node = last_node
def insert_at_end(self, value):
new_node = Node(value)
if not self.first_node: # if there are no elements yet in the linked list
self.first_node = new_node
self.last_node = new_node
else:
new_node.previous_node = self.last_node # else, set the new node's previous node as the last node
self.last_node.next_node = new_node # set the last node's next node to the new node
self.last_node = new_node # set the last node as the new node
def remove_from_front(self):
removed_node = self.first_node # set the node to be removed
self.first_node = self.first_node.next_node # set the first node to be the next node
return removed_node # return the removed node
class Queue:
def __init__(self):
self.queue = DoublyLinkedList()
def enque(self, value):
self.queue.insert_at_end(value)
def deque(self):
removed_node = self.queue.remove_from_front
return removed_node
def tail(self):
return self.queue.last_node.data
if __name__ == '__main__':
node_1 = Node("once")
node_2 = Node("upon")
node_1.next_node = node_2
node_3 = Node("a")
node_2.next_node = node_3
node_4 = Node("time")
node_3.next_node = node_4
dlist = DoublyLinkedList(node_1)
print(dlist.remove_from_front().data)
q = Queue()
q.enque(dlist)
b = q.tail()
print(b.first_node.data) |
f45d49a14960ddbab0693c8ab02badf2ae1fd70b | jocogum10/learning_data_structures_and_algorithms | /countdown.py | 150 | 3.5 | 4 | def countdown(number):
print(number)
if number == 0: # base case
pass
else:
countdown(number-1)
countdown(10) |
9d8201904553de2ece7e8fd3bc52a54548f96f8b | emelyalonzo/vaccination-system | /phase-1/dlist.py | 7,717 | 4 | 4 | # -*- coding: utf-8 -*-
"""
First, we must implement the class Node to store the nodes. In addition to the element and the
reference to the next node, the class includes a reference, **prev**, to the previous node.
"""
class DNode:
def __init__(self,elem,next=None,prev=None ):
self.elem = elem
self.next = next
self.prev = prev
class DList:
def __init__(self):
"""creates an empty list"""
self._head=None
self._tail=None
self._size=0
def __len__(self):
return self._size
def isEmpty(self):
"""Checks if the list is empty"""
#return self.head == None
return len(self)==0
def __str__(self):
"""Returns a string with the elements of the list"""
nodeIt=self._head
result=''
while nodeIt:
result += str(nodeIt.elem)+',\n'
nodeIt=nodeIt.next
if len(result)>0:
result=result[:-2]
return result
def addFirst(self,e):
"""Add a new element, e, at the beginning of the list"""
#create the new node
newNode=DNode(e)
#the new node must point to the current head
if self.isEmpty():
self._tail=newNode
else:
newNode.next=self._head
self._head.prev=newNode
#update the reference of head to point the new node
self._head=newNode
#increase the size of the list
self._size+=1
def addLast(self,e):
"""Add a new element, e, at the end of the list"""
#create the new node
newNode=DNode(e)
if self.isEmpty():
self._head=newNode
else:
newNode.prev=self._tail
self._tail.next=newNode
#update the reference of head to point the new node
self._tail=newNode
#increase the size of the list
self._size+=1
def removeFirst(self):
"""Returns and remove the first element of the list"""
result=None
if self.isEmpty():
print("Error: list is empty")
else:
result=self._head.elem
self._head= self._head.next
if self._head==None:
self._tail=None
else:
self._head.prev = None
self._size-=1
return result
def removeLast(self):
"""Returns and remove the last element of the list"""
result=None
if self.isEmpty():
print("Error: list is empty")
else:
result=self._tail.elem #1
self._tail= self._tail.prev
if self._tail==None:
self._head=None
else:
self._tail.next = None
self._size-=1
return result
def getAt(self,index):
"""return the element at the position index.
If the index is an invalid position, the function
will return -1"""
result=None
if index not in range(0,len(self)):
print(index,'Error getAt: index out of range')
else:
nodeIt=self._head
i=0
while nodeIt and i<index:
nodeIt=nodeIt.next
i+=1
#nodeIt is at the position index
result=nodeIt.elem
return result
def index(self,e):
"""returns the first position of e into the list.
If e does not exist in the list,
then the function will return -1"""
nodeIt=self._head
index=0
while nodeIt:
if nodeIt.elem==e:
return index
nodeIt=nodeIt.next
index+=1
#print(e,' does not exist!!!')
return -1
def insertAt(self,index,e):
"""It inserts the element e at the index position of the list"""
if index not in range(len(self)+1):
print('Error: index out of range')
elif index==0:
self.addFirst(e)
elif index==len(self):
self.addLast(e)
else:
#we must to reach the node at the index position
nodeIt=self._head
for i in range(1,index+1):
nodeIt=nodeIt.next
#nodeIt is the node at the index
newNode=DNode(e)
#we have to insert the new node before nodeIt
newNode.next=nodeIt
newNode.prev=nodeIt.prev
nodeIt.prev.next=newNode
nodeIt.prev=newNode
self._size+=1
def removeAt(self,index):
"""This methods removes the node at the index position in the list"""
#We must check that index is a right position in the list
#Remember that the indexes in a list can range from 0 to size-1
"""This methods removes the node at the index position in the list"""
result=None
#We must check that index is a right position in the list
#Remember that the indexes in a list can range from 0 to size-
#print(str(self)," len=", len(self), "index=",index)
if index not in range(len(self)):
print(index,'Error removeAt: index out of range')
elif index==0:
result= self.removeFirst()
elif index==len(self)-1:
result= self.removeLast()
else:
#we must to reac
#we must to reach the node at the index position
nodeIt=self._head
for i in range(1,index+1):
nodeIt=nodeIt.next
#nodeIt is the node to be removed
result=nodeIt.elem
prevNode=nodeIt.prev
nextNode=nodeIt.next
prevNode.next=nextNode
nextNode.prev=prevNode
self._size-=1
return result
###Main
if __name__ == '__main__':
import random
l=DList()
print("list:",str(l))
print("len:",len(l))
#we generate 5 random integers
for i in range(5):
#creates a positive integer between 0 <=x<= 100
x=random.randint(0,100)
#l.addFirst(x)
l.addLast(x)
print(l)
for i in range(len(l)):
print('getAt({})={}'.format(i,l.getAt(i)))
print(str(l))
print()
print("index of {}={}".format(20,l.index(20)))
print("index of {}={}".format(0,l.index(0)))
print("index of {}={}".format(5,l.index(5)))
print("index of {}={}".format(10,l.index(10)))
while l.isEmpty()==False:
print("after removeLast():{}, {}".format(l.removeLast(),l))
l.insertAt(-1,1)
l.insertAt(0,0)
print(str(l))
print('after l.insertAt(0,0)', str(l))
l.insertAt(len(l)//2,3)
print('after l.insertAt(2,3)', str(l))
print("index of {}={}".format(3,l.index(3)))
print('len of l',len(l))
l.insertAt(len(l),3)
print('after l.insertAt(12,3)', str(l))
print("index of {}={}".format(3,l.index(3)))
l.insertAt(len(l),100)
print('after l.insertAt(13,100)', str(l))
print()
print('testing removeAt', str(l))
x=0
print('after l.removeAt({})={}, {}'.format(x,l.removeAt(x), str(l)))
x=len(l)//2
print('after l.removeAt({})={}, {}'.format(x,l.removeAt(x), str(l)))
x=len(l)-1
print('after l.removeAt({})={}, {}'.format(x,l.removeAt(x), str(l))) |
63f36d415be02e5f70247cc14470f96ac3cb6e2b | m3xw3ll/RockPaperScissors | /main.py | 4,898 | 3.5625 | 4 | # Icons are under creative commons license by Cristiano Zoucas from the Noun Project
# His work is available under https://thenounproject.com/cristiano.zoucas/
from tkinter import *
from PIL import Image, ImageTk
from tkinter import font
from functools import partial
import random
BACKGROUND = '#e0e0e0'
def update_user_score():
'''
Update the player score
:return: None
'''
score = int(user_score_label['text'])
score += 1
user_score_label['text'] = str(score)
def update_computer_score():
'''
Update the computer score
:return: None
'''
score = int(comp_score_label['text'])
score += 1
comp_score_label['text'] = str(score)
def update_message(result):
'''
Update the message text after each round
:param result: The text message
:return: None
'''
textmessage['text'] = result
def update_labels(user_choice, comp_choice):
'''
A function which updates the images for user and computer
:param user_choice: The choice the user made with the button click
:param comp_choice: The random computer choice
:return: None
'''
if user_choice == 'rock':
user_pick.configure(image=player_rockimg)
elif user_choice == 'paper':
user_pick.configure(image=player_paperimg)
else:
user_pick.configure(image=player_scissorimg)
if comp_choice == 'rock':
comp_pick.configure(image=computer_rockimg)
elif comp_choice == 'paper':
comp_pick.configure(image=computer_paperimg)
else:
comp_pick.configure(image=computer_scissorimg)
def play(choice):
'''
The acutial rock paper scissor function with the game logic
:param choice: The user choice
:return: None
'''
user_choice = choice
comp_choice = random.sample({'rock', 'paper', 'scissor'}, 1)
comp_choice = str(comp_choice[0])
update_labels(user_choice, comp_choice)
if user_choice == comp_choice:
update_message('Tie')
elif user_choice == 'rock':
if comp_choice == 'paper':
update_message('You loose')
update_computer_score()
else:
update_user_score()
update_message('You win')
elif user_choice == 'paper':
if comp_choice == 'scissor':
update_message('You loose')
update_computer_score()
else:
update_message('You win')
update_user_score()
elif user_choice == 'scissor':
if comp_choice == 'rock':
update_message('You loose')
update_computer_score()
else:
update_message('You win')
update_user_score()
root = Tk()
root.title("Rock Paper Scissor")
root.configure(background=BACKGROUND)
root.resizable(0, 0)
# Load images
player_rockimg = ImageTk.PhotoImage(Image.open('./src/player_rock.png'))
player_paperimg = ImageTk.PhotoImage(Image.open('./src/player_hand.png'))
player_scissorimg = ImageTk.PhotoImage(Image.open('./src/player_scissor.png'))
computer_rockimg = ImageTk.PhotoImage(Image.open('./src/computer_rock.png'))
computer_paperimg = ImageTk.PhotoImage(Image.open('./src/computer_hand.png'))
computer_scissorimg = ImageTk.PhotoImage(Image.open('./src/computer_scissor.png'))
# Labels
infofont = font.Font(family='Arial', size=10, weight='normal')
messagefont = font.Font(family='Arial', size=20, weight='bold')
user_pick = Label(root, image=player_rockimg, bg=BACKGROUND)
comp_pick = Label(root, image=computer_rockimg, bg=BACKGROUND)
user_pick.grid(row=1, column=0, padx=20, pady=(60,0))
comp_pick.grid(row=1, column=4, padx=20, pady=(60,0))
textmessage = Label(root, text='', font=messagefont, bg=BACKGROUND)
textmessage.grid(row=0, column=2, pady=(20,0))
usertext = Label(root, text='Player', font=infofont, bg=BACKGROUND).grid(row=0, column=0)
computertext = Label(root, text='Computer', font=infofont, bg=BACKGROUND).grid(row=0, column=4)
# Scores
scorefont = font.Font(family='Arial', size=50, weight='bold')
user_score_label = Label(root, font=scorefont, text=0, bg=BACKGROUND)
user_score_label.grid(row=1, column=1, pady=(60,0))
sep = Label(root, font=scorefont, text=':', bg=BACKGROUND).grid(row=1, column=2, pady=(60,0))
comp_score_label = Label(root, font=scorefont, text=0, bg=BACKGROUND)
comp_score_label.grid(row=1, column=3, pady=(60,0))
# Buttoms
btnfont = font.Font(family='Arial', size=10, weight='bold')
rockbtn = Button(root, width=20, height=2, text="Rock", bg='#F77494', font=btnfont, highlightcolor='white', command=partial(play, 'rock')).grid(row=4, column=1, padx=5)
paperbtn = Button(root, width=20, height=2, text="Paper", bg='#FFE076', font=btnfont, command=partial(play, 'paper')).grid(row=4, column=2, padx=5)
scissorbtn = Button(root, width=20, height=2, text="Scissor", bg='#A1E3F3', font=btnfont, command=partial(play, 'scissor')).grid(row=4, column=3, pady=20, padx=5)
root.mainloop()
|
f9b9480cc340d3b79f06e49aa31a53dbea5379f5 | abilash2574/FindingPhoneNumber | /regexes.py | 377 | 4.1875 | 4 | #! python3
# Creating the same program using re package
import re
indian_pattern = re.compile(r'\d\d\d\d\d \d\d\d\d\d')
text = "This is my number 76833 12142."
search = indian_pattern.search(text)
val = lambda x: None if(search==None) else search.group()
if val(search) != None:
print ("The phone number is "+val(search))
else:
print("The phone number is not found")
|
49e8d98d43bd848f61f35c3fdce6caebf87948f2 | kabitakumari20/List_Questions | /daignol.elmint.py | 215 | 3.65625 | 4 | a=[[1,2,3],[4,5,6],[7,8,9]]
i=0
j=0
c=[ ]
while i<len(a):
b=a[i][j]
j=j+1
c.append(b)
i=i+1
print(c)
# 1,5,9
# a=[[4,5,6],[7,8,9],[10,11,12]]
# i=0
# j=2
# while i<len(a):
# print(a[i][j])
# j=j-1
# i=i+1 |
9103df329de4f8b0a8e89aaec2c17d8b31df529f | kabitakumari20/List_Questions | /row_cloum.py | 265 | 3.765625 | 4 | row=int(input("enter the row="))
cloum=int(input("enter the cloum="))
i=1
a=1
list1=[]
while i<=row:
b=a
j=1
list2=[]
while j<=cloum:
list2.append(b)
j=j+1
b=b+1
list1.append(list2)
i=i+1
a=a+cloum
print(list1)
|
7cfc609c407bd5531caeb049e809fbf6ccf7ec7e | 1789479668/DIP-Homework | /Histogram-Equalization/show_hist.py | 634 | 3.59375 | 4 | from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import sys
def main():
# image
filename = sys.argv[1]
im_matrix = np.array(Image.open(filename).convert('L'))
# create a histogram of the image
hist = np.zeros(256)
count = 0
for row in im_matrix:
for gray_data in row:
hist[gray_data] += 1
count += 1
hist = hist / count
# create the plot
plt.title("Histogram")
plt.plot(hist)
plt.axis([0, 255, 0, np.max(hist) * 1.05])
plt.xlabel("Gray Level")
plt.ylabel("Frequence")
plt.show()
if __name__ == "__main__":
main() |
ddf2124551bc9a6c08f4e1d4b4347c6cd1a3cb91 | gogoamy/repository1 | /type.py | 2,561 | 4.125 | 4 | # -*- coding: utf-8 -*-
# Number类型(int, float, boolean, complex)
print('Number类型(int, float, boolean, complex)')
a = 10
print('整形(int) a = ',a)
b = 20.00
print('浮点型(float) b = ',b)
c = 1.5e11
print('浮点型,科学计数法(float) c = ',c)
d = True
print('布尔型(boolean) d = ',d)
e = False
print('布尔型(boolean) e = ',e)
f = 3.14j
print('复数(complex) f = ',f)
g = complex(1.2,2.3)
print('复数(complex) g = ',g)
print()
print()
print()
# String类型
print('String类型')
s1 = 'hello'
print('String类型 s1 = ',s1)
s2 = "let's go"
print('String类型 s2 = ',s2)
# 转义符号\,\n,\t
s3 = 'let\'s go'
print('String类型 s3 = ',s3)
s4 = 'abc\ncba'
print('String类型 s4 = ',s4)
s5 = '\\\t\\'
print('String类型 s5 = ',s5)
#跨越多行
s6 = '''abc
123
erf
333
tyu
'''
print('String类型 s6 = ',s6)
# 星号 (*) 表示复制当前字符串,紧跟的数字为复制的次数
s7 = 'hello world '*5
print('String类型 s7 = ',s7)
print()
print()
print()
# String中字符串检索
print('String中字符串检索')
test = 'hello'
print('test[0]: ',test[0])
print('test[1]: ',test[1])
print('test[2]: ',test[2])
print('test[3]: ',test[3])
print('test[4]: ',test[4])
# String中的切片
# str[x:y]: 输出从x位置开始的字符一直到y位置(不包括y)
print('test[0:2]: ',test[0:2])
print('test[2:4]: ',test[2:3])
print('test[2:5]: ',test[2:5])
# 索引切片可以有默认值,切片时,忽略第一个索引的话,默认为0
# 忽略第二个索引,默认为字符串的长度
print('test[:2]: ',test[:2])
print('test[2:]: ',test[2:])
# 索引也可以是负数,这将导致从右边开始计算
print('test[-1]: ',test[-1])
print('test[-2]: ',test[-2])
print('test[-3]: ',test[-3])
print('test[-4]: ',test[-4])
print('test[-5]: ',test[-5])
print('test[-2:]: ',test[-2:])
print('test[:-2]: ',test[:-2])
# 内置函数 len() 返回字符串长度
s = 'abcdefghijk'
print('字符串s的长度是: ',len(s))
print()
print()
print()
# 格式化字符串
# 在字符串内部,%s表示用字符串替换,%d表示用整数替换
# 有几个%占位符,后面就跟几个变量或者值,顺序要对应好
print('格式化字符串')
print('hello,%s' % 'world')
print('your name is %s, your score is %d' % ('testing',98))
print('浮点数:%f' % 3.14)
print('浮点数:%.2f' % 3.14)
|
120ffe29ab10d7b33f42c301e52c2f0c45a3e499 | ShivamBhosale/CTCI_Self_Practice | /Chapter_1/P01_practice.py | 397 | 3.828125 | 4 | """ Is Unique """
def isUnique(str1):
sorted_str = sorted(str1)
last_character = None
for charz in sorted_str:
if charz == last_character:
return False
last_character = charz
return True
print(isUnique("Helo"))
""" is Unique in a pythonic way """
def isUnique_pythonic(str2):
return len(set(str2)) == len(str2)
print(isUnique_pythonic("Hello"))
|
b6626631ba1cbf87a2c93bdeeb06eaf139202a97 | GoncharovArtyom/python-yandex-praktikum | /service1_fulltext_search/task1_debug/main.py | 2,757 | 3.890625 | 4 | from typing import Optional
class Matrix:
"""
Код нашего коллеги аналитика
Очень медленный и тяжелый для восприятия. Ваша задача сделать его быстрее и проще для понимания.
"""
def __init__(self):
self.data = []
self.size = 1
def matrix_scale(self, scale_up: bool):
"""
Функция отвечает за создание увеличенной или уменьшенной матрицы.
Режим работы зависит от параметра scale_up. На выходе получаем расширенную матрицу.
:param matrix: исходная матрица
:param scale_up: если True, то увеличиваем матрицу, иначе уменьшаем
:return: измененная матрица
"""
if scale_up:
self.size += 1
else:
self.size -= 1
def add_item(self, element: Optional = None):
"""
Добавляем новый элемент в матрицу.
Если элемент не умещается в (size - 1) ** 2, то расширить матрицу.
"""
if element is None:
raise ValueError
if len(self.data) >= (self.size - 1) ** 2:
self.matrix_scale(scale_up=True)
self.data.append(element)
def pop(self):
"""
Удалить последний значащий элемент из массива.
Если значащих элементов меньше (size - 1) * (size - 2) уменьшить матрицу.
"""
if self.size == 1:
raise IndexError()
value = self.data.pop()
if len(self.data) <= (self.size - 1) * (self.size - 2):
self.matrix_scale(scale_up=False)
return value
def __str__(self):
"""
Метод должен выводить матрицу в виде:
1 2 3\nNone None None\nNone None None
То есть между элементами строки должны быть пробелы, а строки отделены \n
"""
result = []
for i in range(self.size):
row = []
for j in range(self.size):
index = self.size * i + j
if index < len(self.data):
row.append(str(self.data[index]))
else:
row.append(str(None))
result.append(' '.join(row))
return '\n'.join(result)
if __name__ == '__main__':
m = Matrix()
m.add_item(1)
print(m) |
ea8af9fd3352dc49621bdb706672635ba756962e | abhishekpandya/Python---Data-Strutures | /ReverseDoublyLinkedList.py | 259 | 4.0625 | 4 | ## Reverse doubly linked list
def reverse(head):
temp=None
p=head
while p is not None:
temp = p.prev
p.prev = p.next
p.next = temp
p = p.prev
if temp is not None:
head = temp.prev
return head |
96c33e195af17073b722e3c9a861be5d3e5d63de | abhishekpandya/Python---Data-Strutures | /BracketsChecker.py | 654 | 3.875 | 4 | ### Check for brackets
def checkBrackets(s):
lst=[]
previousBracket = ""
for char in s:
if char == "{" or char == "(" or char == "[" and len(lst)>=0:
lst.append(char)
previousBracket = char
elif previousBracket == "[" and char == "]" or previousBracket == "(" and char == ")" or previousBracket == "{" and char == "}" and len(lst)>0:
lst.pop();
if len(lst)>0:
previousBracket = lst[len(lst)-1]
else:
return False
if len(lst)==0:
return True
else:
return False
print(checkBrackets("{([()])}{}[()]")) |
d40ce6c4c585ac147dc2112e3b49c897b1f3fdc1 | abhishekpandya/Python---Data-Strutures | /BinaryStrings.py | 393 | 3.5625 | 4 | ## Generate all binary strings for ex 1?1 -> 101 , 111 ( Replaces ? with 0 and 1)
def binaryStrings(s,index):
if index==len(s):
print(s)
return
if s[index]=='?':
s=s[:index]+"0"+s[index+1:]
completeStrings(s,index+1)
s=s[:index]+"1"+s[index+1:]
completeStrings(s,index+1)
else:completeStrings(s,index+1)
binaryStrings("1??0?101",0) |
4c7becf4f5583de6c814c831f58bbc82107082e8 | andresmiguel/hacker-rank-exs | /statistics/day0_Weighted_Mean.py | 356 | 3.578125 | 4 | n = input()
numbers = []
weights = []
line = input()
numbers = list(map(lambda x: int(x), line.split(" ")))
line = input()
weights = list(map(lambda x: int(x), line.split(" ")))
weightAndNumberSum = 0
weightSum = sum(weights)
for idx, number in enumerate(numbers):
weightAndNumberSum += number * weights[idx]
print(weightAndNumberSum / weightSum)
|
d8e66b7676addfb742698f8057a2dbe59d9991c5 | DamirKozhagulov/python_basics_homework | /home_tasks_1/practical_work_1_4.py | 571 | 4.15625 | 4 | # 4)
# Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
number = input('Введите целое положительное число: ')
print(len(number))
result = []
i = 0
while i < len(number):
num = number[i]
result.append(num)
i += 1
number = sorted(result)
print(number)
print('Самая большая цифра ' + number[-1])
|
3305479f970d922cc09a4eb0216375bca2b194e9 | DamirKozhagulov/python_basics_homework | /Lesson16/game.py | 1,548 | 3.71875 | 4 | import random
def game():
number = random.randint(1, 100)
# print(number)
userNumber = None
count = 0
levels = {1: 10,
2: 5,
3: 3}
level = int(input("Выберите уровень сложности(1, 2 или 3) : "))
max_count = levels[level]
userCount = int(input('Введите количество игроков: '))
users = []
for i in range(userCount):
userName = input(f'Введите Имя пользователя {i + 1}: ')
users.append(userName)
i += 1
print(users)
is_winner = False
winnerName = None
while not is_winner:
count += 1
if count > max_count:
print('Все пользователи проиграли!')
print(f'Правильный ответ {number}')
break
print(f'Попытка номер {count}')
for user in users:
print(f'Ход пользователя {user}')
userNumber = int(input('Введите число от 1 до 100: '))
if userNumber == number:
is_winner = True
winnerName = user
break
elif userNumber < number:
print('Вы ошиблишсь! Вы ввели число меньше загаданного')
else: # userNumber > number:
print('Ваше число больше загаданного')
else:
print(f'Победа игрока {winnerName}!')
|
3f33affe4552cc0e2aa22542e3eb4051fcca8eaf | beajmnz/IEDSbootcamp | /theory/06-Pandas/PD2.py | 2,155 | 3.59375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 16:56:09 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Write on your console:
url = 'https://raw.githubusercontent. justmarkham /DAT8/master/ chipotle.tsv
chipo = pd.read_csv url , sep = t')
For these data:
1. have a look to the first 10 entries. What are the data about?
2. How many observations do we have in the data?
3. What is the number of columns in the dataset? Print the name of all columns
4. How is the dataset indexed?
5. Which was the most ordered item in times?
6. How many items of this product were ordered?
7. What was the most ordered item in the choice_description column?
8. How much was the revenue for the period in the dataset?
9. How many items were ordered in total?
10. How many orders were made in the period?
11. What is the average amount per order? (not yet)
12. How many different items are sold?
"""
import pandas as pd
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv'
chipo = pd.read_csv(url , sep = '\t')
# 1. have a look to the first 10 entries. What are the data about?
chipo.head(10)
# 2. How many observations do we have in the data?
chipo.shape[0]
# 3. What is the number of columns in the dataset? Print the name of all columns
chipo.shape[1]
chipo.columns
# 4. How is the dataset indexed?
chipo.index
# 5. Which was the most ordered item in times?
chipo.item_name.value_counts().idxmax() # también vale .index[0]
# 6. How many items of this product were ordered?
chipo.item_name.value_counts()[0]
# 7. What was the most ordered item in the choice_description column?
chipo.choice_description.value_counts().idxmax()
# 8. How much was the revenue for the period in the dataset?
chipo.item_price.str.replace('$','').astype(float).sum()
chipo.item_price.apply(lambda x:float(x[1:])).sum()
# 9. How many items were ordered in total?
chipo.quantity.sum()
# 10. How many orders were made in the period?
chipo.drop_duplicates(subset=["order_id"]).shape[0]
# 11. What is the average amount per order? (not yet)
# 12. How many different items are sold?
chipo.drop_duplicates(subset="item_name").shape[0]
|
be8b2ea14326e64425af9ee13478ec8c97890804 | beajmnz/IEDSbootcamp | /pre-work/pre-work-python.py | 1,135 | 4.3125 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 17:39:23 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
#Complete the following exercises using Spyder or Google Collab (your choice):
#1. Print your name
print('Bea Jimenez')
#2. Print your name, your nationality and your job in 3 different lines with one single
#print command
print('Bea Jimenez\nSpanish\nCurrently unemployed, but I\'m a COO wannabe :)')
#3. Create an integer variable taking the value 4
intFour = 4
#4. Create other integer variable taking the value 1
intOne = 1
#5. Transform both variables into boolean variables. What happens?
intFour = bool(intFour)
intOne = bool(intOne)
# -> both variables are transformed into booleans and get True value
#6. Transform this variable "23" into numerical variable.
str23 = '23'
int23 = int(str23)
#7. Ask the user their age in the format 1st Jan, 2019 (check the command input for
#this). Using this info, show on the screen their year of birth
birthdate = input(prompt='Please state your birthdate in the format 1st Jan, 2019')
print('From what you just told me, you were born in the year '+birthdate[-4:])
|
a992508b6236cb8c683ff8813c2a6655401040de | beajmnz/IEDSbootcamp | /theory/02a-Data Types and Variables/DTV1.py | 296 | 3.890625 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 15:59:40 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Programming challenge DTV.1
"""
number1 = int(input("please write one number: "))
number2 = int(input("please write another number: "))
print("\nthe sum is",number1+number2)
|
a77aed14d5edc7d79f698bb2968cd92524dbd8a1 | beajmnz/IEDSbootcamp | /theory/06-Pandas/PD3.py | 2,372 | 3.640625 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 15:26:05 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
With the chipo data:
1. How many items are more expensive than 10$?
2. What is the price of each item when only 1 item is bought?
3. Sort by the name of the item
4. What was the quantity of the most expensive item ordered?
5. How many times were a Veggie Salad Bowl ordered?
6. How many times people ordered more than one Canned Soda?
7. How many units where sold by item_name?
"""
import pandas as pd
url = "https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv"
chipo = pd.read_csv(url, sep="\t")
# 1. How many items are more expensive than 10$?
chipo["item_price_num"] = chipo.item_price.apply(lambda x: float(x[1:]))
chipo.loc[chipo.item_price_num > 10, :].shape[0]
# 2. What is the price of each item when only 1 item is bought?
chipo.loc[chipo.quantity == 1, :].loc[
:, ["item_name", "item_price_num"]
].drop_duplicates(subset="item_name", keep="first")
# extra
chipo.loc[chipo.quantity == 1, :].loc[
:, ["item_name", "item_price_num"]
].drop_duplicates(subset="item_name", keep="first").sort_values(
by="item_price_num", ascending=0
)
# 3. Sort by the name of the item
chipo.loc[chipo.quantity == 1, :].loc[
:, ["item_name", "item_price_num"]
].drop_duplicates(subset="item_name", keep="first").sort_values(
by="item_name", ascending=1
)
# 4. What was the quantity of the most expensive item ordered?
chipo.loc[
chipo.item_name
== chipo.loc[chipo.quantity == 1, :]
.loc[:, ["item_name", "item_price_num"]]
.drop_duplicates(subset="item_name", keep="first")
.sort_values(by="item_price_num", ascending=0)
.item_name[0],
:,
].quantity.max()
# 5. How many times were a Veggie Salad Bowl ordered?
chipo.loc[chipo.item_name == "Veggie Salad Bowl", :].shape[0]
# 6. How many times people ordered more than one Canned Soda?
chipo.loc[((chipo.item_name == "Canned Soda") & (chipo.quantity > 1)), :].shape[0]
# 7. How many units where sold by item_name?
chipo.loc[:, ["item_name", "quantity"]].groupby(by="item_name", as_index=False).sum()
# 8. Top 3 more profitable item names (greater added price)
chipo.loc[:, ["item_name", "item_price_num"]].groupby(
by="item_name", as_index=False
).sum().sort_values(by="item_price_num", ascending=False).head(3)
|
28e93fcc30fca3c0adec041efd4fbeb6a467724e | beajmnz/IEDSbootcamp | /theory/03-Data Structures/DS6.py | 452 | 4.34375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 5 18:24:27 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Write a Python program to count the elements in a list until an element
is a tuple.
Input: [10,20,30,(10,20),40]
Output: 3
"""
Input = [10,20,30,(10,20),40]
counter = 0
for i in Input:
if type(i) != tuple:
counter+=1
else:
break
print("There were",counter,"elements before the first tuple")
|
e29dcf2e71f5f207a18e22067c0b26b530399225 | beajmnz/IEDSbootcamp | /theory/02b-Flow Control Elements/FLOW3.py | 468 | 4.125 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 5 13:03:37 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Write a Python program that asks for a name to the user. If that name is your
name, give congratulations. If not, let him know that is not your name
Mark: be careful because the given text can have uppercase or lowercase
letters
"""
name = input('Guess my name').strip().lower()
if name == 'bea':
print('congrats!')
else:
print('too bad') |
50882249dd72e984296a90ec327947e2536a9034 | beajmnz/IEDSbootcamp | /theory/06-Pandas/PD1.py | 1,243 | 3.75 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 17:13:26 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
For Boston data:
1. show the names of the variables and a brief summary of them
2. extract the first 10 rows
3. extract the rows 4 th and 5 th with the last 4 variables
4. extract the rows with AGE bigger than 95. How many rows are they?
5. extract the rows 2 and 3 for the variables DIS, RAD and TAX
6. erase the columns B and LSTAT
7. replace the maximum value on DIS by 1
"""
import pandas as pd
from sklearn.datasets import load_boston
dataset = load_boston()
df = pd.DataFrame(dataset.data, columns = dataset.feature_names)
# 1. show the names of the variables and a brief summary of them
df.describe()
# 2. extract the first 10 rows
df.head(10)
# 3. extract the rows 4 th and 5 th with the last 4 variables
df.iloc[4:6,:].iloc[:,-4:]
# 4. extract the rows with AGE bigger than 95. How many rows are they?
df.loc[df.AGE>95,:]
df.loc[df.AGE>95,:].shape[0]
# 5. extract the rows 2 and 3 for the variables DIS, RAD and TAX
df.iloc[2:4,:].loc[:,["DIS","RAD","TAX"]]
# 6. erase the columns B and LSTAT
df.drop(columns=["B","LSTAT"])
# 7. replace the maximum value on DIS by 1
df.iloc[df.DIS.idxmax(),:].DIS = 1
|
5570ef99771116d22a8852b5f756f403891d668d | beajmnz/IEDSbootcamp | /theory/02a-Data Types and Variables/DTV7.py | 320 | 3.890625 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 17:24:17 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Write a Python program to reverse the following wrong text.
Example: "aserpme ed otutitsni". Expected result: "instituto de empresa"
"""
wrongText = "aserpme ed otutitsni"
rightText = wrongText[::-1] |
4d8087d998cdad9646eb40cf110388bd5aab0f48 | beajmnz/IEDSbootcamp | /theory/02a-Data Types and Variables/DTV8.py | 442 | 4.09375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 17:37:20 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Ask for a number and for a text. Write a program that prints the text the
number of times specified
"""
text = input("please write some text: ")
text = text + "\n" # we add a break line character
number = int(input("please input the number of times to write the text: "))
repeatedText = text*number
print(repeatedText) |
7b93ba6fe50685ece8dad9473027ba0d343856b2 | edutilos6666/CL_Uebung2 | /Uebung2/Aufgabe2.py | 1,136 | 4.03125 | 4 | # Aufgabe 2
###############################
# Entwickeln Sie ein Programm, welches vom Nutzer eingegebene Woerter
# alphabetisch sortiert ausgibt. Der Ntzer soll dazu bis zu 5 Woerter
# eingeben koennen.
# Hinweis: Da wir bisher noch keine Listen behandelt haben, speichern
# Sie die Woerter in verschiedenen Variablen.
str1 = None
str2 = None
str3 = None
str4 = None
str5 = None
str1 = input("Gib den ersten String ein: ")
str2 = input("Gib den zweiten String ein: ")
if str2 < str1:
str1 , str2 = str2 , str1
str3 = input("Gib den dritten String ein: ")
if str3 < str1:
str1 , str3 = str3 , str1
if str3 < str2:
str2, str3 = str3 , str2
str4 = input("Gib den vierten String ein: ")
if str4 < str1:
str1 , str4 = str4, str1
if str4 < str2:
str2 , str4 = str4, str2
if str4 < str3:
str3, str4 = str4, str3
str5 = input("Gib den fuenften String ein: ")
if str5 < str1:
str1, str5 = str5, str1
if str5 < str2:
str2, str5 = str5, str2
if str5 < str3:
str3, str5 = str5, str3
if str5 < str4:
str4, str5 = str5, str4
print("Sortierte Strings: ", str1, str2, str3, str4, str5, sep = " ") |
2198fde045a0f392956cb2b62ede50504c028ecd | edutilos6666/CL_Uebung2 | /Hausaufgabe4/Test.py | 1,557 | 3.75 | 4 | filename = "foo.txt"
with open(filename , "w") as f :
f.write("edu\n");
f.write("tilos\n");
f.write("pako\n");
with open(filename, "r") as f:
print("<<content of " + filename + ">>")
for line in f:
line = line.strip()
print(line)
with open(filename , "a") as f:
f.write("new_edu\n")
f.write("new_tilo\n")
with open(filename, "r") as f:
print("<<content>>")
lines = f.readlines()
for line in lines:
line = line.rstrip()
print(line)
with open(filename, "r") as f:
print("\n<<content>>")
content = f.read()
print(content)
filename = "person.txt"
class Person:
def __init__(self, name, age , wage):
self.name = name
self.age = age
self.wage = wage
def to_string(self):
msg , nl2 = "", "\n"
nl = ";"
msg = msg + "name = "+ self.name + nl + "age = " + str(self.age) + nl+ "wage = " + str(self.wage) + nl2
return msg
p1 = Person("foo", 10, 100.0)
p2 = Person("bar", 20 , 200.0)
print(p1.to_string())
print(p2.to_string())
import copy
with open(filename, "w") as f:
people = [copy.deepcopy(p1), copy.deepcopy(p2), Person("bim", 30 , 300.0) ]
for p in people:
f.write(p.to_string())
with open(filename, "r") as f:
print("<<content of " + filename + ">>")
for line in f:
line = line.strip()
props = line.split(";")
for prop in props:
splitted = prop.split(" = ")
k,v = splitted[0], splitted[1]
print(k , "=> ", v)
|
9df482d4d9b2ad4b4ae132086efbcabeed9ca5a0 | jkbockstael/adventofcode-2017 | /day06_part2.py | 532 | 3.625 | 4 | # Advent of Code 2017 - Day 6 - Memory Reallocation - Part 2
# http://adventofcode.com/2017/day/6
import re
from day06_part1 import reallocate, reallocate_until_cycle
def cycle_length(memory):
initial = memory[:]
steps = 0
while True:
memory = reallocate(memory[:])
steps = steps + 1
# this is guaranteed to happen
if memory == initial:
return steps
memory = [int(x) for x in re.split('\s+', input())]
_, memory = reallocate_until_cycle(memory)
print(cycle_length(memory))
|
93baa56efd9fc968519ec76d5d696d1669cb9848 | muyang-feng/homework | /zhangna/exercise_string_list.py | 1,477 | 3.75 | 4 | #1.创建一个函数,除去字符串前面和后面的空格
def blank():
strl = ' aa bb cc '
print(strl)
str2 = strl.replace(" ", "")
print(str2)
blank()
# 2.输入一个字符串,判断是否为回文
string = input('请输入一个字符串:')
str_len = len(string)
i = 0
while i <= str_len / 2:
if string[i] == string[str_len-i-1]:
count=1
i=i+1
else:
count=0
break
if count==1:
print('输入的字符是回文')
else:
print('输入的字符不是回文')
'''给出一个整型值,能够返回该值得英文,例如输入89,返回eighty-nine,限定值在0~100'''
single = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
double = ['ten', 'eleven', 'tweleve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seveteen', 'eighteen', 'nineteen']
tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
numstr = input('请输入一个数字,范围在0-100: ')
numlen = len(numstr)
num = int(numstr)
print(num)
if numlen == 1:
if int(numstr[0]) > 0:
print(single[num])
else:
print('zero')
elif numlen == 2:
if numstr[0] == '1':
print(double[num - 10])
else:
print(tens[int(numstr[0])] + '-' + single[int(numstr[1])])
elif numlen == 3:
print('one hundred')
'''给出两个可以识别格式的日期,比如MM/DD/YY 或者 DD/MM/YY 计算两个日期的相隔天数'''
|
f4d8bdaa7f10d34a1ee0d489757795c30c547243 | narenbac/Python_Exercises | /exercise3.py | 17,137 | 4.46875 | 4 | #Problems on strings:
#1. Write a Python program to calculate the length of a string.
'''
print('calculate the length of a string.')
s=input('Enter a string:')
print('length of given string is:',len(s))
'''
#2. Write a Python program to count the number of characters (character frequency) in a string.
# Sample String : 'google.com'
# Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}
'''
print('count the number of characters (character frequency) in a string')
s=input('Enter a string:')
d={}
for i in s:
dict={i:s.count(i)}
#print(dict)
d.update(dict)
print(d)
'''
#3. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string.
# If the string length is less than 2, return instead of the empty string.
# Sample String : ‘skillologies' Expected Result : 'skes'
# Sample String : 'mi' Expected Result : 'mimi'
# Sample String : ' m' Expected Result : Empty String
'''
print('to get a string made of the first 2 and the last 2 chars from a given a string')
s=input('Enter a string:')
if len(s)>=2:
print(s[0],s[1],s[-2],s[-1],sep='',end=' ')
else:print('Empty string')
'''
#4. Write a Python program to get a string from a given string where
# all occurrences of its first char have been changed to '$', except the first char itself.
# Sample String : 'restart' Expected Result : 'resta$t'
'''
s=input('Enter a string:')
t=s.replace(s[0],'$')
for i in range(len(t)):
if i==0:
print(s[0],end='')
else:
print(t[i],end='')
'''
#5. Write a Python program to get a single string from two given strings,
# separated by a space and swap the first two characters of each string.
# Sample String : 'abc', 'xyz' Expected Result : 'xyc abz'
'''
s=input('Enter a first string:')
t=input('Enter a second string:')
a=s.replace(s[0],t[0])
b=a.replace(a[1],t[1])
c=t.replace(t[0],s[0])
d=c.replace(c[1],s[1])
print(b+' '+d)
'''
'''
s=input('Enter a first string:')
t=input('Enter a second string:')
for i in range(len(s)):
if i>1:
p=(s[i])
for i in range(len(t)):
if i>1:
q=(t[i])
print(t[0],t[1],p,' ',s[0],s[1],q,sep='',end='')
'''
#6. Write a Python program to add 'ing' at the end of a given string (length should be at least 3).
# If the given string already ends with 'ing' then add 'ly' instead.
# If the string length of the given string is less than 3, leave it unchanged.
# Sample String : 'abc' Expected Result : 'abcing'
# Sample String : 'string' Expected Result : 'stringly'
'''
s=input('Enter a string:')
if len(s)>=3:
if s.endswith('ing'):
print(s.__add__('ly'))
else:
print(s.__add__('ing'))
else:
print(s)
'''
#7. Write a Python program to find the first appearance of the substring 'not' and 'poor'
# from a given string,
# if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'.
# Return the resulting string.
# Sample String : 'The lyrics is not that poor!' Expected Result : 'The lyrics is good!'
'''
s=input('Enter a string:')
a=int(s.find('not'))
print(a)
b=int(s.find('poor'))
print(b)
c=int(s.find('bad'))
print(c)
if (b>a) and a>0 and b>0:
t=s.replace(s[a:(b+4)],'good')
print(t)
if (c>a) and a>0 and c>0:
t=s.replace(s[a:(c+3)],'good')
print(t)
else: print(s)
'''
#8. Write a Python function that takes a list of words and returns the length of the longest one.
'''
def maxima():
s=(input('Enter words:'))
l=s.split()
list=[]
for i in l:
list.append(len(i))
m=max(list)
for i in l:
if len(i)==m:
print(i,':',m)
maxima()
'''
#9. Write a Python program to remove the nth index character from a nonempty string.
'''
print('remove the nth index character from a nonempty string')
s=input('Enter a string:')
n=int(input('Enter nth index:'))
t=s.replace(s[n],'')
print(t)
'''
#10. Write a Python program to change a given string to a new string
# where the first and last chars have been exchanged.
'''
s=input('Enter a string:')
for i in range(len(s)):
if i==0:
print(s[-1],end='')
elif i==(len(s)-1):
print(s[0],end='')
else:
print(s[i],end='')
'''
#11. Write a Python program to remove the characters which have odd index values of a given string.
'''
s=input('Enter a string:')
for i in range(len(s)):
if i%2:
pass
else:
print(s[i],end='')
'''
#12. Write a Python program to count the occurrences of each word in a given sentence.
'''
s=input('Enter a string:')
t=s.split()
d=set(t)
l=list(d)
for i in range(len(l)):
c=t.count(l[i])
print(l[i],':',c)
'''
#13. Write a Python script that takes input from the user and displays that input back in upper and lower cases.
'''
s=input('Enter a string:')
u=s.upper()
l=s.lower()
print('Display in upper case',u)
print('Display in lower case',l)
'''
#14. Write a Python program that accepts a comma separated sequence of words as input and
# prints the unique words in sorted form (alphanumerically).
# Sample Words : red, white, black, red, green, black
# Expected Result : black, green, red, white.
'''
s=input('Enter a string:')
p=s.split(sep=',')
q=set(p)
t=list(q)
t.sort()
for i in range(len(t)):
print(t[i],end='')
if i==(len(t)-1):
print('.')
else: print(',',end='')
'''
#15. Write a Python function to create the HTML string with tags around the word(s).
# Sample function and result :
# add_tags('i', 'Python') -> '<i>Python</i>'
# add_tags('b', 'Python Tutorial') -> '<b>Python Tutorial </b>'
'''
def add_tags(a,b):
print("'<",a,">",b,"</",a,">'",sep='')
s=input('Enter a string:')
t=input('Enter second string:')
add_tags(s,t)
'''
#16. Write a Python function to insert a string in the middle of a string.
# Sample function and result :
# insert_sting_middle('[[]]', 'Python') -> [[Python]]
# insert_sting_middle('<<>>', 'Python') -> <<Python>>
# insert_sting_middle('{{}}', 'PHP') -> {{PHP}}
'''
def insert_string_middle(a,b):
for i in range(0,len(a)):
if i==(len(a)/2):
print(b,end='')
print(a[i],end='')
s=input('Enter a string')
t=input('Enter second string')
insert_string_middle(s,t)
'''
#17. Write a Python function to get a string made of 4 copies of the last two characters
# of a specified string (length must be at least 2).
# Sample function and result :
# insert_end('Python') -> onononon
# insert_end('Exercises') -> eseseses
'''
def insert_end(s):
if len(s)<2:
print(s)
else:
t=s[len(s)-2:len(s)]
print(t*4)
s=input('Enter a string:')
insert_end(s)
'''
#18. Write a Python function to get a string made of its first three characters of a specified string.
# If the length of the string is less than 3 then return the original string.
# Sample function and result :
# first_three('ipy') -> ipy
# first_three('python') -> pyt
'''
def first_three(s):
if len(s)>=3:
print(s[0:3])
else:
print(s)
s=input('Enter a string:')
first_three(s)
'''
#19. Write a Python program to get the last part of a string before a specified character.
# https://www.w3resource.com/python-exercises
# https://www.w3resource.com/python
'''
s=input('Enter a string:')
t=s[::-1]
l=''
for i in t:
if i.isalnum():
l+=i
else: break
print(l[::-1])
'''
#20. Write a Python function to reverses a string if it's length is a multiple of 4.
'''
def reverse_string_mul4(s):
if (len(s)%4):
print(s)
else:
print(s[::-1])
s=input('Enter a string:')
reverse_string_mul4(s)
'''
#21. Write a Python function to convert a given string to all uppercase
# if it contains at least 2 uppercase characters in the first 4 characters.
'''
def all_upper_if2_in_first4(s):
count=0
for i in range(4):
if s[i].isupper():
count+=1
if count>=2:
print(s.upper())
else:
print(s)
s=input('Enter a string:')
all_upper_if2_in_first4(s)
'''
#22.Write a Python program to sort a string lexicographically.
'''
s=input('Enter a string:')
l=[]
[l.append(i) for i in s]
l.sort()
t=''
for i in l:
t+=i
print(t)
'''
#23.Write a Python program to remove a newline in Python.
'''
s='ak\njd\nnrn\nsk\n'
print(s)
t=s.replace('\n','')
print(t)
'''
#24. Write a Python program to check whether a string starts with specified characters.
'''
s=input('Enter a string:')
n=input('specified character')
t=s.find(n)
if t==0:
print('the string starts with the character')
else:
print('the string does not start with the character')
'''
'''
s=input('Enter a string:')
#if 'a'<=s[0]<='z' or 'A'<=s[0]<='Z' or '0'<=s[0]<='9' or s[0]==' ':
if s[0].isalnum() or s[0].isspace():
print('the string does not start with specified character')
else:
print('the string starts with the character', s[0])
'''
#25. Write a Python program to create a Caesar encryption.
'''
s=input('Enter a string:')
for i in s:
o=ord(i)
print(chr(o+3),end='')
'''
#26. Write a Python program to display formatted text (width=50) as output.
'''
s='Python is a widely used high-level, general-purpose, interpreted,dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.'
t=len(s)
i=0
while t>0:
print(s[i:i+50],end='')
print()
i+=50
t-=50
'''
'''
s='Python is a widely used high-level, general-purpose, interpreted,dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.'
import textwrap
t=textwrap.fill(s,width=50)
print(t)
'''
#27. Write a Python program to remove existing indentation from all of the lines in a given text.
'''
s=" Python is a widely used high-level, general \n purpose, interpreted,dynamic programming language. \n Its design philosophy emphasizes code readability,\n and its syntax allows programmers to express \n concepts in fewer lines of code than possible in \n languages such as C++ or Java."
import textwrap
t=textwrap.dedent(s)
print(t)
'''
'''
s=" Python is a widely used high-level, general \n purpose, interpreted,dynamic programming language. \n Its design philosophy emphasizes code readability,\n and its syntax allows programmers to express \n concepts in fewer lines of code than possible in \n languages such as C++ or Java."
t=s.split('\n')
for i in t:
j=i.lstrip()
print(j)
'''
#28. Write a Python program to add a prefix text to all of the lines in a string.
'''
s="Python is a widely used high-level, general \npurpose, interpreted,dynamic programming language. \nIts design philosophy emphasizes code readability,\nand its syntax allows programmers to express \nconcepts in fewer lines of code than possible in \nlanguages such as C++ or Java."
t=s.split('\n')
for i in t:
print('"This is prefix"',i)
'''
'''
import textwrap
s="Python is a widely used high-level, general \npurpose, interpreted,dynamic programming language. \nIts design philosophy emphasizes code readability,\nand its syntax allows programmers to express \nconcepts in fewer lines of code than possible in \nlanguages such as C++ or Java."
t=textwrap.indent(s,'"This is prefix"')
print(t)
'''
#29. Write a Python program to set the indentation of the first line.
'''
s="Python is a widely used high-level, general \npurpose, interpreted,dynamic programming language. \nIts design philosophy emphasizes code readability,\nand its syntax allows programmers to express \nconcepts in fewer lines of code than possible in \nlanguages such as C++ or Java."
print(' '+s)
'''
'''
s="Python is a widely used high-level, general \npurpose, interpreted,dynamic programming language. \nIts design philosophy emphasizes code readability,\nand its syntax allows programmers to express \nconcepts in fewer lines of code than possible in \nlanguages such as C++ or Java."
t=s.splitlines(False)
t[0]=' '+t[0]
for i in t:
print(i)
'''
#30. Write a Python program to print the following floating numbers upto 2 decimal places.
'''
s=float(input('Enter float number:'))
print("Formatted Number: ",s.__round__(2))
print("Formatted Number: ",round(s,2))
print("Formatted Number: %.2f"%s)
print("Formatted Number: {:.2f}".format(s))
'''
#31. Write a Python program to print the following floating numbers upto 2 decimal places with a sign.
'''
s=float(input('Enter float number:'))
print("Formatted Number: ",+s.__round__(2))
print("Formatted Number: ",+round(s,2))
print("Formatted Number: %+.2f"%s)
print("Formatted Number: {:+.2f}".format(s))
'''
#32. Write a Python program to print the following floating numbers with no decimal places.
'''
s=float(input('Enter float number:'))
print("Formatted Number: ",s.__round__())
print("Formatted Number: ",round(s))
print("Formatted Number: %.0f"%s)
print("Formatted Number: {:.0f}".format(s))
'''
#33. Write a Python program to print the following integers with zeros on the left of specified width.
'''
s=input('Enter a integer:')
u=s.zfill(5)
print(u)
'''
'''
t=int(input('Enter a integer:'))
print('{:0>5d}'.format(t))
'''
#34. Write a Python program to print the following integers with '*' on the right of specified width.
'''
t=int(input('Enter a integer:'))
print('{:*<5d}'.format(t))
'''
#35. Write a Python program to display a number with a comma separator.
'''
n=int(input('Enter a number:'))
print('{:,}'.format(n))
'''
#36. Write a Python program to format a number with a percentage.
'''
f=float(input('Enter a number:'))
print('{:.2%}'.format(f))
'''
#37. Write a Python program to display a number in left, right and center aligned of width 10.
'''
x = int(input('Enter a number:'))
print("Left aligned (width 10) :"+"{:< 10d}".format(x));
print("Right aligned (width 10) :"+"{:10d}".format(x));
print("Center aligned (width 10) :"+"{:^10d}".format(x));
'''
#38. Write a Python program to count occurrences of a substring in a string.
'''
os=input("Enter original string:")
ss=input("Enter substring:")
print(os.count(ss))
'''
#39. Write a Python program to reverse a string.
'''
s=input('Enter a string:')
print(s[::-1])
'''
#40. Write a Python program to reverse words in a string.
'''
s=input('Enter a string:')
l=s.split()
t=' '.join(reversed(l))
print(t)
'''
#41. Write a Python program to strip a set of characters from a string.
'''
s=input('Enter string:')
char=input('Enter a set of characters:')
for i in s:
if i not in char:
print(i,end='')
'''
#42. Write a python program to count repeated characters in a string.
# Sample string: 'thequickbrownfoxjumpsoverthelazydog'
# Expected output : o 4 e 3 u 2 h 2 r 2 t 2
'''
s=input('Enter a string:')
set=set(s)
#{print(j, s.count(j)) for j in set if s.count(j)>1}
for j in set:
if s.count(j)>1:
print(j, s.count(j))
'''
'''
s=input('Enter a string:')
from collections import Counter
c=Counter(s)
{print(k,v) for k,v in c.items() if v>1}
'''
#43. Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder.
# Sample output: The area of the rectangle is 1256.66cm2
# The volume of the cylinder is 1254.725cm3
'''
area = 1256.66
volume = 1254.725
q=input('What you want to be printed?:')
if q=='area':
print("The area of the rectangle is {}cm\u00b2".format(area))
elif q=='volume':
print("The volume of the cylinder is {} cm\u00b3".format(volume))
else:
print('Kindly give an input "area" or "volume"')
'''
#44. Write a Python program to print the index of the character in a string.
# Sample string: w3resource
# Expected output:
# Current character w position at 0
# Current character 3 position at 1
# Current character r position at 2
# - - - - - - - - - - - - - - - - - - - - - - - -
# Current character c position at 8
# Current character e position at 9
'''
s=input('Enter a string:')
for i in range(len(s)):
print('Current character',s[i],'position at',i)
'''
#45. Write a Python program to check if a string contains all letters of the alphabet.
#The quick brown fox jumps over the lazy dog
'''
import string
s=set(input('Enter a string:'))
l=set(string.ascii_lowercase)
print(s>=l)
'''
#46. Write a Python program to convert a string in a list.
'''
s=input('Enter a string:')
l=[]
[l.append(i) for i in s]
print(l)
'''
#47. Write a Python program to lowercase first n characters in a string.
'''
s=input('Enter a string:')
n=int(input('Enter number of characters:'))
print(s[:n].lower()+s[n:])
'''
#48. Write a Python program to swap comma and dot in a string.
# Sample string: "32.054,23" Expected Output: "32,054.23"
'''
s=input('Enter a string:')
t=s.translate(s.maketrans(',.','.,'))
print(t)
'''
#49. WrIte a Python program to count and display the vowels of a given text.
'''
s=input('Enter a string:')
v='aeiouAEIOU'
print([i for i in s if i in v])
print(len([i for i in s if i in v]))
'''
#50. Write a Python program to split a string on the last occurrence of the delimiter.
'''
s=input('Enter a string:')
t=s.rsplit(',',1)
print(t)
'''
|
37b2d8a716c5e5a130cf1761e92a65ea3a517ab7 | JovieMs/dp | /behavioral/strategy.py | 1,003 | 4.28125 | 4 | #!/usr/bin/env python
# http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern
# -written-in-python-the-sample-in-wikipedia
"""
In most of other languages Strategy pattern is implemented via creating some
base strategy interface/abstract class and subclassing it with a number of
concrete strategies (as we can see at
http://en.wikipedia.org/wiki/Strategy_pattern), however Python supports
higher-order functions and allows us to have only one class and inject
functions into it's instances, as shown in this example.
"""
import types
class SortedList:
def set_strategy(self, func=None):
if func is not None:
self.sort = types.MethodType(func, self)
def sort(self):
print(self.name)
def bubble_sort(self):
print('bubble sorting')
def merge_sort(self):
print('merge sorting')
if __name__ == '__main__':
strat = SortedList()
strat.set_strategy(bubble_sort)
strat.sort()
strat.set_strategy(merge_sort)
strat.sort() |
6fecada7427819fa3f4cb90ad70fc02d4d8405d0 | pedroogarcez/pip | /src/ultralytics/utils/general.py | 1,081 | 3.828125 | 4 | # General utils
def colorstr(*input):
# Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
*args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
colors = {'black': '\033[30m', # basic colors
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'magenta': '\033[35m',
'cyan': '\033[36m',
'white': '\033[37m',
'bright_black': '\033[90m', # bright colors
'bright_red': '\033[91m',
'bright_green': '\033[92m',
'bright_yellow': '\033[93m',
'bright_blue': '\033[94m',
'bright_magenta': '\033[95m',
'bright_cyan': '\033[96m',
'bright_white': '\033[97m',
'end': '\033[0m', # misc
'bold': '\033[1m',
'underline': '\033[4m'}
return ''.join(colors[x] for x in args) + f'{string}' + colors['end'] |
f7ec32f5eca38094be3343b2e4d54fac7e2c5839 | devBubo/helpfulfunctions | /helpfulfunctions.py | 2,190 | 3.828125 | 4 | from random import *
from math import *
#complex unit sqrt(-1)
i = 1j
j = 1j
#average of the list
def avg(list):
sum_list = 0
n = 0
for i in list:
sum_list+=i
n+=1
return sum_list / n
#round number to closest integer
def round(num):
if float(num)-int(float(num))<0.5 :
return int(float(num))
if float(num)-int(float(num))>=0.5:
return int(float(num))+1
#encryptes message
def encryption(key):
alphabet='qrupwtiey-oax2fb3jml1szdc 5gvhnk;#6^07(!$&)@%8*,.9-4?:_"/`-+'
string=input('Enter string: ')
len_string=len(string)
key=int(key)
repeated=0
for char in string:
spot=alphabet.find(char)
lenght=len(alphabet)
new=(spot+len_string*key+int(pow(key,key)))%lenght
if repeated<len(string)-1:
print(new,end=',')
repeated+=1
else:
print(new)
#decryptes message
def decryption(list):
alphabet = 'qrupwtiey-oax2fb3jml1szdc 5gvhnk;#6^07(!$&)@%8*,.9-4?:_"/`-+'
key=int(input('Enter key: '))
decrypt_list=[]
#appends what will happen to symbol after encryption
for i in range(int(len(alphabet))):
decrypt_list.append((i+len(list)*key+pow(key,key))%len(alphabet))
#compares indexes of both and checks the other list what's on that index
for i in list:
index_list=decrypt_list.index(i)
print(alphabet[index_list],end='')
#quadratic_equation using quadratic formula
def quadratic_equation(a,b,c):
x1=(-b+pow(pow(b,2)-4*a*c,0.5))/2*a
x2=(-b-pow(pow(b,2)-4*a*c,0.5))/2*a
print('First solution is',x1)
print('Second solution is',x2)
#factorial
def factorial(n):
x=1
for i in range(1,n+1):
x*=i
print(x)
#throws a dice
def dice():
i=randint(1,6)
print(i)
#fibonacci sequence
def fibonacci(number):
a=0
b=1
c=0
for i in range(number-1):
c=b
b+=a
a=c
return a
#def cos in complex numbers
def cosequals(number):
b=number*-2
x1 = (-b + pow(pow(b, 2) - 4 * 1 * 1, 0.5)) / 2
x2 = (-b - pow(pow(b, 2) - 4 * 1 * 1, 0.5)) / 2
print(log(x1)/j,'+ 2πn, n ∈ ℤ')
print(log(x2)/j,'+ 2πn, n ∈ ℤ')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.