blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
11c4d5323069e9508fda5693123e227fe17e78d0 | sahasatvik/assignments | /CS2201/problemset01/problem03.py | 695 | 4.5625 | 5 | #!/usr/bin/env python3
"""
Consider three strings str1 = ‘123’, str2 = ‘234’ and str3 = ‘456’ and print
the sum, product and average of the numbers in the strings.
"""
str1 = "123"
str2 = "234"
str3 = "456"
def sum_digits(s):
total = 0
for digit in s:
total += int(digit)
return total
def prod_digits(s):
product = 1
for digit in s:
product *= int(digit)
return product
def mean_digits(s):
return sum_digits(s) / len(s)
for s in [str1, str2, str3]:
print(f"Sum of digits in {s} is {sum_digits(s)}")
print(f"Product of digits in {s} is {prod_digits(s)}")
print(f"Average of digits in {s} is {mean_digits(s)}")
print()
|
77a391438b547b91ed225b0c7639189166f89713 | chavhanpunamchand/PythonPractice | /Number_Series/Notes_practice/Star_Pattern2.py | 231 | 4.125 | 4 | n=int(input("Enter the number of row:"))
for i in range (1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()
for a in range(1,n+1):
for b in range(1,n+1-a):
print("*",end=" ")
print()
|
4d10f15cd43125bd7b93ad519f6a89655fc2d177 | amaeva911/learn_python_14 | /week 2/web/weather.py | 1,334 | 3.515625 | 4 | import requests
def weather_by_city(city_name):
weather_url = 'http://api.worldweatheronline.com/premium/v1/weather.ashx'
params = {
"key": "c319fbdb846845a58c8134926192809",
"q": city_name,
"format": "json",
"num_of_days": "1",
"lang": "ru"
}
try:
result = requests.get(weather_url, params = params) # возвращает строку, которую необходимо преобразовать
result.raise_for_status() # магия с обработкой ответных кодов от сервера
weather = result.json() # получение "питоновского словаря"
if 'data' in weather:
if 'current_condition' in weather['data']:
try:
return weather['data']['current_condition'][0] # получение части json
except(IndexError,TypeError):
return False
except(requests.RequestException,ValueError):
print('Сетевая ошибка')
return False
return False
if __name__ == "__main__":
print(weather_by_city("Moscow, Russia")) # не получилось запустить из-за ConnectionError и TimeoutError :( пробовала и свой ключ и ключ Михаила из видео...
|
4f894f14232c1f4c87e772b7a8dc6e9ac11be3c1 | Crown0815/ESB-simulations | /polygon.py | 216 | 3.71875 | 4 | from math import *
small_radius = 1.3
side_length = 2 * small_radius
number_of_sides = 4
radius = side_length / (2*(sin(pi / number_of_sides)))
print(radius+small_radius)
print((radius+small_radius)/small_radius)
|
7f1e1c5a3f0a2e2614b33284fd6dde14fc83294e | cedie1/Python_guanabara_100-exerc-cios- | /ex4.py | 416 | 4.03125 | 4 | #dissecando variavel
#Resolução:
n1 = (input("Digite algo: "))
print("O tipo primitivo desse valor é",type(n1))
print("Só tem espaços ? ", n1.isspace())
print("É um número ? ", n1.isnumeric())
print("É alfabetico ? ", n1.isalpha())
print("É alfanúmerico", n1.isalnum())
print("Só tem maiúsculas ?",n1.isupper())
print("Só tem minúsculas ? ", n1.islower())
print("Está capitalizada? ", n1.istitle())
|
d43c28b0f84d8e5843f1ec639d4f091c126f5468 | raffyenriquez/CodingPractice | /codefights/Arcade/Intro/adjacentElementsProduct.py | 192 | 3.640625 | 4 | def adjacentElementsProduct(inputArray):
"""returns the product of the pair of adjacent elements with the largest product"""
return max(x*y for x,y in zip(inputArray, inputArray[1:]))
|
0dd20076a088a1758102133f0233661d2ce4afe0 | wwlorey/stylesheet-stealer | /parser.py | 4,847 | 3.609375 | 4 | import sys
import os.path
# Returns an empty string if char is a space, returns space (' ') otherwise
def insertSpaceCheck(char):
if char is ' ':
return ''
else:
return ' '
# Read command line arguments
if len(sys.argv) == 3: # All expected arguments are present
fileInName = sys.argv[1]
fileOutName = sys.argv[2]
elif len(sys.argv) == 2: # No output file was given
fileInName = sys.argv[1]
# Defult to a standard output file
fileOutName = 'formatted.css'
else: # Neither input or output file was given, or something else weird happened
# Default to standard input/output files
fileInName = 'unformatted.css'
fileOutName = 'formatted.css'
# Open the input & output files
# Check to make sure the input file exists
if(os.path.isfile(fileInName)):
fileIn = open(fileInName, 'r')
else:
print("\nPlease see the readme for instructions on command line arguments.\n")
# End the program
sys.exit()
fileOut = open(fileOutName, 'w')
# Remove all newlines & tabs from the input string
cssText = fileIn.read().replace('\n', '').replace('\t', '')
# Stack (really a list being used as a stack) that keeps track of what curly
# braces have been encountered
braceStack = []
# Stack for parentheses
parenthStack = []
# Bool used in keeping track of whether an '@' has been seen in the current context
seenAtSymbol = False
# Bool used in formatting curly braces in media queries. It specifies when a closing
# curly brace needs tab(s) before it
insertTabBeforeBrace = False
# Iterate through the input file string and output formatted CSS to the output file
textLength = len(cssText)
for i in range(0, textLength):
# Get the prev char, current char, and next char in the input file string
char = cssText[i]
if i + 1 >= textLength:
nextInputChar = None
else:
nextInputChar = cssText[i + 1]
if i - 1 < 0:
prevInputChar = None
else:
prevInputChar = cssText[i - 1]
nextOutputChar = ''
prevOutputChar = ''
# Process characters
# @ symbol
if char == '@':
seenAtSymbol = True
# Commas
elif char == ',':
nextOutputChar = insertSpaceCheck(nextInputChar)
# Colons
elif char == ':':
# This block checks to see if the current char is within parenthesis OR
# curly braces as well as in a media query (including some stipulations)
# before inserting a space after the colon
if len(parenthStack) > 0 or len(braceStack) > 0:
if not seenAtSymbol: # Not currently in a media query
nextOutputChar = insertSpaceCheck(nextInputChar)
else: # Currently in the media query
if len(braceStack) % 2 == 0: # The char is within attr. assignment in the media query
nextOutputChar = insertSpaceCheck(nextInputChar)
# Opening parentheses
elif char == '(':
parenthStack.append(char)
# Opening curly brackets
elif char == '{':
braceStack.append(char)
# Check to see if the next line needs to be indented twice (it is in a media query
# in the attribute assignment section)
if seenAtSymbol and (len(braceStack) % 2 == 0):
nextOutputChar = '\n\t\t'
else:
nextOutputChar = '\n\t'
prevOutputChar = insertSpaceCheck(prevInputChar)
# Semicolons
elif char == ';':
if nextInputChar != '}':
if seenAtSymbol:
nextOutputChar = '\n\t\t'
else:
nextOutputChar = '\n\t'
else:
# Tab the next ending brace if it's in a media query
if seenAtSymbol:
insertTabBeforeBrace = True
# Closing parentheses
elif char == ')':
parenthStack.pop() # Remove the last parenthesis
# Closing curly brackets
elif char == '}':
braceStack.pop() # Remove the last brace in the stack
if insertTabBeforeBrace:
prevOutputChar = '\n\t'
insertTabBeforeBrace = False
if not (nextInputChar == '}'):
nextOutputChar = '\n\n\t'
else:
if nextInputChar == '}':
prevOutputChar = '\n'
else:
prevOutputChar = '\n'
nextOutputChar = '\n\n'
if len(braceStack) == 0 and seenAtSymbol:
# Clear the '@' flag
seenAtSymbol = False
# Endings of selector fields in media queries
elif nextInputChar == '}' and seenAtSymbol and not (len(braceStack) == 1):
insertTabBeforeBrace = True
# Write the current character(s) to the output file
fileOut.write("%s%s%s" % (prevOutputChar, char, nextOutputChar))
fileIn.close()
fileOut.close()
# The program is finished
print("\nDone!\n")
|
32f79970476e37641d3af22bc777c6da46338941 | bud-welsh/FourHourPython | /stringPractice.py | 777 | 4 | 4 | print("Good Times") # A regular string
print("A\nnew\nline") # A new line
print("\"Escaping quotes\"")
phrase = "This string comes from the variable \"phrase\"."
print(phrase)
print(phrase + "\nThis string comes from concatenation.")
print(phrase.lower()) # Make phrase all lower case letters
print(phrase.upper()) # Make phrase all upper case letters
print(len(phrase)) # checking the length of the phrase
print(phrase[0]) # printing the first letter of the phrase
print(phrase[3]) # printing the fourth letter of the phrase
print(phrase.index("m")) # find the index of the letter m in the phrase
print(phrase.index("the")) # find the starting index of the word the in the phrase
print(phrase.replace("comes", "is")) # replace one part of the string with a new string
|
cedf9ef191f6c9315bbdde0700321bdddad929a5 | henryscala/leetcode | /py/p25_reverse_k_group.py | 2,380 | 3.765625 | 4 | # problem 25 of leetcode
# Reverse Nodes in k-Group
# Given this linked list: 1->2->3->4->5
# For k = 2, you should return: 2->1->4->3->5
# For k = 3, you should return: 3->2->1->4->5
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
length = self.node_list_len(head)
if length < k:
return head
node = head
newHead = None
newTail = None
while k <= length:
nodeGroupHead = None
nodeGroupTail = None
for i in range(k):
nodeNext = node.next
node.next = nodeGroupHead
nodeGroupHead = node
if nodeGroupTail == None:
nodeGroupTail = node
node = nodeNext
length -= k
if newHead == None:
newHead = nodeGroupHead
if newTail == None:
newTail = nodeGroupTail
else:
newTail.next = nodeGroupHead
newTail = nodeGroupTail
if newTail:
newTail.next = node
return newHead
def node_list_len(self,head):
length = 0
while head != None:
length += 1
head = head.next
return length
def array_to_node_list(self,arr):
arr.reverse()
head=None
for v in arr:
node=ListNode(v)
node.next = head
head = node
return head
def node_list_to_array(self,head):
res = []
while head != None:
res.append(head.val)
head = head.next
return res
solution = Solution()
print("test 1")
head = solution.array_to_node_list([1,2,3,4,5])
print(solution.node_list_to_array(head))
head = solution.reverseKGroup(head, 2)
print(solution.node_list_to_array(head))
print( "test 2" )
head = solution.array_to_node_list([1,2,3,4,5])
print(solution.node_list_to_array(head))
head = solution.reverseKGroup(head, 3)
print(solution.node_list_to_array(head))
|
eba92b0ed7d5e31c1e5c1c095c7634d575381061 | codershona/python-Programming-Language-Learning | /Python Operator/operator.py | 1,126 | 4.59375 | 5 | # Python Operators
# Operators are used to perform operations on variables and values.
# Python divides the operators in the following groups:
# Arithmetic operators
# Assignment operators
# Comparison operators
# Logical operators
# Identity operators
# Membership operators
# Bitwise operators
# Python Arithmetic Operators
# Arithmetic operators are used with numeric values to perform common mathematical operations:
# Operator |Name |Example
# + |Addition |x + y
# - |Subtraction |x - y
# * |Multiplication |x * y
# / |Division |x / y
# % |Modulus |x % y
# ** |Exponentiation |x ** y
// |Floor division |x // y
# Addition :
x = 5
y = 3
print(x + y)
# Subtraction :
x = 5
y = 3
print(x - y)
# Multiplication:
x = 5
y = 3
print(x * y)
# Division :
x = 12
y = 3
print(x / y)
# Modulus :
x = 5
y = 2
print(x % y)
# Exponentiation :
x = 2
y = 5
print(x ** y) #same as 2*2*2*2*2
# Floor division :
x = 15
y = 2
print(x // y)
#the floor division // rounds the result down to the nearest whole number
|
502260d0f40b827aaf48ede5a205d81c8d9a8910 | palanuj402/Py_lab | /File/q16.py | 322 | 4.625 | 5 | #Write a python program to check whether the string is Palindrome or not.
def check(s):
if s==s[::-1]:
return True
else:
return False
s=input("Enter a string to check pallindrome: ")
c=check(s)
if c is True:
print(s,"is Pallindrome")
else:
print(s,"is NOT a Pallindrome") |
8b37718000fa70a91814884105e24eb9e72f69a8 | caowens/Blackjack | /blackjack_final.py | 1,214 | 4 | 4 | # DO NOT REMOVE
from deck import print_card, draw_card, print_header, draw_starting_hand, print_end_turn_status, print_end_game_status
# User turn
# draw a starting hand for the user and store it into a variable
user_hand = draw_starting_hand("YOUR")
# allow the user to see hand value and decide to hit or stand
response = input('You have ' + str(user_hand) + '. Hit (y/n)? ')
# if the user's hand is less than 21, then they can keep deciding to hit
while user_hand < 21 and response == 'y':
user_hand = user_hand + draw_card()
if user_hand < 21:
response = input('You have ' + str(user_hand) + '. Hit (y/n)? ')
# output the user's final hand and if black jack, bust or neither
print_end_turn_status(user_hand)
# Dealer turn
# draw a starting hand for the dealer and store it into a variable
dealer_hand = draw_starting_hand("DEALER")
# per dealer rules, as long as the dealer hand is 17 or less, they keep drawing cards
while dealer_hand <= 17:
dealer_hand += draw_card()
# output dealer's final hand and if black jack, bust or neither
print_end_turn_status(dealer_hand)
# compare user's and dealer's final hand and who won, lost, or tied
print_end_game_status(user_hand, dealer_hand) |
85380438fd80cc9a8a3c45f1996e1bff043e7923 | Insookim0702/python_Algorithm | /책/DFSBFS/me음료수얼려먹기3.py | 410 | 3.578125 | 4 | n,m = 3,3
graph= [[0,0,1],[0,1,0],[1,0,1]]
result = 0
def dfs(x,y):
if x <= -1 or x >=n or y <= -1 or y >=m:
return False
if graph[x][y] == 0:
graph[x][y] = 1
dfs(x+1, y)
dfs(x-1, y)
dfs(x, y+1)
dfs(x, y-1)
return True
return False
for i in range(n):
for j in range(m):
if dfs(i,j) ==True:
result +=1
print(result)
|
e1e77285d533abb2e3b93200a64749b0bf93012a | daniel-reich/turbo-robot | /88RHBqSA84yT3fdLM_10.py | 1,216 | 4.125 | 4 | """
Create a function that takes a single word string and does the following:
1. Concatenates `inator` to the end if the word ends with a consonant, otherwise, concatenate `-inator` instead.
2. Adds the word length of the original word to the end, supplied with "000".
The examples should make this clear.
### Examples
inator_inator("Shrink") ➞ "Shrinkinator 6000"
inator_inator("Doom") ➞ "Doominator 4000"
inator_inator("EvilClone") ➞ "EvilClone-inator 9000"
### Notes
For the purposes of this challenge, vowels will be **a, e, i, o** and **u**
only.
"""
def inator_inator(inv): #w/o built-in
def l(s):
count = 0
while s != "":
count += 1
s = s[1:]
return count
d = {1: "1", 2: "2", 3: "3", 4: "4", 5: "5",
6: "6", 7: "7", 8: "8", 9: "9", 0: "0"}
c, lst = l(inv), []
while c > 0:
lst += [c % 10]
c //= 10
lst, n = [d[x] for x in lst], ""
for i in lst:
n += i
if inv[-1] in 'aeiouAEIOU':
return inv + "-inator " + n + "000"
return inv + "inator " + n + "000"
def inator_inator(inv):
return '{}-inator {}000'.format(inv, len(inv)) if inv[-1] in 'aeiouAEIOU' else\
'{}inator {}000'.format(inv, len(inv))
|
f37d3b616846f6283f2b8821b1f6ea141b1ed4d2 | Mostofa-Najmus-Sakib/Applied-Algorithm | /Leetcode/Python Solutions/Matrix/SetMatrixZeroes.py | 1,213 | 3.859375 | 4 | """
LeetCode Problem: 73. Set Matrix Zeroes
Link: https://leetcode.com/problems/set-matrix-zeroes/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(M*N)
Space Complexity: O(M*N)
M: Number of rows
N: Number of columns
"""
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# A helper function that sets all the cells in a particular row and column to 0
def setRowColumn(matrix, row, column):
for r in range(len(matrix)):
matrix[r][column] = 0
for c in range(len(matrix[0])):
matrix[row][c] = 0
rows = len(matrix)
columns = len(matrix[0])
# Creates a copy of the original matrix
originalMatrix = [[matrix[row][col] for col in range(columns)] for row in range(rows)]
for row in range(rows):
for column in range(columns):
# If any of the cell is 0 then set all the cells in that row and column to be 0
if originalMatrix[row][column] == 0:
setRowColumn(matrix, row, column) |
a7384a2e25f3745462f7f0e9ff32589bdd0693a4 | Buthjaga/pdsnd_github | /bikeshare.py | 7,329 | 4.25 | 4 | from sys import exit
import calendar
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv'}
#Took out washington because it's missing the Gender and Year columns thus causing errors
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago or new york city). HINT: Use a while loop to handle invalid inputs
cities = ['chicago', 'new york city']
while True:
city = input("For your city, enter 'chicago', or 'new york city'").lower()
#city is entered here instead of outside the loop coz it will run in infinite loop
if city in cities:
print("Thanks for your input")
break
else:
print("Enter a valid city")
# TO DO: get user input for month (all, january, february, ... , june)
months = ['all', 'january', 'february', 'march', 'april', 'may', 'june']
while True:
month = input("For your month, enter any mohth from 'january' through 'june' or enter 'all'").lower()
if month in months:
print("Thanks for your input")
break
else:
print("Enter a valid month")
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
day_of_week = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
while True:
day = input("Which day best suits you. You can enter all if that's what you want.").lower()
if day in day_of_week:
print("Thanks for your input. Please wait as the data loads.")
break
else:
print("Enter a valid weekday.")
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month and day of week from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week_name'] = df['Start Time'].dt.weekday_name
df['hour'] = df['Start Time'].dt.hour
df['start_end_station'] = df['Start Station'] + ' to ' + df['End Station']
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week_name'] == day.title()]
return df
def choose_interphase(df):
"""Will ask user if they want the first five rows of raw data
or would they prefer it be broken down by me"""
while True:
choice = input("Would you prefer first five rows of raw data? Yes or No ")
if choice.lower() == 'yes':
print(df.head())
exit()
elif choice.lower() == 'no':
print("You made a wise choice")
break
else:
print("Enter a valid input")
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
list_of_month = df.groupby(['month'])['month'].count()
print("The most common month is ", list_of_month.idxmax())
# TO DO: display the most common day of week
list_of_day = df.groupby(['day_of_week_name'])['day_of_week_name'].count()
print("The most common day of week is ", list_of_day.idxmax())
# TO DO: display the most common start hour
print("The most common start hour is ", df['hour'].mean())
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
list_of_start = df.groupby(['Start Station'])['Start Station'].count()
print("The most commonly used start station is ", list_of_start.idxmax())
# TO DO: display most commonly used end station
list_of_end = df.groupby(['End Station'])['End Station'].count()
print("The most commonly used end station is ", list_of_end.idxmax())
# TO DO: display most frequent combination of start station and end station trip
list_of_both = df.groupby(['start_end_station'])['start_end_station'].count()
print("The most commonly used start and end station is ", list_of_both.idxmax())
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
print("The total travel time in hours is ", df['hour'].sum())
# TO DO: display mean travel time
print("The average travel time in hours is ", df['hour'].mean())
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
print("This is how the user types are grouped by numbers.\n", df.groupby(['User Type'])['User Type'].count())
# TO DO: Display counts of gender
print("This is how the male female genders are grouped by numbers.\n", df.groupby(['Gender'])['Gender'].count())
# TO DO: Display earliest, most recent, and most common year of birth
print("The earliest year of birth is ", df['Birth Year'].min())
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
choose_interphase(df)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
4841d95fdd984b88a29c3ccb579c8c048e934d45 | xjr7670/corePython | /2-15b.py | 345 | 3.875 | 4 | #!/usr/bin/env python
a = int(raw_input("Please input num 1: "))
b = int(raw_input("Please input num 2: "))
c = int(raw_input("Please input num 3: "))
if a > b > c:
print a, b, c
elif a > c > b:
print a, c, b
elif b > a > c:
print b, a, c
elif b > c > a:
print b, c, a
elif c > a > b:
print c, a, b
else:
print c, b, a
|
35f261c70dbe3a6995a0aa8705a588baa6bd8b13 | JavasMiddi/PythonTasks | /GradeCals.py | 147 | 3.875 | 4 | mark = int(input("Please input a mark: "))
if mark > 85:
print("Distinction!")
elif 65 < mark < 85:
print("Pass!")
else:
print("Fail!") |
ee95a2687f8685de55d662df75c9bfd75b49ed11 | BIAOXYZ/variousCodes | /_CodeTopics/CodeForces/problemset/4A/4A.py | 203 | 4 | 4 | weight = raw_input()
remainder = int(weight) % 2
if int(weight) < 3:
print "NO"
elif remainder:
print "NO"
else:
print "YES"
"""
https://codeforces.com/problemset/submission/4/94371519
"""
|
3db370ca624b4616e1278e4ad2cb15ae45ac3b08 | borislavstoychev/Soft_Uni | /soft_uni_OOP/Attributes and Methods/lab/integer_2.py | 1,218 | 3.875 | 4 | class Integer:
def __init__(self, value: int):
self.value = value
@staticmethod
def from_float(value):
if not isinstance(value, float):
return "value is not a float"
return Integer(int(value))
@staticmethod
def from_roman(value):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(value)):
if i > 0 and rom_val[value[i]] > rom_val[value[i - 1]]:
int_val += rom_val[value[i]] - 2 * rom_val[value[i - 1]]
else:
int_val += rom_val[value[i]]
return Integer(int_val)
@staticmethod
def from_string(value):
if not isinstance(value, str):
return "wrong type"
return Integer(int(value))
def add(self, integer):
if not isinstance(integer, Integer):
return "number should be an Integer instance"
return self.value + integer.value
def __str__(self):
return f"{self.value}"
first_num = Integer(10)
second_num = Integer.from_roman("IV")
x = Integer.from_float(3.5)
print(x)
y = Integer.from_string("2")
print(y)
print(first_num.add(second_num)) |
9025ab5e1f0780171ad5caa2d6021b0ffecdfb80 | nickbent1/PythonCasino | /Slotmachine.py | 4,458 | 3.859375 | 4 | # Please make sure this file name is "Slotmachine.py" (with a capital S)
# Please make sure you have Casino.py
print("You have 20 coins.", "\n","1 coin = 1 spin", "\n", "Match 3 symbols in a row in order to win!", "\n", "[ 777 ] = 15x ","\n","[ Win ] = 2x","\n","[ BAR ] = 3x","\n","[ BANKRUPT ] = LOSE","\n","[ (8) ] = 8x","\n","[ $$$ ] = 18x")
B = 20 #B stands for Balance, so this is the starting balance.
Bet = 0 #Bet is the amount you can play per spin, your bet cannot exceed your balance and you cannot continue betting once you've reached 0 balance.
W = 0 #W stands for winnings.
def quit():
stream = open("casino.py")
read_file = stream.read()
exec(read_file)
import random
def respin():#Respin will initiate after a user spins and wins or loses.
global B
global Bet
user_input1 = input("Would you like to try another spin? Y or N?\n")
if user_input1 == "Y" or user_input1 == "y" or user_input1 == "":
print("How much would you like to bet?")
Bet = int(input("Bet amount: "))
if Bet == 0 or Bet > B:
print("Insufficient Funds.\n")
respin()
spin()
else:
print(" Score: ", B)
print("Thank you for playing!")
quit()
def spin(): #The spin function defines the symbols and their winning variables. It spins 3 random symbols and based on their combination will determine whether or not the user wins or loses.
global B
global W
global Bet
B = B - Bet
print(" | -", Bet," coins | ")
Slot1 = random.choice(["[ $$$ ]", "[ 777 ]", "[ BAR ]", "[ (8) ]", "[ Win ]", "[ BANKRUPT ]"])
Slot2 = random.choice(["[ $$$ ]", "[ 777 ]", "[ BAR ]", "[ (8) ]", "[ Win ]", "[ BANKRUPT ]"])
Slot3 = random.choice(["[ $$$ ]", "[ 777 ]", "[ BAR ]", "[ (8) ]", "[ Win ]", "[ BANKRUPT ]"])
print("|",Slot1,Slot2,Slot3,"|","\n")
while B >= 1: #While your balance is greater than or equal to 1, you are able to spin.
if Slot1 == Slot2 == Slot3 == "[ $$$ ]":
W = Bet * 18
B = B + W
print (" ====!!!YOU WIN!!!====\n"," +", W, "COINS\n"," Balance:", B,"coins","\n"," =====================")
respin()
elif Slot1 == Slot2 == Slot3 == "[ 777 ]":
W = Bet * 15
B = B + W
print (" ====!!!YOU WIN!!!====\n"," +", W, "COINS\n"," Balance:", B,"coins","\n"," =====================")
respin()
elif Slot1 == Slot2 == Slot3 == "[ BAR ]":
W = Bet * 3
B = B + W
print (" ====!!!YOU WIN!!!====\n"," +", W, "COINS\n"," Balance:", B,"coins","\n"," =====================")
respin()
elif Slot1 == Slot2 == Slot3 == "[ (8) ]":
W = Bet * 8
B = B + W
print (" ====!!!YOU WIN!!!====\n"," +", W, "COINS\n"," Balance:", B,"coins","\n"," =====================")
respin()
elif Slot1 == Slot2 == Slot3 == "[ Win ]":
W = Bet * 2
B = B + W
print (" ====!!!YOU WIN!!!====\n"," +", W, "COINS\n"," Balance:", B,"coins","\n"," =====================")
respin()
elif Slot1 == Slot2 == Slot3 == "[ BANKRUPT ]": #The twist to our game comes from the bankrupt symbol which will cash out your entire winnings and account balance.
W = Bet - Bet
B = B - B
print(" YOU STRUCK OUT\n")
else:
print(" ___ You Lose ___\n", " Balance:", B,"coins", "\n", " ________________")
respin()
else:
print(" |||||You lost|||||\n", " Balance: ",B," coins")
print(" Score: ", B)
print(" Thank you for playing!\n")
respin()
#smgame is the starting function found in the Casino.py file, this function will trigger the program to run.
def smgame():
global B
global Bet
user_input = input("Would you like to spin? Y or N?\n")
if user_input == "Y" or user_input == "y" or user_input == "":
print("How much would you like to bet?")
Bet = int(input(" Bet: "))
if Bet > B:
print("Insufficient Funds.\n")
respin()
spin()
else:
print(" Score: ", B)
print(" Thank you for playing!")
respin()
|
d980a4d6c7a610e4506661fbfcf4d50ff6fc1a81 | ThayseSantos/security-tools-with-python | /ComparadorHash/ch.py | 601 | 3.53125 | 4 | import hashlib
arquivo1 = 'primeiro.txt'
arquivo2 = 'segundo.txt'
#ripemd160 = algoritmo de hash
hash1 = hashlib.new('ripemd160')
hash1.update(open(arquivo1, 'rb').read())
hash2 = hashlib.new('ripemd160')
hash2.update(open(arquivo2, 'rb').read())
#comparação:
if hash1.digest() != hash2.digest():
print('Hashs Diferentes:')
print('Hash do primeiro arquivo: {} \nHash do segundo arquivo: {}'.format(hash1.hexdigest(), hash2.hexdigest()))
else:
print('Hashs Iguais:')
print('Hash do primeiro arquivo: {} \nHash do segundo arquivo: {}'.format(hash1.hexdigest(), hash2.hexdigest()))
|
ae4fd272273c34efead67b5110db09548a21c8fa | sabergjy/Leetcode_Programing | /36.有效的数独.py | 795 | 3.765625 | 4 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
col = defaultdict(set) #表示建立一个字典(哈希结构),其value是一个集合 ,也可以放一个列表,一样的
row = defaultdict(set)
sqrt = defaultdict(set)
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == ".":
continue
point = (i//3)*3 + j//3
if board[i][j] not in row[i] and board[i][j] not in col[j] and board[i][j] not in sqrt[point]:
row[i].add(board[i][j])
col[j].add(board[i][j])
sqrt[point].add(board[i][j])
else:
return False
return True |
4f71562f177993c4397ff1b89f16b1b00464d608 | andreztz/estrutura_de_dados | /queue.py | 2,070 | 4.3125 | 4 | '''
Fila (=queue)
FIFO (=First_In-First_Out) significa primeiro a entrar, primeiro a sair.
É uma estrura de dados implementada para gerar fila de espera. Em uma fila
do tipo FIFO os elementos vão sendo colocadosna fila e retirados (ou processados)
por ordem de chegada. A idéia fundamental da fila é que só podemos inserir um
novo elemento no final da fila e só podemos retirar o elemento do início.
Como exemplo de aplicação para filas, pode-se citar a fila de processos de um
sistema operacional. Nela, é estabelecido um tempo t a ser usado por cada um
dos processos. Se durante a execução de um processo o tempo passa de 0 a t,
este é posto na fila e o processo seguinte é executado. Se o processo seguinte
não terminar de ser executado no tempo t, ele é posto na fila e o processo
subsequente é executado, e assim por diante até todos os processos serem
executados.
'''
class Queue:
def __init__(self):
'''
Inicializa uma lista e uma variavel que
controla o tamanho da fila.
'''
self.queue = []
self.len_queue = 0
def push(self, e):
'''
Insere um elemento no fim da fila
'''
self.queue.append(e)
self.len_queue += 1
def pop(self):
'''
Remove um elemento do inicio da fila
'''
if not self.empty():
self.queue.pop(0)
self.len_queue -= 1
def empty(self):
'''
Verifica se a fila não é vazia
'''
if self.len_queue == 0:
return True
return False
def length(self):
'''
Retorna o tamanho da fila
'''
return self.len_queue
def front(self):
'''
Retorna o primeiro elemento da fila se não for vazia
'''
if not self.empty():
return self.queue[0]
return None
if __name__ == '__main__':
q = Queue()
q.push(1)
q.push(2)
q.push(3)
print(q.front())
|
26f7a004bef968a024ea37136cb2a1c8860674c7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/mdlsan019/question2.py | 2,176 | 4.28125 | 4 | '''SANELE MDLALOSE
MDLSAN019
Vectors: additional, dot products and normalization
Assignment6,Question2
21 April 2014'''
from math import *
A=input("Enter vector A:\n") #Get vector values
A=A.split()
B=input("Enter vector B:\n")
B=B.split()
A_add_B=[' ', ' ', ' '] #Create a list of three spaces
for i in range(len(A)):
A_add_B[i] = int(A[i])+int(B[i]) #Change each space to a sum of corresponding integer items of vectors A and B
print("A+B =",A_add_B) #Output Result
A_mult_B=[' ', ' ', ' '] #Create a list of three spaces
for j in range(len(A)):
A_mult_B[j] = int(A[j])*int(B[j]) #Change each space to a product of corresponding integer items of vectors A and B
for l in range(len(A_mult_B)):
A_mult_B[l] = str(A_mult_B[l]) #Convert each item in A_mult_B list to a string
A_mult_B="+".join(A_mult_B) #Join the string items by character "+"
print("A.B =",eval(A_mult_B)) #Evaluate the joined string into a number and output the result
norm_A=[' ', ' ', ' '] #Create a list of three spaces
for a in range(len(A)):
norm_A[a]= int(A[a])**2 #Change each space into a square of corresponding integer items in list A
for m in range(3):
norm_A[m]=str(norm_A[m]) #Change each item in list norm_A into a string
norm_A="+".join(norm_A) #Join the list of strings
norm_A=sqrt(eval(norm_A)) #Evaluate the resultant string into a square root number
if norm_A==0.0:
norm_A='%.2f'%norm_A
print("|A| =",norm_A)
else:
print("|A| =", round(norm_A,2)) #Output a 2-decimal rounded answer
norm_B=[' ', ' ', ' '] #Create a list of three spaces
for b in range (len(B)):
norm_B[b] = int(B[b])**2 #Change each space into a square of integer items in list B
for n in range (len(norm_B)):
norm_B[n] = str(norm_B[n]) #Convert each item in the list into a string
norm_B="+".join(norm_B) #Join the string items
norm_B=sqrt(eval(norm_B)) #Evaluate the string into square root number
if norm_B==0.0:
norm_B='%.2f'%norm_B
print("|B| =",norm_B)
else:
print("|B| =",round(norm_B,2)) #Output a 2-decimal-digit-rounded answer
|
58f40c1bd905abf5f69cb094603422f3cfe132a1 | ravenac95/testvirtstrapdocs | /tests/tools/data.py | 521 | 3.59375 | 4 | """
Various Data Test Tools
"""
import random
NUMBER = "0123456789"
SYMBOL = """!@#$%^&*()_+=-[]\;',./{}|:"<>?~`"""
ALPHA_LOWER = "abcdefghijklmnopqrstuvwxyz"
ALPHA_UPPER = ALPHA_LOWER.upper()
ALL_ALPHA = ALPHA_LOWER + ALPHA_UPPER
ALPHA_NUMERIC = ALL_ALPHA + NUMBER
ALL_CHARS = SYMBOL + ALPHA_NUMERIC
def random_string(length, chars=ALL_CHARS):
"""Generates a random string of length"""
array = []
for i in xrange(length):
c = random.choice(chars)
array.append(c)
return "".join(array)
|
f78e9e7476ff7a34765f10df6752b8d2c5183d97 | EmersonElectricCo/lowball | /lowball/models/provider_models/auth_db.py | 2,136 | 3.828125 | 4 | from abc import ABC, abstractmethod
class AuthDatabase(ABC):
"""Base class for user-defined Auth Database classes.
The data that is passed into the init is determined by the developer and the config that
is passed into the init.
"""
def __init__(self, **kwargs):
pass
@abstractmethod
def add_token(self, token_object):
"""Add a token to the auth database.
:param token_object: object containing all data to be written by auth db
:type token_object: Token
:return: None
"""
pass
@abstractmethod
def lookup_token(self, token_id):
"""Lookup a token in the auth database
:param token_id: identifier of the token in the auth database
:type token_id: str
:return: Token Object
"""
pass
@abstractmethod
def revoke_token(self, token_id):
"""Revoke a token that is stored in the auth database.
:param token_id: identifier of the token in the auth database
:type token_id: str
:return: None
"""
pass
@abstractmethod
def list_tokens(self):
"""List all the tokens that are in the auth database.
:return: List of Token Objects
"""
pass
@abstractmethod
def list_tokens_by_client_id(self, client_id):
"""List all the tokens for a specific user.
:param client_id: the username to lookup tokens for
:type client_id: str
:return: List of Token Objects
"""
pass
@abstractmethod
def list_tokens_by_role(self, role):
"""List all tokens in the auth database that have a specific role.
:param role: the role to lookup in the database
:type role: str
:return: List of Token Objects
"""
pass
@abstractmethod
def cleanup_tokens(self):
"""Remove all expired tokens from the auth database.
:return: None
"""
pass
@abstractmethod
def revoke_all(self):
"""Revoke all tokens in the auth database.
:return: None
"""
pass
|
d697e5d9e9b5f444e4ce29da002257f237a2d6ed | Aaron44201/Assignment | /Money counting.py | 588 | 3.90625 | 4 | #Aaron Bentley
#19/09/14
#money counting
amount = int(input("Please input your amount of money: "))
twenty = amount // 20
remainder = amount % 20
ten = remainder // 10
remainder2 = remainder % 10
five = remainder2 // 5
remainder3 = remainder2 % 5
two = remainder3 // 2
remainder4 = remainder3 % 2
one = remainder4 // 1
print("The answer is: ")
print("{0} twenty pound notes".format (twenty))
print("{0} ten pound notes".format (ten))
print("{0} five pound notes".format (five))
print("{0} two pound coins".format (two))
print("{0} one pound coins".format (one))
|
827c4be6a60e7aa3cfa56c1b4eb568aebe54413e | johnwanjema/python | /hello.py | 989 | 4.25 | 4 |
# importing date class from datetime module
from datetime import date
# creating the date object of today's date
todays_date = date.today()
print("Hello Python")
# List is the most basic Data Structure in python.
# List is a mutable data structure i.e items can be added to list later after the list creation.
# creates a empty list
nums = []
# appending data in list
nums.append(21)
nums.append(40.5)
nums.append("String")
# print(nums)
# Python program to illustrate
# functions
def hello():
name = input("Enter your name: ")
result = int(input("Enter year of birth: "))
print("Hello", name)
print("your are", todays_date.year -result,"years old" )
def countSubstrings():
# string in which occurrence will be checked
string = "geeks for geeks"
# counts the number of times substring occurs in
# the given string and returns an integer
print(string.count("geeks"))
def Main():
hello()
if __name__=="__main__":
Main() |
33789f992f4c9ca852c871a6d5c172f88e2c46c3 | JANSSOC/python-challenge | /pypoll/maindevlopment.py | 2,576 | 3.6875 | 4 | import os
import csv
Filepath = os.path.join('..','..','..','UNCCHAR201811DATA3','02-Homework','03-Python','Instructions','PyPoll','Resources','election_data.csv')
#print(Filepath)
#C:/Users/cjans/documents/Bootcamp/HW2VBA/python-challenge/pypoll/.git/
#Filepath = '..\..\..\UNCCHAR201811DATA3\02-Homework\03-Python\Instructions\PyPoll\Resources\election_data.csv'
class Elect():
def __init__(self, name):
self.name = name
self.votes = 1
def countVote(self,z):
self.votes += z
print(self.votes)
def countVote1(self):
self.votes += 1
def displayCanidate(self,total):
#print(f"Name : {self.name} Salary: {self.votes}")
print(f"{self.name}: {round(self.votes/total*100,3)}% ({self.votes})")
MyElection = {}
i = 0
with open(Filepath,newline= "") as Pollfile:
csv_poll = csv.reader(Pollfile, delimiter=",")
csv_header = next(csv_poll)
print(csv_header)
for row in csv_poll:
n = row[2]
i += 1
#print(n)
if n in MyElection:
#print(n)
#p1=MyElection[n]
#print(p1.name)
#p1.votes +=1
#p1.countVote(1)
#MyElection[n].countVote(1)
MyElection[n].countVote1()
#print(p1.votes)
#p1.n.countVote
#MyElection[n]= p1
#print(p1.votes)
else:
p2 = Elect(n)
#print(p2.name.title()+ "new")
MyElection[n] = p2
if i >1000:
break
Totalvotes = 0
Winner = ""
Maxvotes = 0
for x in MyElection:
Totalvotes =Totalvotes + MyElection[x].votes
print (Totalvotes)
for x in MyElection:
if MyElection[x].votes > Maxvotes:
Maxvotes = MyElection[x].votes
Winner = MyElection[x].name
print(Winner)
#print(len(MyElection))
print(f" Election Results")
print(f"----------------------------")
print(f"Total Votes: {Totalvotes}")
print(f"----------------------------")
for x in MyElection:
MyElection[x].displayCanidate(Totalvotes)
#print(f"{p3.name}: {p3.votes/Totalvotes*100}% ({p3.votes})")
#p3.displayCanidate(Totalvotes)
print(f"----------------------------")
print(f"Winner: {Winner}")
print(f"----------------------------")
""" Election Results
-------------------------
Total Votes: 3521001
-------------------------
Khan: 63.000% (2218231)
Correy: 20.000% (704200)
Li: 14.000% (492940)
O'Tooley: 3.000% (105630)
-------------------------
Winner: Khan
------------------------- """
|
de05add23302fc384fdbf1aafbe8bf5f5eb509fa | natacadiz/Nata | /Ejercicios Unidad 1/1.8.py | 323 | 3.703125 | 4 | # Escribir el programa del ejercicio 1.7 usando solamente dos variables diferentes.
#2+3+4
suma = int(input())
suma += int(input()) #suma = suma + int(input())
suma += int(input()) #suma = suma + int(input()) + int(input())
print (suma) #colocamos el nombre de la variable principal y nos imprime la operacion de las tres |
ad5f3d41a24b117f7926c3a191f6418a31d17006 | 05suraj/my-python-tutorial | /map_fil.py | 443 | 3.875 | 4 | # def addtion(n):
# return n+n
# number=(1,2,3,4,5,6)
# result=map(addtion,number)
# print(list(result))
# todo------that is lamda in in line fun-----
# number = (1, 2, 3, 4, 5, 6)
# result=map(lambda x:x+x,number)
# print(list(result))
number1 = [1, 2, 3, 4]
number2 = [5, 6, 7, 8]
result = map(lambda x, y: x*y, number1, number2)
print(list(result))
l = ['suraj', 'niraj', 'ajay', 'saxena']
test = list((map(list, l)))
print(test)
|
1a806319d41a3c5642466858e791becc34e07ac7 | daressatyam/PYTHON-WITH-DATA-STRUCTURE | /week 3/matrixflip.py | 190 | 3.515625 | 4 | def matrixflip(m,d):
tempm = m.copy()
if d=='h':
for i in range(0,len(tempm),1):
tempm[i].reverse()
elif d=='v':
tempm.reverse()
return(tempm) |
eba0e2c33e10cbadcb222b911afa203fef6e3859 | dragos-vacariu/Python-Exercises | /Exercises/zipping, combining multiple lists and tuples together.py | 306 | 4.34375 | 4 | #Zipping (combining) list together.
Lst1 = ["Dragos", "Alan", "Robin"]
Lst2 = ["Blake", "Walker", "Williams"]
names = zip(Lst1,Lst2)
#names will be a new list, a 2D list I might say, containing all the elements in
#Lst1 and Lst2 combined.
#Iterating names:
for a,b in names:
print("Name = ", a, b)
|
135f701576a50cb261bdddd7a2d5695792c3d20f | OhadAvnery/do_you_mind | /doyoumind/utils/reader_utils.py | 1,266 | 4.0625 | 4 | import struct
def unpack_format(file, fmt):
'''
Unpacks the format from the file using struct.unpack,
to the correct number of bytes, and returns the result.
:param file: the file to read from
:type file: Path
:param fmt: the format to read
:type fmt: str
:returns: the result of the read
:rtype: str/List(str)
'''
vals = struct.unpack(fmt, file.read(struct.calcsize(fmt)))
if len(vals) == 1: # vals is a tuple of the form (x,)
return vals[0]
else:
return vals
def unpack_string(file, str_len):
return struct.unpack("{:d}s".format(str_len), file.read(str_len))[0].decode()
fmt = {'uint64': 'Q', 'uint32': 'L', 'double': 'd'}
size = {st:struct.calcsize(val) for st, val in fmt.items()}
class PackedString:
'''
an object representing a string, together with an offset that saves
where we read from last.
:param msg: The message string
:type msg: str
:param offset: the offset of the string we're reading
:type offset: int
'''
def __init__(self, msg):
self.msg = msg
self.offset = 0
def unpack(self, fmt):
val = struct.unpack_from(fmt, self.msg, self.offset)
self.offset += struct.calcsize(fmt)
return val
|
30dbb1b12318f7693f8281df31a28390e53cc8a2 | stevenyan7/mario-game | /My_Mario_Version_2.py | 7,227 | 3.953125 | 4 | #Assignment 5 - My_Mario_Version_2.py
#
##The goal of our Assignment 5 is to allow the player (user) to play our game by moving Mario
##around the maze.
#There are also rewards and exploding obstacles in the maze!
#
#Chu Yan
#Yaben Yang
#April 8, 2016
import random
def playGame(score,MPosition, rewardingObstaclesList, explodingObstaclesList, maze,emptyMazCell):
MPositionList = MPosition
while score>0 :
#promot user input + validation
userChoose = userInput(mazeHeight, mazeWidth, MPosition)
if userChoose == "x":
print("\n")
print("------")
#if exit
elif userChoose == "exit":
print("\n")
print("Mario has reached the exit gate with a score of %i! You win!" %score)
else:
if userChoose == "u":
MPositionList[0]-=1
elif userChoose == "d":
MPositionList[0]+=1
elif userChoose == "l":
MPositionList[1]-=1
elif userChoose == "r":
MPositionList[1]+=1
testList=str(MPosition[0])+' '+str(MPosition[1])
if testList in rewardingObstaclesList:
score += 1
elif testList in explodingObstaclesList:
score -= 1
turnMapCellToNormal(maze,MPositionList, emptyMazCell)
maze = createMaze(mazeHeight, mazeWidth, emptyMazCell)
addItem(symbolOfExplodingObstacles, maze, aNumOfRewardingObstacles, rewardingObstaclesList)
addItem(symbolOfRewardingObstacles, maze, aNumOfExplodingObstacles,explodingObstaclesList)
Mario(maze,symbolOfMario,symbolOfGate, topBoundary, botBoundary, topBotBorder, MPosition, score)
playGame(score,MPosition, rewardingObstaclesList, explodingObstaclesList, maze,emptyMazCell)
return
#create a function of creating maze
def createMaze(mazeHeight, mazeWidth, emptyMazCell):
maze = list()
for i in range(mazeHeight):
row = list()
for i in range(mazeWidth):
row.append(emptyMazCell)
maze.append(row)
return maze
#draw frame of maze
def mazeFrame(maze, rowNum, columnNum, topBoundary, botBoundary, leftRightBorder):
print("\n")
topNum = list()
for topNum in range(1, columnNum + 1):
columnNum = list()
if topNum == 1:
columnNum = " " + str(topNum) + " "
elif topNum < 10:
columnNum = str(topNum) + " "
else:
columnNum = str(topNum) + ""
print (columnNum, end=" ")
#print top boundary
print(topBoundary)
sideNum = 1
for i in maze:
if sideNum < 10:
rowNum = str(sideNum)+" "+leftRightBorder
else:
rowNum = str(sideNum)+leftRightBorder
sideNum += 1
for c in i:
rowNum += " " + c + " "
print (rowNum + leftRightBorder)
#print bottom boundary
print(botBoundary)
return maze
#draw random obstacles
def addItem(name, maze, amount, objectList):
for i in range(amount):
r = int(objectList[i].split()[0])
c = int(objectList[i].split()[1])
maze[r][c] = name
return maze
#initial mario's location from user
def Mario(maze, mario, gate, topBoundary, botBoundary, topBotBorder, MPosition, score):
theParts = MPosition
userR = int(theParts[0])
userC = int(theParts[1])
maze[userR][userC] = mario
if userC < int(mazeWidth/2):
if userC < int(mazeWidth/2):
num = random.randint(0,1)
if num == 1:
botBoundary = " " + (topBotBorder * mazeWidth)[:-1]+gate
topBoundary = "\n " + topBotBorder * mazeWidth
else:
topBoundary = "\n " + (topBotBorder * mazeWidth)[:-1]+gate
botBoundary = " " + topBotBorder * mazeWidth
else:
num = random.randint(0,1)
if num == 1:
botBoundary = " " + gate + (topBotBorder * mazeWidth)[:-1]
topBoundary = "\n " + topBotBorder * mazeWidth
else:
topBoundary = "\n " + gate + (topBotBorder * mazeWidth)[:-1]
botBoundary = " " + topBotBorder * mazeWidth
botBoundary = " " + topBotBorder * mazeWidth + "\n\n-------"
mazeFrame(maze, mazeHeight, mazeWidth, topBoundary, botBoundary, leftRightBorder)
print("Mario's score -> ",score)
print("\n")
def userInput(mazeHeight, mazeWidth, MPosition):
MPositionList = MPosition
userChoose = input("Move Mario by entering the letter 'r' for right, 'l' for left, 'u' for up and 'd' for down, 'x' to exit the game: ")
userChoose = userChoose.lower()
#validation
allowList = ['u', 'd', 'l', 'r','x']
while (userChoose.lower() not in allowList) :
userChoose = input("Invalid input or cannot move, please Enter a direction: ")
return userChoose
def turnMapCellToNormal(maze,MPositionList, emptyMazCell):
maze[MPosition[0]][MPosition[1]] = emptyMazCell
#Main
print("Welcome to my Mario game.")
#read file
##inputFile = 'InputData_Assn_5_1.txt'
inputFile = input("Please, enter a filename: ")
# Opening a file for reading
fileR = open(inputFile, 'r')
myDataList = list(fileR)
#remove \n for each data file line
for i in range(len(myDataList)):
myDataList[i] = myDataList[i].strip()
mazeHeight = int(myDataList[1])
mazeWidth = int(myDataList[0])
aNumOfExplodingObstacles = int(myDataList[3])
aNumOfRewardingObstacles = int(myDataList[2])
emptyMazCell = myDataList[4]
symbolOfExplodingObstacles = myDataList[5]
symbolOfRewardingObstacles = myDataList[6]
symbolOfMario = myDataList[7]
symbolOfGate = myDataList[8]
topBotBorder = myDataList[9]
leftRightBorder = myDataList[10]
topBoundary = "\n " + topBotBorder * mazeWidth
botBoundary = " " + topBotBorder * mazeWidth + "\n"
MPosition = myDataList[11]
MPosition = (MPosition.split())
#re-structure MPosition to [int, int]
MPosition[0] = int(MPosition[0])
MPosition[1] = int(MPosition[1])
rewardingObstaclesList = myDataList[12:12+aNumOfRewardingObstacles]
explodingObstaclesList = myDataList[12+aNumOfRewardingObstacles:]
score = aNumOfExplodingObstacles//3
maze = createMaze(mazeHeight, mazeWidth, emptyMazCell)
addItem(symbolOfExplodingObstacles, maze, aNumOfRewardingObstacles, rewardingObstaclesList)
addItem(symbolOfRewardingObstacles, maze, aNumOfExplodingObstacles,explodingObstaclesList)
Mario(maze,symbolOfMario,symbolOfGate, topBoundary, botBoundary, topBotBorder, MPosition, score)
playGame(score,MPosition, rewardingObstaclesList, explodingObstaclesList, maze,emptyMazCell)
|
ef0c1ea9df08aece100e344ad05646ccba342526 | sbhotika/15112-term-project | /ui_main.py | 14,696 | 3.609375 | 4 | # events-example0.py
# copied from https://www.cs.cmu.edu/~112/notes/events-example0.py
# Super Maze! from Shubhangi Bhotika + sbhotika
# all algorithms were based on those found at:
# https://en.wikipedia.org/wiki/Maze_generation_algorithm
# the images were found on the Google
# the buttons were drawn using this very handy website:
# http://dabuttonfactory.com/
from tkinter import *
from random import *
from Maze import *
class Puzzle(object):
# handles interaction with Maze
def __init__(self, rows, cols, cellSize, width, height, puzzle=""):
self.rows = rows
self.cols = cols
self.cellSize = cellSize
self.game = Maze(rows, cols, cellSize, width, height, puzzle)
##########################################################################
def instructions(data):
# stores instructions for maze
data.mazeInstructions = """
Find your way from
beginning to finish.
Use arrows to move the ball and
help navigate its way to the finish line
(where the flag is).
Press 'i' for instructions,
'r' to restart, and 'q'
to quit the game
(apart from the buttons).
The goal is to find the finish
as fast as possible.
Press anywhere on screen
to go back to main menu.
"""
def init(data):
# load data.xyz as appropriate
data.gameOver = data.gamePaused = data.instructions = data.gameWon = False
data.kruskalPlay = data.primPlay = False
data.menu = True
data.score = data.time = 0
data.margin = 100
data.cellSize = min((data.width-data.margin)/data.cols,
(data.height-data.margin)/data.rows)
data.kruskalPuzzle = Puzzle(data.rows, data.cols, data.cellSize,
data.width-data.margin, data.height-data.margin,
"kruskal")
data.primPuzzle = Puzzle(data.rows, data.cols, data.cellSize,
data.width-data.margin, data.height-data.margin,
"prim")
instructions(data)
loadImages(data)
def loadImages(data):
# load images into data so I can make my game look pretty later
data.helpBtn = PhotoImage(file="images/help.png")
data.pauseBtn = PhotoImage(file="images/pause.png")
data.restartBtn = PhotoImage(file="images/restart.png")
data.kruskalBtn = PhotoImage(file="images/kruskal.png")
data.primBtn = PhotoImage(file="images/prim.png")
data.instructionsBtn = PhotoImage(file="images/instructions.png")
data.maze_bg = PhotoImage(file="images/maze_bg.png")
data.exit = PhotoImage(file="images/exit.png")
data.backBtn = PhotoImage(file="images/back.png")
def mousePressed(event, data):
# use event.x and event.y
if (data.menu == False or data.primPlay or data.kruskalPlay
and data.instructions and
(0 <= event.x <= data.width) and
(0 <= event.y <= data.height)):
# removes instructions screen
data.instructions = False
if data.kruskalPlay == False and data.primPlay == False: data.menu = True
if (data.menu and data.instructions == False
and 175 <= event.x <= 525 and 120 <= event.y <= 205):
# toggles instructions screen
data.instructions = True
data.menu = False
if (data.menu and data.instructions == False
and 175 <= event.x <= 525 and 285 <= event.y <= 355):
# checks if Kruskal button selected on main screen
data.kruskalPlay = True
data.menu = False
if (data.menu and data.instructions == False
and 175 <= event.x <= 525 and 420 <= event.y <= 505):
# checks if Prim button selected on main screen
data.primPlay = True
data.menu = False
if (data.gameWon and 235 <= event.x <= 470
and 540 <= event.y <= 610):
# checks if back to main menu option selected on game won screen
# and then re-initializes new puzzle for user
data.gameWon = False
data.menu = True
if data.kruskalPlay:
data.kruskalPlay = False
data.kruskalPuzzle = Puzzle(data.rows, data.cols, data.cellSize,
data.width-data.margin, data.height-data.margin,
"kruskal")
if data.primPlay:
data.primPlay = False
data.primPuzzle = Puzzle(data.rows, data.cols, data.cellSize,
data.width-data.margin, data.height-data.margin,
"prim")
if (data.gameWon == False and
data.instructions == False and
(data.primPlay or data.kruskalPlay) and data.gameOver == False):
if (data.gamePaused == False and
625 <= event.x <= 675 and 125 <= event.y <= 152):
data.instructions = True
if (data.gamePaused and 0 <= event.x <= data.width and
0 <= event.y <= data.height):
data.gamePaused = False
if (625 <= event.x <= 675 and 180 <= event.y <= 210):
data.gamePaused = True
if (data.gamePaused == False and 630 <= event.x <= 655
and 250 <= event.y <= 300):
init(data)
return None
def keyPressed(event, data):
# use event.char and event.keysym
if (event.char == "r"):
# restarts game
init(data)
return None
if (event.char == "q"):
# quits game
data.gameOver = True
if (event.char == "p") and (data.gameOver == False):
# pauses or un-pauses game if game is not over
data.gamePaused = not(data.gamePaused)
if (data.gameOver == False and data.menu == False and
data.gamePaused == False and data.instructions == False):
if (event.keysym == "Up" or event.keysym == "Down" or
event.keysym == "Right" or event.keysym == "Left"):
move = None
if data.kruskalPlay:
move = data.kruskalPuzzle.game.onKeyPressed(event.keysym)
elif data.primPuzzle:
move = data.primPuzzle.game.onKeyPressed(event.keysym)
if move == True:
data.gameWon = True
def timerFired(data):
# handles the time elapsed for game
if (data.kruskalPlay or data.primPlay) and data.gameOver == False:
data.time += 1
def redrawAll(canvas, data):
# draw in canvas
canvas.create_rectangle(0,0,data.width,data.height,fill="beige")
drawBoard(canvas, data)
def drawBoard(canvas, data):
# checks state of board before drawing
if data.gameOver:
drawGameOver(canvas, data)
elif data.gamePaused:
drawGamePaused(canvas, data)
elif data.instructions:
drawInstructions(canvas, data)
else:
canvas.create_image(0, 0, anchor=NW, image=data.maze_bg)
if data.menu:
drawMainScreen(canvas, data)
else:
drawGame(canvas, data)
def drawMainScreen(canvas, data):
# got stipple from http://www.kosbie.net/cmu/fall-11/15-112/handouts/
# misc-demos/src/semi-transparent-stipple-demo.py
startX, startY = data.width/2, data.height - 80
# dark slate blue
canvas.create_text(startX, startY, text="Super Maze!",
font="Georgia 60 bold", fill="gray30")
startY -= 150
canvas.create_image(startX, startY, image=data.primBtn)
startY -= 150
canvas.create_image(startX, startY, image=data.kruskalBtn)
startY -= 150
canvas.create_image(startX, startY, image=data.instructionsBtn)
def drawGameOver(canvas, data):
# got stipple from http://www.kosbie.net/cmu/fall-11/15-112/handouts/
# misc-demos/src/semi-transparent-stipple-demo.py
message = "Press 'r' to \nto restart game"
score = str(data.score)
minutes = data.time//60
seconds = data.time%60
canvas.create_rectangle(0, 0, data.width, data.height, fill="pink",
stipple="gray75")
canvas.create_text(data.width/2, 100, text="Game over!",
fill="gray9", font="Georgia 45 bold")
canvas.create_text(data.width/2, data.height/2,
text="Time: %d:%d \nScore: " % (minutes, seconds) + score,
fill="gray9", font="Georgia 30 bold")
canvas.create_text(data.width/2, data.height - 80,text=message,
fill="gray9", font="Georgia 30 bold")
def drawGamePaused(canvas, data):
# got stipple from http://www.kosbie.net/cmu/fall-11/15-112/handouts/
# misc-demos/src/semi-transparent-stipple-demo.py
message = """Press 'p' to un-pause game
or press anywhere on screen"""
canvas.create_rectangle(0, 0, data.width, data.height, fill="cyan",
stipple="gray75")
canvas.create_text(data.width/2, data.height/2, text=message, fill="gray9",
font="Georgia 30 bold")
def drawInstructions(canvas, data):
# draws instructions for puzzles
message = data.mazeInstructions
canvas.create_rectangle(0, 0, data.width, data.height, fill="orange",
stipple="gray75")
canvas.create_text(data.width/2, data.height/2, text=message,
fill="gray9", font="Georgia 20 bold")
def drawGame(canvas, data):
# checks if game has been won or still being played- draws accordingly
if data.gameWon:
message = "CONGRATULATIONS!"
canvas.create_rectangle(0, 0, data.width, data.height, fill="orange",
stipple="gray75")
canvas.create_text(data.width/2, 100, text=message,
fill="gray9", font="Georgia 30 bold")
message = "You finished the maze!"
canvas.create_text(data.width/2, data.height/2, text=message,
fill="gray9", font="Georgia 25 bold")
canvas.create_image(data.width/2, data.height - 100, image=data.backBtn)
else:
drawMargins(canvas, data)
drawPuzzle(canvas, data)
def drawMargins(canvas, data):
# just branch off to the different margins
drawRightMargin(canvas, data)
drawBottomMargin(canvas, data)
def drawPuzzle(canvas, data):
# draw kruskal or prim
if data.kruskalPlay:
data.kruskalPuzzle.game.draw(canvas, data.exit)
elif data.primPlay:
data.primPuzzle.game.draw(canvas, data.exit)
def drawRightMargin(canvas, data):
# draws right margin for playing screen
startX = data.width - data.margin
center = (startX + data.width)/2
minutes = data.time//60
seconds = data.time%60
startY = 40
fontSize = 25
canvas.create_text(center, startY, text="Timer:", font="Georgia 10 bold")
startY += fontSize
canvas.create_text(center, startY,
text= str(minutes) + " mins " + str(seconds) + " secs",
font="Georgia 10 bold")
startY += fontSize
canvas.create_text(center, startY, text="Score: " + str(data.score),
font="Georgia 10 bold")
createButtons(canvas, data, startX, startY, center)
def createButtons(canvas, data, startX, startY, center):
# creates buttons on right margin
buttonSize = 20
spacing = 40
startY += buttonSize + spacing
canvas.create_image(center, startY, image=data.helpBtn)
startY += buttonSize + spacing
canvas.create_image(center, startY, image=data.pauseBtn)
startY += buttonSize + spacing
canvas.create_image(center, startY, image=data.restartBtn)
def drawBottomMargin(canvas, data):
# handles drawing the instructions on the bottom part of the screen
startY = data.height - data.margin
middleY = (startY + data.height)/2
startX = 10
buttonSize = 20
message = """Helpful
Keys"""
canvas.create_text(startX+buttonSize*2, middleY, text=message,
fill="gray9", font="Georgia 15")
spacing = 40
middleX = data.width/2 - spacing*3
canvas.create_text(middleX, startY+spacing, text="Press 'r' to restart",
fill="gray9", font="Georgia 10")
canvas.create_text(middleX, data.height-spacing, text="Press 'q' to quit game",
fill="gray9", font="Georgia 10")
middleX = data.width - spacing*6
canvas.create_text(middleX, data.height-spacing,
text="Press 'p' to pause or un-pause game",
fill="gray9", font="Georgia 10")
canvas.create_text(middleX, startY+spacing, text="Press 'i' for instructions",
fill="gray9", font="Georgia 10")
####################################
# use the run function as-is
####################################
def run(rows, cols, width=700, height=650):
def redrawAllWrapper(canvas, data):
canvas.delete(ALL)
redrawAll(canvas, data)
# canvas.update()
# the time I rekt Python and my computer and caused a low-level
# system error :')
def mousePressedWrapper(event, canvas, data):
mousePressed(event, data)
redrawAllWrapper(canvas, data)
def keyPressedWrapper(event, canvas, data):
keyPressed(event, data)
redrawAllWrapper(canvas, data)
def timerFiredWrapper(canvas, data):
timerFired(data)
redrawAllWrapper(canvas, data)
# pause, then call timerFired again
canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)
# create the root so images can be loaded
root = Tk()
# Set up data and call init
class Struct(object): pass
data = Struct()
data.width = width
data.height = height
# this is the hack-y part
data.rows = rows
data.cols = cols
data.timerDelay = 1000 # milliseconds
init(data)
# create the canvas
canvas = Canvas(root, width=data.width, height=data.height)
canvas.pack()
# set up events
root.bind("<Button-1>", lambda event:
mousePressedWrapper(event, canvas, data))
root.bind("<Key>", lambda event:
keyPressedWrapper(event, canvas, data))
# root.bind("<>")
timerFiredWrapper(canvas, data)
# and launch the app
root.mainloop()
# blocks until window is closed
print("bye!")
run(10, 10, 700, 680)
# you can mess with any of these 4 values and the game should still look alright |
df0d9ec77a96d471c4ff47bef12ee6181e308649 | jemand2001/adventofcode2020 | /day_10.py | 1,261 | 3.578125 | 4 | from utils import run, test, cached
from typing import List, Tuple
from collections import Counter
examples = ("""16
10
15
5
1
11
7
19
6
12
4""", """28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3""")
# @test(examples=examples)
@run()
def day_10_1(adapters: List[int]):
adapters.sort()
# phone = adapters[-1] + 3
# print("phone adapter:", phone)
differences = Counter()
adapters.insert(0, 0)
adapters.append(adapters[-1] + 3)
while len(adapters) > 1:
current = adapters.pop(0)
next_adapter = adapters[0]
# print(f'current: {current}; next: {next_adapter}')
differences += Counter([next_adapter - current])
# differences += Counter([3])
return differences[1] * differences[3]
@cached
def combinations(adapters: Tuple[int], current):
if current == adapters[-1]:
return 1
return sum(combinations(adapters, i) for i in adapters if current < i <= current + 3)
# @test(examples=examples)
@run()
def day_10_2(adapters: List[int]):
adapters.sort()
return sum(combinations(tuple(adapters), i) for i in adapters if i <= 3)
if __name__ == '__main__':
# print("1-steps * 3-steps:", day_10_1())
print("arrangements:", day_10_2())
|
e46c7fb3bdf740fe741c7e5580bfd85d17ee5bb0 | nekapoor7/Python-and-Django | /GREEKSFORGREEKS/List/swap_position.py | 274 | 4.09375 | 4 | #Python3 program to swap elements
# at given positions
def swapElement(list,pos1,pos2):
list[pos1],list[pos2] = list[pos2] , list[pos1]
return list1
list1 = list(map(int,input().split()))
pos1 = int(input())
pos2 = int(input())
print(swapElement(list1,pos1,pos2)) |
0c0218b74a9eda64b228f046a5afbddabffdaede | mkabajah/Recursive_Univirsal_Diff | /Recursive_Univirsal_Diff.py | 9,812 | 3.703125 | 4 | """
@copyright:
This code related to Eng.Mohammad Kabajah
email: Kabajah.mohammad@gmail.com
@author:
Mohammad Kabajah
@Contact:
Kabajah.mohammad@gmail.com
@date:
Nov 24, 2014
@Purpose:
Getting the Deep Difference of dictionaries, iterables,
strings and other objects. It will recursively look for all the changes.
"""
from __future__ import print_function
import difflib
import datetime
import json
from collections import Iterable
class Extensive_Diff(object):
"""
Deep Difference of dictionaries, iterables, strings and other objects. It will recursively look for all the changes.
the Function work with(String ,Tuples ,List ,Set ,dictionary , combination of these types with multiple stages)
Parameters
----------
t1 : Any Pyhton Object(List, dictionary, string that has __dict__
This is the first item to be compared to the second item
t2 : Any Pyhton Object(List, dictionary, string that has __dict__
The second item to be compared to the first one
Returns
-------
A Extensive_Diff object that has already calculated the difference of the 2 items. You can access the result in the 'changes' attribute
Examples
--------
Importing
>>> from Recursive_Univirsal_Diff import Extensive_Diff
>>> from pprint import pprint
>>> from __future__ import print_function
Same object returns empty dict
>>> t1 = {'instantID':1, 'username':'kabajah', 'password':12345}
>>> t2 = t1
>>> ddiff = Extensive_Diff(t1, t2)
>>> print (ddiff.changes)
{}
Type of an item has changed
>>> t1 = {'instantID':1, 'username':'kabajah', 'password':12345}
>>> t2 = {'instantID':'1', 'username':'kabajah', 'password':12345}
>>> ddiff = Extensive_Diff(t1, t2)
>>> print (ddiff.changes)
{'type_changes': ["root['instantID']: 1=<type 'int'> vs. 1=<type 'str'>"]}
Value of an item has changed
>>> t1 = {'instantID':1, 'username':'kabajah', 'password':12345}
>>> t2 = {'instantID':1, 'username':'kabajah', 'password':55555}
>>> ddiff = Extensive_Diff(t1, t2)
>>> print (ddiff.changes)
{'values_changed': ['root['password']: 12345 ====>> 55555']}
Item added and/or removed
>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = Extensive_Diff(t1, t2)
>>> pprint (ddiff.changes)
{'dic_item_added': ['root[5, 6]'],
'dic_item_removed': ['root[4]'],
'values_changed': ['root[2]: 2 ====>> 4']}
String difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"Mohammad", "b":"Kabajah"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"Mohammad", "b":"Kabajah!!!!"}}
>>> ddiff = Extensive_Diff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'values_changed': [ 'root[2]: 2 ====>> 4',
"root[4]['b']:\n--- \n+++ \n@@ -1 +1 @@\n-Kabajah\n+Kabajah!!!!"]}
>>>
#for accessing the differences from the ddiff object.
>>> print (ddiff.changes['values_changed'][1])
root[4]['b']:
---
+++
@@ -1 +1 @@
-Kabajah
+Kabajah!!!!
String difference 2
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = Extensive_Diff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'values_changed': [ "root[4]['b']:\n--- \n+++ \n@@ -1,5 +1,4 @@\n-world!\n-Goodbye!\n+world\n 1\n 2\n End"]}
>>>
>>> print (ddiff.changes['values_changed'][0])
root[4]['b']:
---
+++
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
1
2
End
Type change
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"Mohammad_Kabajah"}}
>>> ddiff = Extensive_Diff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'type_changes': [ "root[4]['b']: [1, 2, 3]=<type 'list'> vs. Mohammad_Kabajah=<type 'str'>"]}
List difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = Extensive_Diff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'list_removed': ["root[4]['b']: [3]"]}
List difference 2: ** Note that it DOES NOT take order into account(Order not Matter in Our Test)
>>> # Note that it DOES NOT take order into account
... t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2]}}
>>> ddiff = Extensive_Diff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ }
List that contains dictionary:
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = Extensive_Diff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
'values_changed': ["root[4]['b'][2][1]: 1 ====>> 3"]}
"""
def __init__(self, t1, t2):
"""
Once the object is initialized, the changes will be filled since
it will call the diff_iterable.
If no changes found
"""
self.changes = {"type_changes":[],
"dic_item_added":[],
"dic_item_removed":[],
"values_changed":[],
"unprocessed":[],# for further issue
"list_added":[],
"list_removed":[]}
self.diff_iterable(t1, t2)
self.changes = dict((k, v) for k, v in self.changes.iteritems() if v)
def diff_dictionary(self, t1, t2, parent):
"""
takes 2 dictionaries and their parent (in a semi-tree structure handling)
This will process the dictionaries keys and fill the 2 lists:
1- dic_item_added
2- dic_item_removed
It will also call diff_iterable method if an iterable object was found.
"""
t2_keys, t1_keys = [
set(d.keys()) for d in (t2, t1)
]
t_keys_intersect = t2_keys.intersection(t1_keys)
t_keys_added = t2_keys - t_keys_intersect
t_keys_removed = t1_keys - t_keys_intersect
if t_keys_added:
self.changes["dic_item_added"].append("%s%s" % (parent, list(t_keys_added)))
if t_keys_removed:
self.changes["dic_item_removed"].append("%s%s" % (parent, list(t_keys_removed)))
for item in t_keys_intersect:
if isinstance(item, basestring):
item_str = "'%s'" % item
else:
item_str = item
self.diff_iterable(t1[item], t2[item], parent="%s[%s]" % (parent, item_str))
def diff_iterable(self, t1, t2, parent="root"):
"""
This method will take 2 iterable objects and determine the type of change between those 2 iterables
in a recursive manner, the types of change could be:
1- type_changes: for example if value was integer and now it's a string
2- values_changed: for example if value was 5 and changed to anything else
3- unprocessed: if the type could not be processed (unicode or unrecognized data)
4- list_added: new list found in iterable
5- list removed: previous list could not be found in iterable
Any change will be stored in local variables in object.
If the iterable was dictionary, it will call diff_dictionary method.
"""
if type(t1) != type(t2):
self.changes["type_changes"].append("%s: %s=%s vs. %s=%s" % (parent, t1, type(t1), t2, type(t2)))
elif isinstance(t1, basestring):
diff = difflib.unified_diff(t1.splitlines(), t2.splitlines(), lineterm='')
diff = list(diff)
if diff:
diff = ' \n '.join(diff)
self.changes["values_changed"].append("%s:\n %s" % (parent, diff))
elif isinstance(t1, (int, long, float, complex, datetime.datetime)):
if t1 != t2:
self.changes["values_changed"].append("%s: %s ====>> %s" % (parent, t1, t2))
elif isinstance(t1, dict):
self.diff_dictionary(t1, t2, parent)
elif isinstance(t1, Iterable):
try:
t1_set = set(t1)
t2_set = set(t2)
# When we can't make a set since the iterable has unhashable items
except TypeError:
for i, (x, y) in enumerate(zip(t1, t2)):
self.diff_iterable(x, y, "%s[%s]" % (parent, i))
if len(t1) != len(t2):
items_added = [item for item in t2 if item not in t1]
items_removed = [item for item in t1 if item not in t2]
else:
items_added = None
items_removed = None
else:
items_added = list(t2_set - t1_set)
items_removed = list(t1_set - t2_set)
if items_added:
self.changes["list_added"].append("%s: %s" % (parent, items_added))
if items_removed:
self.changes["list_removed"].append("%s: %s" % (parent, items_removed))
else:
try:
t1_dict = t1.__dict__
t2_dict = t2.__dict__
except AttributeError:
pass
else:
self.diff_dictionary(t1_dict, t2_dict, parent)
return
|
7a7427f6e72389b41ef3e0e05963e397c4dbe73f | atul0058/Python_Data_Structures | /week4.py | 2,296 | 4.34375 | 4 | atul='string'
print(atul[1])
print("-----")
for i in atul:
print(i)
print("-----")
atul1="after three hours you will hop in a bus which will be going to Amsterdam"
x=atul1.split() #this returns a list. Always remember, the split funciton gives you a string
print(x)
print("-----")
#line.rstrip vs line.split()
#line.rstrip removes the \n line where as the line.split() removes the gap between
#the words. The former works on removing the spaces between the lines, while the latter works on removing
#the spaces between the words
#if you want to chop between spaces use line.split()
#if you want to chop between some specail character then use line.split(':')
"""
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.
You can download the sample data at http://www.py4e.com/code3/romeo.txt
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line=line.rstrip()
for x in line.split():
if x not in lst:
lst.append(x)
lst.sort()
print(lst)
"""
"""
Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.
Hint: make sure not to include the lines that start with 'From:'.
fname = input("Enter file name: ")
if len(fname) < 1 :
fname = "mbox-short.txt"
fh = open(fname)
count=0
lst=[]
for line in fh:
line.rstrip()
if line.startswith('From '):
z=line.split()
z1=z[1]
lst.append(z1)
count=count+1
for i in lst:
print(i)
print("There were", count ,"lines in the file with From as the first word")
"""
You can download the sample data at http://www.py4e.com/code3/mbox-short.txt
|
6a9b52f819c13ae1a4fbeb2848b0afac94873a71 | gokou00/python_programming_challenges | /coderbyte/MaxSubarray.py | 261 | 3.75 | 4 | def MaxSubarray(arr):
max_ending_here = max_so_far = arr[0]
for x in arr[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
print(MaxSubarray( [-2, 5, -1, 7, -3])) |
170391e61e272dfffab2f52e12c625a5a87ccfdc | jagannath/bacterialoperons | /gen_fgoc_calc.py | 15,835 | 3.828125 | 4 | #! usr/bin/python
# Script calculates the gen-fgoc score for every organisms. The accession number of the organisms is passed and it calculates the gen-fgoc score. The gen-fgoc score is the 2 * number of conserved adjacent gene pairs (correct direction) / # gene_pairs (ecoli) + # gene_pairs (orgX). This can be normalized with the score obtained between E.coli and E.coli.
from __future__ import division
import os
import sys
import shelve
import pickle
def open_file(name_file, open_status = 'r'):
""" This function just opens the file for reading and returns back the file handle for the file. If the file cannot be opened it just exits! It can open and read any type of files. It can also return back the file handle for writing. The default status for opening is to read the file. Note that the file handle is and must be closed in the place from where this function was called """
#Opening and reading/writing the passed file_name """
try:
file = open(name_file,open_status)
except IOError,err: # If the file cannot be opened i am exiting
print "File %s cannot be opened : %s "%(name_file,err.strerror)
sys.exit(0)
return file
def get_acc_nbr(pairs):
"""
@param pairs: Gets the list (makes a set) of all accession_numbers from the gene details of all pairs
@function: parses the list and gets all the accession_numbers. Then makes a set of non-redundant accession_numbers
@returns: set of all the accession_numbers
"""
# Initializing
list_acc_nbr = []
acc_nbr = ''
# (1) Change the string list to eval list
all_pairs = eval(pairs)
# (2) Iterate among the pairs and obtain the 5th element in the 1st pair which is the accession_number
for pair in all_pairs:
# Condition to eliminate those cases where there is no adjacent gene pairs. Also if there is no non adjacent gene pairs it is an empty set.
if not str(pair).startswith('No'):
acc_nbr = (pair[0])[5]
#(3) Add to the list of all_accession_numbers
list_acc_nbr.append(acc_nbr)
else:
list_acc_nbr = []
# (4) Make a set of these accession_numbers (it is non redundant) and return this
return set(list_acc_nbr)
def create_dic_group_pair_acc_nbr(lines,status):
"""
@param lines: This is the set of lines from the walk_in_ecoli_operons_ver2.txt file.
@param status: This is to determine whether we have to calculate between operon pairs(2) or within operon pairs (1)
@function: Makes a dictionary key pair between group_pair : {[list of accession_number of all conserved adjacent genes] | {[list of accession_number of all non adjacent genes]}.
@ return: key: value pair
"""
# Initializing
pair_acc_nbr_dictionary = {}
list_acc_adj = list_acc_non_adj = acc_nbrs = pair = adj_pairs = non_adj_pairs = ''
if status == '1':
# (1) Read through lines and obtain - group_pair, details of adjacent gene pairs, details of non adjacent gene pairs
for line in lines:
if not line.startswith('///'):
pair, adj_pairs, non_adj_pairs = line.split('\t')[1], line.split('\t')[8], line.split('\t')[9] # For within operon pairs
# (2) Obtain the list of accession_numbers for all adjacent pairs
list_acc_adj = get_acc_nbr(adj_pairs)
# (3) Obtain the list of accession_numbers for all non adjacent but conserved gene pairs
#list_acc_non_adj = get_acc_nbr(non_adj_pairs)
# (4) Convert the pair, list_acc_adj, list_acc_non_adj to strings and join accession_numbers
#acc_nbrs = str(list_acc_adj) + '|' + str(list_acc_non_adj)
acc_nbrs = str(list_acc_adj)
# (5) Create dictionary
pair_acc_nbr_dictionary[pair] = acc_nbrs
if status == '2': #Between operon pairs; Very similar but the line split values differ
# (1) Read through the lines and obtain - group_pair, details of adjacent gene pairs and details of non adjacent gene pairs
for line in lines:
pair, adj_pairs, non_adj_pairs = line.split('\t')[0], line.split('\t')[6], line.split('\t')[7]
# (2) Obtain the list of accession_numbers for all adjacent pairs
list_acc_adj = get_acc_nbr(adj_pairs)
# (3) Obtain the list of accession_numbers for all non adjacent but conserved gene pairs
#list_acc_non_adj = get_acc_nbr(non_adj_pairs)
# (4) Convert the pair, list_acc_adj, list_acc_non_adj to strings and join accession_numbers
#acc_nbrs = str(list_acc_adj) + '|' + str(list_acc_non_adj)
acc_nbrs = str(list_acc_adj)
# (5) Create dictionary
pair_acc_nbr_dictionary[pair] = acc_nbrs
return pair_acc_nbr_dictionary
def get_nbr_adjacent_pairs(all_group_pairs, org_nbr, pair_acc_nbr_dictionary):
"""
@param all_group_pairs: This is a list of all group pairs (ref E.coli operonic group pair. But this may change if between walks are considered)
@param org_nbr: Accession number of the organisms to compare with
@param pair_acc_nbr_dictionary: Dictionary - key= group_pair (of ecoli): value set(all organism_accession_number)
@function: Counts the number of times the group pair was conserved in the set of adjacent genes
"""
# Initializing
nbr_adjacent_pairs = 0
all_conserved_pairs = []
#(1) Iterate over all group pairs and obtain a group pair
for pair in all_group_pairs:
# (2) Obtain the value when this group pair is passed as the key
set_adj_acc_nbrs = pair_acc_nbr_dictionary[str(pair)]
# (3) Check if the query_acc_nbr is in the set of adj_acc_nbrs
if org_nbr in set_adj_acc_nbrs:
nbr_adjacent_pairs += 1
all_conserved_pairs.append(pair)
#returns the nbr_adjacent_pairs across all the pairs for that organism
return nbr_adjacent_pairs, all_conserved_pairs
def create_dic_acc_nbrgenes(file_name):
"""
@param file_name: File that has accession_nbr \t nbr_genes
@function: Create dictionary = keys (accession_number): values (number_genes)
"""
# Initializing
acc_nbrgenes_dictionary = {}
# (1) Open file and read lines
ifile = open_file(file_name)
lines = ifile.readlines()
ifile.close()
for line in lines:
# (2) Obtain the accession_number and the number of genes
accession_number, number_genes = line.split('\t')[0], line.split('\t')[1]
# (3) Create the key: value pair
acc_nbrgenes_dictionary[accession_number] = number_genes
return acc_nbrgenes_dictionary
def main(argument):
"""
@param argument: Passed as the accession number of the organsism
@function: Computes the gen-fgoc calculated with respect to E.coli
"""
#Initializing
line = lines = pair = ''
all_group_pairs = []
#assert isinstance(argument,str) #Checks for correct argument
[org_nbr,status] = argument[0],argument[1]
if status == '-2':
# (1) Opens file walk_in_ecoli_operons_ver2.tmp
file_name = 'bw_ecoli_operons_homology_ver6.txt'
ifile = open_file(file_name)
lines = ifile.readlines()
ifile.close()
# (2) Obtain a list of all group_pairs for E.coli (all these are within operon); Applicable only for between operon pairs
all_group_pairs = [line.split('\t')[0] for line in lines if not line.startswith('///')]
# (3) Make dictionary pair between pair and all adjacent conserved acc_nbr
pair_acc_nbr_dictionary = create_dic_group_pair_acc_nbr(lines,'2') #1 is for status - within (1) and between (2)
print pair_acc_nbr_dictionary.keys()[0:20]
# (4) Shelve the pair: acc_nbr dictionary; This is useful only for between operon pairs
shelve_file = os.getcwd() + '/shelve_files/bw_operons_pair:acc_nbrs_dictionary'
s = shelve.open(shelve_file)
for key, value in pair_acc_nbr_dictionary.items():
s[key] = value
s.close()
print "Pair : [Accession numbers] shelved"
print pair_acc_nbr_dictionary.keys()[0:20]
# (5) Pickle list of all group_pairs; This is useful only for between operon pairs
pkl_file = os.getcwd() + '/pkl_files/bw_operons_group_pairs_list'
ofile = open(pkl_file,'wb')
pickle.dump(all_group_pairs, ofile)
ofile.close()
print "All group pairs (between operons) pickled"
# (6) Shelve accession number : number of genes dictionary; This is common to both between and within operon pairs
acc_nbrgenes_dictionary = create_dic_acc_nbrgenes('orgs_acc_nbrgenes.txt')
shelve_file = os.getcwd() + '/shelve_files/acc_nbr:number_genes_dictionary'
s = shelve.open(shelve_file)
for key, value in acc_nbrgenes_dictionary.items():
s[str(key)] = value
s.close()
print acc_nbrgenes_dictionary.keys()[0:10]
print "Accession number : number of genes shelved"
if status == '-1':
# (1) Opens file walk_in_ecoli_operons_ver2.tmp
file_name = 'walk_in_ecoli_operons_ver6_homolog.txt'
ifile = open_file(file_name)
lines = ifile.readlines()
ifile.close()
# (2) Obtain a list of all group_pairs for E.coli (all these are within operon); Applicable only for between operon pairs
all_group_pairs = [line.split('\t')[1] for line in lines if not line.startswith('///')]
# (3) Make dictionary pair between pair and all adjacent conserved acc_nbr
pair_acc_nbr_dictionary = create_dic_group_pair_acc_nbr(lines,'1') #1 is for status - within (1) and between (2)
print pair_acc_nbr_dictionary.keys()[0:20]
# (4) Shelve the pair: acc_nbr dictionary; This is useful only for between operon pairs
shelve_file = os.getcwd() + '/shelve_files/within_operons_pair:acc_nbrs_dictionary'
s = shelve.open(shelve_file)
for key, value in pair_acc_nbr_dictionary.items():
s[key] = value
s.close()
print "Pair : [Accession numbers] shelved"
# (5) Pickle list of all group_pairs; This is useful only for between operon pairs
pkl_file = os.getcwd() + '/pkl_files/within_operons_group_pairs_list'
ofile = open(pkl_file,'wb')
pickle.dump(all_group_pairs, ofile)
ofile.close()
print "All group pairs (within operons) pickled"
# (6) Shelve accession number : number of genes dictionary; This is common to both between and within operon pairs
#acc_nbrgenes_dictionary = create_dic_acc_nbrgenes('orgs_acc_nbrgenes.txt')
#shelve_file = os.getcwd() + '/shelve_files/acc_nbr:number_genes_dictionary'
#s = shelve.open(shelve_file)
#for key, value in acc_nbrgenes_dictionary.items():
#s[str(key)] = value
#s.close()
#print acc_nbrgenes_dictionary.keys()[0:10]
#print "Accession number : number of genes shelved"
if status == '1': # Within operon pair calculation
shelve_file = os.getcwd() + '/shelve_files/acc_nbr:number_genes_dictionary'
acc_nbrgenes_dictionary = shelve.open(shelve_file)
shelve_file = os.getcwd() + '/shelve_files/within_operons_pair:acc_nbrs_dictionary'
pair_acc_nbr_dictionary = shelve.open(shelve_file)
pkl_file = os.getcwd() + '/pkl_files/within_operons_group_pairs_list'
ifile = open(pkl_file)
all_group_pairs = pickle.load(ifile)
ifile.close()
print "All group pairs (within operons) pickled"
print pair_acc_nbr_dictionary[str(['ECHOM_b0002', 'ECHOM_b0003'])]
## (1) Opens file walk_in_ecoli_operons_ver2.tmp
#file_name = 'walk_in_ecoli_operons_ver2.txt'
#ifile = open_file(file_name)
#lines = ifile.readlines()
#ifile.close()
## (2) Obtain a list of all group_pairs for E.coli (all these are within operon)
#all_group_pairs = [line.split('\t')[1] for line in lines if not line.startswith('///')]
## (3) Make dictionary pair between pair and all adjacent conserved acc_nbr
#pair_acc_nbr_dictionary = create_dic_group_pair_acc_nbr(lines,status)
# (4) Get number of conserved adjacent gene pairs
nbr_conserved_adjacent_pairs, all_conserved_pairs = get_nbr_adjacent_pairs(all_group_pairs,org_nbr, pair_acc_nbr_dictionary)
## (5) Make dictionary pair between accession_number and the number of genes. Made a file from the database using table organisms : accession_nbr \t nbr_genes. Filename is orgs_acc_nbrgenes.txt
#acc_nbrgenes_dictionary = create_dic_acc_nbrgenes('orgs_acc_nbrgenes.txt')
# (6) Obtain number of genes for E.coli and the organism passed as argument
nbr_ecoli_genes = acc_nbrgenes_dictionary['NC_000913']
nbr_query_org_genes = (acc_nbrgenes_dictionary[org_nbr])[:-1]
# (7) Calculate the gen_fgoc_score
genome_fgoc = (2 * int(nbr_conserved_adjacent_pairs)) / (int(nbr_ecoli_genes) + int(nbr_query_org_genes))
# (8) Calculate normalized gen_fgoc_score
# Normalizing with the gen_fgoc_score obtained when querying with E.coli accession_number. The value neednt be calculated everytime.
# ref_fgoc_score = 0.2129
ref_fgoc = 0.391012277044
norm_genome_fgoc = (genome_fgoc / ref_fgoc) * 100
print genome_fgoc
print norm_genome_fgoc
# (9) Write the details to file - orgs.genome_fgoc. It is in appending mode and other genome_fgoc can be added when running sequence
info_to_write = '\t'.join(str(item) for item in [org_nbr, nbr_conserved_adjacent_pairs, nbr_query_org_genes, genome_fgoc, norm_genome_fgoc, all_conserved_pairs, '\n'])
ofile = open_file('within_orgs_ref_ecoli_ver6.genome_fgoc','a')
ofile.write(info_to_write)
ofile.close()
if status == '2':
# Opening shelves and unpickling
shelve_file = os.getcwd() + '/shelve_files/bw_operons_pair:acc_nbrs_dictionary'
pair_acc_nbr_dictionary = shelve.open(shelve_file)
pkl_file = os.getcwd() + '/pkl_files/bw_operons_group_pairs_list'
ifile = open(pkl_file)
all_group_pairs = pickle.load(ifile)
ifile.close()
shelve_file = os.getcwd() + '/shelve_files/acc_nbr:number_genes_dictionary'
acc_nbrgenes_dictionary = shelve.open(shelve_file)
print pair_acc_nbr_dictionary[str(['ECHOM_b0004', 'ECHOM_b0005'])]
## (1) Open file - bw_ecoli_operons.ver2.txt; This contains gene pairs between the ecoli operons
#file_name = 'bw_ecoli_operons_homology_ver6.txt.txt'
#ifile = open_file(file_name)
#lines = ifile.readlines()
#ifile.close()
## (2) Obtain a list of all group_pairs for E.coli (all these are between operon)
#all_group_pairs = [line.split('\t')[0] for line in lines]
## (3) Make dictionary pair between pair and all adjacent conserved acc_nbr
#pair_acc_nbr_dictionary = create_dic_group_pair_acc_nbr(lines,status)
# (4) Get number of conserved adjacent gene pairs
nbr_conserved_adjacent_pairs, all_conserved_pairs = get_nbr_adjacent_pairs(all_group_pairs,org_nbr, pair_acc_nbr_dictionary)
## (5) Make dictionary pair between accession_number and the number of genes. Made a file from the database using table organisms : accession_nbr \t nbr_genes. Filename is orgs_acc_nbrgenes.txt
#acc_nbrgenes_dictionary = create_dic_acc_nbrgenes('orgs_acc_nbrgenes.txt')
# (6) Obtain number of genes for E.coli and the organism passed as argument
nbr_ecoli_genes = acc_nbrgenes_dictionary['NC_000913']
nbr_query_org_genes = (acc_nbrgenes_dictionary[org_nbr])[:-1]
# (7) Calculate the gen_fgoc_score
genome_fgoc = (2 * int(nbr_conserved_adjacent_pairs)) / (int(nbr_ecoli_genes) + int(nbr_query_org_genes))
# (8) Calculate normalized gen_fgoc_score
# Normalizing with the gen_fgoc_score obtained when querying with E.coli accession_number. The value neednt be calculated everytime.
ref_fgoc = 0.284225156359
#ref_fgoc = 0.0488765346305
norm_genome_fgoc = (genome_fgoc / ref_fgoc) * 100
# (9) Write the details to file - orgs.genome_fgoc. It is in appending mode and other genome_fgoc can be added when running sequence
info_to_write = '\t'.join(str(item) for item in [org_nbr, nbr_conserved_adjacent_pairs, nbr_query_org_genes,genome_fgoc, norm_genome_fgoc, all_conserved_pairs, '\n'])
ofile = open_file('bw_operons_orgs_ref_ecoli_ver6.genome_fgoc','a')
print norm_genome_fgoc
ofile.write(info_to_write)
ofile.close()
return True
if __name__ == '__main__':
argument = sys.argv[1:]
print "Processing %s ..."%(argument)
main(argument)
import time
print "Script - gen_fgoc_calc.py %s \t Completed \t %s"%(argument, time.strftime("%d %b %Y %H:%M:%S",time.localtime()))
|
a17afce3ff4d127a615411bf093bf59fcfa98c9a | makramjandar/Test_Code | /Problems/compressString.py | 1,758 | 3.734375 | 4 | #!/usr/local/bin/python3
def main():
# Test suite
tests = [None, '', 'AABBCC', 'AAABCCDDDD']
results = [None, '', 'AABBCC', 'A3BCCD4']
for i in range(len(tests)):
temp_result = compress_string(tests[i])
if temp_result == results[i]:
print('PASS: {} returned {}'.format(tests[i], temp_result))
else:
print('FAIL: {} returned {}, should have returned {}'.format(tests[i], temp_result, results[i]))
return 0
def compress_string(string):
'''
Compresses a string such that 'AAABCCDDDD' becomes 'A3BCCD4'. Only compresses
the string if it saves space ('AABBCC' stays same).
Input: string
Output: string
'''
if string is None:
return None
# Check length
s_length = len(string)
if s_length == 0:
return string
# Create compressed string
compressed = []
count = 1
base_char = string[0]
for i in range(1, s_length):
# Current char is different than last one
if string[i] != base_char:
compressed.append(base_char)
if count == 2:
compressed.append(base_char)
elif count > 2:
compressed.append(str(count))
# Change base_char to new character and reset count
base_char = string[i]
count = 1
# Current char is same as last one
else:
count += 1
# Append the last set of chars
compressed.append(base_char)
if count == 2:
compressed.append(base_char)
elif count > 2:
compressed.append(str(count))
if len(compressed) >= s_length:
return string
else:
return ''.join(compressed)
if __name__ == '__main__':
main()
|
7961eb265bee00c41add25f83adc17ee67aa45f8 | doug460/UAV_DL | /UAV_control/Environment.py | 6,971 | 3.609375 | 4 | '''
Created on Feb 20, 2018
@author: dabrown
'''
import GlobalVariables as vars
from UAV import UAV
from Target import Target
import random
import math
import numpy as np
class Environement(object):
'''
This is the environment for the game world
Basically this class will control the world of a UAV tracking a target
'''
def __init__(self):
'''
Constructor
Will create the world based on the globalVariables
estTargets is the estimated position of targets, an object for each target
'''
# create UAV and targets
self.uav = None
self.targets = []
self.populateUAV()
self.populateTargets()
# limit on how large uncertainty for a single target can be
self.uncertLimit = vars.uav_dfov/2
self.uncertLimit_termial = vars.uav_dfov*2
def populateUAV(self):
'''
create a single UAV
'''
# randomly place UAV in search radius reduced by 50%
# random distance and angle
# radius = random.random() * vars.search_radius * 0.5
direction = random.random() * math.pi * 2
# position = np.array([(2*random.random() - 1) * radius, (2*random.random() - 1) * radius])
position = np.array([0.0,0.0])
self.uav = UAV(position=position, direction=direction)
def populateTargets(self):
'''
create targets and populate targets list
'''
# create targets
for indx in range(vars.target_num):
# randomly place target outside of UAV FOV, so this radius is in addition to d_fov
radius = random.random() * vars.uav_dfov/2
# get random angle direction to place target
angle = random.random()*2*math.pi
direction = random.random() * math.pi * 2
position = np.array([(radius+vars.uav_dfov/2)*math.cos(angle),
(radius+vars.uav_dfov/2)*math.sin(angle)]) + self.uav.position
# create target
target = Target(position=position, direction=direction)
# add measurement of initial location
# measured = np.array([target.position]).T
# target.measure(measured)
# create targets
self.targets.append(target)
def getUncert(self,target):
# INPUT:
# target
# OUTPUT:
# uncertainty
# get Pythagorean uncertainty of position for variance
# square root of variance and then go to 97 % confidence (3 * sigma)
uncertainty = 3 * math.sqrt(math.sqrt(target.uncertainty[0,0]**2 + target.uncertainty[0,0]**2))
return uncertainty
def reset(self):
'''
Reset the environment
'''
self.uav = None
self.targets = []
self.populateUAV()
self.populateTargets()
def checkTerminal(self):
'''
Check if should continue
OUTPUT:
shoudlContinue: boolean, if UAV is out of bounds or not
'''
terminal = False
for target in self.targets:
# if targets are outside
if(np.linalg.norm(target.position) > vars.search_radius):
terminal = True
# if uncertainty is too large
# pathagorean and square root of variance
uncertainty = self.getUncert(target)
if(uncertainty > self.uncertLimit_termial):
terminal = True
# if uav is within search radius
test = (np.linalg.norm(self.uav.position) > vars.search_radius) or terminal
return test
def step(self, action):
'''
This makes one step in the environment
INPUT:
action: this is the action for the UAV
defined in global variables
OUPUT:
state: (row vector)
UAV Position (x,y)
Target e position (x,y)
Target uncertainty (x)
Reward: reward for run
+1: detecting target
+0.1: for exploring
-1: if uncertainty > uncertaintyLimit for a single target
terminal:
bool to continue
'''
# move all targets
for target in self.targets:
# update predicitons
if(np.linalg.norm(self.uav.position - target.position) < vars.uav_dfov/2):
# add some noise to the measurement
measured = np.array([target.position]).T + np.random.normal(vars.noiseMean, vars.noiseStd, (2,1))
target.measure(measured)
reward = 1
else:
target.predict()
reward = 0.1
# # move target
target.step()
# three sigma of uncertainty
# so Pathagorean and square root of variance
uncertainty = self.getUncert(target)
if(uncertainty > self.uncertLimit):
cost = uncertainty
reward = -1
# move UAV
self.uav.step(action)
# get state info
# UAV position, direction
# target position, direction relative to UAV, uncertainty
uavPos = self.uav.position
uavDir = self.uav.direction
# state = uavPos
# state = np.append(state, uavDir)
state = None
totalUncertainty = 0
for target in self.targets:
uncertainty = self.getUncert(target)
# state = np.append(state, target.position)
totalUncertainty += uncertainty
# get vector than angle of target relative to uav position and direction
tPos = target.ePosition
tPos = np.array([tPos[0,0],tPos[1,0]])
vect = tPos - uavPos
dist = np.linalg.norm(vect)
angle = np.angle(vect[0] + vect[1]*1j)
angle = angle - uavDir
while angle > math.pi:
angle -= 2*math.pi
while angle < -math.pi:
angle += 2*math.pi
# append distance angle and uncertainty to state
if state is None:
state = np.array([dist])
else:
state = np.append(state,dist)
state = np.append(state,angle)
state = np.append(state, uncertainty)
# just do uncertainty for reward
reward = -totalUncertainty+10
reward = reward/100
return state, reward, self.checkTerminal()
|
f086b8d4f5e1c9e6ea62995a5572ba4a155c07df | Powergears/Python-Repository | /erste-pythonchallenge.py | 156 | 3.890625 | 4 | text = input("Please write a first number: ")
text2 = input("Please write a second number: ")
text3 = text * text2
print("%s*%d=%r") % (text, text2, text3)
|
5ac53654244fe241084ee01629a1c5448091e6f3 | cudjoeab/Object-Oriented_Programming-3 | /01-Reinforcing_OOP/reinforce.py | 697 | 3.5 | 4 | class Task:
def __init__(self, description, due_date):
self.description = description
self.due_date = due_date
def __str__(self):
return f'{self.description} due: {self.due_date}'
def __repr__(self):
return self.__str__
class TodoList:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append(task)
homework = Task('Homework', 'Friday')
laundry = Task('Laundry', 'Sunday')
groceries = Task('Get groceries', 'Saturday')
print(homework)
print(laundry)
print(groceries)
my_list = TodoList()
my_list.add_task(homework)
my_list.add_task(laundry)
my_list.add_task(groceries)
|
90db8db2c1d2b1f68c56c4449b4c65a612723e22 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/c213610e0b9b4c54954dc991b63da0ad.py | 322 | 3.71875 | 4 | def div_by_4(year):
return not year % 4
def div_by_100(year):
return not year % 100
def div_by_400(year):
return not year % 400
def is_leap_year(year):
if div_by_100(year) and not div_by_400(year):
return False
elif div_by_4(year):
return True
else:
return False
|
84814f34bc22f7945563bdfff04690abe34ed9cb | Pepper-Targaryen/PythonStudy | /learnML/day003.py | 807 | 3.640625 | 4 | import pandas as pd
import numpy as np
dataset = pd.read_csv('dataset/50_Startups.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1].values
# Encode categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder = LabelEncoder()
X[:, 3] = labelencoder.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features=[3])
X = onehotencoder.fit_transform(X).toarray()
# Avoid dummy variable trap
X = X[:, 1:]
from sklearn.cross_validation import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(
X, Y, test_size=0.2, random_state=0)
# training
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
Y_pred = regressor.predict(X_test)
print(Y_test)
print(Y_pred.round(2))
|
e32750f662b94ea2665f5f4743a2b896114a8ca0 | jas7553/project-euler | /problem_20.py | 180 | 3.765625 | 4 | '''Jason A Smith'''
def factorial(number):
if number == 1:
return 1
else:
return number * factorial(number - 1)
print(sum([int(i) for i in str(factorial(100))]))
|
562da3552e9669563d24001af8a889338681fd85 | Seemasikander116/ASSIGNMENT-1-2-AND-3 | /ASSIGNMENT 1.py | 1,405 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# Seema Sikander
# seemasikander116@gmail.com
# Assignment #1
# PY04134
# In[4]:
##1. Write python program to print the following string in a specific format.
a="Twinkle"
b="twinkle"
c="little"
d="star"
e="wonder"
f="diamond"
g="world"
print(a, b,c, d+",")
print(" How I ",e +" What You are!")
print(" Up above the " + g +" so high,")
print(" Like a diamomd in the sky,")
print(a, b,c, d+",")
print(" How I ",e +" What You are")
# In[5]:
##2.Calculate the circle
Pi=3.142
r=float(input("Enter radius:"))
area=Pi*r * r
print("Area of Cicle is:")
print(area)
# In[6]:
##3.Sum of two numbers by taking input from user.
x=int(input("Enter value of x:"))
y=int(input("Enter value of y:"))
summ=x+y
print("Sum:")
print(summ)
# In[7]:
##4.Write a program to print current date and time
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
# In[8]:
##5. Write a program take input from user first name and last name and print them in reverse order
firsname = input("Enter First Name : ")
lastname = input("Enter your Last Name : ")
print ( " "+ lastname + " " + firsname)
# In[9]:
##6. Write a python program to get the Python Version you are using.
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
# In[ ]:
|
9f596b9995f248bab6c5f195e732f039855fff3f | WellJay/learn-python3 | /3.advanced/3.ListComprehensions.py | 1,827 | 4.1875 | 4 | '''
列表生成式
列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
举个例子,要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)):
list(range(1, 11))
但如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环:
L = []
for x in range(1, 11):
L.append(x * x)
但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的list:
'''
# tips:写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来,十分有用,多写几次,很快就可以熟悉这种语法。
l = [x * x for x in range(1, 11)]
print(l)
# tips:筛选出仅偶数的平方
l = [x * x for x in range(1, 11) if x % 2 == 0]
print(l)
# tips:还可以使用两层循环,可以生成全排列
l = [m + n for m in 'ABC' for n in '123']
print(l)
# tips:运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现
import os
files = [d for d in os.listdir('.')]
print(files)
# ['1.Slice.py', '2.Iteration.py', '3.ListComprehensions.py']
# tips:for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:
d = {'x': 'A', 'y': 'B', 'z': 'C'}
for k, v in d.items():
print(k, '=', v)
# z = C
# x = A
# y = B
d = {'x': 'A', 'y': 'B', 'z': 'C' }
l = [k + '=' + v for k, v in d.items()]
print(l)
# ['z=C', 'y=B', 'x=A']
# 最后把一个list中所有的字符串变成小写
L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s for s in L1 if isinstance(s, str)]
print(L2)
# ['Hello', 'World', 'Apple'] |
5047d214a8c793393a651903eb38d43f0302b751 | CodeHemP/CAREER-TRACK-Data-Scientist-with-Python | /09_Introduction to Data Visualization with Seaborn/03_Visualizing a Categorical and a Quantitative Variable/01_Count plots.py | 1,569 | 4.3125 | 4 | '''
01 - Count plots
In this exercise, we'll return to exploring our dataset that
contains the responses to a survey sent out to young people.
We might suspect that young people spend a lot of time on the
internet, but how much do they report using the internet each
day? Let's use a count plot to break down the number of survey
responses in each category and then explore whether it changes
based on age.
As a reminder, to create a count plot, we'll use the catplot()
function and specify the name of the categorical variable to
count (x=____), the Pandas DataFrame to use (data=____), and the
type of plot (kind="count").
Seaborn has been imported as sns and matplotlib.pyplot has been
imported as plt.
Instructions 1/3
- Use sns.catplot() to create a count plot using the survey_data
DataFrame with "Internet usage" on the x-axis.
'''
# Create count plot of internet usage
sns.catplot(x='Internet usage',
data=survey_data,
kind='count')
# Show plot
plt.show()
'''
Instructions 2/3
- Make the bars horizontal instead of vertical.
'''
# Change the orientation of the plot
sns.catplot(y="Internet usage",
data=survey_data,
kind="count")
# Show plot
plt.show()
'''
Instructions 3/3
- Create column subplots based on "Age Category", which separates
respondents into those that are younger than 21 vs. 21 and older.
'''
# Create column subplots based on age category
sns.catplot(y="Internet usage", data=survey_data,
kind="count", col='Age Category')
# Show plot
plt.show()
|
4cb4e8d3373c086518bd6c83921f240b852fa4cb | RivasCVA/AlgoShell | /mvp/AlgoShell/solutions/sales_path.py | 543 | 3.75 | 4 | def get_cheapest_cost(rootNode):
return getMinSalesPath(rootNode)
def getMinSalesPath(node):
if not node.children:
return node.cost
childSums = [getMinSalesPath(child) for child in node.children]
return node.cost + min(childSums)
# NOTE: This Node class should be kept commented for the user to see.
# An exact version is also used in the test cases.
class Node:
# Constructor to create a new node
def __init__(self, cost):
self.cost = cost
self.children = []
self.parent = None
|
95a9901d417313b455dce96f188d841f2a3b0b11 | ishauchuk/crash_course | /3.3.py | 215 | 4 | 4 | cars = ['Ferrari', 'Lamborghini', 'Buggati', 'McLaren']
print(f'My favorite auto is {cars[0]}.')
print(f"{cars[1]} is named cars bull's names.")
print(f"{cars[-1]} is one cars's company from my list outside Italy.") |
868fc123255830d3a1dc03a2be09530320baab50 | happyrabbit456/hellopython | /src/withs.py | 1,199 | 3.796875 | 4 |
def m2():
f = open("output.txt", "w")
try:
f.write("python之禅")
except IOError:
print("oops error")
finally:
f.close()
# 一种更加简洁、优雅的方式就是用 with 关键字。
# open 方法的返回值赋值给变量 f,当离开 with 代码块的时候,
# 系统会自动调用 f.close() 方法,
# with 的作用和使用 try/finally 语句是一样的。
def m3():
with open("output.txt", "w") as f:
f.write("Python之禅")
class my_file():
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
print("entering")
self.f = open(self.filename, self.mode)
return self.f
def __exit__(self, *args):
print("will exit")
self.f.close()
from contextlib import contextmanager
@contextmanager
def my_open(path, mode):
f = open(path, mode)
yield f
f.close()
if __name__=='__main__':
m2()
m3()
with my_file('out.txt', 'w') as f:
print("writing")
f.write('hello, python')
with my_open('out.txt', 'w') as f:
f.write("hello , the simplest context manager")
|
158e339371c3b0c796f9f2b63071b19e8b4ab15e | JeffreyLinWeiYou/flask_project | /flaskproject/blog_simple/app/app.py | 11,294 | 3.734375 | 4 | '''
學習http://charlesleifer.com/blog/how-to-make-a-flask-blog-in-one-hour-or-less/
簡單的網誌配置
使用sqlite資料庫
需要的庫
Flask, a lightweight web framework.
Peewee, for storing entries in the database and executing queries.
pygments, syntax highlighting with support for a ton of different languages.
markdown, formatting for our entries.
micawber, for converting URLs into rich content objects. For example if you wanted to embed a YouTube video, just place the URL to the video in your post and a video player will automagically appear in its place.
BeautifulSoup, required by micawber for parsing HTML.
'''
import datetime
import functools
import os
import re
import urllib
from flask import (Flask, flash, Markup, redirect, render_template, request,
Response, session, url_for)
from markdown import markdown
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.extensions.extra import ExtraExtension
from micawber import bootstrap_basic, parse_html
from micawber.cache import Cache as OEmbedCache
from peewee import *
from playhouse.flask_utils import FlaskDB, get_object_or_404, object_list
from playhouse.sqlite_ext import *
# Blog configuration values.
# You may consider using a one-way hash to generate the password, and then
# use the hash again in the login view to perform the comparison. This is just
# for simplicity.
ADMIN_PASSWORD = 'secret'
APP_DIR = os.path.dirname(os.path.realpath(__file__))
# The playhouse.flask_utils.FlaskDB object accepts database URL configuration.
DATABASE = 'sqliteext:///%s' % os.path.join(APP_DIR, 'blog.db')
DEBUG = False
# The secret key is used internally by Flask to encrypt session data stored
# in cookies. Make this unique for your app.
SECRET_KEY = 'shhh, secret!'
# This is used by micawber, which will attempt to generate rich media
# embedded objects with maxwidth=800.
SITE_WIDTH = 800
# Create a Flask WSGI app and configure it using values from the module.
app = Flask(__name__)
app.config.from_object(__name__)
# FlaskDB is a wrapper for a peewee database that sets up pre/post-request
# hooks for managing database connections.
flask_db = FlaskDB(app)
# The `database` is the actual peewee database, as opposed to flask_db which is
# the wrapper.
database = flask_db.database
# Configure micawber with the default OEmbed providers (YouTube, Flickr, etc).
# We'll use a simple in-memory cache so that multiple requests for the same
# video don't require multiple network requests.
oembed_providers = bootstrap_basic(OEmbedCache())
# The Entry model will have the following columns:
#
# title
# slug: URL-friendly representation of the title.
# content: markdown-formatted entry.
# published: boolean flag indicating whether the entry is published (visible on site).
# timestamp: time the entry is created.
# id: peewee automatically will create an auto-incrementing primary key for us, so we don't need to define this explicitly.
# The search index will be stored using the FTSEntry model class:
#
# docid: The primary key of the indexed entry. This field is automatically created on tables using the SQLite full-text-search extension, and supports fast lookups. We will explicitly set it to the value of it's corresponding Entry primary key, thus acting like a foreign-key.
# content: Search content for the given entry.
class Entry(flask_db.Model):
title = CharField()
slug = CharField(unique=True)
content = TextField()
published = BooleanField(index=True)
timestamp = DateTimeField(default=datetime.datetime.now, index=True)
@property
def html_content(self):
"""
Generate HTML representation of the markdown-formatted blog entry,
and also convert any media URLs into rich media objects such as video
players or images.
"""
hilite = CodeHiliteExtension(linenums=False, css_class='highlight')
extras = ExtraExtension()
markdown_content = markdown(self.content, extensions=[hilite, extras])
oembed_content = parse_html(
markdown_content,
oembed_providers,
urlize_all=True,
maxwidth=app.config['SITE_WIDTH'])
return Markup(oembed_content)
def save(self, *args, **kwargs):
# Generate a URL-friendly representation of the entry's title.
if not self.slug:
self.slug = re.sub('[^\w]+', '-', self.title.lower()).strip('-')
ret = super(Entry, self).save(*args, **kwargs)
# Store search content.
self.update_search_index()
return ret
def update_search_index(self):
# Create a row in the FTSEntry table with the post content. This will
# allow us to use SQLite's awesome full-text search extension to
# search our entries.
exists = (FTSEntry
.select(FTSEntry.docid)
.where(FTSEntry.docid == self.id)
.exists())
content = '\n'.join((self.title, self.content))
if exists:
(FTSEntry
.update({FTSEntry.content: content})
.where(FTSEntry.docid == self.id)
.execute())
else:
FTSEntry.insert({
FTSEntry.docid: self.id,
FTSEntry.content: content}).execute()
@classmethod
def public(cls):
return Entry.select().where(Entry.published == True)
@classmethod
def drafts(cls):
return Entry.select().where(Entry.published == False)
@classmethod
def search(cls, query):
words = [word.strip() for word in query.split() if word.strip()]
if not words:
# Return an empty query.
return Entry.select().where(Entry.id == 0)
else:
search = ' '.join(words)
# Query the full-text search index for entries matching the given
# search query, then join the actual Entry data on the matching
# search result.
return (Entry
.select(Entry, FTSEntry.rank().alias('score'))
.join(FTSEntry, on=(Entry.id == FTSEntry.docid))
.where(
FTSEntry.match(search) &
(Entry.published == True))
.order_by(SQL('score')))
class FTSEntry(FTSModel):
content = TextField()
class Meta:
database = database
# Adding login and logout functionality
def login_required(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
if session.get('logged_in'):
return fn(*args, **kwargs)
return redirect(url_for('login', next=request.path))
return inner
@app.route('/login/', methods=['GET', 'POST'])
def login():
next_url = request.args.get('next') or request.form.get('next')
if request.method == 'POST' and request.form.get('password'):
password = request.form.get('password')
# TODO: If using a one-way hash, you would also hash the user-submitted
# password and do the comparison on the hashed versions.
if password == app.config['ADMIN_PASSWORD']:
session['logged_in'] = True
session.permanent = True # Use cookie to store session.
flash('You are now logged in.', 'success')
return redirect(next_url or url_for('index'))
else:
flash('Incorrect password.', 'danger')
return render_template('login.html', next_url=next_url)
@app.route('/logout/', methods=['GET', 'POST'])
def logout():
if request.method == 'POST':
session.clear()
return redirect(url_for('login'))
return render_template('logout.html')
@app.route('/')
def index():
search_query = request.args.get('q')
if search_query:
query = Entry.search(search_query)
else:
query = Entry.public().order_by(Entry.timestamp.desc())
# The `object_list` helper will take a base query and then handle
# paginating the results if there are more than 20. For more info see
# the docs:
# http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#object_list
return object_list(
'index.html',
query,
search=search_query,
check_bounds=False)
def _create_or_edit(entry, template):
if request.method == 'POST':
entry.title = request.form.get('title') or ''
entry.content = request.form.get('content') or ''
entry.published = request.form.get('published') or False
if not (entry.title and entry.content):
flash('Title and Content are required.', 'danger')
else:
# Wrap the call to save in a transaction so we can roll it back
# cleanly in the event of an integrity error.
try:
with database.atomic():
entry.save()
except IntegrityError:
flash('Error: this title is already in use.', 'danger')
else:
flash('Entry saved successfully.', 'success')
if entry.published:
return redirect(url_for('detail', slug=entry.slug))
else:
return redirect(url_for('edit', slug=entry.slug))
return render_template(template, entry=entry)
@app.route('/create/', methods=['GET', 'POST'])
@login_required
def create():
return _create_or_edit(Entry(title='', content=''), 'create.html')
@app.route('/drafts/')
@login_required
def drafts():
query = Entry.drafts().order_by(Entry.timestamp.desc())
return object_list('index.html', query, check_bounds=False)
@app.route('/<slug>/')
def detail(slug):
if session.get('logged_in'):
query = Entry.select()
else:
query = Entry.public()
entry = get_object_or_404(query, Entry.slug == slug)
return render_template('detail.html', entry=entry)
@app.route('/<slug>/edit/', methods=['GET', 'POST'])
@login_required
def edit(slug):
entry = get_object_or_404(Entry, Entry.slug == slug)
return _create_or_edit(entry, 'edit.html')
@app.template_filter('clean_querystring')
def clean_querystring(request_args, *keys_to_remove, **new_values):
# We'll use this template filter in the pagination include. This filter
# will take the current URL and allow us to preserve the arguments in the
# querystring while replacing any that we need to overwrite. For instance
# if your URL is /?q=search+query&page=2 and we want to preserve the search
# term but make a link to page 3, this filter will allow us to do that.
querystring = dict((key, value) for key, value in request_args.items())
for key in keys_to_remove:
querystring.pop(key, None)
querystring.update(new_values)
return urllib.urlencode(querystring)
# Initialization code
@app.errorhandler(404)
def not_found(exc):
return Response('<h3>Not found</h3>'), 404
def main():
database.create_tables([Entry, FTSEntry], safe=True)
app.run(debug=True)
if __name__ == '__main__':
main()
|
d662b53e82fb0084779167e13cef30f7ce2f0498 | Annal-L/pythonProject | /Operators.py | 3,311 | 4.28125 | 4 | # Arithmetic operations
n1 = int(input('Enter First number: '))
n2 = int(input('Enter Second number '))
add = n1 + n2
sub = n1 - n2
mul = n1 * n2
div = n1 / n2
floor_div = n1 // n2
power = n1 ** n2
modulus = n1 % n2
print('Addition of ',n1 ,'and' ,n2 ,'is :',add)
print('Subtraction of ',n1 ,'and' ,n2 ,'is :',sub)
print('Multiplication of' ,n1 ,'and' ,n2 ,'is :',mul)
print('Division of ',n1 ,'and' ,n2 ,'is :',div)
print('Floor Division of ',n1 ,'and' ,n2 ,'is :',floor_div)
print('Exponent of ',n1 ,'and' ,n2 ,'is :',power)
print('Modulus of ',n1 ,'and' ,n2 ,'is :',modulus)
print('\n')
# Assignment operators
a = 3
temp = 18
temp += a # Using += Operator
print("The Value of the temp after using += Operator is: ", temp )
temp -= a # Using -= Operator
print("The Value of the temp after using -= Operator is: ", temp )
temp *= a # Using *= Operator
print("The Value of the temp after using *= Operator is: ", temp )
temp //= a # Using //= Operator
print("The Value of the temp after using //= Operator is: ", temp )
temp **= a # Using **= Operator
print("The Value of the temp after using **= Operator is: ", temp )
temp /= a # Using /= Operator
print("The Value of the temp after using /= Operator is: ", temp )
temp %= a # Using %= Operator
print("The Value of the temp after using %= Operator is: ", temp )
x = 5
y = 12
x &= y # Using &= Operator
print("The Value of the x after using &= Operator is: ", x)
x |= 9 # Using |= Operator
print("The Value of the x after using |= Operator is: ", x)
x ^= y # Using ^= Operator
print("The Value of the x after using ^= Operator is: ", x)
print('\n')
# Comparison operators
x = 14
y = 16
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
print('\n')
# Comparison operators
if 1 < 2 and 4 > 2:
print("condition true")
if 1 > 2 and 4 > 10:
print("condition false")
if 4 < 10 or 1 < 2:
print("condition true")
x = False
if not x :
print("condition met")
else:
print("condition not met")
print('\n')
# Identity Operators
# compare the objects,
x = ["Pen", "Pencil"]
y = ["Pen", "Pencil"]
z = x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y,
# even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is"
# and "==": this comparison returns True
# because x is equal to y
print('\n')
# Membership Operators
# in , not in
# test if a sequence is presented in an object
x = ["Pen", "Pencil"]
print("eraser" not in x)
print('\n')
# Bitwise Operators
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b; # 12 = 0000 1100
print ("Line 1 - Value of c is ", c)
c = a | b; # 61 = 0011 1101
print ("Line 2 - Value of c is ", c)
c = a ^ b; # 49 = 0011 0001
print ("Line 3 - Value of c is ", c)
c = ~a; # -61 = 1100 0011
print ("Line 4 - Value of c is ", c)
c = a << 2; # 240 = 1111 0000
print ("Line 5 - Value of c is ", c)
c = a >> 2; # 15 = 0000 1111
print ("Line 6 - Value of c is ", c)
print('\n') |
c3c9ed77ec3715181eba74def5fd45e35db9aabd | chanyoonzhu/leetcode-python | /1597-Build_Binary_Expression_Tree_From_Infix_Expression.py | 1,180 | 3.875 | 4 | # Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
"""
- stack (two stacks)
- similar questions: Basic calculator III
"""
def expTree(self, s: str) -> 'Node':
ops = []
digits = []
def construct():
r = digits.pop()
l = digits.pop()
digits.append(Node(ops.pop(), l, r))
for c in s:
if c.isdigit():
digits.append(Node(c))
elif c in ["+", "-"]:
while ops and ops[-1] in ["+", "-", "*", "/"]:
construct()
ops.append(c)
elif c in ["*", "/"]:
while ops and ops[-1] in ["*", "/"]:
construct()
ops.append(c)
elif c == "(":
ops.append(c)
elif c == ")":
while ops[-1] != "(":
construct()
ops.pop()
while ops:
construct()
return digits[0] |
da6e85ccae9de50f9e5de364e9b6a3761b73c93f | StephanieMaia15/Python | /desafio048_impares_multiplos_3.py | 306 | 3.765625 | 4 | #verificando quais numeros sao impares em uma lista de um ate 500 e realizando a soma deles
soma = 0
cont = 0
for c in range(1, 501, 2):# 2 = pulando de dois em dois
if c % 3 == 0:
soma += c
cont += 1
print('\33[0:44mA soma dos {} valores multiplos por 3 é: {}\33[m'.format(cont, soma))
|
25a4d3bceb5d593fda81e219b206cc4393edd4ff | tushsoni/PYTHON-BEGINNERS-TO-ADVANCED | /PYTHON COURSE/40 - Chapter-3_Exercise-4.py | 879 | 4.25 | 4 | # **************************************** CHAPTER-3_EXERCISE-4 ******************************************** #
# QUESTION 2 OF THREE
# QUESTION 2 : Ask user to input a number containing more than one digit , example-1256 , calculate 1+2+5+6 and print
# Algorithm use to solve the problem ----
# step 1 : ask input in string, i.e. don't change string to int ,
# step 2 : example - "1256"
# step 3 : pick string character one by one and change to int
# step 4 : int(example[0]) + int(example[1]) ....... go upto len(example)
# ************************************************ ANSWER ************************************************** #
n = input("Enter a value : ")
total=0
i = 0
while i < len(n):
total += int(n[i])
i += 1
print(total)
|
f8d4a8e36b776e9607ab343451df6b200a6ebd55 | vlanunez/IS211_Assignment4 | /sort_compare.py | 2,284 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
import time
import random
def insertion_sort(a_list):
start_time = time.time()
for index in range(1, len(a_list)):
current_value = a_list[index]
position = index
while position > 0 and a_list[position - 1] > current_value:
a_list[position] = a_list[position - 1]
position = position - 1
a_list[position] = current_value
end_time = time.time()
run_time = end_time - start_time
return (run_time, a_list)
def gap_insertion_sort(a_list, start, gap):
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while position >= gap and a_list[position - gap] > current_value:
a_list[position] = a_list[position - gap]
position = position - gap
a_list[position] = current_value
def shell_sort(a_list):
start_time = time.time()
sublist_count = len(a_list) // 2
while sublist_count > 0:
for start_position in range(sublist_count):
gap_insertion_sort(a_list, start_position, sublist_count)
sublist_count = sublist_count // 2
end_time = time.time()
run_time = end_time - start_time
return (run_time, a_list)
def python_sort(a_list):
start_time = time.time()
a_list.sort()
end_time = time.time()
run_time = end_time - start_time
return (run_time, a_list)
def list_gen(maxval):
samplist = random.sample(range(1, (maxval + 1)), maxval)
return samplist
def main():
samp_size = [500, 1000, 10000]
tests = {'Insertion': 0,
'Shell': 0,
'Python': 0}
for smpl in samp_size:
counter = 0
while counter < 100:
test_list = list_gen(smpl)
tests['Insertion'] += insertion_sort(test_list)[0]
tests['Shell'] += shell_sort(test_list)[0]
tests['Python'] += python_sort(test_list)[0]
counter += 1
print ('For sample size %s:' % (smpl))
for tst in tests:
print (('%s Sort took %10.7f seconds to run,'
'on average.') % (tst, tests[tst] / counter))
if __name__ == '__main__':
main()
|
62e05dbee2729ec2ed6021689836e0f209f7451b | Eemann33/Python-Data-Structures | /stack.py | 1,056 | 4.375 | 4 |
'''Creating a Stack in Python by using a list'''
class Stack:
def __init__(self):
self.items = []
def push(self,item):
'''Appends item to end of list'''
self.items.append(item)
def pop(self):
'''Returns and removes items at front of the Stack'''
self.items.pop()
if self.items:
return self.items.pop()
return None
def peek(self):
'''Shows the next item to be removed'''
if self.items:
return self.items[-1]
return None
def size(self):
'''Returns the size of the Stack'''
return len(self.items)
def is_empty(self):
'''Returns a Boolean showing if Stack is empty or not'''
return self.items == []
mystack = Stack()
mystack.push('apple')
print(mystack.items)
mystack.push('banana')
print(mystack.items)
# # mystack.push('carrot')
# print(mystack.items)
# print(mystack.pop())
# print(mystack.items)
# mystack.peek()
print(mystack.size())
print(mystack.peek())
print(mystack.is_empty()) |
353f91ae3eb863495d124bef1a384fae127b0580 | Iamnahin/Games | /pong_game.py | 3,017 | 3.734375 | 4 |
import turtle
wn=turtle.Screen()
wn.title("Pong game by Nahin")
wn.bgcolor("black")
wn.setup(width=800,height=600)
wn.tracer(0)
score_left=0
score_right=0
#Left paddle
left_paddle=turtle.Turtle()
left_paddle.speed(0)
left_paddle.shape("square")
left_paddle.color("white")
left_paddle.shapesize(stretch_wid= 5,stretch_len=1)
left_paddle.penup()
left_paddle.goto(-360,0)
#right paddle
right_paddle=turtle.Turtle()
right_paddle.speed(0)
right_paddle.shape("square")
right_paddle.color("white")
right_paddle.shapesize(stretch_wid= 5,stretch_len=1)
right_paddle.penup()
right_paddle.goto(360,0)
#ball
ball=turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0,0)
ball.dx=.2
ball.dy=-.2
#pen
pen=turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write("Player A:0 and Player B:0", align="center",font=("Courier",24,"normal"))
#function for moving left and right paddle
def left_paddle_up(): #moving for left paddle up
y=left_paddle.ycor()
y+=20
left_paddle.sety(y)
def left_paddle_down(): # moving for left paddle down
y = left_paddle.ycor()
y -= 20
left_paddle.sety(y)
def right_paddle_up(): #moving for right paddle up
y=right_paddle.ycor()
y+=20
right_paddle.sety(y)
def right_paddle_down(): # moving for right paddle down
y = right_paddle.ycor()
y -= 20
right_paddle.sety(y)
#keyboard binding
wn.listen()
wn.onkeypress(left_paddle_up,"w") # calling the up function to moving the left paddle up
wn.onkeypress(left_paddle_down,"s") #calling the down function to moving the left paddle down
wn.onkeypress(right_paddle_up,"Up") # calling the up function to moving the right paddle up
wn.onkeypress(right_paddle_down,"Down") # calling the up function to moving the left paddle dowm
#main game loop
while True:
wn.update()
#move the ball
ball.setx(ball.xcor()+ball.dx)
ball.sety(ball.ycor() + ball.dy)
#border checking
if ball.ycor()>290:
ball.sety(290)
ball.dy*=-1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *=-1
if ball.xcor() >390:
ball.goto(0,0)
ball.dx*=-1
score_left+=1
pen.clear()
pen.write("Player A:{} and Player B:{}".format(score_left,score_right), align="center", font=("Courier", 24, "normal"))
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_right+=1
pen.clear()
pen.write("Player A:{} and Player B:{}".format(score_left, score_right), align="center",font=("Courier", 24, "normal"))
#bouncing ball off the paddles
if (ball.xcor()>340 and ball.xcor() <350) and (ball.ycor() <right_paddle.ycor() +40 and ball.ycor() >right_paddle.ycor() -40):
ball.setx(340)
ball.dx*=-1
if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < left_paddle.ycor() + 40 and ball.ycor() > left_paddle.ycor() - 40):
ball.setx(-340)
ball.dx *= -1
|
6ddf8529b09adab966ca963e656b217c273e1164 | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/Sorting Algorithms/pancake_sort.py | 696 | 4.0625 | 4 | #pancake sort implementation in python
def flip(arr, i):
start = 0
while start < i:
temp = arr[start]
arr[start] = arr[i]
arr[i] = temp
start += 1
i -= 1
def findMax(arr, n):
maxi = 0
for i in range(0,n):
if arr[i] > arr[maxi]:
maxi = i
return maxi
def pancake_sort(arr, n):
c = n
while c > 1:
maxi = findMax(arr, c)
if maxi != c-1:
flip(arr, maxi)
flip(arr, c-1)
c = c-1
if __name__=="__main__":
arr=[5,4,9,7,3,1]
print("Unsorted Array : ",end="")
print(arr)
pancake_sort(arr,len(arr))
print("Sorted Array : ",end="")
print(arr)
|
fbfa489bc2cf6479be7b9917d62868b4f60ac3ed | Shubhankar-wdsn/Hackerrank-Python | /Utopian Tree.py | 592 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the utopianTree function below.
def utopianTree(n):
tall = 1
i = 0
while i < n:
if i % 2 != 0:
tall = (tall + 1)
elif i % 2 == 0:
tall = (tall*2)
i = i+1
return(tall)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = utopianTree(n)
fptr.write(str(result) + '\n')
fptr.close()
|
1a341e8a49507502a2c98421782cd9be3627b0ee | rabbitxyt/leetcode | /657_Judge_Route_Circle.py | 674 | 3.890625 | 4 | # Initially, there is a Robot at position (0, 0).
# Given a sequence of its moves, judge if this robot makes a circle,
# which means it moves back to the original place.
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
p = [0,0]
for i in range(len(moves)):
if moves[i] == "U":
p[1] += 1
if moves[i] == "D":
p[1] -= 1
if moves[i] == "L":
p[0] -= 1
if moves[i] == "R":
p[0] += 1
if p == [0,0]:
return True
else:
return False |
df5bf9f301d2b8c7401fdb046853b73660a3fa29 | Ri-Hong/CCC-Solutions | /CCC '04/CCC '04 J3 - Smile with Similes.py | 898 | 3.984375 | 4 | '''
Author: Ri Hong
Date AC'd: Feb 1, 2020
Problem: https://dmoj.ca/problem/ccc04j3
'''
#Explanation
'''
Get each adjective and store them in an adjective list
Get each noun and store them in an noun list
Loop through each element of the adjective list. For each element of the adjective list, loop through all the elements of the
noun list and print each combination of adjective and noun.
'''
#Code
#get input
numAdjectives = int(input())
numNouns = int(input())
#create the adjective and noun lists
adjectiveList = []
nounList = []
#get the adjectives and nouns and place them in their respective lists
for i in range(numAdjectives):
adjectiveList.append(input())
for i in range(numNouns):
nounList.append(input())
#loop through teh adjectives and nouns and print each combination of adj + noun
for adj in adjectiveList:
for noun in nounList:
print("{} as {}".format(adj, noun))
|
842b5223f6125d9f1f0c4b8e5880c18c653fc810 | AmritaDeb/Automation_Repo | /PythonBasics/py_programas/Assignment_13_12_18/Fibonacii_Yield.py | 261 | 3.859375 | 4 | class Fibonacii_Yield:
def fibonacii(self,n):
a, b = 0, 1
while n > 1:
yield a
a, b = b, a + b
ob=Fibonacii_Yield()
m=ob.fibonacii(2)
i=(iter(m))
print(i)
for x in range(6):
print(next(i))
raise StopIteration
|
2fbeb9fa5838b26ddcc3aa8402f70b7d7bd1b1f7 | aimdarx/data-structures-and-algorithms | /solutions/Trees and Graphs/Binary Trees/construct_binary_tree_from_preorder_and_inorder_traversal.py | 5,056 | 4.15625 | 4 | """
Construct Binary Tree from Preorder and Inorder Traversal:
Given two integer arrays preorder and inorder where
preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree,
construct and return the binary tree.
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
"""
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# ---------------------------------------------------------------------------------------------------------------------
"""
- The root will be the first element in the preorder sequence
- Next, locate the index of the root node in the inorder sequence
- this will help you know the number of nodes to its left & the number to its right
- repeat this recursively
"""
class SolutionBF(object):
def buildTree(self, preorder, inorder):
return self.dfs(preorder, inorder)
def dfs(self, preorder, inorder):
if len(preorder) == 0:
return None
root = TreeNode(preorder[0])
mid = inorder.index(preorder[0])
root.left = self.dfs(preorder[1: mid+1], inorder[: mid])
root.right = self.dfs(preorder[mid+1:], inorder[mid+1:])
return root
class SolutionBF0:
def buildTree(self, preorder, inorder):
if len(inorder) == 0:
# the remaining preorder values do not belong in this subtree
return None
if len(preorder) == 1:
return TreeNode(preorder[0])
ino_index = inorder.index(preorder.pop(0)) # remove from preorder
node = TreeNode(inorder[ino_index])
node.left = self.buildTree(preorder, inorder[:ino_index])
node.right = self.buildTree(preorder, inorder[ino_index+1:])
return node
class SolutionBF00:
def buildTree(self, preorder, inorder):
preorder_pos = 0
def buildTreeHelper(preorder, inorder):
nonlocal preorder_pos
# we do not have valid nodes to be placed
if len(inorder) == 0: # invalid side
return
if preorder_pos >= len(preorder):
return
# # create node
# node
inorder_idx = inorder.index(preorder[preorder_pos])
preorder_pos += 1
node = TreeNode(inorder[inorder_idx])
# children -> will pass only valid children below -> (inorder[:inorder_idx] & inorder[inorder_idx+1:] does that)
node.left = buildTreeHelper(preorder, inorder[:inorder_idx])
node.right = buildTreeHelper(preorder, inorder[inorder_idx+1:])
return node
return buildTreeHelper(preorder, inorder)
# def buildTreeHelper2( preorder, inorder):
# nonlocal preorder_pos
# if preorder_pos >= len(preorder):
# return
# # # create node
# # node
# inorder_idx = inorder.index( preorder[preorder_pos] )
# preorder_pos += 1
# node = TreeNode(inorder[inorder_idx ])
# left = inorder[:inorder_idx]
# right = inorder[inorder_idx+1:]
# if left:
# node.left = buildTreeHelper(preorder, left)
# if right:
# node.right = buildTreeHelper(preorder, right)
# return node
# return buildTreeHelper2(preorder, inorder)
# ---------------------------------------------------------------------------------------------------------------------
"""
- The root will be the first element in the preorder sequence
- Next, locate the index of the root node in the inorder sequence
- this will help you know the number of nodes to its left & the number to its right
- repeat this recursively
- iterate through the preorder array and check if the current can be placed in the current tree(or recursive call)
- We use the remaining inorder traversal to determine(restrict) whether
the current preorder node is in the left or right
"""
class Solution:
def buildTree(self, preorder, inorder):
preorder_pos = 0
inorder_idxs = {val: idx for idx, val in enumerate(inorder)}
def helper(inorder_left, inorder_right):
nonlocal preorder_pos
if preorder_pos == len(preorder):
return
if inorder_left > inorder_right:
return
val = preorder[preorder_pos]
preorder_pos += 1
node = TreeNode(val)
inorder_idx = inorder_idxs[val]
# start with left !
node.left = helper(inorder_left, inorder_idx-1)
node.right = helper(inorder_idx+1, inorder_right)
return node
return helper(0, len(inorder)-1)
|
41b5ee9a68fb16f0e5a406218bd1987264744680 | Alonsovau/sketches | /chapter8/st8.py | 2,057 | 4.03125 | 4 | # 子类中扩展property
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._name = value
@name.deleter
def name(self):
raise AttributeError("Can't delete attribute")
class SubPerson(Person):
@property
def name(self):
print('Getting name')
return super().name
@name.setter
def name(self, value):
print('Setting name to', value)
super(SubPerson, SubPerson).name.__set__(self, value)
@name.deleter
def name(self):
print('Deleting name')
super(SubPerson, SubPerson).name.__delete__(self)
s = SubPerson('IU')
print(s.name)
class SubPerson2(Person):
@Person.name.getter
def name(self):
print('Getting name2')
return super().name
s2 = SubPerson2('suzy')
print(s2.name)
# A descriptor 描述器
class String:
def __init__(self, name):
self.name = name
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
instance.__dict__[self.name] = value
# A class with descriptor
class PersonWithDesc:
name = String('name')
def __init__(self, name):
self.name = name
class SubPersonWithDesc(PersonWithDesc):
@property
def name(self):
print('Getting name')
return super().name
@name.setter
def name(self, value):
print('Setting name to', value)
super(SubPersonWithDesc, SubPersonWithDesc).name.__set__(self, value)
@name.deleter
def name(self):
print('Deleting name')
super(SubPersonWithDesc, SubPersonWithDesc).name.__delete__(self)
s3 = SubPersonWithDesc('Hyojoo')
# s3 = SubPersonWithDesc(9)
|
21f2aae2b9f7b12ccc84e0c679a3a8cb95f38be4 | timolegros/StoreProductOrganizer | /V1.py | 8,632 | 4.15625 | 4 | def onShelves():
"""This function opens the onshelves.txt file and appends the information to a list. The product # and ammount
in stock is appended to a list. Then the function converts this information into int format and filters the
products to find those that actually need to be ordered. These are appended to a new list called orderList"""
# creates the lists to be used and opens the first file
products = []
orderList = []
file = open("onshelves.txt", 'r')
# Creates a list containing lists that contain the product # and amount in stock in int format
for lines in file.readlines():
line = lines.rstrip()
products.append(line.split('#'))
for product in range(len(products)):
for item in range(len(products[product])):
products[product][item] = int(products[product][item])
file.close()
# Using the old list, this creates a new list that contains only the products that need tbo and quantity tbo
for product in products:
if product[1] < 50:
product[1] = 50 - product[1]
orderList.append(product)
return orderList
def productName(orderList):
"""This function opens the products.txt file containing the product codes and product names. It then matches the
product codes from orderList created earlier to the product codes in the new list created when the products.txt
file was opened. If the product codes match than the product name from the productsList is appended to orderList"""
productsList = []
file = open("products.txt", "r")
# opens file and puts every line into a list stored in another list while converting the product # to an integer
for lines in file.readlines():
line = lines.rstrip()
productsList.append(line.split(';'))
for product in range(len(productsList)):
productsList[product][0] = int(productsList[product][0])
file.close()
# Matches all product codes of products that need to be ordered and appends the product name
for products in orderList:
productID = products[0]
for item in productsList:
if item[0] == productID:
products.append(item[1])
return orderList
def suppliers(orderList):
"""This function opens the availability.txt file and puts all its information into a list called supplierList.
Then using this new list, the function filters through the list and appends each line to another new list if and
only if the product code does not already exist in this new list called multipleSuppliers. If the product code is
already present in the new list, meaning there is a match, then the function compares the prices of each item and
appends/removes items according to the prices. The multipleSuppliers list is therefore left with only products for
the lowest prices."""
supplierList = []
multipleSuppliers = []
count = -1
file = open("availability.txt", "r")
# puts suppliers available into a list and converts supplier ID to int and price to float
for lines in file.readlines():
line = lines.rstrip()
supplierList.append(line.split(','))
for supplier in supplierList:
supplier[0] = int(supplier[0])
for item in supplierList:
item[2] = float(item[2])
# removes any suppliers that offer the same product as another but at a higher price
for item in supplierList:
if not any(item[0] in sublist for sublist in multipleSuppliers):
multipleSuppliers.append(item)
else:
for product in multipleSuppliers:
if product[0] == item[0]:
if item[2] <= product[2]:
multipleSuppliers.remove(product)
multipleSuppliers.append(item)
# matches the product codes from orderList to multipleSuppliers and appends the info from multipleSuppliers to orderList
for item in orderList:
count += 1
if any(item[0] in sublist for sublist in multipleSuppliers):
for product in multipleSuppliers:
if product[0] == item[0]:
orderList[count].append(product[2])
orderList[count].append(product[1])
return orderList
def idontknowyet():
def draw(orderList):
"""This function opens the suppliers.txt file containing the companies phone numbers, name, and address. This info
is put into a list. If the company phone number matches any of those in orderList then the company name is appended
to the corresponding item in orderList. The function also formats all the data in orderList to be able to properly
print the output. The total cost of each ordered product is calculated and append to orderList. Then the phone
number is properly formatted and finally an astrix is added to the product name of any product whose order quantity
is greater than 40. The function then filters for highest cost. Finally the function prints/writes all the info
from orderList in the correct format using string formatting."""
separator = ('+' + '-'*14 + '+' + '-'*18 + '+' + '-'*8 + '+' + '-'*16 + '+' + '-'*10 + '+')
totalCost = 0
highestCost = 0
highCostSuppliers = []
supplierNames = []
supplier = []
# Matches the company name to their phone numbers already in the list and appends it
file = open('suppliers.txt', 'r')
for lines in file.readlines():
line = lines.rstrip()
supplierNames.append(line.split(';'))
for item in orderList:
for name in supplierNames:
if item[4] == name[0]:
item.append(name[1])
file.close()
# prepares data for entry into table by calculating cost, formatting phone number, adding astrix to product names
for item in orderList:
item.append(item[1]*item[3])
phoneNumber = item[4]
totalCost += item[6]
item[4] = '('+phoneNumber[:3]+')'+' '+phoneNumber[3:6]+' '+phoneNumber[6:10]
if item[6] > highestCost:
highestCost = item[6]
if item[1] > 40:
item[2] = '*'+item[2]
string = item[2]
if len(item[2]) >16 and string[:1] != '*':
item[2] = string[:16]
else:
item[2] = string[:17]
print(orderList)
# finds the supplier with the highest total order value and appends the company name, number, and cost to a list
companyName = []
someList = []
cost = 0
for item in orderList:
if not item[5] in companyName:
companyName.append(item[5])
for item in companyName:
x = 0
for product in orderList:
if product[5] == item:
x += product[6]
someList.append(x)
for item in someList:
if item >= cost:
cost = item
for item in someList:
if cost == item:
index = someList.index(item)
name = companyName[index]
for y in orderList:
if name == y[5]:
supplier.append(name)
supplier.append(y[4])
supplier.append(cost)
highCostSuppliers.append(supplier)
# prints all of the information contained in orderList
print(separator)
print('| Product code | Product Name |Quantity| Supplier | Cost |')
print(separator)
for item in orderList:
print("|{:^14d}|{:^18s}|{:7d} |{:^16s}| ${:7.2f} |".format((item[0]), (item[2]), (item[1]), (item[4]),(item[6])))
print(separator)
print('| Total Cost | $ %7.2f|'%(totalCost))
print('+' + '-'*14 + '+' + '-'*27 + '+')
for highCostSupplier in highCostSuppliers:
print('Highest cost: {:s} {:s} [${:0.2f}]'.format((highCostSupplier[0]), (highCostSupplier[1]), (highCostSupplier[2])))
file = open('orders.txt', 'w')
file.write(separator)
file.write('\n| Product code | Product Name |Quantity| Supplier | Cost |')
file.write('\n'); file.write(separator)
for item in orderList:
file.write("\n|{:^14d}|{:^18s}|{:7d} |{:^16s}| ${:7.2f} |".format((item[0]), (item[2]), (item[1]), (item[4]),(item[6])))
file.write('\n'); file.write(separator)
file.write('\n| Total Cost | $ %7.2f|'%(totalCost))
for highCostSupplier in highCostSuppliers:
file.write('\nHighest cost: {:s} {:s} [${:0.2f}]'.format((highCostSupplier[0]), (highCostSupplier[1]), (highCostSupplier[2])))
def main():
x = onShelves()
y = productName(x)
z = suppliers(y)
draw(z)
main()
|
abdf84ab8f870517c4e04544c2a2696fa7213380 | yorickcleerbout/Advent-Of-Code-2020 | /Day_02/Day_02.py | 820 | 3.859375 | 4 | import re
def check_pass(password):
p = re.search('(\d+)-(\d+) ([a-z]): (.*)', password)
count = p[4].count(p[3])
if int(p[1]) <= count <= int(p[2]):
return True
else:
return False
def check_pass_2(password):
p = re.search('(\d+)-(\d+) ([a-z]): (.*)', password)
pos1 = p[4][int(p[1])-1] == p[3]
pos2 = p[4][int(p[2])-1] == p[3]
if pos1 != pos2:
return True
else:
return False
with open("Day_02/input.txt", 'r') as f:
data = f.readlines()
good_passwords = [i for i in data if check_pass(i)]
print(f"Number of good passwords using requirements 1: {len(good_passwords)}")
good_passwords = [i for i in data if check_pass_2(i)]
print(f"Number of good passwords using requirements 2: {len(good_passwords)}")
|
cf139df6d0e54d901e7350087dac0a3e727eeccc | xyuuzz/belajar-python | /no 1-9/4.slicing_string.py | 1,498 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 12 11:09:16 2021
@author: xyuuz
"""
# Slicing adalah sebuah metode memecah value dari tipe data yang bersifat itterable
# cara memecahnya pun mudah, yaitu dengan menggunakan rumus :
# [i.awal:i.akhir:jarak]
# ingat, indeks awal dimulai dari 0
# contoh slicing pada string
slicing_string = "Halo namaku Maulana"
print(slicing_string[0:2])
# kita mengakses string dari indeks ke 0 sampai indeks ke 2
# namun, perlu diingat bahwa, indeks akhir tidak ditampilkan
# jadi jika kita slicing sebuah tipe data maka yang akan keluar adalah :
# indeks awal - indeks akhir - 1
# la terus kalau kita mau mengakses value dari indeks terakhir bagaimana kak?
# kita tinggal mengosongkan argument dari i.akhir nya saja
# maka python akan mengetahui bahwa kita akan mengakses tipe data tersebut sampai indeks terakhir
print(slicing_string[2:])
# artinya kita akan mengakses dari indeks ke 2 sampai indeks terakhir
# menggunakan jarak
print(slicing_string[:7:2])
# kita akan mengakses dari indeks ke 0 sampai indeks ke 7, dan tampilkan valuenya setiap 2 indeks
# jarak digunakan ketika kita ingin melompati sebuah indeks dengan aturan tertentu
# membalikan urutan pada tipe data
# Kita dapat membalikan urutan dengan cara memberi argument jarak dengan value -1
# nanti python akan menganggap bahwa kita akan mulai dari indeks -1
# jangan lupa kosongkan argument i.awal dan i.akhir nya
print(slicing_string[::-1]) # analuaM ukaman olaH
|
ca0cdde561e243579594d11f9cacc3ecb027edf4 | nikitiwari/Learning_Python | /sum_nrecurson.py | 194 | 4.125 | 4 | print "Sum of n natural numbers using recursion"
n = (int)(raw_input("Enter a number :"))
def sum_n( x) :
if x == 1 :
return 1
else :
return (x+sum_n(x-1))
print sum_n(n) |
0974cd89d6cdaada3d6621ee22eff0a2bc1cdb6f | goncalo-reis/CS50-Harvard-Online-Course | /pset7/houses/roster.py | 591 | 3.734375 | 4 | from cs50 import SQL
import sys
# Check number of arguments
if len(sys.argv) != 2:
print("Wrong number of arguments.")
exit(1)
# Execute
db = SQL("sqlite:///students.db")
list_results = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first", sys.argv[1])
# Print the results
for i in range(len(list_results)):
print(list_results[i]['first'], end=' ')
if list_results[i]['middle'] != None:
print(list_results[i]['middle'], end=' ')
print(list_results[i]['last'], end=', ')
print(f"born {list_results[i]['birth']}") |
37e512e8bcfbe4aadb2485049edf1b1f85a06a46 | djmar33/python_work | /ex/ex7/rollercoaster.py | 292 | 4.09375 | 4 | #7.1.2使用int()获取数值输入
height = input("你的身高多少?")
#将字符串转换为数值;
height = int(height)
#将用户提供信息进行判断;
if height >= 36:
print("你身高适合玩过山车呀!")
else:
print("你身高还不适合玩过山车哦~")
|
b368340827aa8168d5e871f3048cce533ca3b33f | adityaranjan65/COURSERA-DSA | /week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.py | 536 | 3.984375 | 4 | # Uses python3
import sys
def get_max_pairwise_sum(n):
pairs = list()
pairs.append(1)
temp = 2
while n != 0:
if n > (temp * 2):
pairs.append(temp)
n -= temp
temp += 1
else:
pairs.append(n)
break
print(len(pairs))
for x in pairs:
print(x, end=' ')
def main():
num = int(input())
if num <= 2:
print("1\n", num)
else:
get_max_pairwise_sum(num - 1)
if __name__ == "__main__":
main()
|
614467a00ad63b92b5ce7ccc818018be4fb08372 | lalapapauhuh/Python | /CursoEmVideo/pythonProject/ex036.py | 811 | 3.796875 | 4 | #aprovando emprestimo
from time import sleep
cores = {'limpar': '\033[m',
'verde': '\033[32m',
'vermelho': '\033[31m',
'pretob': '\033[7;30m'
}
casa = float(input('Qual o valor da casa? R$ '))
salario = float(input('Qual valor do seu salário? R$ '))
anos = int(input('Em quantos anos você deseja financiar? '))
prestacao = casa/(anos*12) #anos virando meses
print('As prestações serão de R$ {:.2f}'.format(prestacao))
num = salario*30/100 #calculando 30% do salario
print('{}ANALISANDO...{}'.format(cores['pretob'], cores['limpar']))
sleep(2) #faz o analisar ficar por alguns segundos
if prestacao > num:
print('{}Emprestimo negado{}'.format(cores['vermelho'], cores['limpar']))
else:
print('{}Emprestimo aprovado{}'.format(cores['verde'], cores['limpar'])) |
e29946eb9ac767710576cc04bfd44f20fa5e14e8 | TravelSir/leetcode_solutions | /1-100/20. Valid Parentheses.py | 1,421 | 3.921875 | 4 | """
解题思路:
首先一个有效括号肯定是有一个左括号和一个右括号,且左括号在右括号左边
但假如在一对括号里包含了其他的括号,那为了保证有效,那肯定这对括号里的括号也肯定满足要求。
那么其实从小我们的数字基础就告诉我们,括号是按就近原则的。
那么转换到这道题里
我们可以用栈的方式,每一个左括号都入栈,当有右括号时,判断栈是否为空或栈末元素是否与右括号为同一类型括号,栈为空或不满足同一类型则一定为无效字符串,满足即可出栈继续判断
最后再判断一下栈是否为空,不为空则还有左括号未找到对应右括号,也无效
这里我们把括号转化为数字,方便判断,左括号都大于0,右括号都小于0。相同类型的左右括号之和为0
"""
class Solution:
def isValid(self, s):
brackets = {
'(': 1,
')': -1,
'{': 2,
'}': -2,
'[': 3,
']': -3
}
stack = []
for i in s:
if brackets[i] > 0:
stack.append(brackets[i])
elif not stack:
return False
elif stack[-1] + brackets[i] == 0:
stack.pop()
else:
return False
if stack:
return False
return True
|
c05b579a878ee242aa0e59edb5a2dadd8002d1a7 | MLlounge/ML-Project | /Basic Project/DNN - Train Mathematical Expression(lnx)/DNN - Train Mathematical Expression(lnx).py | 3,230 | 3.796875 | 4 | # you can watch more on ' www.mllounge.com '
# DNN model to learn ln(x)
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import Adam
import numpy as np
import matplotlib.pyplot as plt
class Data: # Create data
def __init__(self):
self.y = 0 # y value.
self.x = np.arange(1, 301) * 3 # create x for training.
# 3 ~ 900 -> [3, 6, 9, 12, ...]
self.e = np.e # e value.
def calc_e(self, x): # function to return ln(x).
# you can change the mathematical expression.
return np.log(x) / np.log(self.e) # return ln(x).
def ret_xy(self): # return x and y(= ln(x))
self.y = self.calc_e(self.x) # calcurate ln(x) and input to y.
return self.x, self.y # return x and y
class Dnn: # create, train, predict DNN model.
# make plot chart for trained data.
def __init__(self):
data = Data()
self.x, self.y = data.ret_xy() # set x, y value for training.
self.learning_rate = 0.003
self.input_shape = 1
self.model = self.build_model() # create moel.
def build_model(self): # function for building model.
model = Sequential()
model.add(Dense(256, input_dim=self.input_shape, activation='relu')) # relu
#model.add(Dropout(0.25))
model.add(Dense(128, activation='relu')) # relu
#model.add(Dropout(0.25))
model.add(Dense(64, activation='relu')) # relu
model.add(Dense(1, activation='linear')) # linear
model.summary()
model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) # mse
return model
def train(self): # function for training.
self.model.fit(np.reshape(self.x, [-1, 1]), np.reshape(self.y, [-1, 1]), epochs=1000)
def predict(self, pre_x): # return predict value of DNN model. input data = pre_x.
return self.model.predict(np.reshape(pre_x, [1, 1]))
def plot_chart(self): # make plot chart for trained data.
plt.subplot(2, 1, 1)
plt.plot(self.x, self.y, '-')
if __name__ == '__main__': # main
dnn = Dnn()
dnn.train() # train the model.
# predict ln(x) with untrained data by using DNN model.
p = [13, 70, 1000, 1250, 2000, 3000] # input 13, 70, 1000, 1250, 2000 = untrained data x.
for i in range(len(p)):
pre = dnn.predict(p[i]) # predict.
# pre_ans = set the real(answer) value of predict value.
pre_ans = np.log(np.full((1, 300), p[i]))/np.log(np.e)
# print predict and real value.
print('\npredict(', p[i], ') = ', pre)
print('real(', p[i], ') = ', pre_ans[0, 1])
# print the difference between predict and real value.
print('difference(', p[i], ') = ', pre - pre_ans[0, 1])
# show plot chart.
# plot chart for trained values.
dnn.plot_chart()
# plot chart for predict values.
pre_x = np.arange(1, 301) * 3
pre_y = np.zeros(300)
for i in range(300):
pre_y[i] = dnn.predict(pre_x[i])
plt.subplot(2, 1, 2)
plt.plot(pre_x, pre_y, '--')
plt.show() |
6c71fc6a94b50b5802a542d7f4debb7ecfc341ff | kanybek740/Chapter1_Part2_Task26 | /task26.py | 251 | 3.828125 | 4 | numbers = input('vvedi chislo: ')
num = list(numbers.split(','))
chetnye = []
nechetnye = []
for number in (num):
if int(number) % 2 == 0:
chetnye.append(num)
else:
nechetnye.append(num)
print(len(chetnye), len(nechetnye)) |
d465097fab5dea1dfcac47522c9925a07880b513 | drakenmang/EjerciciosJava | /Python/EjercicioindependienteWhile.py | 469 | 3.828125 | 4 | print("Confirme su contraseña (2) ")
pw=(input("escriba su contraseña: "))
lim = 3
print("Tiene " + str(lim) + " intentos para confirmar su contraseña ")
pw2=(input("Escriba de nuevo su contraseña "))
contador=1
while pw != pw2 and contador < limite:
print("Las contraseñas no coinciden. Hagalo de nuevo ")
pw2=(input("Escriba de nuevo su contraseña "))
contador+-1
if pw == pw2:
print("todo ok chao ")
else:
print("Todo mal ")
|
c5ea44e23d92e25b59415877b0aababde4572478 | Ravi5ingh/ibm-recommendation-engine | /investigations.py | 812 | 3.515625 | 4 | import utility.util as ut
def get_article_id_frequency(articles):
"""
Get the frequency with which each article Id appears
:param articles: The articles data
:return: The frequency mapping
"""
print('Scanning articles for dupes...')
total = ut.row_count(articles)
article_frequency_mapping = {}
for index, row in articles.iterrows():
if row['article_id'] in article_frequency_mapping:
article_frequency_mapping[row['article_id']] += 1
else:
article_frequency_mapping[row['article_id']] = 1
ut.update_progress(index, total)
print('\n')
for article_id, frequency in ut.sorted_dictionary(article_frequency_mapping, ascending=False):
print(f'Article Id: {article_id} appeared {frequency} times')
input()
|
f641da7814a84894ea0fceed0c74c0ea239fb5b5 | jaredjamieson/personal | /python/FileFunctions/Lab 9 -Jamieson Cardaropoli.py | 4,860 | 3.859375 | 4 | #Lab 9 Jamieson & Cardaropoli
#Imports
import random
import csv
#Takes filename and prints one line at a time
def display_file(filename):
userfile = open(filename, 'r')
for line in userfile:
print(int(line))
userfile.close()
#Takes filename and n, prints top n lines
def display_head(filename, n):
numbersFile = open('names.txt', 'r')
for x in range(n):
line = numbersFile.readline()
line = line.rstrip("\n")
print(line)
numbersFile.close()
#Takes filename and prints each line with line num
def print_line_numbers(filename):
count = 1
userfile = open(filename, 'r')
for line in userfile:
line = line.rstrip('\n')
print(count, '', line)
count += 1
userfile.close()
#takes filename and returns the length
def count_lines(filename):
file = open(filename,"r")
count = 0
for lines in file:
count = count+1
file.close()
return count
#Takes a filename and prints int total
def read_sum(filename):
userfile = open(filename, 'r')
total = 0
for line in userfile:
total += int(line)
print(total)
userfile.close()
#Takes a filename and returns the average of nums in file
def read_average(filename):
file = open(filename, 'r')
total = 0
for x in filename:
total = total + 1
print(total)
#Takes filename and n, appends n random num to file
def write_random(filename, n):
userfile = open(filename, 'w')
for i in range(int(n)):
num = str(random.randint(1, 500)) + '\n'
userfile.write(num)
userfile.close()
print(userfile)
# takes a file and lists it out, prints the total of the numbers
def read_average(filename):
userfile = open(filename, 'r')
total = 0
for line in userfile:
total += int(line)
line = line.rstrip("\n")
print(line)
print("The total is:",total)
userfile.close()
#Takes a filename, asks for a name and age, adds appends age/name pair
def write_ages(filename):
userfile = open(filename, 'w')
again = 'y'
while again =='y':
print('Enter the following data:')
name = input('Name: ')
age = input('Age: ')
total = '\n%s : %s' % (name, age)
userfile.write(total)
again = input('Another record (y/n)? ')
userfile.close()
#reads a file and prints name/age within file
def read_ages(filename):
file = open(filename, 'r')
for line in file:
line = line.rstrip("\n")
x = (line.split(':'))
print("Name:",x[0])
print("Age:",x[1])
file.close()
#Takes a filename and prints ave num words per line
def average_num_words(filename):
userfile = open(filename, 'r')
file = userfile.readlines()
lines = 0
count = 0
for i in file:
lines += 1
for j in i:
count += 1
final = count / lines
userfile.close()
print('The average number of words per line is: ', final)
#Takes a file and returns num that survived
def num_survived(filename):
with open(filename, 'r') as csvfile:
#file = csv.readline()
reader = csv.reader(csvfile, delimiter = ',')
tlived = 0
for row in reader:
if row[1] == '1':
tlived += 1
print('The total number of people who survived are', tlived)
#Takes a filename and gender then prints survivers of gender
def num_gender_survived(filename, gender):
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
tlived = 0
for row in reader:
if row[4] == gender:
if row[1] == '1':
tlived += 1
print('The total number of', gender, 'who survived are', tlived)
#Take a filename and returns the average age of the survivors
def average_age(filename):
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
totalage = 0
used = 0
line = csvfile.readline()
for row in reader:
if row[5] != '':
totalage += float(row[5])
used += 1
average = totalage / used
print('The average age of the survivors is', average)
def main():
#Variables
filename = 'titanic.csv'
#n = input('Enter a number: ')
#gender = input('Enter a gender (male/female): ')
#Function calls
#display_file(filename)
#display_head(filename, n)
#display_head(filename, n)
#print_line_numbers(filename)
#print(count_lines(filename))
#write_random(filename, n)
#read_average(filename)
#write_ages(filename)
#read_ages(filename)
#average_num_words(filename)
#num_gender_survived(filename, gender)
#num_survived(filename)
average_age(filename)
main()
|
011cd3e018c479f412aa87c312c972ba541cdef2 | jibinwu/test | /testHome/use_random.py | 190 | 3.53125 | 4 | import random
ll=[]
# result=random.randrange(1,3)#不包括3
for i in range(10):
result=random.randint(1,1000)#包括3
ll.append(result)
ll.sort(reverse=True)
sorted(ll)
print(ll) |
e09ec11b9800ac7942edfc145d5f2e22f0e47ace | iamish08/Py-Program | /commonwords.py | 523 | 3.984375 | 4 | #to count the 10 most common word in a given text file
#create a text file before execution
import string
fname=input('Enter filename:')
fhand=open(fname)
counts=dict()
for line in fhand:
line=line.translate(str.maketrans(","," ",string.punctuation))
line=line.lower()
words=line.split()
for word in words:
if word in words:
counts[word]=1
else:
counts[word]+=1
lst=list()
for key,val in list(counts.items()):
lst.append((val,key))
lst.sort(reverse=True)
for key,val in lst[:10]:
print(key,val)
#random changes
|
7cb11f1c98515b496a983359c8034a1693377bc7 | mukundajmera/competitiveprogramming | /Deque/Insertion in deque.py | 565 | 3.75 | 4 | # User function Template for python3
def deque_Init(arr, n):
# code here
dq = deque()
for i in range(len(arr)):
dq.append(arr[i])
return dq
# {
# Driver Code Starts
# Initial Template for Python 3
# contributed by RavinderSinghPB
if __name__ == '__main__':
from collections import deque
tcs = int(input())
for _ in range(tcs):
n = int(input())
arr = [int(x) for x in input().split()]
dq = deque_Init(arr, n)
for e in dq:
print(e, end=' ')
print()
# } Driver Code Ends |
41df1d5f9ebe3e09be81e304b9a9db99cf7f1fb0 | CapSOSkw/My_leetcode | /中文leetcode/简单/1460. 通过翻转子数组使两个数组相等.py | 1,451 | 3.640625 | 4 | '''
给你两个长度相同的整数数组 target 和 arr 。
每一步中,你可以选择 arr 的任意 非空子数组 并将它翻转。你可以执行此过程任意次。
如果你能让 arr 变得与 target 相同,返回 True;否则,返回 False 。
示例 1:
输入:target = [1,2,3,4], arr = [2,4,1,3]
输出:true
解释:你可以按照如下步骤使 arr 变成 target:
1- 翻转子数组 [2,4,1] ,arr 变成 [1,4,2,3]
2- 翻转子数组 [4,2] ,arr 变成 [1,2,4,3]
3- 翻转子数组 [4,3] ,arr 变成 [1,2,3,4]
上述方法并不是唯一的,还存在多种将 arr 变成 target 的方法。
示例 2:
输入:target = [7], arr = [7]
输出:true
解释:arr 不需要做任何翻转已经与 target 相等。
示例 3:
输入:target = [1,12], arr = [12,1]
输出:true
示例 4:
输入:target = [3,7,9], arr = [3,7,11]
输出:false
解释:arr 没有数字 9 ,所以无论如何也无法变成 target 。
示例 5:
输入:target = [1,1,1,1,1], arr = [1,1,1,1,1]
输出:true
提示:
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
'''
'''
思路:只要元素及对应元素的个数相等,通过翻转是可以完成转换的。
'''
class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
target.sort()
arr.sort()
return True if target == arr else False |
a04a577606937fccf49694038adc1e27f6376c03 | rayjustinhuang/ProjectEuler | /Problem 3.py | 1,289 | 4.09375 | 4 | #Define prime factorization function
def primefactorize(number):
factors = []
for i in range(1,int(number**(.5)+1)):
if number%i != 0 or i == 1:
continue
else:
number = number/i
factors.append(i)
return factors
#n = input("Enter the integer to find the prime factors of: ")
#n = int(n)
#print("The prime factors of", n, "excluding 1 and itself are", primefactorize(n))
def isprime(number):
test = 0
for i in range(2,int(number**(.5)+1)):
if number%i == 0 or number == 0:
return False
return True
#print(isprime(13195))
def largestprime(number):
bigprime = 0
if isprime(number):
return number
for i in range(int(number**(.5)+1),1,-1):
if number%i != 0 or i == 1 or i == number:
continue
else:
if isprime(i):
bigprime = i
break
else:
continue
return bigprime
#n = input("Enter the integer to find the largest prime factor of: ")
#n = int(n)
#print("The largest prime factor of", n, "is", largestprime(n))
#print(largestprime(13195))
#print(primefactorize(largestprime(13195)))
print(largestprime(600851475143))
|
a612cb6fcb41516596882e54d3beeb57d1b27e24 | davidlyness/Advent-of-Code-2017 | /21/21a.py | 2,804 | 4.0625 | 4 | # coding=utf-8
"""Advent of Code 2017, Day 21, Part 1"""
def convert_string_to_grid(grid_string):
"""
Convert the string representation of the grid to a 2D array.
:param grid_string: input string
:return: 2D representation of the grid
"""
return list(map(list, grid_string.split("/")))
def convert_grid_to_string(grid):
"""
Convert the 2D representation of the grid to a string.
:param grid: input 2D array
:return: string representation of the grid
"""
return "/".join("".join(row) for row in grid)
with open("input.txt") as f:
puzzle_input = f.read().rstrip().split("\n")
rules = {}
for line in puzzle_input:
rule_input, rule_output = line.split(" => ")
for flip_count in range(2):
for rotation_count in range(4):
equivalent_rule_input = convert_string_to_grid(rule_input)
grid_rule_length = len(equivalent_rule_input)
for _ in range(flip_count):
equivalent_rule_input = [list(reversed(row)) for row in equivalent_rule_input]
for _ in range(rotation_count):
temp_grid = [[None] * grid_rule_length for _ in range(grid_rule_length)]
for i in range(grid_rule_length):
for j in range(grid_rule_length):
temp_grid[i][j] = equivalent_rule_input[- j - 1][i]
equivalent_rule_input = temp_grid
rules[convert_grid_to_string(equivalent_rule_input)] = rule_output
current_pattern = [
[".", "#", "."],
[".", ".", "#"],
["#", "#", "#"]
]
for _ in range(5):
grid_length = len(current_pattern)
if grid_length % 2 == 0:
new_grid_length = grid_length // 2 * 3
split_length = 2
iterated_split_length = 3
else:
new_grid_length = grid_length // 3 * 4
split_length = 3
iterated_split_length = 4
output_grid = [[None] * new_grid_length for _ in range(new_grid_length)]
for i in range(0, grid_length // split_length):
for j in range(0, grid_length // split_length):
start_i = i * split_length
start_j = j * split_length
new_grid = [row[start_j:start_j + split_length] for row in current_pattern[start_i:start_i + split_length]]
new_grid_string = convert_grid_to_string(new_grid)
transformed_new_grid = convert_string_to_grid(rules[new_grid_string])
output_i = i * iterated_split_length
output_j = j * iterated_split_length
for a in range(iterated_split_length):
for b in range(iterated_split_length):
output_grid[output_i + a][output_j + b] = transformed_new_grid[a][b]
current_pattern = output_grid
print(convert_grid_to_string(current_pattern).count("#"))
|
df04100da24ce78fc094488edcb25452f3d389c3 | nicholasgdml/exercicioscursoemvideo-python | /ex_python_mundo1/ex007.py | 170 | 3.828125 | 4 | print('Digite suas notas escolares')
nota1 = float(input('Nota1: '))
nota2 = float(input('Nota2: '))
media = (nota1 + nota2) / 2
print('A sua média é {}'.format(media)) |
9ed6979a4b6cf2549f952b81e5fca48833017dae | YuZhangIsCoding/Algorithms_python | /Classic_problems/searchMatrix.py | 7,287 | 3.65625 | 4 | class sol(object):
def searchMatrix(self, matrix, target):
'''
Search the target value in an m*n matrix.
The integers in each row are sorted from left to right
The first integer is larger than the last integer of previous row.
Use global binary search.
66 ms, 12.73%.
Second try
52 ms, 32.10%.
'''
if not matrix:
return False
m, n = len(matrix), len(matrix[0])
low, high = 0, m*n-1
while low <= high:
mid = (low+high)/2
realmid = (mid/n, mid%n)
if matrix[realmid[0]][realmid[1]] == target:
return True
elif matrix[realmid[0]][realmid[1]] > target:
high = mid-1
else:
low = mid+1
return False
def searchMatrix_2(self, matrix, target):
'''
First locates row and then locates column. This method also avoids overflow.
However, the performance is even worse
69 ms, 9.04%.
Tried second time
42 ms, 80.07%
'''
if not matrix or not matrix[0]:
return False
low, high = 0, len(matrix)-1
while low <= high:
mid = (low+high)/2
if target < matrix[mid][0]:
high = mid -1
elif target > matrix[mid][-1]:
low = mid+1
else:
low = 0
high = len(matrix[mid])
while low <= high:
submid = (low+high)/2
if matrix[mid][submid] == target:
return True
elif matrix[mid][submid] > target:
high = submid-1
else:
low = submid+1
return False
return False
def searchWord(self, board, word):
'''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell,
where "adjacent" cells are those horizontally or vertically neighboring.
Same letter cell may not be used more than once.
The following script works fine for board and word with less duplicates,
but achieves time limit when the board consists of a lot of duplicates.
The use of dictionary increase the randomness of searching pattern.
The critical step maybe the search in path.
'''
if len(word) < 1:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if self.check_nb(board, (i, j), word, 0, [(i, j)]):
return True
return False
def check_nb(self, board, coord, word, ind, path):
if ind == len(word)-1:
return True
nb = self.get_nb(board, coord, path)
for item in nb.keys():
if word[ind+1] == nb[item]:
# path[item] = True
if self.check_nb(board, item, word, ind+1, path+[item]):
return True
return False
def get_nb(self, board, coord, path):
ans = {}
locs = [(coord[0]+1, coord[1]), (coord[0], coord[1]+1), \
(coord[0]-1, coord[1]), (coord[0], coord[1]-1)]
for item in locs:
# if not path.get(item, False) and min(item) >= 0 and item[0] < len(board)\
# and item[1] < len(board[0]):
if item not in path and min(item) >= 0 and item[0] < len(board)\
and item[1] < len(board[0]):
ans[item] = board[item[0]][item[1]]
return ans
def searchWord_2(self, board, word):
'''
Try to check in one direction
This script breaks the string into lists and put '#'in the list
if a match is found.
'''
if not board:
return False
board = [[i for i in item] for item in board]
for i in range(len(board)):
for j in range(len(board[0])):
if self.check_exist(board, i, j, word, 0):
return True
return False
def check_exist(self, board, i, j, word, ind):
if ind == len(word):
return True
if min(i, j) < 0 or i >= len(board) or j >= len(board[0]) or board[i][j] != word[ind]:
return False
temp = word[ind]
board[i][j] = '#'
## the if loop is equavalent
# if self.check_exist(board, i+1, j, word, ind+1) or\
# self.check_exist(board, i, j+1, word, ind+1) or\
# self.check_exist(board, i-1, j, word, ind+1) or\
# self.check_exist(board, i, j-1, word, ind+1):
# return True
res = self.check_exist(board, i+1, j, word, ind+1) or\
self.check_exist(board, i, j+1, word, ind+1) or\
self.check_exist(board, i-1, j, word, ind+1) or\
self.check_exist(board, i, j-1, word, ind+1)
board[i][j] = temp
return res
mysol = sol()
#matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]
#matrix = [[]]
#target = 3
#print mysol.searchMatrix_2(matrix, target)
board = ["ABCE","SFCS","ADEE"]
board = ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaab"]
word = "baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
print mysol.searchWord(board, word)
print mysol.searchWord_2(board, word)
|
705211c543585794c977facbef6c6406f9588d5d | amandanagai/bootcamp_prep | /codewars_rotated_word.py | 654 | 4 | 4 | def num_clockwise_rotated(str1, str2):
count = 0
if str1 == str2:
return count
else:
while count < len(str1)-1:
str1 = "".join([str1[x] for x in range(1, len(str1))])+str1[0]
count += 1
if str1 == str2:
return count
num_clockwise_rotated("coffee", "eecoff")
def num_rotated(str1, str2):
count = 0
if str1 == str2:
return count
else:
while count < len(str1)-1:
str1 = str1[-1] + "".join([str1[x] for x in range(0, len(str1)-1)])
count += 1
if str1 == str2:
return count
elif count == len(str1)-1:
return -1
print(num_rotated("Esham", "Esham")) |
beeea39f7304a2bae86ad21f68cf1ff94cb7c21f | caoxin1988/leetcode | /python/206_Reverse_Linked_List/reverse.py | 1,030 | 3.9375 | 4 | class LinkNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverse(self, head):
if head is None or head.next is None:
return head
ptr = head
prev = None
while ptr:
next_ptr = ptr.next
ptr.next = prev
prev = ptr
ptr = next_ptr
return prev
def transfer_link_list_to_string(head):
result = ''
while head:
result += str(head.val) + ', '
head = head.next
return '[' + result[0:-2] + ']'
def transfer_to_linked_list(items):
dummyptr = LinkNode(0)
ptr = dummyptr
for item in items:
ptr.next = LinkNode(item)
ptr = ptr.next
ptr = dummyptr.next
return ptr
def main():
items = input('please input : ')
head = transfer_to_linked_list(items)
ret = Solution().reverse(head)
out = transfer_link_list_to_string(ret)
print(out)
if __name__ == '__main__':
main() |
4aea2662412f205c0c1159bbf50a0d91c22e0e3b | KhMassri/DTNWorkspace | /Parser/src/test.py | 1,158 | 3.71875 | 4 |
from numpy.random import rand
''' how to build aniterator'''
class it:
def __init__(self):
#start at -1 so that we get 0 when we add 1 below.
self.count = -1
#the __iter__ method will be called once by the for loop.
#the rest of the magic happens on the object returned by this method.
#in this case it is the object itself.
def __iter__(self):
return self
#the next method will be called repeatedly by the for loop
#until it raises StopIteration.
def next(self):
self.count += 1
if self.count < 4:
return self.count
else:
#a StopIteration exception is raised
#to signal that the iterator is done.
#This is caught implicitly by the for loop.
raise StopIteration
def some_func():
return it()
for i in some_func():
print i
s=[1,2,3,4]
print id(s)
s+=[1,1,1,1]
print id(s)
'''
def some_function():
for i in xrange(4):
yield i
yield [7,8,9]
for i in some_function():
print i
for i, v in enumerate(['tic', 'tac', 'toe']):
print i, v
''' |
ec260fab891501b13de54196637729a47793a15c | davidpablos25/TareasBecasDigitaliza | /Calculadora.py | 2,114 | 4 | 4 | import math
def suma(a,b):
return a + b
def resta (a,b):
return a - b
def multiplicacion(a,b):
return a*b
def division(a,b):
return a/b
def potencia(x,y):
return pow(x, y)
def raiz(x):
return math.sqrt(x)
def logarit(x):
return math.log10(x)
def menu():
print("CALCULADORA")
print()
print("1. Suma")
print("2. Resta")
print("3. Multiplicación")
print("4. División")
print("5. Potencia")
print("6. Raíz cuadrada")
print("7. Logaritmos base 10")
operacion = input("Elige una operación: ")
return operacion
x= float(input("Introduzca el primer número: "))
while True:
try:
print("Primer número: "+ str(x))
print()
opera= menu()
if opera == "1":
y= float(input("Introduzca el segundo número: "))
resultado = suma(x,y)
elif opera=="2":
y= float(input("Introduzca el segundo número: "))
resultado = resta(x,y)
elif opera =="3":
y= float(input("Introduzca el segundo número: "))
resultado = multiplicacion(x,y)
elif opera == "4":
y= float(input("Introduzca el segundo número: "))
resultado = division(x,y)
elif opera == "5":
y= float(input("Introduzca el segundo número: "))
resultado = potencia(x,y)
elif opera =="6":
resultado = raiz(x)
elif opera =="7":
resultado = logarit(x)
else:
print("Opción incorrecta, reinicie el programa")
break
print("El resultado es: ", resultado)
x= resultado
continuar = input("Introduzca (n) si no quiere continuar, y cualquier tecla para sí: ")
if continuar == "n":
print("Has parado el programa")
break
print()
except KeyboardInterrupt:
print("Has cerrado el programa")
break |
e30697fdfa7f330e1f3cac2a650e7499dc4161ab | AmandaCasagrande/Entra21 | /Exercícios URI/Iniciante/1021.py | 1,175 | 3.859375 | 4 | cedulas = float(input(""))
notas100 = int(cedulas / 100)
cedulas = cedulas % 100
notas50 = int(cedulas / 50)
cedulas = cedulas % 50
notas20 = int(cedulas / 20)
cedulas = cedulas % 20
notas10 = int(cedulas / 10)
cedulas = cedulas % 10
notas5 = int(cedulas / 5)
cedulas = cedulas % 5
notas2 = int(cedulas / 2)
cedulas = cedulas % 2
print(f"NOTAS:")
print(f"{notas100} nota(s) de R$ 100.00")
print(f"{notas50} nota(s) de R$ 50.00")
print(f"{notas20} nota(s) de R$ 20.00")
print(f"{notas10} nota(s) de R$ 10.00")
print(f"{notas5} nota(s) de R$ 5.00")
print(f"{notas2} nota(s) de R$ 2.00")
moedas1 = int(cedulas / 1)
cedulas = (cedulas % 1) * 100
moedas50 = int(cedulas / 50)
cedulas = cedulas % 50
moedas25 = int(cedulas / 25)
cedulas = cedulas % 25
moedas10 = int(cedulas / 10)
cedulas = cedulas % 10
moedas05 = int(cedulas / 5)
cedulas = cedulas % 5
moedas01 = int(cedulas / 1)
cedulas = cedulas % 1
print(f"MOEDAS:")
print(f"{moedas1} moeda(s) de R$ 1.00")
print(f"{moedas50} moeda(s) de R$ 0.50")
print(f"{moedas25} moeda(s) de R$ 0.25")
print(f"{moedas10} moeda(s) de R$ 0.10")
print(f"{moedas05} moeda(s) de R$ 0.05")
print(f"{moedas01} moeda(s) de R$ 0.01") |
6efe65031b35a325655c8c80dd5ff15e5f76e315 | girishgupta211/algorithms | /find_summer_temparature.py | 1,764 | 4.28125 | 4 | # I've just tried a coding challenge to write a function that returns the length of the shortest possible
# left partition of an array of numbers, all of whose elements are less than all of the elements in the corresponding right partition.
#
# The scenario given was finding the divide between "winter" and "summer" given a variable number of monthly
# temperature readings, with the rule that all winter temperatures are lower than all summer temperatures.
# We can assume that there is at least one correct partition, and the goal is to get the shortest winter.
# https://stackoverflow.com/questions/46689119/finding-array-partition-where-maxleft-minright-possible-in-on-time
def solution(arr):
left_max = maximum = arr[0]
position = 1 # there is always one day of winter
for i in range(1, len(arr) - 1):
if arr[i] < left_max:
position = i + 1
left_max = maximum
elif arr[i] > maximum:
maximum = arr[i]
return position
print(solution([5, -2, 3, 8, 6]))
print(solution([-5, -5, -5, -42, 6, 12]))
def shortestWinterLength(arr):
if len(arr) == 0:
return 0
winter_high = arr[0]
overall_high = arr[0]
winter_length = 0
# Get max in the left array
for temperature in arr:
if temperature <= winter_high:
winter_high = overall_high
elif temperature > overall_high:
overall_high = temperature
# count all the values which are less than max in left array
for temperature in arr:
if temperature <= winter_high:
winter_length += 1
# total length of the left array
return winter_length
print(shortestWinterLength([5, -2, 3, 8, 6]))
print(shortestWinterLength([-5, -5, -5, -42, 6, 12]))
|
56a90cb7cf3e2ec9ac92f342c8ea52510577ae2f | yuanhawk/Digital-World | /Python Project/Wk 2 In Class Activities + Homework/Largest Number.py | 143 | 3.96875 | 4 | def is_larger(n1, n2):
if n1 > n2:
return True
else:
return False
print(is_larger(2, -1))
print(is_larger(-1, 2))
print(is_larger(2, 2)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.