blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
ddea2dcdf682f00d0bb331022ffb9bcda2961982 | Potrik98/plab2 | /proj3/crypto/MultiplicationCipher.py | 805 | 3.65625 | 4 | from crypto.Cipher import Cipher, alphabet, alphabet_length
from crypto.SimpleCipher import SimpleCipher
from crypto.crypto_utils import modular_inverse
class MultiplicationCipher(SimpleCipher):
class Key(Cipher.Key):
def __init__(self, factor: int):
self._factor = factor
self._inverse = modular_inverse(factor, alphabet_length)
def __str__(self):
return "Multiplication key: factor %d, inverse %d" % (self._factor, self._inverse)
def __init__(self):
super().__init__()
def _encrypt_character(self, char):
return alphabet[(alphabet.index(char) * self._key._factor) % alphabet_length]
def _decrypt_character(self, char):
return alphabet[(alphabet.index(char) * self._key._inverse) % alphabet_length]
|
ea93a608608867db9112c90d2bafd74f4f5942fc | arizpando/Hacktoberfest1 | /arbol.py | 782 | 3.75 | 4 | x=int(input("opción= "))
espacios=x+2
if espacios >= 1:
if (x%2)==0:
for i in range(0,(espacios//2)-1):
espacio=" "
espacios-=2
numEspac=(espacio*espacios)
inicEspac=espacio*i
print(inicEspac,"\\",numEspac,"/")
for i in range(0,(espacios//2)-1,-1):
espacio=" "
espacios+=2
numEspac=(espacio*espacios)
inicEspac=espacio*i
print(inicEspac,"/",numEspac,"\\")
else:
for i in range(0,(espacios//2)-1):
espacio=" "
espacios-=2
numEspac=(espacio*espacios)
inicEspac=espacio*i
print(inicEspac,"\\",numEspac,"/")
|
c17edcf8c17fae20d8072f584ecb1337e6f9cac1 | djtorel/python-crash-course | /Chapter 09/Try It/Try04/number_served.py | 2,171 | 4.59375 | 5 | # Start with your program from Exercise 9-1 (page 166). Add an attribute
# called number_served with a default value of 0. Create an instance
# called restaurant from this class. Print the number of customers the
# restaurant has served, and then change this value and print it again.
# Add a method called set_number_served() that lets you set the number
# of customers that have been served. Call this method with a new number
# and print the value again.
# Add a method called increment_number_served() that lets you increment
# the number of customers who’ve been served. Call this method with any
# number you like that could represent how many customers were served
# in, say, a day of business.
class Restaurant():
"""A simple way to model a restaurant"""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize the name and type attributes"""
self.name = restaurant_name
self.type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""Print the name and type of restaurant"""
print("The restaurant " + self.name.title() +
" serves " + self.type.title() + " style cuisine.")
def open_restaurant(self):
"""Print that the restaurant is now open"""
print(self.name.title() + " is now open!")
def set_number_served(self, num_customers):
"""Set the number of customers served"""
self.number_served = num_customers
def increment_number_served(self, num_served):
"""Increment self.number_served by num_served amount"""
self.number_served += num_served
restaurant = Restaurant("paulys pizza", "pizza")
print(restaurant.name)
print(restaurant.type)
print("Number served: " + str(restaurant.number_served))
restaurant.describe_restaurant()
restaurant.open_restaurant()
restaurant.number_served = 2
print("Number served: " + str(restaurant.number_served))
restaurant.set_number_served(4)
print("Number served: " + str(restaurant.number_served))
restaurant.increment_number_served(30)
print("Number served: " + str(restaurant.number_served))
|
a3750ca9cc89a0a6940c6264a5bc3523c5911929 | juntwelfth/Notes | /Python/Computer Science/Algorithms/Searching/Linear Search.py | 300 | 3.890625 | 4 | def linear_search(search_list, target_value):
for idx in range(len(search_list)):
if search_list[idx] == target_value:
return idx
raise ValueError("{0} not in list".format(target_value))
print(linear_search([1, 2, 3, 4, 5], 4))
print(linear_search([1, 3, 5, 7, 9], 10))
|
00946591f304cb8f9aced866210a7f8e344a4016 | marcusshepp/dotpy | /acm_comp/pc.py | 662 | 3.875 | 4 | #!/usr/bin/python
import copy
the_in = raw_input().strip().split()
method = the_in[1]
size = int(the_in[0])
def split_list(l):
return l[len(l)/2:], l[:len(l)/2]
def merge(r, l, m):
z = []
if m == "in":
return [item for pair in zip(r, l) for item in pair]
elif m == "out":
return [item for pair in zip(l, r) for item in pair]
if __name__ == "__main__":
orig_list = range(size)
left, right = split_list(orig_list)
temp_list = merge(left, right, method)
i = 1
while temp_list != orig_list:
left, right = split_list(temp_list)
temp_list = merge(left, right, method)
i += 1
print i
|
2c809d3629a624d5553d91f9bb627bec88bc0556 | m-lab/bigsanity | /bigsanity/formatting.py | 1,415 | 4.0625 | 4 | # Copyright 2015 Measurement Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def indent(s, spaces=2):
"""Indent a string by prepending a specified number of space characters.
Adds an indent to a string on each line with the specified number of spaces.
For example:
The following input string (pipe characters represent line starts):
|foo
| bar
|baz
Indented two spaces becomes:
| foo
| bar
| baz
Args:
s: The string to indent.
spaces: The number of spaces to indent. Must be >= 0.
Returns:
The value of s with prepended spaces on each line.
Raises:
ValueError: An invalid value was specified for spaces.
"""
if spaces < 0:
raise ValueError('spaces must be non-negative, but was %d' % spaces)
spacing = ' ' * spaces
return spacing + s.replace('\n', '\n' + spacing)
|
fbd451ae7116eedee1d7f5b854e17946f459fd88 | devecis/learning | /Python_Workout/Exercise01/Exercise01.py | 1,372 | 4.5 | 4 | """
Write a function (guessing_game) that takes no arguments.
When run, the function chooses a random interger between 0 - 100 inclusive
Then asks the user to guess what number has been chosen
Each time the user enters a guess, the program indicates one of the following:
- Too High
- Too Low
- Just right
If the user guesses correctly, the program exits. Otherwises , the user is asked to try agian
The program exits after the user guess correctly
Give user 3 tries
"""
from os import system, name
from time import sleep
import random
def clear(): # Used to clear the screen after session
if name == 'nt':
_ = system('cls')
answer = random.randint(1, 100) #picking as number between 1 and 100
def guessing_game(): #the guessing game. The user input is in here instead of main because the user has to do it 3 times
for i in range(3):
user_guess = int(input("Guess a number between 1 - 100, you only get 3 tries. "))
if user_guess == answer:
print(f"Right! The answer is {user_guess}")
break
elif user_guess < answer:
print(f"Your guess of {user_guess} is too low!")
elif user_guess > answer:
print(f"Your guess of {user_guess} is too high!")
def main():
guessing_game()
sleep(2)
clear()
if __name__ == "__main__":
main() |
51bc534916cb106dad19fdba834e24a9dd15cab4 | shanuman816/project-1 | /L-11 Assignment Water Gates.py | 362 | 3.640625 | 4 | # Fuction to check
def balance(s):
stack = []
balanced = True
i = 0
c = 0
while i<len(s) and balanced:
char = s[i]
if char == '(' : stack.append(char)
else:
if stack==[]: balanced = False
else:
stack.pop()
c+=1
i+=1
if stack==[] and balanced: print(c)
else: print(-1)
# Taking Input
s = input("Enter the water gates : ")
balance(s)
|
76350336dd46c3e7d13d97bd3717748e3eea5d19 | Jyun-Neng/LeetCode_Python | /130-surrounded-regions.py | 2,720 | 3.9375 | 4 | """
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
Input:
X X X X
X O O X
X X O X
X O X X
Output:
X X X X
X X X X
X X X X
X O X X
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'.
Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'.
Two cells are connected if they are adjacent cells connected horizontally or vertically.
"""
import collections
class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
h = len(board)
w = len(board[0]) if board else 0 # check if board is empty
# surrounded regions will not exist
# finish this function directly
if h < 2 or w < 2:
return
queue = collections.deque([])
# find all 'O's on the border
# change them to '-' and put their coordinate into queue
for x in range(w):
if board[0][x] == 'O':
queue.append([x, 0])
board[0][x] = '-'
if board[h - 1][x] == 'O':
queue.append([x, h - 1])
board[h - 1][x] = '-'
for y in range(h):
if board[y][0] == 'O':
queue.append([0, y])
board[y][0] = '-'
if board[y][w - 1] == 'O':
queue.append([w - 1, y])
board[y][w - 1] = '-'
# BFS
while queue:
x, y = queue.popleft()
if x > 0 and board[y][x - 1] == 'O':
board[y][x - 1] = '-'
queue.append([x - 1, y])
if x < w - 1 and board[y][x + 1] == 'O':
board[y][x + 1] = '-'
queue.append([x + 1, y])
if y > 0 and board[y - 1][x] == 'O':
board[y - 1][x] = '-'
queue.append([x, y - 1])
if y < h - 1 and board[y + 1][x] == 'O':
board[y + 1][x] = '-'
queue.append([x, y + 1])
# change '-' back to 'O', it means that the region is not a surrounded region
for x in range(w):
for y in range(h):
board[y][x] = 'O' if board[y][x] == '-' else 'X'
if __name__ == "__main__":
board = [['X', 'X', 'O', 'X'], ['X', 'O', 'X', 'X'], [
'X', 'X', 'O', 'X'], ['X', 'X', 'O', 'X'], ['X', 'O', 'O', 'X']]
Solution().solve(board)
print(board)
|
0c1f2a4bce64b04570725861e01b4813f68c3cbc | jordanmmck/cs | /alg_ds/hackerrank/python_path/07.collections/2.defaultdict.py | 566 | 3.75 | 4 | from collections import defaultdict
# d = defaultdict(list)
# d['python'].append("awesome")
# d['something-else'].append("not relevant")
# d['python'].append("language")
# for i in d.items():
# print(i)
# print(d)
n, m = map(int, input().split())
# group A
A = []
for i in range(n):
A.append(input())
# group B
B = defaultdict(list)
for i, x in enumerate(A):
B[x].append(i + 1)
for i in range(m):
word = input()
if word in B:
l = B[word]
for c in l:
print(c, end=' ')
print('')
else:
print(-1)
|
486137f6731552af3b034e2a74b036ba8470024d | clarkngo/python-projects | /python-list-mastery/two-pointers-switch-in-place.py | 636 | 3.640625 | 4 | # Remove Duplicates from Sorted Array
# Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
pointer_1 = 0
pointer_2 = 1
count = 0
for pointer_2 in range(len(nums)):
if nums[pointer_1] != nums[pointer_2]:
pointer_1 += 1
nums[pointer_1] = nums[pointer_2]
return pointer_1 + 1
|
e765039ed759174736885b56c4587ccb108d1205 | calvinterpstra/TUDelftPython | /PythonQ2/IndentationLevel.py | 1,688 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
IndentationLevel.py -- experiment whith source code indentation levels
@author: Bart Gerritsen
"""
# EXPERIMENT: try shifting any line at this level (including def's) one to
# position to the right
# EXPERIMENT: try shifting all lines at this level (consistently) to the right
print('Starting')
# comment at indentation level 0 ...
# for comments, the indentation level is irrelevant
# put them anywhere you see fit
a,b = 1,2
# EXPERIMENT: break the indentation consistency
# this would cause an error because we breach indentation consistency
# we might observe the orange triangle in Spyder, signalling this as
# soon as we uncomment the next line
#c = 3
# EXPERIMENT: try replacing a single TAB by 2 TABs
# define a function with an indentation composed of 1 TAB character
# (Spyder may instantly replace this by a consistent number of spaces)
def myFunc():
print('... ... entering myFunc()')
# my2ndFunc()
my2ndFunc()
print('... ... returning from myFunc()')
# EXPERIMENT: let try another (consistent!) indentation format
# define a function with an indentation composed of just a single space
def my2ndFunc():
print('... ... ... entering my2ndFunc()')
# ... do some other stuff
print('... ... ... returning from my2ndFunc()')
# EXPERIMENT: and yet another ...
def runMain():
print('... entering runMain()')
myFunc()
print('... returning from runMain()')
# invoke main from level 0
runMain()
print('Terminating') |
f3c1853b5a640cd5abc22df26fb5affb35b2517e | karthikram003/Projects | /secretSanta/shuffle.py | 485 | 3.515625 | 4 | ##import random
##import queue
##
##q = queue.Queue()
##
##randlist = list(range(1,11))
##print(randlist)
##random.shuffle(randlist)
##print(randlist)
##
##for i in randlist:
## q.put(i)
##
##if not q.empty():
## print("hihihihihih")
##
##import itertools
##
##permlist = [i for i in range(1,4)]
##print(permlist)
##
##x = itertools.permutations(permlist,len(permlist))
##xlist = list(x)
##
##print(xlist)
##
##print(xlist[0][2])
x = "sup bro"
print('I love the number %s' %x)
|
a07daf176c8b1bcc93fe331fc45717b7cbbb82ff | dikshakurwa/learning | /wishlist.py | 183 | 3.765625 | 4 | wishList = ["takis", "new macbook", "license", "car", "vacation"]
item = str(input("please enter one of diksha's wishes: "))
if item in wishList:
print("True")
else:
print("False")
|
37e792ecfee97e1b5687c2c2fcbb4e6c28b401fc | JulianCSalazar/Python_Tutorial | /PythonIntro.py | 10,256 | 3.890625 | 4 | #############################################################
# File : PythonIntro.py
# Author: Julian Salazar
# Date: 7/21/18
# Description:
# This file is a testing platform for basic python commands
# Contents:
# 1. Print Statements
# 2. Variables and Types
# 3. Logical Operators
# 4. Mathematical Operators
#
# Notes:
# >>Python is a dynamic scripting language rather than a static one like C.
# The difference between the two is that dynamic languages don't need to be
# compiled and static ones do. We can see this in action if we write an
# incorrect instruction in Python and in C. The code will run all previous
# correct lines of code first before expressing there is an error once it
# hits it. In C, however, the program will never run any lines because it
# must compile first and is unable to do so because of the line with the
# error.
#############################################################
#############################################################
# Print Statements
#############################################################
print("This begins output of Print Statements section.")
print("Bananas")
# Also try:
#print('Bananas')
# Each print statement puts the output on a new line. So the output of this
# line with the previous line will give:
# >>Bananas
# >>Give them to me
print("Give them to me")
# The print statement will print, in a literal sense, anything in quotation
# marks. However, it will print values without the quotation marks, as well
# as boolean values. The last line (line 27) will give an error because the
# boolean value is case sensitive and must be exactly 'True' or 'False'
print(5)
print(42.3)
print(True)
print(False)
#print(TRUE)
# The following prints multiple values and strings on the same line. Notice
# that all the values are just comma separated. The output of this line gives
# the output:
# >>Why is 6 afraid of 7
print("Why is", 6, "afraid of", 7)
print(' ')
print("This begins output of the Variables and Types section.")
#############################################################
# Variables and Types
#############################################################
# Variables such as 'myNum' below can be used to store values and change
# with different processes. Notice that it can also change data types as
# needed. In this example it can change from an integer to a float and will
# print:
# >>myNum is 16
# >>myNum is now 16.1
myNum = 16
print("myNum is", myNum, "and is of type", type(myNum))
myNum = 16.1
print("myNum is now", myNum, "and is of type", type(myNum))
# The variables myNum is created and initialized when we assign them
# a value. However, it is possible to initialize a variable without assigning
# it a value by setting the variable to 'None' which is Python's special word
# for null.
# Some operators will only work on certain data types. For example it doesn't
# make sense to multiply a string by 2.5. However, there are some funky
# tricks. Try running the commented line in the series below:
myString = "Bananas"
myNum = 2.5
#print(myString*myNum)
# The line will give an error that species you can't multiply a non-int with
# our string. So lets try an int:
myNum = 3
print("This is the result of multiplying a String and an Int: ",
myString*myNum)
# The output in this case is going to be our string printed 3 times as:
# >>BananasBananasBananas
# Booleans can also be mathematically operated on, and assume the values 1 for
# 'True' and 0 for 'False'.
# Play area:
d = print("Adding two strings together: ", "Hello" + "World")
print("The value of the output of a print statement is:", d)
# Type Casting
myNum = 5
print("I currently have value of", myNum, "that is type ", type(myNum))
# Above is some code that will print some info about the variable myNum. Next,
# we will do the same thing but after some type casting. What the following
# code will do is take our numeric value and translate it into text.
myNum = str(myNum)
print("I now have value of", myNum, "that is type ", type(myNum))
# Now we will play with casting different types to floats, ints, and bools
# using the functions float(), int(), and bool().
print("TYPE CASTING")
# This line will cast a float to an int but in doing, we will lose all info
# after the decimal. Printing this value will only give '5'.
print(int(5.1))
# This lines casts an int to a float. We make it into a decimal value and it
# will print '5.0'
print(float(5))
# We can cast strings to floats and ints but only in particular circumstances.
# The first few lines below will print successfully, but the
# other lines will throw errors for different reasons. Check each out
# individually to see exactly goes wrong.
print(int("5"))
print(float("5"))
print(bool(0.0))
print(int(False))
print(bool("0"))
print(bool(5.1))
#print(float("a"))
#print(int("5.1"))
#print(int("a"))
# It appears the bool() type caster will set any value to true unless it is the
# the integer or float value 0.
# Try different strings at the command terminal to see if they can be casted
# into these forms.
#v1 = input("See if this value can be casted from a string to an int: ")
#int(v1)
#print("SUCCESS!")
#v2 = input("See if this value can be casted from a string to a float: ")
#float(v2)
#print("SUCCESS!")
#v3 = input("See if this value can be casted from a string to a bool: ")
#bool(v3)
#print("SUCCESS!")
print(' ')
print("This begins output of the Logical Operators section.")
#############################################################
# Logical Operators
#############################################################
# Logical operators include:
# >>'==' to check for equality
# >>'>' to check for one value being greater than another
# >>'<' to check for one value being less than another
# >>'>=' to check for one value being greater than or equivalent to another
# >>'<=' to check for one value being less than or equivalent to another
# >>'and' is a boolean operator that does a bitwise and on your values
# >>'or' is a boolean operator that does a bitwise or on your values
# >>'not' is a boolean operator that is inverts a single values bits
# The following is some code using logical operators. The output of the code
# will give boolean values for the relational operators and numeric values
# for boolean ones.
a = 5
b = 4
c = 3
# This line will print the value 'True' since 5 is greater than 4
print("Result of a>b is: ", a>b)
# This line will print 'False' since 5 is not equivalent to 4
print("Result of a==b is: ", a==b)
# This will print the value '4'. Since 5 = 0b0101 and 4 = 0b0100, a bit wise
# will leave only 0b0100. Typically the boolean operators will be used on
# boolean values rather than integers. 'and' statements are only true if
# both statements are true. 'or' statements are true if either statement is
# true. 'not' statements would simply make a true into a false, and a false
# into a true.
print("Result of a and b is: ", a and b)
# Relational operators can be operated on strings too, not just number values.
# in the code below, we will illustrate some of the nuances of doing such
# things.
string_1 = "dead"
string_2 = "beef"
# This statement will return false since dead and beef are not the same
print("Result of 'dead'=='beef' is:", string_1 == string_2)
# This statement will return true! The operator will compare the value of the
# first letter of each word. Since 'd' is after 'b', it perceives it as 'd'
# being greater than 'b'
print("Result of 'dead' > 'beef' is:", string_1 > string_2)
string_1 = "Dead"
# This statement will return False. Python interprets capital letters as being
# less than lower case letters, no matter the letter.
print("Result of 'Dead' > 'beef' is:", string_1 > string_2)
# The 'in' set operator will check to see if a value or subset is contained
# within a list or larger set. In this example we will just see if some
# letters and words are in string.
string_1 = "This **** is bananas"
print("Checks to see if 'bananas' is in string_1:", "bananas" in string_1)
print("Checks to see if 'beef' is in string_1:", "beef" in string_1)
print("Checks to see if the letter 's' is in string_1:", "s" in string_1)
# Orders of operation. Python will usually run the 'and' statements first, and
# then the 'or's. The statements belows should give the outputs True.
print(True or True and False)
print(True and False or True)
print(' ')
print("This begins output of the Mathematical Operators section.")
#############################################################
# Mathematical Operators
#############################################################
# There are four basic mathematical operators: '+', '-', '/', and '*'. Division
# is the only math operator that doesn't maintain int types when ints are
# involved. If we divide 2 ints, it will automatically make the result a
# float, besides whether or not the ints evenly divide.
# There is a fifth operator python can often implement called modulus and is
# represented as '%'. It takes two values and will give you a remainder. The
# mod operator won't take in 'False' as its second value, and can't work on
# strings.
print("The result of 6.5%4.2 is:", 6.5%4.2)
print("The result of 7%True is:", 7%True)
# In terms of order of operations. It will perform the mod like a mult or div.
print("The result of 1+3%2 is:", 1+3%2) #Notice it performs the mod first.
# There are some other operators in python. One of them is floor division,
# given as '//'. Using this between any two values it will auto round down.
# Another is the exponentiation operator, given as '**'.
print("The result of 4**2-1 is:", 4**2-1) # Performs the exp first
print("The result of 4**2**2 is:", 4**2**2) # Mults the exps together
print("The result of 4**2*2 is:", 4**2*2) # Performs the exp first
print("The result of 4*2**2 is:", 4*2**2) # Performs the exp first
# Floor operators receive the same priority as regular division
# Self-Incrementing. In line 237, we use a self incrementing operator. We can
# actually replace the '+' with any math operator.
letterCount = 0
for character in "Hello World":
letterCount+=1
print(letterCount) |
47d7d110119490e9a81a417410e268f92b1ab3cb | lnhote/leetcode | /46_permutation.py | 1,229 | 3.71875 | 4 | class Solution(object):
"""docstring for Solution"""
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
return self.permuteResult([], nums)
def permuteResult(self, result, nums):
import copy
new_result = []
if len(nums) == 1:
perm_item = copy.deepcopy(result)
perm_item.append(nums[0])
new_result.append(perm_item)
else:
for j in range(0, len(nums)):
perm_item = copy.deepcopy(result)
perm_item.append(nums[j])
subresult = []
if j == 0:
subresult = self.permuteResult(perm_item, nums[1:])
elif j == len(nums) -1:
subresult = self.permuteResult(perm_item, nums[0:-1])
else:
subresult = self.permuteResult(perm_item, nums[0:j]+nums[j+1:])
for k in range(0, len(subresult)):
new_result.append(copy.deepcopy(subresult[k]))
return new_result
if __name__ == '__main__':
print Solution().permute([1,2,3])
print Solution().permute([1,2,3,4])
|
1adb1b699317592682b801b011c15cf2a09cafad | o-henry-coder/python05_12_2020 | /univer/HW/chapter02/algorithmic trainer.py | 999 | 3.984375 | 4 | #Task1
height = input('please, enter your height ')
print('thank you! your height is ', height)
#Task2
color = input('Now please, enter your favourite color ')
print('thank you! your color is ', color)
#Task3
a = int(input('enter a '))
b = a + 2
a = b * 4
b = a / 3.14
a = b - 8
print(a,b)
#Task4
w = 5
x = 4
y = 8
z = 2
result = x + y
result = z * 2
result = y / x
result = y - z
result = w // z
print(result)
#Task5
total = 10 + 14
#Task6
due = total - down_payment
#Task7
total = subtotal * 0.15
#Task8
a = 5
b = 2
c = 3
result = a + b * c
print(result)
#result should be 11
#Task9
num = 99
num = 5
print(num)
#num will be the last - 5
#Task10
sales = float(input('please enter a float number '))
print("a new shortened number is ", format(sales, '.2f'))
#Task11
number = 1234567.456
print(format(number, ',.1f'))
#Task12
print('George', 'John', 'Paul', 'Ringo', sep='@')
#output is George@John@Paul@Ringo
#Task13
turtle graphics TBD
#Task14
turtle graphics TBD
#Task15
turtle graphics TBD |
9c6706bae39da017aa9d24bd5e5dc424b853aa0e | jmac03/CSE310 | /client.py | 2,652 | 3.515625 | 4 | import socket
import errno
import sys
# Constants
HEADER_LENGTH = 16
FORMAT = "utf-8"
RECEIVE_COLOR = "\033[35m"
NORMAL_COLOR = "\033[32m"
ERROR_COLOR = "\033[31m"
# IP address of this computer
IP = socket.gethostbyname(socket.gethostname())
PORT = 1234
ADDR = (IP, PORT)
my_username = input("Username: ")
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(ADDR)
client_socket.setblocking(False)
username = my_username.encode(FORMAT)
username_header = f"{len(username):<{HEADER_LENGTH}}".encode(FORMAT)
client_socket.send(username_header + username)
def display(data, color=None):
"""
Prints colored text to the console
Parameters:
data(string): message to be printed
color(string): color for message to be printed in
"""
if color is not None:
print(color + data + NORMAL_COLOR)
else:
print(NORMAL_COLOR + data)
# Display blank message to set text color
display("", NORMAL_COLOR)
while True:
# Message to be sent to server
message = input(f"{my_username} > ")
# If a message was entered prepare and send message to server
if message:
message = message.encode(FORMAT)
message_header = f"{len(message):<{HEADER_LENGTH}}".encode(FORMAT)
client_socket.send(message_header + message)
# receive all messages loop
try:
while True:
# Receive username header
username_header = client_socket.recv(HEADER_LENGTH)
if not len(username_header):
display("Connection closed by the server.", ERROR_COLOR)
sys.exit()
username_length = int(username_header.decode(FORMAT))
# Receive username
username = client_socket.recv(username_length).decode(FORMAT)
# Receive message header
message_header = client_socket.recv(HEADER_LENGTH)
message_length = int(message_header.decode(FORMAT))
# Receive message
message = client_socket.recv(message_length).decode(FORMAT)
# Prepare and display message
display_message = f"{username} > {message}"
display(display_message, RECEIVE_COLOR)
except IOError as e:
# If the IOError error was not expected, display the error and stop the client program
if e.errno != errno.EAGAIN and e.errnor != errno.EWOULDBLOCK:
display(f"Reading error {str(e)}", ERROR_COLOR)
sys.exit()
continue
except Exception as e:
# If there is any non-IOError, display it
display(f"General error {str(e)}", ERROR_COLOR)
sys.exit()
|
8741c3ec2c5dba3f088820dfce94c27587c9512f | shouliang/Development | /Python/PyDS/array_sum.py | 801 | 3.8125 | 4 | # coding=utf-8
'''
数组求和
'''
# 循环遍历做法
def sum1(array):
sum = 0
for value in array:
sum += value
return sum
# 递归: 分解为最后一位+前n-1项的求和,递归终止条件:n == 1
def sum2(array):
def sumCore(array, n):
if n == 1:
return array[0]
return array[n - 1] + sumCore(array, n - 1)
return sumCore(array, len(array))
# 二分递归:分解为前后两部分求和
def sum3(array):
def sumCore(array, i, n):
if n <= 1:
return array[i]
return sumCore(array, i, n // 2) + sumCore(array, i + (n // 2), n // 2)
return sumCore(array, 0, len(array) - 1)
sum1 = sum1([5, 3, 6, 7])
print(sum1)
sum2 = sum2([5, 3, 6, 7])
print(sum2)
sum3 = sum3([5, 3, 6, 7])
print(sum2)
|
37ee2ccc42bdbbb544291b2587f49a00ea4d061d | StetsenTech/rolodex-reader | /rolodex/utils/process.py | 2,320 | 3.65625 | 4 | """Module that adds methods to help with processing input"""
import re
import phonenumbers
# Regex validators for file input
VALID_ONE = re.compile((
r'(?P<last>[A-z]+),\s(?P<first>[A-z. ]+),\s'
r'(?P<phone>\([0-9]{3}\)-[0-9]{3}-[0-9]{4}),\s'
r'(?P<color>[A-z ]+),\s(?P<zip>[0-9]{5})'
))
VALID_TWO = re.compile((
r'(?P<first>[A-z. ]+)\s(?P<last>[A-z]+),\s'
r'(?P<color>[A-z ]+),\s(?P<zip>[0-9]{5}),\s'
r'(?P<phone>[0-9]{3}\s[0-9]{3}\s[0-9]{4})'
))
VALID_THREE = re.compile((
r'(?P<first>[A-z. ]+),\s(?P<last>[A-z]+),\s'
r'(?P<zip>[0-9]{5}),\s(?P<phone>[0-9]{3}\s[0-9]{3}\s[0-9]{4}),\s'
r'(?P<color>[A-z ]+)'
))
def process_entries(entries, p_format="{}-{}-{}"):
"""Checks if entry data is valid
Args:
entries(list): List of personal information
p_region(basestring): Region the phone is from
p_format(basestring): Output format for phone number
Returns:
list, list: List of entry dictories and a list of invalid indices
"""
valid_entries = [] # Tracks valid entries
errors = [] # Tracks invalid entry indices
for i, entry in enumerate(entries):
# Check to see if entry is valid
# If invalid, add index to list of invalid entries
if VALID_ONE.match(entry):
entry_match = VALID_ONE.match(entry)
elif VALID_TWO.match(entry):
entry_match = VALID_TWO.match(entry)
elif VALID_THREE.match(entry):
entry_match = VALID_THREE.match(entry)
else:
errors.append(i)
continue
# Convert phone number
# @ TODO: Handle in marshmallow schema
phone = _format_phone_number(entry_match.group("phone"), p_format)
# Check to see if entry is valid
entry_dict = {
"first_name": entry_match.group("first"),
"last_name": entry_match.group("last"),
"phone_number": phone,
"color": entry_match.group("color"),
"zipcode": entry_match.group("zip")
}
valid_entries.append(entry_dict)
return valid_entries, errors
def _format_phone_number(phone, p_format):
"""Converts phone number to desired format"""
phone_object = phonenumbers.parse(phone, "US")
return phonenumbers.format_number(phone_object, p_format)
|
7b6c9b49eff36473333993646501077b86ab7e4b | salim7ali/HackerRank | /Algorithms/Implementation/Encryption/solution.py | 907 | 4.03125 | 4 | #https://www.hackerrank.com/challenges/encryption
#!/bin/python3
import math
import os
import random
import re
import sys
from itertools import zip_longest
# Complete the encryption function below.
def encryption(text):
low = math.floor(math.sqrt(len(text)))
high = math.ceil(math.sqrt(len(text)))
newText = []
for ind, char in enumerate(text):
if ind ==0:
newText.append(list(text[0:high]))
if ind%high==0 and ind>=high :
newText.append(list(text[ind:ind+high]))
result = list(zip_longest(*newText, fillvalue=''))
finalRes = ""
for res in result:
for ch in res:
finalRes += ch
finalRes += ' '
return finalRes
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = encryption(s)
fptr.write(result + '\n')
fptr.close() |
5b5f1892d90bc5af3fea0a93d7dc44343ae65093 | cheonyeji/algorithm_study | /이코테/구현/q11_기둥과보.py | 5,241 | 3.53125 | 4 | # 2021-01-30
# 이코테 ch12 구현 문제 Q11 기둥과 보 설치
# https://programmers.co.kr/learn/courses/30/lessons/60061
# 해설
# 구현 과정이 복잡하고, 시간이 5초로 넉넉하기 때문에 m^3의 시간복잡도로 간단하게 해결하는 풀이
# 설치 및 삭제 연산을 요구할때마다 일일히 전체 구조물을 확인하며 규칙 체크
# 현재 설치된 구조물이 가능한 구조물인지 확인
def possible(answer):
for x, y, stuff in answer:
if stuff == 0: # 기둥 설치
if (
y == 0
or [x - 1, y, 1] in answer
or [x, y, 1] in answer
or [x, y - 1, 0] in answer
):
continue
return False
elif stuff == 1: # 보 설치
if (
[x, y - 1, 0] in answer
or [x + 1, y - 1, 0] in answer
or ([x - 1, y, 1] in answer and [x + 1, y, 1] in answer)
):
continue
return False
return True
def solution(n, build_frame):
answer = []
for frame in build_frame:
x, y, stuff, operate = frame
if operate == 0:
answer.remove([x, y, stuff])
if not possible(answer):
answer.append([x, y, stuff])
if operate == 1:
answer.append([x, y, stuff])
if not possible(answer):
answer.remove([x, y, stuff])
return sorted(answer)
print(
solution(
5,
[
[0, 0, 0, 1],
[2, 0, 0, 1],
[4, 0, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[2, 1, 1, 1],
[3, 1, 1, 1],
[2, 0, 0, 0],
[1, 1, 1, 0],
[2, 2, 0, 1],
],
)
)
# 테스트케이스 2개만 맞고 나머지 경우는 모두 틀린 판정이 난 풀이
# 기둥이 설치된 경우 해당 교차점의 왼쪽좌표에 +1
# 보가 설치된 경우 해당 교차점의 한칸 아래에 +2
"""
arr_g = []
arr_b = []
# 기둥이 조건 만족하는지 체크
def check_g(graph, x, y):
# 바닥 위/ 보의 한쪽 끝 부분 위/ 다른 기둥 위
if (
y == 0
or (graph[y - 1][x - 1] >= 2 or graph[y - 1][x] >= 2)
or graph[y - 1][x] % 2 == 1
):
return True
return False
# 보가 조건 만족하는지 체크
def check_b(graph, x, y):
# 한쪽 끝 부분이 기둥 위 / 양쪽 끝 부분이 다른 보와 동시에 연결
if (
graph[y - 1][x] % 2 == 1
or graph[y - 1][x + 1] % 2 == 1
or (graph[y - 1][x - 1] >= 2 and graph[y - 1][x + 1] >= 2)
):
return True
return False
def check_all(graph):
avail_g = True
avail_b = True
for i in arr_g:
avail_g = check_g(graph, i[0], i[1])
if not avail_g:
break
for i in arr_b:
avail_b = check_b(graph, i[0], i[1])
if not avail_b:
break
if not avail_b or not avail_g:
return False
else:
return True
# a 0 기둥 / 1 보
# b 0 삭제 / 1 설치
def build(graph, build_frame):
for i in build_frame:
x, y, a, b = i
if b == 1:
# 기둥 설치
if a == 0:
if check_g(graph, x, y):
graph[y][x] += 1
arr_g.append((x, y))
# 보 설치
else:
if check_b(graph, x, y):
graph[y - 1][x] += 2
arr_b.append((x, y))
else:
# 기둥 삭제
if a == 0:
arr_g.remove((x, y))
graph[y][x] -= 1
removable = check_all(graph)
if not removable:
arr_g.append((x, y))
graph[y][x] += 1
# 보 삭제
else:
arr_b.remove((x, y))
graph[y - 1][x] -= 2
removable = check_all(graph)
if not removable:
arr_b.append((x, y))
graph[y - 1][x] += 2
def print_result():
result = []
for i in arr_g:
result.append([i[0], i[1], 0])
for i in arr_b:
result.append([i[0], i[1], 1])
result.sort(key=lambda data: (data[0], data[1], -data[2]))
return result
def solution(n, build_frame):
answer = [[]]
graph = [[0] * (n + 1) for _ in range(n)] # 가로 n+1 * 세로 n
build(graph, build_frame)
answer = print_result()
return answer
print(
solution(
5,
[
[0, 0, 0, 1],
[2, 0, 0, 1],
[4, 0, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[2, 1, 1, 1],
[3, 1, 1, 1],
[2, 0, 0, 0],
[1, 1, 1, 0],
[2, 2, 0, 1],
],
)
)
"""
"""
TC 1
5, [[1,0,0,1],[1,1,1,1],[2,1,0,1],[2,2,1,1],[5,0,0,1],[5,1,0,1],[4,2,1,1],[3,2,1,1]]
-> [[1,0,0],[1,1,1],[2,1,0],[2,2,1],[3,2,1],[4,2,1],[5,0,0],[5,1,0]]
TC 2
5, [[0,0,0,1],[2,0,0,1],[4,0,0,1],[0,1,1,1],[1,1,1,1],[2,1,1,1],[3,1,1,1],[2,0,0,0],[1,1,1,0],[2,2,0,1]]
-> [[0,0,0],[0,1,1],[1,1,1],[2,1,1],[3,1,1],[4,0,0]]
"""
|
7fc685e7bc1be522d8416ba0f3d77131e448234c | 1bcb1/Lab06 | /Conservation of Angular Momentum.py | 1,617 | 3.625 | 4 | # Brooks Brickley & Hector Hernandez CC: 2019
from statistics import mean
from math import sqrt
before = input('What is the name of the before file? : ') + '.csv'
after = input('What is the name of the after file? : ') + '.csv'
beforeID = open(before, 'r')
data = []
firstline = beforeID.readline()
nextline = beforeID.readline()
while nextline != '':
data.append(nextline.split(','))
nextline = beforeID.readline()
bvx = []
bvy = []
for i in range(len(data)):
bvx.append(float(data[i][0])/100)
bvy.append(float(data[i][1])/100)
afterID = open(after, 'r')
data = []
firstline = afterID.readline()
nextline = afterID.readline()
while nextline != '':
data.append(nextline.split(','))
nextline = afterID.readline()
avx = []
avy = []
for i in range(len(data)):
avx.append(float(data[i][0])/100)
avy.append(float(data[i][1])/100)
magnitude_before = sqrt((mean(bvx))**2 + (mean(bvy))**2)
magnitude_after = sqrt((mean(avx))**2 + (mean(avy))**2)
radius1 = float(input('What is the radius from the point tracked to the center of mass in cm? : ')) / 100
radius2 = float(input('What is the distance of the 20-gram mass from the center of mass in cm? : ')) /100
w_before = magnitude_before/radius1
w_after = magnitude_after/radius1
print(w_before)
print(w_after)
I_before = 9.7 * 10 ** -4
I_weight = 2.34 * 10 ** -6
mass = 20/1000
momentum_before = I_before * w_before
momentum_after = (I_before + I_weight + mass * radius2 ** 2) * w_after
print('The momentum before is', momentum_before)
print('The momentum after is', momentum_after)
print('The net momentum is', abs(momentum_before-momentum_after))
|
164fe64755c132ef76ab8d92f9a308b2760d2002 | srclayton/Python-uDemy | /ex01.py | 167 | 4.03125 | 4 | # -*- coding: utf-8 -*-
idade = int(input("Digite sua idade: "))
if idade > 17:
print("Você é maior de idade!")
else:
print("Oh não, você é menor de idade!") |
d70045f170b1622864cf036131c038c7ea1b03bf | zhkflame/StudyCode | /BFSandDFS/mytree.py | 766 | 3.609375 | 4 | class TreeNode(object):
def __init__(self,v=None):
self.val=v
self.right=None
self.left=None
def addLeft(self,ele):
self.left=ele
def addRight(self,ele):
self.right=ele
def setValue(self,v):
self.val=v
if __name__=='__main__':
binT=TreeNode('t')
binA=TreeNode('a')
binB=TreeNode('b')
binC=TreeNode('c')
binD=TreeNode('d')
binE=TreeNode('e')
binF=TreeNode('f')
binG=TreeNode('g')
binH=TreeNode('h')
binT.addLeft(binA)
binT.addRight(binB)
binA.addLeft(binC)
binA.addRight(binD)
binB.addRight(binE)
binD.addLeft(binF)
binE.addLeft(binG)
binE.addRight(binH)
print(binT.value)
print(binT.left.value)
print(binT.right.value)
|
c0ec3abac0da9ec860aedff8efbe9b9688797788 | hrishisd/CS170-Solver | /phase2/solver.py | 5,098 | 3.828125 | 4 | import argparse
import random
import numpy as np
from collections import defaultdict
import operator
"""
======================================================================
Complete the following function.
======================================================================
"""
def solve(num_wizards, num_constraints, wizards, constraints):
"""
Write your algorithm here.
Input:
num_wizards: Number of wizards
num_constraints: Number of constraints
wizards: An array of wizard names, in no particular order
constraints: A 2D-array of constraints,
where constraints[0] may take the form ['A', 'B', 'C']i
Output:
An array of wizard names in the ordering your algorithm returns
"""
def map_wiz_to_index(partial_ordering):
mapping = {}
for i, wiz in enumerate(partial_ordering):
mapping[wiz] = i
return mapping
def count_invalid_constraints(partial_ordering):
wiz_to_invalid = map_wiz_to_invalid_constraint(partial_ordering)
count = sum(wiz_to_invalid.values())
return count/3
def map_wiz_to_invalid_constraint(partial_ordering):
wiz_to_index = map_wiz_to_index(partial_ordering)
mapping = defaultdict(int)
for constraint in constraints:
w1, w2, w3 = constraint[0], constraint[1], constraint[2]
i, j, k = wiz_to_index[w1], wiz_to_index[w2], wiz_to_index[w3]
if (k > i and k < j) or (k < i and k > j):
mapping[w1] += 1
mapping[w2] += 1
mapping[w3] += 1
return mapping
def get_most_invalid_wiz(partial_ordering):
#get mapping from wiz to num invalid
wiz_to_invalid = map_wiz_to_invalid_constraint(partial_ordering)
#get wiz with max invalid count
max_wiz = max(wiz_to_invalid.iteritems(), key=operator.itemgetter(1))[0]
return max_wiz
def update(partial_ordering):
"""
returns a better ordering from 1 swap
"""
max_wiz = get_most_invalid_wiz(partial_ordering)
bad_wiz_index = partial_ordering.index(max_wiz)
curr_num_invalid = count_invalid_constraints(partial_ordering)
for i in range(num_wizards):
if i == bad_wiz_index:
pass
partial_ordering[i], partial_ordering[bad_wiz_index] = partial_ordering[bad_wiz_index], partial_ordering[i]
if count_invalid_constraints(partial_ordering) < curr_num_invalid:
return list(partial_ordering)
else:
partial_ordering[i], partial_ordering[bad_wiz_index] = partial_ordering[bad_wiz_index], partial_ordering[i]
return list(partial_ordering)
#def random_update(partial_ordering):
best = wizards
best_invalid = count_invalid_constraints(wizards)
print ("num constraints", num_constraints)
print("init invalid", best_invalid)
while(best_invalid > 100):
temp = np.random.permutation(wizards)
curr_invalid = count_invalid_constraints(temp)
#print(curr_invalid)
if (curr_invalid < best_invalid):
best_invalid = curr_invalid
best = temp
print(best_invalid)
print best
if best_invalid == 0:
break
updated_ordering = best.tolist()
prev_num_invalid = count_invalid_constraints(updated_ordering)
while (best_invalid > 10):
updated_ordering = update(updated_ordering)
curr_num_invalid = count_invalid_constraints(updated_ordering)
print curr_num_invalid
if curr_num_invalid == prev_num_invalid:
pass
prev_num_invalid = curr_num_invalid
#print(constraints, constraints)
return updated_ordering
"""
======================================================================
No need to change any code below this line
======================================================================
"""
def read_input(filename):
with open(filename) as f:
num_wizards = int(f.readline())
num_constraints = int(f.readline())
constraints = []
wizards = set()
for _ in range(num_constraints):
c = f.readline().split()
constraints.append(c)
for w in c:
wizards.add(w)
wizards = list(wizards)
return num_wizards, num_constraints, wizards, constraints
def write_output(filename, solution):
with open(filename, "w") as f:
for wizard in solution:
f.write("{0} ".format(wizard))
if __name__=="__main__":
parser = argparse.ArgumentParser(description = "Constraint Solver.")
parser.add_argument("input_file", type=str, help = "___.in")
parser.add_argument("output_file", type=str, help = "___.out")
args = parser.parse_args()
num_wizards, num_constraints, wizards, constraints = read_input(args.input_file)
solution = solve(num_wizards, num_constraints, wizards, constraints)
write_output(args.output_file, solution)
|
232dd01c726bd37b6e46ee7221954bf112624929 | bumjin/python-essential | /18_gui-programming/gui.py | 561 | 3.53125 | 4 | #!/usr/bin/env python
import wx
def sayHello(event):
#print "hello world!"
#textArea.SetValue("hello World!")
labelValue = myLable.GetValue()
textArea.AppendText(" Hello "+labelValue)
app = wx.App()
frame = wx.Frame(None, title="hello world!", size=(400,400))
frame.Show()
helloButton = wx.Button(frame, label='say hello!', pos=(160,20), size=(80,20))
helloButton.Bind(wx.EVT_BUTTON, sayHello)
textArea = wx.TextCtrl(frame, style=wx.TE_MULTILINE, pos=(20,100), size=(360, 250))
myLable = wx.TextCtrl(frame, pos=(10,40), size=(140,20))
app.MainLoop() |
65cb8faecf0cdecf2904f56145becca0093d2a01 | Nora-Wang/Leetcode_python3 | /Stack/716. Max Stack.py | 1,983 | 4.1875 | 4 | Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
Note:
-1e7 <= x <= 1e7
Number of operations won't exceed 10000.
The last four operations won't be called when stack is empty.
code:
class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.max_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.max_stack:
self.max_stack.append(x)
else:
self.max_stack.append(max(x, self.max_stack[-1]))
def pop(self) -> int:
self.max_stack.pop()
return self.stack.pop()
def top(self) -> int:
return self.stack[-1] if self.stack else None
def peekMax(self) -> int:
return self.max_stack[-1] if self.max_stack else None
def popMax(self) -> int:
Max = self.max_stack[-1]
temp = []
while self.stack and self.stack[-1] != Max:
temp.append(self.stack.pop())
self.max_stack.pop()
self.stack.pop()
self.max_stack.pop()
for num in temp[::-1]:
self.push(num)
return Max
# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax()
|
048c631503e728b70329a317514a8e4621177193 | vidi-vidi/Tugas | /5a.py | 279 | 3.6875 | 4 | print("MENGECEK KELULUSAN")
jwb = "y"
while jwb.lower() == "y":
n = input("Masukan nilai =")
if int(n) > 60:
status = "Lulus"
else:
status = "Ulang"
print(status)
jwb = input("Input Lagi y/t")
if jwb.lower() == "t":
print(jwb)
break |
d00d3c1c3ef2bceaa49c2da91dc20fa16aba507a | ZhangYajun12138/buxianxian | /BuXianXian/buxianxian10.py | 1,619 | 4.53125 | 5 | # coding:utf-8
# string
def main():
str1 = "hello world!"
# 通过len函数计算字符串的长度
print(len(str1))
# 获得字符串首字母大写的拷贝
print(str1.capitalize())
# 获得字符串变大写的拷贝
print(str1.upper())
# 从字符串中查找子字符串所在位置
print(str1.find("or"))
print(str1.find("shit"))
# 与find类似但找不到子字符串时会引发异常
print(str1.index("or"))
# print(str1.index("shit"))
# 检查字符串是否以指定的字符串开头
print(str1.startswith("he"))
print(str1.startswith("ee"))
# 检查字符串是否以指定的字符串结尾
print(str1.endswith("!"))
print(str1.endswith("d"))
# 将字符串以指定宽度居中放置左侧填充指定字符
print(str1.center(50,"*"))
# 将字符串以指定宽度靠右放置左侧填充指定字符
print(str1.rjust(50,'*'))
str2 = "abc123456"
# 从字符串中取出指定位置的字符,下标运算
print(str2[2])
# 字符串切片,从指定的开始索引到指定的结束索引
print(str2[2:5])
print(str2[2:])
print(str2[2::2])
print(str2[::2])
print(str2[::-1])
print(str2[-3::-1])
# 检查字符串是否由数字构成
print(str2.isdigit())
# 检查字符串是否由字母构成
print(str2.isalpha())
# 检查字符串是否由数字和字母组成
print(str2.isalnum())
# 获得字符串修剪左右两侧空格的拷贝
str3 = " 234cvb "
print(str3)
print(str3.strip())
if __name__ == "__main__":
main() |
5b23fd00af451fa857ac8ddbb77487e0eb83fc34 | darvid7/fit2085-notes | /algorithms/01-bubble_sort.py | 168 | 3.75 | 4 | def bubble_sort(L):
n = len(L)
for i in range(n - 1):
for j in range(n - 1):
if L[j] > L[j + 1]:
L[i], L[j] = L[j], L[i] |
334138e515e0fa63ad033f3648a67c9ad83f3361 | ridbit10/PS1-Parinati-Solutions | /DateAndTime/Date.py | 689 | 4.15625 | 4 | import datetime
#gets current date and time
datetime_object=datetime.datetime.now()
print(datetime_object)
#gets todays date
date_object=datetime.date.today()
print(date_object)
#date is a constructor
d=datetime.date(1999,10,6)
print(d)
#date from timestamp
timestamp=datetime.date.fromtimestamp(1326244364)
print("Date =",timestamp)
today =datetime.date.today()
print("Year is",today.year)
print("Month is",today.month)
print("Day is",today.day)
#different ways to construct time object
time_1=datetime.time()
print("time_1 =",time_1)
time_2=datetime.time(7,24,50)
print("time_2 =",time_2)
#last argument is microsecond
time_3=datetime.time(7,24,50,10000)
print("time_3=",time_3)
|
af0062ca859e0b372db17af63c7e4d618dc62f5b | alejo979/Address-Book | /ab1.py | 5,618 | 4.1875 | 4 | # Create your own command-line address-book program using which you can browse, add, modify, delete or search for your contacts
# such as friends, family and colleagues and their information such as email address and/or phone number.
# Details must be stored for later retrieval.
import pickle
from pathlib import Path
abfile = 'abfile.pkl' # where data is stored
if not Path('abfile.pkl').exists(): # Si no existe # C:\\Py\\Projects\\
ab = {} # Create empty Dictionary
else:
f = open("abfile.pkl","rb")
ab = pickle.load(f)
print('''Welcome to your address book (Current Contacts: {})'''.format(len(ab)))
def print_main_menu():
print('''What do you want to do?
1: Create a contact
2: Find a contact
3: Show all your contacts
4: Update a contact
5: Delete a contact
6: Exit''')
def input_selection_func():
global input_Selection
input_Selection = int(input('Type a number >>> '))
def next_step_func():
next_step = int(input('\nDo you want to (0)Exit or go back to (1)Main menu?>>> '))
while True:
if next_step == 0:
global running
running = False
break
else:
print_main_menu()
break
class Contact:
def __init__(self,name,email,tel):
self.name = name
self.email = email
self.tel = tel
def whoIam(self):
print('Contact created >>>',
'Name:',self.name,
' E-mail:',self.email,
' Tel:',self.tel)
print_main_menu()
running = True
while running:
input_Selection = int(input('Type a number >>> '))
if input_Selection == 1: # Create a contact
print('Creating contact:')
contact1_name = input('Type the name: ')
contact1_email = input('Type in the email: ')
contact1_tel = input('Type in Tel: ')
contact1 = Contact(contact1_name,contact1_email,contact1_tel)
contact1.whoIam()
ab[contact1_name] = [contact1_email, contact1_tel]
print('You have now {} contacts'.format(len(ab)))
f = open(abfile, 'wb')
pickle.dump(ab, f)
f.close()
next_step_func()
elif input_Selection == 2: # Find a contact by name
print('Finding contact:')
find2 = input('Type in the name: ')
if find2 in ab:
for key,value in ab.items():
if key == find2:
print(value)
next_step_func()
else:
print('Contact does not exist')
next_step_func()
elif input_Selection == 3: # Show all contacts
print("All your contacts and details:")
#print(sorted(ab)) --- this just prints the keys
for key,value in sorted(ab.items(), key=lambda x: x[0]):
print(key,value, sep='\t') # for snack in fruit: print(fruit[snack]) >> just prints the values, not the keys
next_step_func()
elif input_Selection == 4: # Update a contact by name
update4 = input("Type in the contact's name to update: ")
if update4 in ab:
running4 = True
while running4:
print('''What do you want to update:
(1: Email
2: Tel)''')
update4_selection = int(input('>>> '))
if update4_selection == 1:
print('Current email: {}'.format(ab[update4][0]))
update4_1 = input('Type the new email: ')
ab[update4][0] = update4_1
print('New email is: {}'.format(ab[update4][0]))
f = open(abfile, 'wb')
pickle.dump(ab, f)
f.close()
next_step_func()
running4 = False
elif update4_selection == 2:
print('Current Tel: {}'.format(ab[update4][1]))
update4_2 = input('Type the new Tel: ')
ab[update4][1] = update4_2
print('New Tel is: {}'.format(ab[update4][1]))
f = open(abfile, 'wb')
pickle.dump(ab, f)
f.close()
next_step_func()
running4 = False
else:
print('Please choose 1 or 2')
#else:
#print('Done loop inside 1email or 2tel')
else:
print('Contact does not exist')
next_step_func()
elif input_Selection == 5: # Delete a contact by name
delete4 = input("Type in the contact's name to delete: ")
del ab[delete4]
print('Contact {} has been deleted'.format(delete4))
f = open(abfile, 'wb')
pickle.dump(ab, f)
f.close()
next_step_func()
elif input_Selection == 6: # Exit
break
print('Goodbye and come back soon')
|
5ce77a872ab716ca11e266d7a8c43b70bb831aa2 | satriansyahw/StudyPython | /Test2.py | 917 | 3.828125 | 4 | # string
name="kiran"
kar1=name[1]
print(kar1)
print(type(name))
print(name.capitalize())
anak=["Ara","Kiran"]
print('print pertama :' + anak[0])
print('print kedua : '+anak[1])
txt ="hai-hello-world"
txtsplit= txt.split('-')
print('Split 0 : '+txtsplit[0])
print('Split 1 : '+txtsplit[1])
print('Split 2 : '+txtsplit[2])
mylist=["apple","orange","grape",234,98.67]
mylist[2]=88
print(mylist[0])
print(mylist[2])
print(mylist[4])
print(mylist)
mylist.append("34")
print(mylist)
#Dictionary object
data ={"p1":"Yayan","p2":"Bintang","p3":"Ara","p4":"Kiran"}
print(data)
print(data['p3'])
myurl = "sixty-north.com/c/t.txt"
from urllib.request import urlopen
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words=[]
for line in story:
line_world=line.split()
for world in line_world:
story_words.append(world)
print(story_words)
|
1778c257042176fb58c7cee607795281900c1f36 | Carmenliukang/leetcode | /算法分析和归类/动态规划/打家劫舍.py | 1,522 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上
# 被小偷闯入,系统会自动报警。
#
# 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
#
#
#
# 示例 1:
#
#
# 输入:[1,2,3,1]
# 输出:4
# 解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
# 偷窃到的最高金额 = 1 + 3 = 4 。
#
# 示例 2:
#
#
# 输入:[2,7,9,3,1]
# 输出:12
# 解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
# 偷窃到的最高金额 = 2 + 9 + 1 = 12 。
#
#
#
#
# 提示:
#
#
# 1 <= nums.length <= 100
# 0 <= nums[i] <= 400
#
# Related Topics 数组 动态规划 👍 1631 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
# 状态 到第I 位置,的最大金额
size = len(nums)
dp = [0] * (size + 1)
dp[1] = nums[0]
for i in range(2, size + 1):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])
return dp[-1]
# leetcode submit region end(Prohibit modification and deletion)
|
49b2a4d7ea2eee79f263366883e457fd22b478b9 | bill-ma/project-euler | /random_number_game.py | 384 | 3.96875 | 4 | import random
low = 1;
high = 100;
x = random.randrange(low,high);
#print(x);
print("I'm thinking of a number b/t", low, "and", high, end="\n\n");
count = 1;
while True:
print("Attempt #", count, end=": ");
guess = int(input());
if(guess < x):
print("Too low!");
elif(guess > x):
print("Too high!");
else:
print("Correct!");
break;
count+=1;
|
d77de5c02531a1311995a7f9c44d1212b455a8de | kenwu90/leetcode | /complement_number.py | 541 | 3.609375 | 4 | import sys
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
# find leading 1
a = num
cnt = 0
while ((a & sys.maxsize) > 0):
cnt += 1
a = a >> 1
b = 0
for i in range(cnt):
b = b | 1
b = b << 1
b = b >> 1
return (num ^ b)
def main():
s = Solution()
print(s.findComplement(5))
if __name__ == '__main__':
main()
|
d37766651b385108883f6094c929120d667a3e99 | TwilightStrafer/LeanCoding | /strings.py | 109 | 3.796875 | 4 | a = 'hello'
b = "hello"
c = """hello
Next Line
Third Line
"""
print(c)
name = input ("What's Your Name?\n") |
5afa4c0b90297824f949b378027a7938ff7649b7 | Ran4/stringexpand | /stringexpand/__init__.py | 1,197 | 3.953125 | 4 | #!/usr/bin/env python3
__all__ = ["expand"]
from typing import List, Tuple
from functools import wraps
def find_braces(s: str) -> Tuple:
return (s.index("{"), s.index("}"))
def string_contains_set_of_braces(s: str) -> bool:
return s.find("}") > s.find("{") >= 0
def split_brace_contents(s: str) -> List[str]:
return s.split(",")
def expand(s: str) -> List[str]:
if not string_contains_set_of_braces(s):
return [s]
expanded_strings = []
begin_brace, end_brace = find_braces(s)
brace_contents = s[begin_brace+1:end_brace]
for content in split_brace_contents(brace_contents):
expanded_string = "{before_brace}{content}{after_brace}".format(
before_brace=s[:begin_brace],
content=content,
after_brace=s[end_brace+1:],
)
expanded_strings.append(expanded_string)
# There might still be more strings to expand
new_list = []
for expanded_string in expanded_strings:
if string_contains_set_of_braces(expanded_string):
new_list += expand(expanded_string)
else:
new_list.append(expanded_string)
return new_list
|
d188c66ed92a38d8348da7a9de56ad36fee0ea21 | iasinDev/codinginterviewquestions | /Simple Queries/Solution.py | 258 | 3.5 | 4 | import bisect
def counts(nums, maxes):
nums.sort()
result = []
for max in maxes:
index = bisect.bisect_right(nums, max)
result.append(index)
return result
print(counts([1,4,2,4],[3,5]))
print(counts([2,10,5,4,8],[3,1,7,8])) |
718c95f8fcac9c60c5783aa11a78c2077bda7ff8 | 316060064/Taller-de-herramientas-computacionales | /Clases/Programas/Tarea4/Problema03.py | 298 | 4 | 4 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
'''
Josue Artemio Hernandez Rodriguez, 316060064
Este programa realiza la conversion de grados
centigrados a farenheit, y viceversa.
'''
def grados(x):
g = 0
if x == 1:
x = (x * 9/5.0) + 32
else:
x = (x - 32) * 5.0/9
return x
|
83d0092762593cfbf4d7111b2c8154c8fda273e3 | smrsassa/Studying-python | /curso/PY3/funcao/funcao2/ex6.py | 263 | 3.546875 | 4 | #exercicio106
while True:
def div_texto():
print ('-='*40)
div_texto()
print ('Sistema de ajuda PyHELP')
div_texto()
opc = str(input('Digite a função aqui: '))
if opc.lower() == 'fim':
break
else:
help(opc)
|
168e854f32e1aa6626bd915aaa3b68ea18f6db68 | Jahanzaib-int/Cryptographic-Algorithms | /RSA.py | 3,590 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 10:39:35 2018
@author: Jahanzaib Malik
"""
import random
'''
Euclid's algorithm for determining the greatest common divisor
Use iteration to make it faster for larger integers
'''
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
'''
Euclid's extended algorithm for finding the multiplicative inverse of two numbers
'''
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def multiplicative_inverse(e, phi):
d = 0
x1 = 0
x2 = 1
y1 = 1
temp_phi = phi
while e > 0:
temp1 = temp_phi / e
temp2 = temp_phi - temp1 * e
temp_phi = e
e = temp2
x = x2 - temp1 * x1
y = d - temp1 * y1
x2 = x1
x1 = x
d = y1
y1 = y
if temp_phi == 1:
return d + phi
def generate_keypair(p, q):
# Calcuating N
n = 919 * 1033
# Calculating Phi
phi = (919 - 1) * (1033 - 1)
# Choose an integer e such that e and phi(n) are coprime
#In our given case Phi will be 947376
# e should in between(1, phi)
e = 517
# Looping and using Euclid's Algorithm to verify that GCD of e and phi(949327) is 1
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
# Use Extended Euclid's Algorithm to generate the private key
d = modinv(e, phi)
#d = 358063
# Return public and private keypair
# Public key(e, n) and private key (d, n)
return ((e, n), (d, n))
def encrypt(pk, plaintext):
# Seperating public key and n from 'pk'
key, n = pk
# Convert each letter in the plaintext to numbers based on the character using a^b mod m
#cipher = [pow(ord(char), key, n) for char in plaintext]
cipher = []
for char in plaintext:
order = ord(char)
print("ASCII is : ", order)
Encryptedletter = pow(order, key, n)
print("Power : ",Encryptedletter)
cipher.append(Encryptedletter)
print(cipher)
# Return the array of bytes
return cipher
def decrypt(pk, ciphertext):
# Seperating private key and n from 'pk'
key, n = pk
# Generate the plaintext based on the ciphertext and key using a^b mod m
print(ciphertext)
#plain = [chr(pow(char, key, n)) for char in ciphertext]
plain = []
for char in ciphertext:
print(char)
power = pow(char, key) % n
print("ASCII is : ", power)
DecryptedMessage = chr(power)
print("Decrypted : ", DecryptedMessage)
plain.append(DecryptedMessage)
# Return the array of bytes as a string
return ''.join(plain)
if __name__ == '__main__':
'''
Detect if the script is being run directly by the user
'''
print("RSA Encryption Assignment---Jahanzaib Malik")
public, private = generate_keypair(919, 1033)
print ("Encypting using Public key ",public," and Private key ",private," . . .")
message = input("Enter a message to encrypt with your private key: ")
encrypted_msg = encrypt(public, message)
print("**********************************************\nYour encrypted message is: ")
print(''.join(map(lambda x: str(x), encrypted_msg)))
print("Decrypting message with public key ", public, " . . .")
print("**********************************************\nhiYour message is:")
print(decrypt(private, encrypted_msg))
|
6802004433d0db42d6a461e6fc26d5605f5cce55 | SurajAravindB-GITAM/data_structures_using_python_lab_assignment-SurajAravind | /10_queue.py | 2,674 | 4.625 | 5 | """ Python Script to create a queue and perform various operations on it """
# Write your code from here
##from queue import Queue
##
##queue_01 = Queue(maxsize = 3)
##
##print("Number of elements in the queue: ", queue_01.qsize())
##
### Adding of element to queue
##queue_01.put('a')
##print("Number of elements in the queue: ", queue_01.qsize())
##queue_01.put('b')
##print("Number of elements in the queue: ", queue_01.qsize())
##queue_01.put('c')
##print("Number of elements in the queue: ", queue_01.qsize())
##
##queue_01.put('d') # if we insert extra items into the queue, the process gets blocked
##
##
##print("\nFull: ", queue_01.full())
# Removing element from queue
##print("\nElements dequeued from the queue")
##print(queue_01.get())
##print(queue_01.get())
##print(queue_01.get())
# Return Boolean for Empty
# Queue
#print("\nEmpty: ", queue_01.empty())
##
##queue_01.put(1)
##print("\nEmpty: ", queue_01.empty())
##print("Full: ", queue_01.full())
# Priority Queue
##from queue import PriorityQueue
##
##queue_02 = PriorityQueue()
##
### insert into queue
##queue_02.put(("Ara", 'a'))
##queue_02.put(("b", 'b'))
##queue_02.put(("Abc", 'c'))
##queue_02.put(("d", 'd'))
##queue_02.put(("e", 'e'))
##
###print("Prioiry Queue : ", queue_02)
##print('Number of items in queue :', queue_02.qsize())
#for item in queue_02:
# print(item)
##print(queue_02.get())
##import collections
# Create a deque
##queue_03 = collections.deque(["122010322001","122010322002","122010322003"])
##print (queue_03)
##
##print("Adding to the right: ")
##queue_03.append("122010322004")
##print (queue_03)
##
##print("Adding to the left: ")
##queue_03.appendleft("122010322005")
##print (queue_03)
##
##print("Removing from the right: ")
##queue_03.pop()
##print (queue_03)
##
##print("Removing from the left: ")
##queue_03.popleft()
##print (queue_03)
##
##print("Reversing the deque: ")
##queue_03.reverse()
##print (queue_03)
# Producer - Consumer Problem
from queue import Queue
from threading import Thread
import time
import random
queue_elements = Queue(maxsize = 2)
class Producer_thread(Thread):
def run(self):
nums = range(5) #Will create the list [0, 1, 2, 3, 4]
global queue_elements
while True:
num = random.choice(nums) #Selects a random number from list [0, 1, 2, 3, 4]
queue_elements.put(num)
print("Produced: ", num)
time.sleep(1)
class Consumer_thread(Thread):
def run(self):
global queue_elements
while True:
print("Consumed: ", queue_elements.get())
time.sleep(3)
Producer_thread().start()
Consumer_thread().start()
|
0166fafa262be33a5b252b595bddc6bdeb5ba2e6 | rcutu/pytest-framework | /dummmy.py | 314 | 3.796875 | 4 |
def add_dots(string):
new_string = ''
for i in range(0, len(string)-1):
new_string = new_string + string[i] + '.'
return new_string+string[len(string)-1]
def remove_dots(string):
new_string = ''
for c in string:
if c != '.':
new_string += c
return new_string
|
3e8701d81b2a5782ac58cd3de2fddce1a7af92c0 | p-p-m/how | /google/tasks/dijkstra-heap.py | 2,561 | 3.65625 | 4 | import functools
import heapq
@functools.total_ordering
class Vertex:
def __init__(self, index, distance):
self.index = index
self.distance = distance
self.is_invalid = False
def __ne__(self, other):
return self.index != other.index
def __lt__(self, other):
return self.distance < other.distance
def __hash__(self):
return hash(self.index)
def __repr__(self):
s = 'V{}(d={})'.format(self.index, self.distance)
if self.is_invalid:
s += 'invalid'
return s
class Dijkstra:
def __init__(self, graph):
self.graph = graph
self.spt = set() # Shortest path tree
self.vertexes = [None] * len(graph)
self.vertexes_heap = []
self._add_vertex(0, 0)
def get_min_vertex(self):
""" Return vertex that has minimum distance and is not visited yet (not in SPT). """
while True:
vertex = heapq.heappop(self.vertexes_heap)
if not vertex.is_invalid:
return vertex
def execute(self):
while len(self.spt) < len(self.vertexes):
min_vertex = self.get_min_vertex()
self.spt.add(min_vertex)
self.update_distances(min_vertex)
def update_distances(self, root_vertex):
""" Update distances of all adjastance vertixes of given vertix. """
for index, distance in enumerate(self.graph[root_vertex.index]):
if distance == 0:
continue
vertex = self.vertexes[index]
if vertex is None:
self._add_vertex(index, root_vertex.distance + distance)
elif vertex.distance > root_vertex.distance + distance:
# Invalidate previous vertex in the heap and add a new one.
vertex.is_invalid = True
self._add_vertex(index, root_vertex.distance + distance)
def _add_vertex(self, index, value):
vertex = Vertex(index, value)
self.vertexes[index] = vertex
heapq.heappush(self.vertexes_heap, vertex)
def print_spt(self):
for vertex in self.spt:
print(vertex)
graph = [
[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
];
dijkstra = Dijkstra(graph)
dijkstra.execute()
dijkstra.print_spt()
|
2f1778d267cbaf2e46ab4af0bb443df99891547a | hahahayden/CPE202 | /Lab4/ordered_list.py | 8,734 | 4.375 | 4 | # Hayden Tam
# Professor Einakian-
# CPE 202-03
# Lab4: Create an ordered double linked list
#
# Design Recipe: Create a node class that creates a node which makes it easier to forming an ordered double linked list
# Data Defintion for Node Class: data= int; next=None; previous=None
class Node:
def __init__(self, itemData):
self.data = itemData
self.next = None
self.previous = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setNext(self, newNext):
self.next = newNext
def getPrevious(self):
return self.previous
def setPrevious(self, newPrevious):
self.previous = newPrevious
def __repr__(self):
return (self.data, self.next, self.previous)
# Data Definition for DoublyLinkedList Class:
# To have all the functions needed to implement including is_empty, add, pop, remove, index, search forward, search backward
# a double linked list has the attributes of head (Node) tail (Node) and num_items(int)
class DoublyLinkedList:
# Purpose: initialize attributes
# Signature: None-> None
def __init__(self):
self.head = None
self.tail = None
self.num_items = 0
# Purpose: represent the attributes
# Signature: none-> none
def __repr__(self):
return(self.head, self.tail, self.num_items)
# Purpose: to check if the doubly linked list is empty; if not return false
# Signature: None-> NOne
def is_empty(self):
if(self.head is None):
return True
else:
return False
# purpose: to add items in a sorted manner
# Signature: Int-> None
def add(self, item):
currentNode = self.head
previousNode = None
stopLoop = False
while((currentNode != None) and not(stopLoop)):
if (currentNode.data > item):
stopLoop = True
else:
previousNode = currentNode
currentNode = currentNode.next
temp = Node(item)
# If the List is Empty set the tail and head to the element
if(previousNode == None and currentNode == None):
# temp.setNext(self.head)
temp.next = self.head
self.head = temp
self.tail = temp
self.num_items += 1
# If the item to be added needs to be at the beginning
elif(previousNode == None):
temp.next = self.head
self.head = temp.previous
self.head = temp
self.num_items += 1
# If the item to be added has to be at the end
elif(currentNode == None):
temp.previous = self.tail
self.tail.next = temp
self.tail = temp
self.num_items += 1
# If the item to be added has to be in th middle
else:
temp.next = currentNode
temp.prev = previousNode
previousNode.next = temp
currentNode.prev = temp
self.num_items += 1
# Purpose: remove a specified integer from the sorted list; once found it removes it and returns the position that it was found at
# if item isn't found returns -1
# Signature: int-> int
def remove(self, item):
current = self.head
previous = None
found = False
count = 0
while(current != None and not(found)):
if(current.data == item):
found = True
else:
previous = current
current = current.next
count += 1
# Removing item at beginning
if(current == None):
return -1
elif(previous == None):
if(current.next != None):
self.head = current.next
self.num_items -= 1
self.head.previous = (None)
elif(current.next == None):
self.head.previous = None
self.head.next = (None)
self.head = None
self.tail = None
self.num_items -= 1
# Removing item at the end
elif(current.next == None):
self.num_items -= 1
self.tail = self.tail.previous
self.tail.next = None
# Removing in the middle
else:
previous.next = current.next
current.next.previous = previous
self.num_items -= 1
return count
# purpose: search for an item using head and returns True if found and if not returns false
# Signature: int-> bool
def search_forward(self, item):
current = self.head
found = False
while(current != None and not(found)):
if(current.data == item):
found = True
else:
current = current.next
return found
# Purpose: search from the tail and backwards to find an item; returns True if found if not false
# Signature: int-> bool
def search_backward(self, item):
current = self.tail
found = False
while(current != None and not(found)):
if(current.data == item):
found = True
else:
current = current.previous
return found
# Purpose: returns the size of the double linked list
# Signature: none-> int
def size(self):
return self.num_items
# Purpose: returns the index of an item
# if item isn't found; returns -1
# Signature: int-> int
def index(self, item):
current = self.head
index = 0
while(current != None):
if(current.data == item):
return index
else:
index += 1
current = current.next
return -1
# Purpose: pops the item from the list; can either be a specified index or not; if not it pops the last element
# Signature: None/int-> int
def pop(self, index=None):
if self.size() <= 0:
return -1
if index == None:
current = self.tail
# Removing at the tail
x = current.data
self.tail = self.tail.previous
# self.tail.setNext(None)
self.tail.next = None
self.num_items -= 1
return x
if index < 0 or index > self.size()-1:
return -1
if (index <= (self.size()/2)):
current = self.head
previous = None
for i in range(index):
previous = current
current = current.next
# self.num_items-=1
# return current.data
elif (index > (self.size()/2)):
current = self.tail
previous = None
for i in range(self.size()-1, index, -1):
previous = current
current = current.previous
# self.num_items-=1
# return current.data
if index == 0: # Removing at the head
x = current.getData()
if (current.next != None): # if it isn't the only one
self.head = self.head.getNext()
self.head.previous = (None)
self.num_items -= 1
if (current.next == None): # take it out
self.head.previous = (None)
self.head.next = (None)
self.head = None
self.tail = None
self.num_items -= 1
return x
elif index == self.size()-1:
current = self.tail
# Removing at the tail
x = current.data
self.tail = self.tail.previous
# self.tail.setNext(None)
self.tail.next = None
self.num_items -= 1
return x
else: # Removing in the middle of the list\
x = current.data
# revious.setNext(current.getNext())
previous.next = current.next
# current.getNext().setPrevious(previous)
current.next = previous
self.num_items -= 1
return x
'''
stack = DoublyLinkedList()
stack.add(3)
stack.add(5)
stack.add(7)
stack.add(8)
print(stack.pop(0)) #3
print(stack.pop(1)) #7
stack.add(10)
print(stack.size(),'heyyyy')
print(stack.pop(0)) #5
print(stack.size(),'hi') #3
print(stack.pop(1))
'''
|
d0a1bb811f1936c933a919fb63af77df65396b1b | ansonmiu0214/algorithms | /2018-06-28_Score-of-Parentheses/solution.py | 655 | 3.78125 | 4 | #!/bin/python3
from collections import deque
def scoreOfParentheses(S):
total = 0
stack = deque()
while S != "":
if S[:2] == "()":
# match token, increment score, advance
total += 1
S = S[2:]
elif S[:1] == "(":
# push current total onto stack, reset and advance
stack.append(total)
total = 0
S = S[1:]
else: # precondition of balanced, so must be ")"
# pop, accumulate and multiply
total = (total * 2) + stack.pop()
S = S[1:]
return total
if __name__ == "__main__":
print("Enter parentheses string to score: ", end="")
s = input().strip()
score = scoreOfParentheses(s)
print("Score: {}".format(score))
|
bf9f1b5d0fe2f1f28c3041d3ed1af49bbf0090d4 | vsdrun/lc_public | /co_ms/215_Kth_Largest_Element_in_an_Array.py | 1,497 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/kth-largest-element-in-an-array/description/
Find the kth largest element in an unsorted array.
Note that it is the kth largest element in the sorted order,
not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
***
PYTHON:
Queue.PriorityQueue is a thread-safe class, while the heapq module makes no
thread-safety guarantees.
"""
import random
import Queue
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
q = Queue.PriorityQueue()
for n in nums:
if q.qsize() == (k + 1):
q.get()
q.put(n)
while q.qsize() != k:
q.get()
return q.get()
def rewrite(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
import heapq
ary = []
for i in nums:
heapq.heappush(ary, i)
if len(ary) > k:
heapq.heappop(ary)
return heapq.heappop(ary)
def build():
return [random.randrange(0, 1000) for _ in xrange(12)], 3
if __name__ == "__main__":
s = Solution()
b = build()
print(b[0])
result = s.findKthLargest(*b)
print(result)
result = s.rewrite(*b)
print(result)
|
cec56f963396caf4746c6742bad16a848693e094 | DJSanti/assignment5 | /assignment5.py | 6,890 | 3.984375 | 4 | # Names: Bradford, Caleb, Sam
# Assignment #5
# Dr. Timofeyev
# CSC 450
# Dijkstra's Algorithm
# libraries used
import sys #For system input
import pandas as pd #For .csv file input
#getnum function to calculate the costs from .csv
def getnum(node, i, df):
return df.loc[node, i]
# get filename of .csv, get it as a dataframe
filename = sys.argv[1]
df = pd.read_csv(filename, index_col=0)
# create N'
nprime = []
# ask for a node
node = raw_input("Please, provide the node's name: ")
#puts each node from .csv in nprime
#Initialization in algorithm
for col in df.columns:
nprime.append(col)
#Cacluates costs for the neighbors attached to starting node
#Initialization in algorithm
distU = getnum(node, 'u', df)
distV = getnum(node, 'v', df)
distW = getnum(node, 'w', df)
distX = getnum(node, 'x', df)
distY = getnum(node, 'y', df)
distZ = getnum(node, 'z', df)
#Used to keep track of the paths and used for shortest path
path = ["u", "v", "w", "x", "y", "z"]
#Beginning node is shortest since it is always 0
shortest = node
#Repeating until there is nothing left in nprime
#Same as repeat in algorithm
while ((len(nprime) > 0)):
#Makes first minimum 9999 since we only want neighbors
minimum = 9999
#Loops through the list of nodes not visited yet and find the minimum value out of all of them
for i in nprime:
#First checks to see if the current node is unvisited and if its current value is less than min
#If so then current value is new min and it shortest path
if i == 'u' and distU < minimum:
minimum = distU
shortest = i
elif i == 'v' and distV < minimum:
minimum = distV
shortest = i
elif i == 'w' and distW < minimum:
minimum = distW
shortest = i
elif i == 'x' and distX < minimum:
minimum = distX
shortest = i
elif i == 'y' and distY < minimum:
minimum = distY
shortest = i
elif i == 'z' and distZ < minimum:
minimum = distZ
shortest = i
#If the shortest node is one of these, then make the shortest distane the same as their cost
if shortest == 'u':
Shortdist = distU
elif shortest == 'v':
Shortdist = distV
elif shortest == 'w':
Shortdist = distW
elif shortest == 'x':
Shortdist = distX
elif shortest == 'y':
Shortdist = distY
elif shortest == 'z':
Shortdist = distZ
#This is where it checks to see if D(v) = min(D(v), D(w) + c(w, v))
#Basically updates each neighbor of the current visited node to figure out its path
#Finally, appends the path of the nodes to the path array
if 'u' in nprime:
change = Shortdist + getnum(shortest, 'u', df)
distU = min(distU, change)
if distU == change:
if shortest == 'v':
path[0] = path[1] + 'u'
if shortest == 'w':
path[0] = path[2] + 'u'
if shortest == 'x':
path[0] = path[3] + 'u'
if shortest == 'y':
path[0] = path[4] + 'u'
if shortest == 'z':
path[0] = path[5] + 'u'
if 'v' in nprime:
change = Shortdist + getnum(shortest, 'v', df)
distV = min(distV, change)
if distV == change:
if shortest == 'u':
path[1] = path[0] + 'v'
if shortest == 'w':
path[1] = path[2] + 'v'
if shortest == 'x':
path[1] = path[3] + 'v'
if shortest == 'y':
path[1] = path[4] + 'v'
if shortest == 'z':
path[1] = path[5] + 'v'
if 'w' in nprime:
change = Shortdist + getnum(shortest, 'w', df)
distW = min(distW, change)
if distW == change:
if shortest == 'u':
path[2] = path[0] + 'w'
if shortest == 'v':
path[2] = path[1] + 'w'
if shortest == 'x':
path[2] = path[3] + 'w'
if shortest == 'y':
path[2] = path[4] + 'w'
if shortest == 'z':
path[2] = path[5] + 'w'
if 'x' in nprime:
change = Shortdist + getnum(shortest, 'x', df)
distX = min(distX, change)
if distX == change:
if shortest == 'u':
path[3] = path[0] + 'x'
if shortest == 'v':
path[3] = path[1] + 'x'
if shortest == 'w':
path[3] = path[2] + 'x'
if shortest == 'y':
path[3] = path[4] + 'x'
if shortest == 'z':
path[3] = path[5] + 'x'
if 'y' in nprime:
change = Shortdist + getnum(shortest, 'y', df)
distY = min(distY, change)
if distY == change:
if shortest == 'u':
path[4] = path[0] + 'y'
if shortest == 'v':
path[4] = path[1] + 'y'
if shortest == 'w':
path[4] = path[2] + 'y'
if shortest == 'x':
path[4] = path[3] + 'y'
if shortest == 'z':
path[4] = path[5] + 'y'
if 'z' in nprime:
change = Shortdist + getnum(shortest, 'z', df)
distZ = min(distZ, change)
if distZ == change:
if shortest == 'u':
path[5] = path[0] + 'z'
if shortest == 'v':
path[5] = path[1] + 'z'
if shortest == 'w':
path[5] = path[2] + 'z'
if shortest == 'x':
path[5] = path[3] + 'z'
if shortest == 'y':
path[5] = path[4] + 'z'
#Removes the current node from the list since it has already been visited and added to path
#Includes part of algorithm where it removes the visited nodes
nprime.remove(shortest)
#Just formatting and output
#Prints shortest path tree for the node
print "Shortest path tree for node {}:".format(node)
if node == 'u':
print "{}, {}, {}, {}, {}".format(path[1], path[2], path[3], path[4], path[5])
if node == 'v':
print "{}, {}, {}, {}, {}".format(path[0], path[2], path[3], path[4], path[5])
if node == 'w':
print "{}, {}, {}, {}, {}".format(path[0], path[1], path[3], path[4], path[5])
if node == 'x':
print "{}, {}, {}, {}, {}".format(path[0], path[1], path[2], path[4], path[5])
if node == 'y':
print "{}, {}, {}, {}, {}".format(path[0], path[1], path[2], path[3], path[5])
if node == 'z':
print "{}, {}, {}, {}, {}".format(path[0], path[1], path[2], path[3], path[4])
#Prints the least-cost paths for the node
print "Costs of least-cost paths for node {}:\nu:{}, v:{}, w:{}, x:{}, y:{}, z:{}".format(node, distU, distV, distW, distX, distY, distZ)
|
e4e36a73a7205364e8f7fb18033fdeff29894d5b | CatalinaYepes/parsers | /select_files.py | 1,526 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Select files inside a folder
@catalinayepes
"""
import os
def select_files(folder=".", start="", end="", contain="", include_path=False):
'''Function to select files inside a folder
:folder: folder name, by default current one
:start: select the files that start with a given string
:end: select the files that end with a given string
:contain: select the files that contain a given string
Returns a list_names of files if more than one
'''
files = []
for file_name in os.listdir(folder):
if file_name.startswith(start):
if file_name.endswith(end):
if isinstance(contain, str):
if file_name.find(contain) != -1:
if include_path==True:
files.append(os.path.join(folder, file_name))
else:
files.append(file_name)
else:
for conts in contain:
if file_name.find(conts) != -1:
if include_path==True:
files.append(os.path.join(folder, file_name))
else:
files.append(file_name)
if len(files) == 1:
return files[0]
else:
assert len(files) != 0, '\nNo files selected\n'
files.sort()
return files |
a6da91a32103ed7211b4141a0ac3865b9fb41c7d | dnivanthaka/demo-programs | /Python/fileio.py | 609 | 3.640625 | 4 | #!/usr/bin/env python
reader = open( 'haiku.txt', 'r' )
data = reader.read()
reader.close()
print len(data)
reader = open( 'haiku.txt', 'r' )
data = reader.read(64)
while data != '':
print len(data)
data = reader.read(64)
print len(data)
reader.close()
reader = open( 'haiku.txt', 'r' )
contents = reader.readlines()
reader.close()
total = 0
count = 0
for line in contents
count += 1
total += len(line)
print 'Average ', float(total) / float(count)
writer = open( 'temp.txt', 'w' )
print >> writer, 'elements'
for gas in ['He', 'Ne', 'Ar', 'Kr']:
print >> writer, gas
writer.close()
|
9c20c0359c8adb2dfa43914c632a035ef98bf9b1 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4378/codes/1734_2508.py | 219 | 3.65625 | 4 | k=int(input("numero de termos: "))
a1=2
a2=3
a3=4
i=0
termo=0
if(k==1):
print("3")
else:
while(i+1<k):
sinal=(-1)**i
termo=termo+sinal*(4/(a1*a2*a3))
a1=a1+2
a2=a2+2
a3=a3+2
i=i+1
print(round(3 + termo,8)) |
621cf56dab1643b68d150b631b0ca56058234c7f | codafett/python | /uncategorised/multiply_even_numbers.py | 416 | 4.09375 | 4 | def multiply_even_numbers(values):
evens = [val for val in values if val % 2 == 0]
sum = evens[0]
for val in evens[1:]:
sum *= val
return sum
print(multiply_even_numbers([2, 3, 4, 5, 6])) # 48
def multiply_even_numbers(lst):
total = 1
for val in lst:
if val % 2 == 0:
total = total * val
return total
print(multiply_even_numbers([2, 3, 4, 5, 6])) # 48
|
076c061216dec7e605ed25b8eb33c23e03490861 | arunkumarpatange/fib100 | /pyd/cake2.py | 1,991 | 3.53125 | 4 |
def uniq(l):
x = 0
for n in l:
x = n ^ x
return x
print uniq([1, 2, 10, 1, 2])
def has_cycle(l, head):
'''
1 - 2 - 3 - 4
| |
- - - - -
'''
next = current = head
while l.get(current) is not None:
current = l.get(current)
next = l.get(l.get(next))
print current, next
if next == current:
return "cycle"
return 'nox cycle'
print has_cycle({
1: 2,
2: 3,
3: 4,
4: 3,
}, 1)
def rev(l, head):
def _rev(l, head):
tail = head
if l.get(head) is not None:
tail = _rev(l, l.get(head))
l[l.get(head)] = head
return tail
print _rev(l, head)
if l.get(head) is not None:
l.pop(head)
return l
assert rev({1: None}, 1) == {1: None}
assert rev({1: 2}, 1) == {2: 1}
assert rev({1: 2, 2: 3}, 1) == {3: 2, 2: 1}
assert rev({1: 2, 2: 3, 3:4, 4:5}, 1) == {2: 1, 3: 2, 4:3, 5:4}
def pyramid(n):
chr = 1
j = 1
for i in xrange(1, n + 1):
space = "{}{}{}".format(' ' * (n - i), "".join([str(i)] * j), ' ' * (n - 1))
j = j + 2
print space
pyramid(4)
print "min cost train"
def min_cost(path, start=0, end=None):
_cost = path[start][end]
for i in xrange(start + 1, end):
_cost = min(_cost,
min_cost(path, start, i) + min_cost(path, i, end))
if start == 0:
assert _cost == min_cost_dp(path, end=end), (start, end, _cost)
return _cost
def min_cost_dp(path, start=0, end=None):
d = [11111] * (end + 1)
d[0] = 0
for i in xrange(start, end + 1):
for j in xrange(start + 1, end + 1):
_cost = path[i][j]
if d[j] > d[i] + _cost:
d[j] = _cost + d[i]
return d[end]
print min_cost([
[0, 15, 80, 90],
[-1, 0, 40, 50],
[-1, -1, 0, 70],
[-1, -1, -1, 0]
], end=3)
def rotate_sorted(list, k):
start, end = 0, len(list) - 1
while start < end:
mid = (start + end) / 2
if list[mid] == k:
return True
elif k < list[mid]:
if list[e] < list[mid] and list[e] >= k:
start = mid + 1
else:
end = mid - 1
else:
if list[s] > list[mid] and list[s] <= k:
end = mid - 1
else:
start = mid + 1
|
8e24cda519daa5a0f048f5aac87c285b458bc4dc | TotumRevolutum/Control_HW_2 | /classes.py | 1,559 | 3.53125 | 4 | import csv
def write_file(products):
with open('products.csv', 'w', encoding="utf8") as csvfile:
writer = csv.DictWriter(csvfile, delimiter=';', fieldnames=['price', 'name', 'q_left'])
writer.writeheader()
for i in products:
writer.writerow({'price': products[i].price, 'name': i, 'q_left': str(products[i].q_left)})
class Customer:
def __init__(self, name: str, login: str, password: str, orders: list):
self.name = name
self.login = login
self.password = password
self.orders = orders
class Products:
def __init__(self, name: str, price: float, q_left: int):
self.name = name
self.price = price
self.q_left = q_left
def check(self, n):
if self.q_left < n:
return False
return True
def buy(self, n, products):
self.q_left -= int(n)
write_file(products)
def change_price(self, n: float, products):
self.price = int(n)
write_file(products)
def change_num(self, n, products):
self.q_left = int(n)
write_file(products)
class Order:
def __init__(self, number: str, date: str, status: str, pos: dict, client: Customer):
self.number = number
self.date = date
self.status = status
self.pos = pos
self.client = client
def check_all(self, product):
for i in self.pos:
print(self.pos[i])
if int(self.pos[i]) > product[i].q_left:
return False
return True
|
4baa9659924ea96fc6cf144cf0c1231424a7807d | brmonitor/PythonMentee | /Level1/Ex8.py | 353 | 3.765625 | 4 | # Python Mentee - Level 1 - Exercises
# https://bairesdev.atlassian.net/servicedesk/customer/article/2101576225
# 8 - Write a Python function to remove an item from a tuple.
def tuple_remove_item(tup, i):
lis = list(tup)
lis.remove(i)
print(tuple(lis))
if __name__ == '__main__':
tup = ('a', 'b', 'c')
tuple_remove_item(tup, 'b')
|
5e4ea86c14decd951d3b7c363fa742ada0c56d83 | Sahil4UI/PythonJuly2020Reg2 | /F_handeling/csv_IO.py | 439 | 3.640625 | 4 | import csv
'''
data = [
{"name":"ram","id":101},
{"name":"shyam","id":102},
{"name":"radhey","id":103},
{"name":"samay","id":104},
{"name":"amar","id":105}
]
with open('data1.csv','w',newline='') as file:
writer = csv.writer(file)
for item in data:
writer.writerow(item.values())
'''
with open('data.csv','r') as file:
reader = csv.reader(file)
for item in reader:
print(item)
|
8dc11df66534147f761a083f5ebb0b8fe9ac9718 | happinessbaby/Project_Euler | /sum_primes.py | 1,008 | 3.796875 | 4 | #summation of all primes below 2 million
import time
def calc_time(func):
def inner(*args, **kwargs):
begin = time.time()
returned_val = func(*args, **kwargs)
end = time.time()
print("time: ", end-begin)
return returned_val
return inner
@calc_time
def sum_primes(N):
m = int((N-1)/2) # sieving thru odd numbers
arr=[True]*m
i = 0
p = 3
primes=set()
while p**2 < N:
if arr[i]== False: #takes care of 15 when i == 5 (taken out by 3 already)
i+=1
p+=2
elif arr[i]== True:
primes.add(p)
print(p)
j = int((p**2-3)/2)
while j < m:
arr[j] = False
j += p
i+=1
p+=2
while i<m: #takes care of leftover primes not seived
if arr[i] == True:
primes.add(p)
i+=1
p+=2
return sum(primes)+2
print(sum_primes(2000000))
|
7bde23e27255f8ba31951e46cbfa6a558dc609d3 | LautaroRuggieri/newbie-cow | /basic mouse capturer in canvas.py | 3,903 | 3.875 | 4 | #last version: 10 may 2020 (aprox. 2.5 months into programming)
#author: Lautaro Ruggieri (https://github.com/LautaroRuggieri)
#desc: bored, quarantined cow presents a basic mouse activity responder:
#1-it draws a circle each time you left click, alternatig between red and blue color.
#2-it draws a text if you double left click.
#3-SHIFT + left click will turn on/off the 'tail mode'. tail mode draws a text after the mouse has
# escaped a radius r>15 from where it was turned on or from the last message displayed.
#4-the window notifies the user if tail mode has been activated or deactivated.
#5-it detects if your mouse is gone from the canvas and politely asks you to come back.
#it also a some 'hidden' feature in the form of commentaries, which makes the title of the
# screen to display the mouse coords. Feel free to erase the '#' in the source code
# and to chose the feature that takes place when you run it.
import tkinter as tk
import math
class Aplicacion:
def __init__(self):
#creo la ventana y un self.color para el metodo presion_mouse:
self.ventana1=tk.Tk()
self.color = 0
#creo el canvas:
self.canvas1=tk.Canvas(self.ventana1, width=600, height=400, background='black')
self.canvas1.grid(column=0, row=2)
#creo los eventos y el modulo que va a disparar cada evento:
#self.canvas1.bind('<Motion>', self.mover_mouse)
self.canvas1.bind('<Button-1>', self.presion_mouse )
self.canvas1.bind('<Enter>', self.presencia_mouse )
self.canvas1.bind('<Leave>', self.ausencia_mouse )
self.canvas1.bind('<Double-Button-1>', self.doblepresion_mouse )
self.canvas1.bind('<Shift Button-1>', self.prender_mensaje_cola)
self.canvas1.bind('<Motion>', self.dibujar_mensaje_cola)
self.mensaje_cola=False
self.ventana1.mainloop()
#def mover_mouse(self, evento):
# self.ventana1.title(str(evento.x) + ';' + str(evento.y))
def presion_mouse(self, evento):
self.color = self.color + 1
if self.color%2==0:
self.ultimocirculo=self.canvas1.create_oval(evento.x-5,evento.y-5 , evento.x+5,evento.y+5, fill='red')
else:
self.ultimocirculo=self.canvas1.create_oval(evento.x-5,evento.y-5 , evento.x+5,evento.y+5, fill='blue')
if self.color==10:
self.color=0
def presencia_mouse(self, evento):
self.ventana1.title('Hey!')
def ausencia_mouse(self, evento):
self.ventana1.title('Come back, now.')
def doblepresion_mouse(self, evento):
self.canvas1.create_text(evento.x,evento.y , text='DOUBLE CLICK XD', fill='blue', font='Arial')
self.canvas1.delete(self.ultimocirculo)
def prender_mensaje_cola(self, evento): #RECORDAR QUE SE ACTIVA Y DESACTIVA CON SHIFT+CLIC IZQ:
if not self.mensaje_cola:
self.mensaje_cola=True
self.ventana1.title('Tail mode ON')
self.coordx=evento.x
self.coordy=evento.y
self.canvas1.create_text(evento.x,evento.y , text='TAIL MODE ACTIVATED!', fill='yellow')
else:
self.mensaje_cola=False
self.ventana1.title('Tail mode OFF')
def dibujar_mensaje_cola(self, evento):
if self.mensaje_cola:
r=math.sqrt((self.coordx-evento.x)**2 + (self.coordy-evento.y)**2)
if r>15:
self.canvas1.create_text(evento.x,evento.y , text='nice tail', fill='yellow')
self.coordx=evento.x
self.coordy=evento.y
app1=Aplicacion()
|
f849bb74a78838c65ae9e1fad12ccc7a2095b19c | bhalder/python-datastructures | /tree/check_largest.py | 380 | 3.796875 | 4 | from bst import BST, Node
def get_maximum( root ):
if not root:
return False
else :
cur = root
while cur.right:
cur = cur.right
return cur.item
if __name__=="__main__":
bst = BST()
l = [ 6, 2, 9, 8, 7, 3, 1 ]
for i in l:
bst._add( i )
print "Maximum is : %d" % ( get_maximum(bst.root) )
|
d5ed336d8cc75e634bb3be34c9e88252fdf06893 | YuanShisong/pythonstudy | /day3/01set.py | 2,973 | 4.3125 | 4 | '''
鸡汤:
《追风筝的人》
《白鹿原》
《琳达看美国》
'''
# 列表 元组(不可变列表) 集合 字符串:不可修改
list1 = [1,9,2,3,2,4,5,3]
print(list1)
list1 = set(list1)
# 集合是有序的??? 官方文档:A set object is an unordered collection of distinct hashable objects.
print(list1)
set1 = set(['2','2','1','4','9','5'])
print(set1)
'''
无序的,不重复的,可哈希的对象集合,但为什么放数字就是有序的???
应该是和哈希算法有关, 数字小计算出的hash值就小?
set1 = set(['2','2','1','4','9','5'])
print(set1) # 三次输出结果如下
{'2', '5', '4', '9', '1'}
{'9', '4', '1', '2', '5'}
{'2', '9', '4', '1', '5'}
set2 = set([1,9,2,3,2,4,5,3])
print(set2) # 结果如下
{1, 2, 3, 4, 5, 9}
{1, 2, 3, 4, 5, 9}
'''
# set2 = set(['a', 'c', 'b', 'c', 'f', 'd', 'e'])
# print(set2)
'''取交集'''
set3 = set([1,9,2,3,4,5])
set4 = set([1,9,6,7])
print(set3.intersection(set4)) # {1, 9}
'''取并集'''
print(set3.union(set4)) # {1, 2, 3, 4, 5, 6, 7, 9}
'''取差集'''
print(set3.difference(set4)) # {2, 3, 4, 5} in set3 not in set4
print(set4.difference(set3)) # {6, 7} in set4 not in set3
'''子集'''
print(set4.issubset(set4)) # False
'''父集'''
print(set4.issuperset(set3)) # False
'''对称交集'''
print(set3.symmetric_difference(set4)) # {2, 3, 4, 5, 6, 7}
'''isdisjoint是否无交集,无交集返回True'''
set5 = set([8, 7])
print(set5.isdisjoint(set3)) # True
print(set5.isdisjoint(set4)) # False
'''用运算符方式表达'''
print(set3 & set4) # {1, 9}
print(set3 | set4) # {1, 2, 3, 4, 5, 6, 7, 9}
print(set3 > set4)
print(set3 >= set4)
set3.add(999)
print(set3) # 确实无序
print(1 in set1)
print(1 in list1)
'''remove pop discard 区别
remove 删除指定元素 返回值为None 删除不存在的元素时会报错
pop 删除随机元素 返回值为被删除元素
discard 删除指定元素 返回值为None 删除不存在的元素时不会报错
'''
print('---------------------')
s6 = set([1,9,2,3,4,5])
s6.remove(1)
print(s6.remove(9))
print(s6)
# s6.remove(8) # 删除不存在的元素时会报错 KeyError: 8
s7 = set([1,9,2,3,4,5])
print(s7.pop())
print(s7.pop())
print(s7.pop())
print(s7)
s8 = set([1,9,2,3,4,5])
print(s8.discard(8))
print(s8.discard(1))
print(s8)
# test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method # test fileno() method |
de10bc49264d8268e0b3b773f12009f40914178b | jainharshit27/C7_AA2_T | /C7 AA2 reference.py | 204 | 3.65625 | 4 | # WHILE LOOP
import random
ring = random.randint(1,18)
print(ring)
i = 1
while i<=18:
if i == ring:
print(i)
break
else:
print(i)
i+=1
|
e39b07186f6c021fc728700ca44caa494a4328db | jparrieta/nk | /python_versions/levinthal_create_landscape.py | 14,481 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Tutorial on Creating Rugged Landscapes
#
# In this tutorial, you will be introduced to a simple model to create NK landscapes following Levinthal (1997). The tutorial does not include search in rugged landscapes, just the creation of the landscapes. You can find a code with the search process in the levinthal.ipynb file in this repository.
#
# **Reference:** Levinthal, D. A. (1997). Adaptation on rugged landscapes. Management science, 43(7), 934-950.
# <h1 id="tocheading">Table of Contents</h1>
# <div id="toc"></div>
# # NK landscape
# In Levinthal (1997) the agent is quite simple. The environment does have some intricancies.
#
# ## 1. Create dependencies
# The k interdependencies in Levinthal's are created at random. Basically, one needs a matrix where the diagonal has a 1 and the off-diagonal has k ones and n-k zeroes. A one represents an interdependency and a zero the lack of it.
# This function includes two variables N and K and outputs a NxN interdependency matrix.
# In[2]:
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
def create_dependencies(n, k, land_style):
dep_mat = np.zeros((n,n)).astype(int)
inter_row = [1]*k+[0]*(n-k-1) # number of off-diagonals 1s and 0s
if land_style == "Rand_mat":
inter = random.sample(inter_row*n, n*(n-1))
for i in range(n):
if land_style == "Rand_row": inter = np.random.choice(inter_row, replace = False, size = (n-1))
elif land_style == "Levinthal": inter = inter_row # The original order is the one from Levinthal (1997)
range_row = list(range(n)[i:])+list(range(n)[:i])
for j in range_row:
if i != j:
dep_mat[i][j] = inter[0]
inter = inter[1:]
else: dep_mat[i][i] = 1
return(dep_mat)
# ### 1.1 Example: How to create a interdependency matrix
# Below you see how an interdependency matrix is built. If you run the code again, the matrix will change.
# In[246]:
n = 3
k = 1
land_style = "Rand_mat"
dep_mat = create_dependencies(n, k, land_style)
dep_mat
# ### 1.2. Miscellaneous function: Int2Pol
# This is a miscellaneous function. It is presented here to avoid confusion. It will be use by the next functions.
# This function takes an integer value and outputs a string of 0s and 1s of length N. This is important as the binary function of Python truncates any zero to the left of the most significant 1.
# In[247]:
def int2pol(pol_int, n):
pol = bin(pol_int)[2:] # removes the '0b'
if len(pol) < n: pol = '0'*(n-len(pol)) + pol
return(pol)
int2pol(pol_int = 5, n = 4)
# ## 2. Fitness contributions
# The second step is building the fitness contributions for each item in the interdependency matrix. Before showing the code, it is important to present the logic of it, here we do so by an example.
#
# ### 2.1 Example
# Let's imagine that our interdependency matrix is:
#
# |1 0 0|
# |0 1 1|
# |1 1 1|
#
# What this means is that the fitness contributions of the first value of a policy P = [a,b,c] will depend ONLY on the value of the first policy value, namely whether a is 1 or 0. Formally the fitness contribution will have twwo values:
# * f1[0] = z0
# * F1[1] = z1
# Where z0 and z1 are numbers drawn from a uniform distribution.
#
# The second row is more complicated as there is one interdependency. Here we will have that the second and third policy values are needed to calculate the fitness contribution. For this we need a function with four values as there are four possible combinations of a and b. The functions have the form f2[b,c].
# * f2[00] = y0
# * f2[01] = y1
# * f2[10] = y2
# * f2[11] = y3
#
# The final row has 3 interdependencies. Now the fitness contributions depends on the values of a, b, and c. The fitness contribution has the for f3[a,b,c]. To depict it, we draw a truth table.
#
# a b c | f3
# 0 0 0 | x0
# 0 0 1 | x1
# 0 1 0 | x2
# 0 1 1 | x3
# 1 0 0 | x4
# 1 0 1 | x5
# 1 1 0 | x6
# 1 1 1 | x7
#
# To create the fitness contributions we need a function that takes one interdependence matrix and outputs the fitness contributions functions for each position. That is, a function that outputs the two f1, four f2, and eight f3.
# The function later on should have a structure such that if one tells it that a = 0 and b = 1 it can give f2[b,a] = y2. For this the ideal structure is a list of dictionaries. Each fitness contribution function is a dictionary that one gives the values and it outputs the and the dictionaries are joined together in a list. Below you find a function that does just that.
#
# ### 2.2 Fitness contribution generator
# The function first creates an empty list. This list will be filled with the dictionaries of fitness contribution functions.
# The next step is entering a for-loop over the N rows of the interdependency matrix. For each iteration in the for-loop, we do a list comprehension where the binary value of the counter is stored as the key of a dictionary with the value drawn from a uniform distribution. The second for-loop will go over 2^q iterations, where q is the number of 1's in the row. As in the example=, q is on average k+1 but not always. At the end the function output a list of with the dictionaries as its entry.
# You see the code below and the outputs is the list of dictionaries of the dependency matrix created in the prior section.
# In[248]:
def fitness_contribution(dep_mat, land_style, k):
fit_con = []
for i in range(len(dep_mat)):
if land_style != "Rand_mat": q = k+1
elif land_style == "Rand_mat": q = sum(dep_mat[i])
fit_con.append({int2pol(j,q):random.random() for j in range(2**q)})
return(fit_con)
fit_con = fitness_contribution(dep_mat, land_style, k)
fit_con
# ## 3. Calculate policy payoffs
# The next step is to calculate the payoff of a policy based upon the fitness contribution functions. To do this we require two things. First to calculate the payoff contribution of every value in a policy and then sum all of them together. We start with the first task.
#
# ### 3.1 Transform Row
# Let's continue with the example. But now we have the policy P = '101'. This policy has three elements and is stored as a string of 0s and 1s.
# In the case of the first value we know we should get z0 as fitness contribution. In the second row, y2 and so on. To do this we need to create a function that takes the values of the policy and matches them to the values other values that are interdependent with it.
# The function below is given two inputs, a policy and a row of a dependency matrix. It creates an empty list and starts to populate it. It does this by starting a for-loop for every element of the policy. If the item of that index is 1 in the interdependency row then it appends the value of policy to the list. If not, it continues to the next policy value. In this way, only the interdependent items are stored. With this, the programs has a list with items that are relevant to calculate the fitness contribution for this policy.
# For example, in the case from before we would have as an output of the for-loop '1' in the first row, '01' in the second row and '101' for the last row. This output is called interact_row.
# These values however are not understandable by the dictionaries of the fitness contribution. The last rows of the function translate the list into a binary value. So that later the dictonary can be queried.
# The process starts by starting trans_pol = 0. This value will store the key value for the dictionary. Then a for-loop starts. The for-loop has the range reversed so that the we keep the items to the left of the list being more significant. This is important because in the the next step we multiply the value of interact_row[i] with the 2^index value. By reversing the order we have that the item most to left in the list will be multiplied by 2^3 if we follow the example from before, the item next to it by 2^2 and so on. The product of the multiplications is added on every loop to the trans_pol value. At the end we have a decimal value. We transform the decimal value and the output is a key we can use in the dictionaries from the fitness contribution. For example for the first row from before we get '1', for the second '01', and for the last row, '101'.
# Below you see an example of this function for the same policy we have used in this example but for the randomly generate dependency matrix from before.
# In[249]:
def transform_row(policy, dep_row):
interact_row = [policy[i] for i in range(len(policy)) if dep_row[i] == 1]
trans_pol = ''
for pol_i in interact_row: trans_pol += pol_i
return(trans_pol)
transform_row('101', dep_mat[1])
# ### 3.2 Transform Matrix
# The transform_row function is called by a transform_matrix function whose job is to take a policy and output a set of keys for the the list of fitness contributions. To do this basically what it does is to to call the transform_row N times can fill out a list with the output of each of the calls of the function. In the example from above we would have: ['0b0', '0b11', '0b101'] as an output. Below you see an example of the function working.
# In[250]:
def transform_matrix(policy, dep_mat):
int_mat = [transform_row(policy, dep_mat[i]) for i in range(len(dep_mat))]
return(int_mat)
transform_matrix('101',dep_mat)
# ### 3.3 Payoff
# The payoff function has three inputs, the policy for which to calculate a payoff, the interdependency matrix, and the list of fitness contributions. The first action it does it to transform the policy into keys to the fitness cotnribution dictionaries. After this is done it sums the entries of all the fitness contributions of the key values and divides the sum by the length of the policy. The last part is done to get a value between 0 and 1. Below we see and example of the code working.
# In[251]:
def payoff(policy,dep_mat,fit_con):
keys = transform_matrix(policy, dep_mat)
pay = np.sum([fit_con[i][keys[i]]/len(policy) for i in range(len(policy))])
return(pay)
payoff('101',dep_mat,fit_con)
# ## 4. Make full-landscape
# Now that we can calculate the payoff for one policy we can make the full-landscape. However, to calculate the landscape we need to make a function that takes integers and makes policies.
#
# ### 4.1 Calculate Landscape
# Having the translating function, the function that calculates the landscape is just a for-loop that fills up a dataframe. The dataframe consists of three entries per policy: The policy in list-value, the policy in integer-value, and the payoff. The integer value of the policy is used for accessing the dataframe, the list-value for searching the landscape.
# Below you will see an example.
# In[252]:
def calc_landscape(dep_mat, fit_con):
land = {}
for i in range(2**len(fit_con)):
pol = int2pol(i,n)
land[pol] = payoff(pol, dep_mat, fit_con)
return(land)
lands = calc_landscape(dep_mat, fit_con)
lands
# ### 4.3 Descriptives of the environment
# We can characterize the environment. Find the maximum, minimum, number of peaks.
# For this we need a function that finds the peaks, which has to find whether a policy gives the highest performance for every neighbor.
# #### 4.3.1 FInd neighbors
# For every policy there are N neighboring positions. These are policies that differ by one change from the current policy. The function shown here takes the starting policy and generates at random the N neighbors. It outputs the integer value of each of these N neighbors. The code asks if the neighbors will be given in a random or list order. This is useful during search.
# Below you see an example.
# In[253]:
def find_neighbors(policy, randomizer):
policy = (policy) #policy changed
neighbors = []
if randomizer: random_order = random.sample(range(len(policy)), len(policy)) # 10x faster than np.random.choice!
else: random_order = range(len(policy))
for i in random_order:
neighbor = list(policy)
if policy[i] == '1': neighbor[i] = '0'
else: neighbor[i] = '1'
neighbors.append(''.join(neighbor))
return(neighbors)
find_neighbors('101', False)
# #### 4.3.1 Summary
# This functions gives a summary of the landscape. The maximum, minimum, and number of peaks. It is most useful for collecting statistics of different landscape configurations (i.e., different n and ks).
#
# In[254]:
def summary(lands):
num_peaks = 0
for current_row in lands.keys():
counter = 1
for neighbor in find_neighbors(current_row, randomizer = False):
if lands[current_row] < lands[neighbor]:
counter = 0
break
num_peaks += counter
return([max(lands.values()), min(lands.values()), num_peaks])
summary(lands)
# # Create landscape from scratch
#
# Below you can find the short way of creating the landscape from scratch
# In[255]:
n = 6
k = 2
land_style = "Rand_row" # "Levinthal", "Rand_mat", "Rand_row"
dep_mat = create_dependencies(n, k, land_style)
fit_con = fitness_contribution(dep_mat,land_style,k)
Environment = calc_landscape(dep_mat, fit_con)
summary(Environment)
# In[256]:
Environment
# # Characterize landscapes
#
# Below we characterize a thousand landscapes by describing their maxima, minima, and number of peaks
# In[257]:
import time
start_time = time.time()
all_max = []
all_min = []
all_num_peaks = []
num_reps = 1000
for i in range(num_reps):
dep_mat = create_dependencies(n, k, land_style)
fit_con = fitness_contribution(dep_mat, land_style, k)
Environment = calc_landscape(dep_mat, fit_con)
max_val, min_val, peaks = summary(Environment)
all_max.append(max_val)
all_min.append(min_val)
all_num_peaks.append(peaks)
print("Computation time: " + str(round(time.time()-start_time, 2)) + " s")
# In[258]:
plt.hist(all_min)
# In[259]:
plt.hist(all_max)
# In[260]:
plt.hist(all_num_peaks)
# # Search
# With the environment finished it is time to search in this rugged landscape.
#
#
# **Note:** The code below builds the table of content.
# In[17]:
get_ipython().run_cell_magic('javascript', '', "$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')")
|
701783cbf3c341b7343750d7d8e8325c021e8d47 | cckhatgt/untitled | /bagWord.py | 756 | 3.53125 | 4 | import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer();
docs = np.array([
"The sun is shining",
"The weather is sweet",
"The sun is shining and the weather is sweet" ])
bag = count.fit_transform(docs)
print(count.vocabulary)
print("##")
print(count.vocabulary_)
print(bag.toarray());
def tokenizer(text):
return text.split();
tokenizer("runners like running and thus they run")
import nltk
nltk.download("stopwords");
from nltk.corpus import stopwords
stop = stopwords.words("English");
[w for w in tokenizer("runners like running and thus they run") if w not in stop]
p = tokenizer("runners like running and thus they run")
for w in p:
if (w not in stop):
print(w)
|
a130ea3a0fd9adf1ec5c12cf6fc23f4ec0bb73e1 | calvindajoseph/patternrecognition | /FakenewsPreProcessing.py | 2,833 | 3.65625 | 4 | """
Preprocess the initial dataset.
Includes dropping columns and encoding the target class.
Partition the dataset into smaller datasets in the end.
"""
# Import re for regex
import re
# Import LabelEncoder
from sklearn.preprocessing import LabelEncoder
# Import FileManager and DatasetPartitioner
from FileManager import FileManager
from DatasetClasses import DatasetPartitioner
#create FileManafer instance
fileManager = FileManager()
#list of the dropeed column names
drop_column_names = ['id',
'tid1',
'tid2',
'title1_zh',
'title2_zh']
#create LabelEncoder from sklearn.preprocessing instance
le = LabelEncoder()
def drop_columns(df, drop_column_names):
"""
Drop columns inside drop_column_names and drop all na values from dataframe df.
Parameters
==========
df: Pandas Dataframe
The original Dataframe.
drop_column_names: list of strings
The column names to be dropped.
Returns
=======
df: Pandas Dataframe
The original Dataframe with the columns dropped and no na values.
"""
df = df.drop(drop_column_names, axis=1)
df = df.dropna()
return df
def pre_process_columns_fakenews(df):
"""
Drop special characters from title1_en and title2_en and encode label (0: related, 1: unrelated)
Steps
=====
1) Drop special characters in titles.
2) Drop html elements in titles.
3) Lowercase string in titles.
4) Replace all agreed and disagreed value in label to related.
5) Encode label column.
Parameters
==========
df: Pandas Dataframe
The original Dataframe.
Returns
=======
df: Pandas Dataframe
The preprocessed Dataframe.
"""
for title_en in ['title1_en', 'title2_en']:
df[title_en] = df[title_en].map(lambda x: re.sub(r'[^a-zA-Z0-9]+', ' ', x))
df[title_en] = df[title_en].map(lambda x: re.sub(r'<[^<]+?>', '', x))
df[title_en] = df[title_en].map(lambda x: x.lower())
df['label'] = df['label'].replace(to_replace = 'agreed', value = 'related')
df['label'] = df['label'].replace(to_replace = 'disagreed', value = 'related')
df['label'] = le.fit_transform(df[['label']])
return df
# Load fakenews dataset.
df = fileManager.load_fakenews_dataset()
# Drop columns.
df = drop_columns(df, drop_column_names)
# Preprocess dataset.
df = pre_process_columns_fakenews(df)
# Save preprocessed dataset.
fileManager.save_preprocessed_fakenews_dataset(df)
### Partition Dataset ###
# Create DatasetPartitioner instance.
partitioner = DatasetPartitioner()
# Partition dataset.
small_datasets = partitioner(df)
# Save smaller datasets.
fileManager.save_preprocessed_fakenews_dataset_smaller(small_datasets) |
3a6108745226f7528a9a426209fa84f01d76767f | nrutkowski1/AI-Projects | /Project 2/Rutkowski_ANN.py | 9,516 | 3.6875 | 4 |
import numpy as np
import sklearn
import matplotlib as mpl
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, InputLayer, Dropout
import keras
import tensorflow as tf
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_score
from keras.utils import to_categorical
import time
# load data
images = np.load('images.npy')
labels = np.load('labels.npy')
# show image
# plt.imshow(images[0], cmap=mpl.cm.binary)
# plt.show()
print(labels[0])
# In[4]:
# flatten the images
images_flatten = np.array([image.flatten() for image in images])
# convert the labels to vectors
outputs = to_categorical(labels)
batch_size = 512
nodes = 50
epochs = 500
learn_rate = 0.001
hidden_layers = 10
# model without dropout layer used actiavtion functions from tutorials. It was not specified what to use in the homework
model = Sequential()
model.add(Dense(nodes, activation='relu', input_shape=images_flatten[0].shape))
for i in range(0, hidden_layers):
model.add(Dense(nodes, activation='relu'))
model.add(Dense(len(outputs[0]), activation='softmax'))
# used sgd optimizer with given learning rate and momentum of 0.5 which was not specified in the homework
sgd = keras.optimizers.SGD(lr=learn_rate, momentum=0.5, nesterov=False)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy', 'mse'])
# split up data into training, testing, validation data sets
x_train = images_flatten[:int(0.6*len(images_flatten))]
x_test = images_flatten[int(0.6*len(images_flatten)):int(0.8*len(images_flatten))]
x_validate = images_flatten[int(0.8*len(images_flatten)):len(images_flatten)]
y_train = outputs[:int(0.6*len(outputs))]
y_test = outputs[int(0.6*len(outputs)):int(0.8*len(outputs))]
y_validate = outputs[int(0.8*len(outputs)):len(outputs)]
# show image
# plt.imshow(x_train[10].reshape(28,28), cmap=mpl.cm.binary)
# plt.show()
print(y_train[10])
history = model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=(x_validate, y_validate))
print(history.history.keys())
# plot model accuracy and error without dropout layer
# epoch_list = np.linspace(1,500, 500)
# plt.plot(epoch_list, history.history['acc'], 'b-')
# plt.plot(epoch_list, history.history['val_acc'], 'r-')
#
# plt.xlabel('Epoch Number')
# plt.ylabel('Accuracy')
# plt.title('Model 1 Accuracy')
# plt.legend(['Training Accuracy', 'Validation Accuracy'])
# # plt.savefig('m1acc_hiddenlayers{}.png'.format(hidden_layers))
# plt.show()
#
#
# plt.plot(epoch_list, history.history['mean_squared_error'], 'b-')
# plt.plot(epoch_list, history.history['val_mean_squared_error'], 'r-')
#
# plt.xlabel('Epoch Number')
# plt.ylabel('Mean Squared Error')
# plt.title('Model 1 Error')
# plt.legend(['Training Error', 'Validation Error'])
# # plt.savefig('m1err_hiddenlayers{}.png'.format(hidden_layers))
# plt.show()
# get confusion matrix
predictions = model.predict(x_test)
y_pred = predictions
conf_mat = confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))
# plot confusion matrix
# plt.matshow(conf_mat, cmap=mpl.cm.binary)
# plt.xlabel('Actual')
# plt.ylabel('Predictions')
# plt.title('Model 1 Confusion Matrix')
# # plt.savefig('m1confmat_hiddenlayers{}_batch{}.png'.format(hidden_layers, batch_size))
# plt.show()
# model with dropout layer
model2 = Sequential()
model2.add(Dropout(0.2, input_shape=images_flatten[0].shape))
for i in range(0, hidden_layers):
model2.add(Dense(nodes, activation='relu'))
model2.add(Dense(len(outputs[0]), activation='softmax'))
sgd = keras.optimizers.SGD(lr=learn_rate, momentum=0.5, nesterov=False)
model2.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy', 'mse'])
x_train = images_flatten[:int(0.6*len(images_flatten))]
x_test = images_flatten[int(0.6*len(images_flatten)):int(0.8*len(images_flatten))]
x_validate = images_flatten[int(0.8*len(images_flatten)):len(images_flatten)]
y_train = outputs[:int(0.6*len(outputs))]
y_test = outputs[int(0.6*len(outputs)):int(0.8*len(outputs))]
y_validate = outputs[int(0.8*len(outputs)):len(outputs)]
history2 = model2.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=(x_validate, y_validate))
# plot the accuracy and error for model with dropout layer
# epoch_list = np.linspace(1,500, 500)
# plt.plot(epoch_list, history2.history['acc'], 'b-')
# plt.plot(epoch_list, history2.history['val_acc'], 'r-')
#
# plt.xlabel('Epoch Number')
# plt.ylabel('Accuracy')
# plt.title('Model 2 Accuracy')
# plt.legend(['Training Accuracy', 'Validation Accuracy'])
# # plt.savefig('m2acc_hiddenlayers{}.png'.format(hidden_layers))
# plt.show()
#
# plt.plot(epoch_list, history2.history['mean_squared_error'], 'b-')
# plt.plot(epoch_list, history2.history['val_mean_squared_error'], 'r-')
#
# plt.xlabel('Epoch Number')
# plt.ylabel('Mean Squared Error')
# plt.title('Model 2 Error')
# plt.legend(['Training Error', 'Validation Error'])
# # plt.savefig('m2err_hiddenlayers{}_batch{}.png'.format(hidden_layers, batch_size))
# plt.show()
# predict test set values and make confusion matrix
predictions2 = model2.predict(x_test)
y_pred2 = predictions2
conf_mat2 = confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))
# plot the confusion matrix
# plt.matshow(conf_mat2, cmap=mpl.cm.binary)
# plt.xlabel('Actual')
# plt.ylabel('Predictions')
# plt.title('Model 2 Confusion Matrix')
# # plt.savefig('m2confmat_hiddenlayers{}_batch{}.png'.format(hidden_layers, batch_size))
# plt.show()
# plt.imshow(x_test[11].reshape(28,28), cmap=mpl.cm.binary)
print(y_test[11], y_pred[11])
batch_size = 32
nodes = 50
epochs = 500
learn_rate = 0.001
hidden_layers = 10
# model to take in for cross validation
model3 = Sequential()
model3.add(Dense(nodes, activation='relu', input_shape=images_flatten[0].shape))
for i in range(0, hidden_layers):
model3.add(Dense(nodes, activation='relu'))
model3.add(Dense(len(outputs[0]), activation='softmax'))
sgd = keras.optimizers.SGD(lr=learn_rate, momentum=0.5, nesterov=False)
model3.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy', 'mse'])
# my cross validation function
def cross_validation_score(model=model3, x=images_flatten, y=outputs):
size = len(x)
# split the data into 3 unique folds
# train test validate
splits = [[0, int(0.6*size), int(0.6*size), int(0.8*size), int(0.8*size), size],
[int(0.2*size), int(0.8*size), int(0.8*size), size, 0, int(0.2*size)],
[int(0.4*size), size, 0, int(0.2*size), int(0.2*size), int(0.4*size)]]
acc= []
for split in splits:
# clone the model and train it 3 times and get accuracy each time
m = keras.models.clone_model(model)
sgd = keras.optimizers.SGD(lr=learn_rate, momentum=0.5, nesterov=False)
m.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy', 'mse'])
x_train_fold = x[split[0]:split[1]]
x_test_fold = x[split[2]:split[3]]
x_val_fold = x[split[4]:split[5]]
y_train_fold = y[split[0]:split[1]]
y_test_fold = y[split[2]:split[3]]
y_val_fold = y[split[4]:split[5]]
history = m.fit(x_train_fold, y_train_fold,
epochs=epochs, batch_size=batch_size,
validation_data=(x_val_fold, y_val_fold))
acc.append([history.history['acc'], history.history['val_acc']])
return acc
# get the accuracy values at each epoch for the cross validation function and plot them
cross_score = cross_validation_score()
# plot the validation function results
# epoch_list = np.linspace(1,500, 500)
#
# for i in cross_score:
#
# plt.plot(epoch_list, i[0])
# plt.plot(epoch_list, i[1])
#
# plt.xlabel('Epoch Number')
# plt.ylabel('Accuracy')
# plt.title('Cross Validation Accuracy w/ Dropout {} Hidden Layers \n{} Batch Size'.format(hidden_layers, batch_size))
# plt.legend(['Train Accuracy, k = 1', 'Validation Accuracy, k = 1',
# 'Train Accuracy, k = 2', 'Validation Accuracy, k = 2',
# 'Train Accuracy, k = 3', 'Validation Accuracy, k = 3'])
# # plt.savefig('cross_val2_hidden_layers{}_batchsize{}.png'.format(hidden_layers, batch_size))
# plt.show()
batch_size = 512
nodes = 50
epochs = 500
learn_rate = 0.001
hidden_layers = 10
size = 6500
# model for my expierments changes the above parameters
start = time.time()
modele = Sequential()
modele.add(Dense(nodes, activation='relu', input_shape=images_flatten[0].shape))
for i in range(0, hidden_layers):
modele.add(Dense(nodes, activation='relu'))
modele.add(Dense(len(outputs[0]), activation='softmax'))
sgd = keras.optimizers.SGD(lr=learn_rate, momentum=0.5, nesterov=False)
modele.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy', 'mse'])
i = images_flatten[:size]
o = outputs[:size]
x_train = i[:int(0.6*len(i))]
x_test = i[int(0.6*len(i)):int(0.8*len(i))]
x_validate = i[int(0.8*len(i)):len(i)]
y_train = o[:int(0.6*len(o))]
y_test = o[int(0.6*len(o)):int(0.8*len(o))]
y_validate = o[int(0.8*len(o)):len(o)]
h = modele.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=(x_validate, y_validate))
print(time.time() - start)
print(h.history['val_acc'][len(h.history['val_acc']) - 1])
|
543512c95ce791129d9229521f546a66a2cd2438 | haydenjeune/patterns | /behavioural/visitor.py | 2,028 | 3.984375 | 4 | """Allows the separation of algorithms from the objects on which they operate"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Optional
@dataclass
class BaseNode(ABC):
value: Any
left: Optional[BaseNode] = None
right: Optional[BaseNode] = None
@abstractmethod
def accept(self, visitor: NodeVisitor):
raise NotImplementedError()
@dataclass
class StrNode(BaseNode):
value: str
def accept(self, visitor: NodeVisitor):
visitor.visit_str(self)
@dataclass
class IntNode(BaseNode):
value: int
def accept(self, visitor: NodeVisitor):
visitor.visit_int(self)
@dataclass
class FloatNode(BaseNode):
value: float
def accept(self, visitor: NodeVisitor):
visitor.visit_float(self)
class NodeVisitor(ABC):
@abstractmethod
def visit_str(self, node: StrNode):
raise NotImplementedError()
@abstractmethod
def visit_int(self, node: IntNode):
raise NotImplementedError()
@abstractmethod
def visit_float(self, node: FloatNode):
raise NotImplementedError()
# now we can add new visitor logic without changing the node classes
class BasicPrintVisitor(NodeVisitor):
def visit_str(self, node: StrNode):
print(f"String Node: {node.value}")
def visit_int(self, node: IntNode):
print(f"Int Node: {node.value}")
def visit_float(self, node: FloatNode):
print(f"Float Node: {node.value:.2f}")
def bfs(node: BaseNode):
stack = [node]
while len(stack):
next = stack.pop(0)
if next.left:
stack.append(next.left)
if next.right:
stack.append(next.right)
yield next
if __name__ == "__main__":
tree = IntNode(
value=3,
left=StrNode(value="Hello", right=StrNode(value="there")),
right=FloatNode(value=3.14),
)
visitor = BasicPrintVisitor()
for node in bfs(tree):
node.accept(visitor)
|
f6bc94e10b34ba8262a655aa1e5093b3aaa9578f | Indiana3/python_exercises | /wb_chapter3/exercise74.py | 419 | 4.15625 | 4 | ##
# Implement Newton's method to compute the square root
# of an x number
#
GOOD_APPROXIMATION = 1e-12
# Read x from the user
x = float(input("Please, enter a number: "))
# Compute the good approximation
guess = x/2
while abs(guess ** 2 - x) > GOOD_APPROXIMATION:
guess = (guess + x/guess) / 2
# Display the approximation with 4 decimal places
print("A good approximation of its square root is %.4f" % guess)
|
5437d6fb2a92a614be8450a4dee64b5c4111ad4c | MarsWilliams/algos | /25_12_2020_single_number.py | 667 | 3.578125 | 4 | from typing import List
from collections import Counter
def single_number(nums: List[int]) -> int:
return (k for k, v in Counter(nums).items() if v == 1).__next__()
assert single_number([4, 1, 2, 1, 2, 2]) == 4
def single_number_set(nums: List[int]) -> int:
singles = {}
for i in nums:
if i in singles:
del singles[i]
else:
singles[i] = None
for i in singles:
return i
assert single_number_set([4, 1, 2, 1, 2, 2]) == 4
def single_number_math(nums: List[int]) -> int:
"""2∗(a+b+c)−(a+a+b+b+c)=c"""
return 2*sum(set(nums))-sum(nums)
assert single_number_math([4, 1, 2, 1, 2]) == 4
|
ec9b61c1ac8453294bca14b903e021fc3aa3e775 | mveselov/CodeWars | /tests/kyu_7_tests/test_area_of_a_circle.py | 498 | 3.5625 | 4 | import unittest
from katas.kyu_7.area_of_a_circle import circleArea
class CircleAreaTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(circleArea(43.2673), 5881.25)
def test_equals_2(self):
self.assertEqual(circleArea(68), 14526.72)
def test_false(self):
self.assertFalse(circleArea(-1485.86))
def test_false_2(self):
self.assertFalse(circleArea(0))
def test_false_3(self):
self.assertFalse(circleArea('number'))
|
f3db1273e8aa1462a043b3329f0a9f91e7d7bfa8 | ruanhq/Leetcode | /Algorithm/69.py | 444 | 3.75 | 4 | #69. Sqrt(x):
class Solution(object):
def mySqrt(self, x):
if x < 2:
return x
if x == 2:
return 1
low = 1
high = x
while low <= high:
med = (low + high) // 2
num = med * med
if num > x:
high = med - 1
elif num < x:
low = med + 1
else:
return med
return high |
53768d5bff7a0315fee0c0388a9e345bd522912d | shashankkarthik/CSE | /CSE 231/Computer Projects/project06/proj06a.py | 1,613 | 3.953125 | 4 | #############################################################################
# Computer project 6a
#
# Algorithm
# try
# prompt user for file name
# open file object
# initialize count variable
# intialize lists for years and temps
# iterate through each line in file
# increase count by 1
# append the first 4 chars. in each line to years list
# append the last 4 chars. in each line to temp list
# if count > 0
# call function to draw graph
# else
# display empty file message.
# except FileNotFoundError
# print error message
# end program
#############################################################################
import pylab
def draw_graph( x, y ):
'''Plot x vs. y (lists of numbers of same length)'''
# Title for the graph and labels for the axes
pylab.title( "Change in Global Mean Temperature" )
pylab.xlabel( "Year" )
pylab.ylabel( "Temperature Deviation" )
# Create and display the plot
pylab.plot( x, y )
pylab.show()
try:
file_name = input("Enter File Name: ")
data_file = open(file_name,"r")
count_lines = 0 #Counts how many lines are in the input file.
year = []
temp = []
for line in data_file:
count_lines += 1
year.append(int(line[:4])) #Gets the first 4 charecters from each line
temp.append(int(line[-4:])) #Gets the last 4 charecters from each line
if count_lines > 0:
draw_graph(year,temp)
else:
print("The file is empty.")
print("Ending program.")
except FileNotFoundError:
print("Unable to open file.")
print("Ending program.") |
c051f09e451bc9a7dd40e1c298e88c996556b289 | natandias/Python_CursoEmVideo | /Fase_17_Lista_part1.py | 2,403 | 4.34375 | 4 | # Listas podem ser alteradas diferentemente das tuplas
lanche = ['hamburguer', 'suco', 'pizza', 'pudim']
print(lanche)
''' Pode-se trocar um elemento realizando atribuição '''
lanche[3] = 'goiabada'
print(lanche)
''' Adicionando valor à lista '''
lanche.append('biscoito')
print(lanche)
''' Adicionando valor entre elementos da lista '''
lanche.insert(0, 'Ice Cream')
print(lanche)
''' Apagando elemento '''
del lanche[3]
print(lanche)
''' Usando método POP '''
lanche.pop(3)
print(lanche)
# utilizando pop sem parametro, é eliminado o último elemento da lista
''' Usando remove (indica-se valor a ser removido) '''
lanche.remove('biscoito')
print(lanche)
# se houver dois valores iguais, irá remover o primeiro
''' Se tentar remover um valor que não está na lista o programa dá erro
pode - se usar uma estrutura de controle para evitar esse problema
'''
if 'suco' in lanche:
lanche.remove('suco')
print(lanche)
''' Pode-se criar lista de duas formas '''
p = []
q = list()
''' Criando lista com valores consecutivos (usando list) '''
valores = list(range(4, 11))
print(valores)
''' Ordenando lista em ordem crescente '''
non_ordered = [8, 2, 5, 4, 9, 3, 0]
non_ordered.sort()
print(non_ordered)
''' Ordenando lista em ordem decrescente '''
non_ordered = [8, 2, 5, 4, 9, 3, 0]
non_ordered.sort(reverse=True)
print(non_ordered)
''' Quantos elementos uma lista possui? '''
size = len(non_ordered)
print(size, 'elementos')
print("\n")
''' Print organizado '''
v = []
v.append(5)
v.append(9)
v.append(4)
for c, elm in enumerate(v):
print(f'Na posição {c} encontrei o valor {elm}')
print('Fim da Lista\n')
''' Lendo valores digitados pelo usuario '''
for cont in range(0, 2):
v.append(int(input("Digite um valor: ")))
for c, elm in enumerate(v):
print(f'Na posição {c} encontrei o valor {elm}')
print('Fim da Lista')
''' Se a uma lista recebe outra, ela irá receber os endereços de mémoria
e não os valores, ou seja, se uma valor é alterado na segunda lista,
ele também é alterado na lista original '''
a = [1, 2, 3, 4]
b = a
print('\nLista A: ', a)
print('Lista B: ', b)
b[2] = 10
print('Lista A depois que Lista B foi alterada: ', a)
''' Copiando todos os elementos de uma lista para outra '''
b = a[:]
b[2] = 5
print('Lista A depois que B foi alterada:', a)
# perceba que os valores da lista A não se alteram
print("\nFIM DA AULA")
|
8a9abcc24e93b87d2221871be0cbf1d7d50a600b | nyroro/leetcode | /LC501.py | 947 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
table = {}
if root==None:
return []
def findNum(root, val):
if root == None:
return 0
ret = findNum(root.left, val)+findNum(root.right, val)
if val == root.val:
ret+=1
return ret
def findAns(root):
if root == None:
return (None, -1)
findAns(root.left)
findAns(root.right)
num = findNum(root, root.val)
table.setdefault(num,[]).append(root.val)
findAns(root)
print table
val = max(table.keys())
return table[val] |
6b1533e953bc6217a9b0d0ec04acdc7c38b4f07c | Stanshiki246/Introduction-to-Programming---Lab | /ATM class.py | 4,481 | 4.28125 | 4 | # Define a class for ATM.
class ATM:
# Define a function to initialize ATM class.
def __init__(self,balance,wallet,another):
self.balance = float(balance) # Variable for my balance.
self.wallet = float(wallet) # Variable for my wallet.
self.another = float(another) # Variable for another balance.
# Define a function to show my balance and my wallet.
def get_balance(self):
return print("Balance:",self.balance,"Wallet:",self.wallet) # print my current balance and wallet.
# Define a function to add my balance amount from my wallet.
def deposit(self):
# print the display of deposit.
print("Enter the amount of money to be put in")
amount = float(input(">")) # Variable for input how many money to be put in my balance.
self.balance += amount # the amount is added to my balance.
self.wallet -= amount # the amount in my wallet is decreased.
if self.wallet < 0: # when my wallet is less than 0, it becomes invalid.
return False
else: # when my wallet is more than or equal to 0, it will print my new balance and wallet.
return print("Balance:",self.balance,"Wallet:",self.wallet)
# Define a function to add my wallet amount from my balance.
def withdraw(self):
# print the display of withdraw.
print("Enter the amount of money to be withdrawn")
amount =float(input(">")) # Variable for input how many money to be withdrawn from my balance.
self.balance -= amount # the amount in my balance is decreased.
self.wallet += amount # the amount is added to my wallet.
if self.balance < 0: # when my balance is less than 0, it becomes invalid.
return False
else: # when my balance is more than or equal to 0, it will print my new balance and wallet.
return print("Balance:",self.balance,"Wallet:",self.wallet)
# Define a function to decrease my balance amount for paying.
def debit(self):
# print the display of debit.
print("Enter the amount of money to be paid")
amount =float(input(">")) # Variable for input how many money to be paid.
self.balance -= amount # the amount in my balance is decreased.
if self.balance < 0: # when my balance is less than 0, it becomes invalid.
return False
else: # when my balance is more than or equal to 0, it will print my new balance and current wallet.
return print("Balance:",self.balance,"Wallet:",self.wallet)
# Define a function to transfer money from my balance to another balance.
def transfer(self):
# print the display of transfer.
print("Enter the amount of money to be transferred to another user")
amount=int(input(">")) # Variable for input how many money to be transferred.
self.balance -= amount # the amount in my balance is decreased.
self.another += amount # the decreased amount from my balance is added to another user.
if self.balance < 0: # when my balance is less than 0, it becomes invalid.
return False
else: # when my balance is more than or equal to 0, it will print my balance and another user after transferring.
return print("Balance:",self.balance,"Another Balance:",self.another)
# Variable for inputiing my initial wallet
setWallet = float(input("My initial wallet: "))
a=ATM(0,setWallet,0) # Variable for ATM class with settings such as my balance=0, my wallet = amount of my initial wallet, another balance = 0.
# while statement is True, it will loop until I press "q" to stop.
while True:
# to show options in ATM.
print("1. Check\n2. Deposit\n3. Withdraw\n4. Debit\n5. Transfer")
# Variable for inputting the number to execute approriated option.
mode = input(">")
if mode == "1": # when i press number 1, it will show my balance and wallet.
a.get_balance()
elif mode == "2": # when i press number 2, it will show deposit option.
a.deposit()
elif mode == "3": # when i press number 3, it will show withdraw option.
a.withdraw()
elif mode == "4": # when i press number 4, it will show debit option.
a.debit()
elif mode == "5": # when i press number 5, it will show transfer option.
a.transfer()
elif mode == "q": # when i press "q", it will be end.
break
|
e7adb157f497204bbffda1bf560638d62b00b38d | Brekkjern/SudokuSolver | /SudokuSolver/cell.py | 3,325 | 4.1875 | 4 | import math
from typing import Union
class Cell(object):
"""
The cell object.
The x and y are the respective coordinates.
neighbours is a list of all cells that impact the current cell.
value is the current value of the cell, or None if there is no value set.
possibilities is a list of current possible numbers for the cell
"""
def __init__(self, board, x, y, value=None):
self.x, self.y = x, y
self.neighbours = None
self._value = None
self.board = board
if value == 0:
self._value = None
else:
self._value = value
def __str__(self):
return "X: {}, Y: {}, Val: {}, Possibilities: {}".format(self.x, self.y, self.value, self.possibilities)
def __repr__(self):
return "Cell({x}, {y}, {value})".format(x=self.x, y=self.y, value=self.value)
def __add__(self, other):
"""Allows for adding the values of cells together"""
try:
return self.value + other.value
except AttributeError:
return self.value + other
@property
def value(self):
return self._value
@value.setter
def value(self, value):
"""Makes sure that you can't set the value of the cell twice"""
if self.value:
raise ValueError("Cell {},{}, value: {}. Tried to set value {}".format(self.x, self.y, self.value, value, ))
print("Changed cell. Value {} to cell {},{}".format(value, self.x, self.y))
self._value = value
@property
def supercell(self):
"""Gets the coordinate of the parent supercell"""
supercell_x = math.floor(self.x / self.board.SUPERCELL_SIZE)
supercell_y = math.floor(self.y / self.board.SUPERCELL_SIZE)
return supercell_x, supercell_y
@property
def possibilities(self) -> list:
"""The current possible values for the cell"""
non_possibilities = [
cell.value
for cell in self.neighbours
if cell.value
]
return [val for val in self.board.get_possible_cell_values() if val not in non_possibilities]
def solve(self) -> Union[bool, None]:
if not self.value:
ret_value = self.solve_last_possibility()
ret_value = ret_value if ret_value else self.solve_last_option()
return ret_value
return None
def solve_last_possibility(self) -> bool:
"""Checks if there is only one possibility left for the cell"""
if len(self.possibilities) == 1:
self.value = self.possibilities[0]
print("solve_last_possibility")
return True
return False
def solve_last_option(self) -> bool:
"""Checks if any of the neighbouring cells have any of the remaining possibilities"""
possibilities = set(self.possibilities.copy())
for cell in self.neighbours:
possibilities_for_neighbour = set([
val
for val in possibilities
if val not in cell.possibilities
])
possibilities -= possibilities_for_neighbour
if len(possibilities) == 1:
self.value = list(possibilities)[0]
print("solve_last_option")
return True
return False |
8666fd1ebec5f5ce91af1e4d34bd76268928ed21 | f0lie/basic_python_workshop | /part_oop_3.py | 562 | 3.796875 | 4 | class Point():
def __init__(self, x, velo):
self.x = x
self.velo = velo
def move(self):
self.x += self.velo
def print(self):
print(self.x, self.velo)
line = 10*[' ']
point_1 = Point(0,1)
point_2 = Point(9,-1)
for i in range(10):
line[point_1.x] = '*'
line[point_2.x] = '*'
print("".join(line))
line[point_1.x] = ' '
line[point_2.x] = ' '
# We can represent behaviors with classes too
# note how its more readible
point_1.move()
point_2.move()
point_1.print()
point_2.print()
|
f9cc881df450647eb781156158c3b1277388ab4e | Tulip4attoo/coding-dojo | /geeky.vn/problem1_2.py | 4,078 | 3.5 | 4 | import sys
import time
def convert_input(s_input):
adj_input = s_input.splitlines()
encrypted_text = adj_input[0].split(' ')
dictionary = adj_input[1]
pre_table = adj_input[2 :]
return encrypted_text, dictionary, pre_table
def split_pre_table(pre_table):
simple_pre_table = []
complex_pre_table = []
for substitution in pre_table:
if len(substitution) == 3:
simple_pre_table.append(substitution)
else:
complex_pre_table.append(substitution)
return simple_pre_table, complex_pre_table
def create_table_list(pre_table, simple_pre_table, encrypted_text, dictionary):
result = encrypted_text[:]
compare_list = encrypted_text[:]
start_time = time.time()
simple_string_list = create_simple_string_list(pre_table)
print("--- %s seconds ---" % (time.time() - start_time))
pair_complex_list = create_pair_complex_list(simple_string_list)
print("--- %s seconds ---" % (time.time() - start_time))
count = 0
while len(compare_list) > 0:
for simple_pair_list in pair_complex_list:
tmpTable = create_simple_table_case(simple_pair_list \
+ simple_pre_table)
for ind in range(len(compare_list) - 1, -1, -1):
word = compare_list[ind]
decoded_word = word.translate(tmpTable)
if decoded_word in dictionary:
result[ind] = decoded_word
del(compare_list[ind])
print("--- %s seconds ---" % (time.time() - start_time))
return ' '.join(result)
def create_pair_complex_list(simple_string_list):
result = []
for string in simple_string_list:
result.append(string.split('.'))
return result
def create_simple_string_list(pre_table):
result = []
if len(pre_table) == 1:
return produce_1len_pair(pre_table[0])
else:
for ind in range(0, len(pre_table)):
new_addition_pair = produce_1len_pair(pre_table[ind])
recursive_result = create_simple_string_list(pre_table[ind + 1:])
for simple_pair in new_addition_pair:
for recursive_pairs in recursive_result:
result.append(simple_pair + '.' + recursive_pairs)
return result
def produce_1len_pair(substitution):
'''
substitution: string
'''
result = []
base = substitution[0 : 2]
for char in substitution[2::2]:
result.append(base + char)
return result
def create_simple_table_case(simple_pair_list):
base_dict = {}
for substitution in simple_pair_list:
base_dict[ord(substitution[0])] = substitution[2]
return base_dict
f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]
f = lambda l: reduce(lambda z, x: z + [y + [x] for y in z], l, [[]])
# def decode_1_word(word, tables_list, dictionary):
# for table in tables_list:
# decoded_word = word.translate(table)
# if decoded_word in dictionary:
# return decoded_word
# def get_decode_text(encrypted_text, tables_list, dictionary):
# result = []
# for word in encrypted_text:
# result.append(decode_1_word(word, tables_list, dictionary))
# return ' '.join(result)
if __name__ == "__main__":
# s_input = sys.stdin.read()
# s_input = str(s_input)
s_input = '''pgfqp td c bt bh dhschddg
rage am holy an fairy engine tale engineer i le me my trust yes thunder truth oh april goddess beach please godzilla neo matrix mogu al capone you know tired of this sheet
b a f
c i
d e k d s w e r c x
f k d s w e u
g r k d s w e r
s g k d s w e r
h k d s w e n
p t k d s w e r
q s
t m'''
encrypted_text, dictionary, pre_table = convert_input(s_input)
simple_pre_table, complex_pre_table = split_pre_table(pre_table)
tables_list = create_table_list(complex_pre_table, \
simple_pre_table, encrypted_text, dictionary)
print(tables_list) |
2d158728e71a0f47a775f4f9a3309fc17820d9c7 | TheGoop/learnWebDev | /test.py | 5,045 | 3.75 | 4 | class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
#could approach in a sort of dfs manner
#start at a 1, search neighboring nodes
# when searching these adjacent nodes, marked them as "discovered"
# and if theyre a "1" append to a list to visit next iteration
# once list is empty, we have discovered the entire island,
# increment count
# after list is empty, call a function to find an undiscovered "1"
# if none of such exist, return count
#Returns coords of an undiscovered land in grid, else returns None
def getUndiscoveredLand(grid, visited, allLand, LAND):
for coord in allLand:
r, c = coord
if not visited[r][c]:
return (r,c)
return None
def getAllUndiscoveredLand(grid, LAND):
nodes = []
for r in range(len(grid)):
for c in range(len(grid[r])):
if grid[r][c] == LAND:
nodes.append((r,c))
if nodes == []:
return None
return nodes
#returns if r,c are valid coords within grid boundaries
def validCoords(r, c, grid):
if 0 <= r and r < len(grid) and 0 <= c and c < len(grid[r]):
return True
else:
return False
#checks all adjacent nodes to grid[row][col] to see if they are land
#and not visited, returns list of all nodes meeting criterion
def getAdjacents(row, col, grid, visited, LAND):
s = []
#check coord north
r = row + 1
c = col
if (validCoords(r, c, grid) and grid[r][c] == LAND and not visited[r][c]):
s.append((r,c))
#check coord south
r = row - 1
c = col
if (validCoords(r, c, grid) and grid[r][c] == LAND and not visited[r][c]):
s.append((r,c))
#check coord east
r = row
c = col + 1
if (validCoords(r, c, grid) and grid[r][c] == LAND and not visited[r][c]):
s.append((r,c))
#checks coord west
r = row
c = col - 1
if (validCoords(r, c, grid) and grid[r][c] == LAND and not visited[r][c]):
s.append((r,c))
if (len(s) > 0):
return s
return None
if (grid == None or len(grid) == 0 ):
return 0
LAND = "1"
visited = []
for row in grid:
temp = []
for i in range(len(row)):
temp.append(False)
visited.append(temp)
toVisit = []
islands = 0
allLand = getAllUndiscoveredLand(grid, LAND)
if allLand == None:
return 0
coord = getUndiscoveredLand(grid, visited, allLand, LAND)
#if no land, returns 0
if coord == None:
return islands
toVisit.append(coord)
while (True):
#dfs of toVisit
while (len(toVisit) != 0):
r, c = toVisit.pop()
visited[r][c] = True
#search adjacent nodes of r,c
#if any unvisited adjacents are land, add to toVisit
toSearch = getAdjacents(r, c, grid, visited, LAND)
if toSearch != None:
toVisit.extend(toSearch)
#increment counter, we have just finished iterating through a land mass
islands += 1
coord = getUndiscoveredLand(grid, visited, allLand, LAND)
#if no undiscovered lands left, return island count
if coord == None:
return islands
#else, append new coord and begin dfs again
toVisit.append(coord)
return islands
def test():
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
x = Solution()
print(x.numIslands(grid))
def validCoords(grid, r, c):
return 0 <= r and r < len(grid) and 0 <= c and c < len(grid[r])
def drownIslandAt(grid, r, c):
if (validCoords(grid, r, c) and grid[r][c] == "1"):
grid[r][c] = '0'
grid = drownIslandAt(grid, r+1, c)
grid = drownIslandAt(grid, r-1, c)
grid = drownIslandAt(grid, r, c+1)
grid = drownIslandAt(grid, r, c-1)
return grid
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
for row in grid:
print(row)
grid = drownIslandAt(grid, 3, 3)
print("Result")
for row in grid:
print (row) |
f3249db436c706be90505c3be7a0cff3c36a427b | srithanrudrangi/PythonCoding | /5_2_SalesTaxProgramRefactoring.py | 513 | 3.953125 | 4 | def sales():
number = int(input(" How many items did you purchase? "))
subTotal = 0
for i in range(number):
price = int(input("Enter price of item: "))
subTotal = price + subTotal
stateSalesTax = subTotal*0.05
countySalesTax = subTotal*0.025
print("Your Sub total:", subTotal)
print("Your State sales Tax:", stateSalesTax)
print("Your County sales Tax:", countySalesTax)
print("Your Total due:", subTotal + stateSalesTax + countySalesTax)
sales()
sales()
|
0dbd40eca7efc0f8c31ec7ba814691966acff9df | SomethingRandom0768/PythonBeginnerProgramming2021 | /Chapter 6 ( Dictionaries )/Exercises/6-10favorite_numbers2.py | 421 | 3.828125 | 4 |
favorite_numbers = {'r': [12, 6],
'c': [9, 3],
's': [13, 1],
'coo': [6, 8],
'e': [9, 2],
'd': [5, 8],
'f': [25, 1],
}
for name, values in favorite_numbers.items():
print(f"\nThe person {name} likes the numbers below:")
for value in values:
print(value) |
c49b33f614578a174b5009b418b525930f6def8c | htmlprogrammist/kege-2021 | /tasks_22/homework/task_22.10.py | 1,476 | 3.8125 | 4 | """
Задание 22 (№834).
Ниже на четырёх языках программирования записан алгоритм.
Получив на вход число x, этот алгоритм печатает два числа: L и M.
Укажите наибольшее число x, не содержащее нулей,
при вводе которого алгоритм печатает сначала 14, а потом 3.
"""
# x = int(input())
# L, M, R = 0, 0, 0
# while x > 0:
# R = R * 10 + x % 10
# x //= 10
# if x <= R:
# M += 1
# else:
# L += x % 10
# print(L)
# print(M)
answers = []
number = 0
answer_L = 14
answer_M = 3
while number < 10000000:
x = number
zero = False # По умолчанию нулей нет
L, M, R = 0, 0, 0
while x > 0:
R = R * 10 + x % 10
x //= 10
if x <= R:
M += 1
else:
L += x % 10
if answer_L == L and answer_M == M:
check_number = number
while check_number > 0: # Расчехляем число по цифрам и смотрим на наличие 0
last_digit = check_number % 10
if last_digit == 0:
zero = True # Ноль есть
check_number //= 10
if not zero: # Если нет нулей, то добавь к ответам
answers.append(number)
number += 1
print(answers)
print(max(answers))
|
92550e32dbfff20120c56734d1c6501bb22faa86 | merissab44/superHero | /hero.py | 5,141 | 3.84375 | 4 | import random
from ability import Ability
from armor import Armor
from weapon import Weapon
class Hero:
# We want out hero to have a default "starting health"
# we set that in the finction header
def __init__(self, name, starting_health=100):
# abilities and armors dont have starting values
self.abilities = list()
self.armors = list()
#name of our hero
self.name = name
#when we create hero, their starting health
#is there current health
self.starting_health = starting_health
# when a hero is created the current health
# us the same as their starting health
self.current_health = starting_health
self.deaths = 0
self.kills = 0
def add_ability(self, ability):
self.abilities.append(ability)
def add_weapon(self, weapon):
self.abilities.append(weapon)
def attack(self):
total_damage = 0
for ability in self.abilities:
# add the damage of the attack to get the total damage
total_damage += ability.attack()
print(f" the total damage was: {total_damage}")
return total_damage
def add_armor(self, armor):
# adding each armor to the list self.armors
self.armors.append(armor)
def defend(self):
total_block = 0
if len(self.armors) == 0:
print('Theres no armor')
return 0
for armor in self.armors:
# adds the "strength" of the armor to get the total block
print(f"name: {armor.name}")
total_block += armor.block()
print(f"Your total block is {total_block}")
return total_block
def take_damage(self, damage):
print(damage)
print(self.defend())
self.current_health -= damage + self.defend()
print(f"Your current health is now {self.current_health}")
return self.current_health
def is_alive(self):
if self.current_health <= 0:
return False
else:
return True
def add_kill(self, num_kills):
self.kills += num_kills
def add_death(self, num_deaths):
self.deaths += num_deaths
def fight(self, opponent):
#Check to see if hero has abilities, if no abilities, print draw
if len(self.abilities) > 0 or len(opponent.abilities) > 0:
while(self.is_alive() and opponent.is_alive()):
#Start fighting loop until a hero has won
print(f'{opponent.name} attacked {self.name}!')
self.take_damage(opponent.attack())
print(f"{self.name}'s remaining health: {self.current_health}")
print(f'{self.name} attacked {opponent.name}!')
opponent.take_damage(self.attack())
print(f"{opponent.name}'s remaining health: {opponent.current_health}")
if self.is_alive() == False:
opponent.add_kill(1)
self.add_death(1)
return (f"{self.name} has been defeated by {opponent.name}")
elif opponent.is_alive() == False:
opponent.add_death(1)
self.add_kill(1)
return (f"{opponent.name} has been defeated by {self.name}")
else:
print("Draw!")
#print(f'{random.choice(hero_choice)} wins!')
# def fight(self, opponent):
# if len(self.abilities) <= 0 or len(opponent.abilities) <= 0:
# print ('Draw')
# else:
# while self.current_health > 0 and opponent.current_health > 0:
# opponent_dmg = opponent.attack()
# self_dmg = self.attack()
# opponent_kills = opponent.add_kill()
# opponent.take_damage(self_dmg)
# print(opponent.is_alive())
# self.take_damage(opponent_dmg)
# print(self.is_alive())
# if self.is_alive() == False:
# print(f"{opponent.name} has won!")
# opponent_kills += 1
# elif opponent.is_alive() == False:
# print(f"{self.name} has won!")
# else:
# print("It's a tie!")
# hero_choice = [self, opponent]
# for hero in hero_choice:
# hero.attack()
# self.take_damage(opponent.attack())
# hero.defend(opponent.attack())
if __name__ == "__main__":
# If you run this file from the terminal
# this block is executed.
hero1 = Hero("Wonder Woman")
hero2 = Hero("Dumbledore")
weapon1 = Weapon("Super Speed", 300)
# ability2 = Ability("Super Eyes", 130)
ability3 = Ability("Wizard Wand", 80)
# ability4 = Ability("Wizard Beard", 20)
hero1.add_weapon(weapon1)
# hero1.add_ability(ability2)
# hero2.add_ability(ability3)
# hero2.add_ability(ability4)
print(hero1.fight(hero2))
hero = Hero("Wonder Woman")
weapon = Weapon("Lasso of Truth", 90)
hero.add_weapon(weapon)
print(hero.attack()) |
1ba80b3cf0672689d966aaf3dfef53b44f6c0969 | ChangxingJiang/LeetCode | /0101-0200/0105/0105_Python_2.py | 1,009 | 3.78125 | 4 | from typing import List
from toolkit import TreeNode
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def recursor(p_left, p_right, i_left, i_right):
if p_left < p_right and i_left < i_right:
# 寻找当前二叉树的根节点
val = preorder[p_left]
root = TreeNode(val)
# 寻找中序遍历中的根节点位置
idx = inorder.index(val) - i_left
# 处理左子树
root.left = recursor(p_left + 1, p_left + idx + 1, i_left, i_left + idx)
# 处理右子树
root.right = recursor(p_left + idx + 1, p_right, i_left + idx + 1, i_right)
# 返回当前树的结果
return root
return recursor(0, len(preorder), 0, len(inorder))
if __name__ == "__main__":
# [3,9,20,None,None,15,7]
print(Solution().buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]))
|
4483ca3c37dc9164404bed8f67703a506a3bad2b | jgabdiaz/mycode | /lab_input/iptaker02.py | 390 | 3.625 | 4 | #!/usr/bin/env python3
user_input = input("Please enter an IPv4 IP address:")
print("You told me the IPv4 address is:", user_input)
VendorID = input("Please enter the vendor name: ")
print("You told me the vendor name is:", VendorID)
User_Name = input("tell me your user_name: ")
DayWeek = input("What day of the week is it?: ")
print ("Hello, " + User_Name + "! Happy", DayWeek + "!")
|
7e75cb00a531cc35bfb23a39d73192924e00da4e | nawendusingh/leetcode | /20validparentheses.py | 717 | 3.890625 | 4 | def vp(str):
paren = {'[': ']', '(': ')', '{': '}'}
stk = []
for i in str:
if i not in paren:
if not stk or i != paren[stk[-1]]:
return False
else:
stk.pop()
else:
stk.append(i)
return stk == []
# imagine a stack,u find opening parenthese u push on stack
# u find closing parenthes u check if it matches top element on stack
# if it does you pop topmost element
# valid: when string is exhausted and the stack is empty
# invalid: stack empty and closing parenthese is current i
# current i not matched topmost element on stack
# if stack not empty and str is exhausted
print(vp('{{[(]}}'))
|
636f6308d26f9712c2a9bbfe902e9ed1e033bc48 | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/Osiddiquee/lesson08/test_circle.py | 808 | 3.8125 | 4 | '''
This is the test program for circle.py
'''
from circle import *
def test_init():
c = Circle(5)
assert c.radius == 5
assert c.diameter == 10
def test_change_diameter():
c = Circle(5)
c.diameter = 8
assert c.radius == 4
def test_area():
c = Circle(2)
assert round(c.area, 2) == 12.57
def test_alternate_constructor():
c = Circle.from_diameter(8)
assert c.diameter == 8
assert c.radius == 4
def test_str():
c = Circle(4)
print(c)
def test_repr():
c = Circle(4)
repr(c)
def test_numeric():
c1 = Circle(2)
c2 = Circle(4)
assert c1 + c2 == 'Circle(6)'
c2 * 3 == 'Circle(12)'
3 * c2 == 'Circle(12)'
def test_sort():
l = [Circle(4), Circle(2), Circle(6)]
assert sorted(l) == [Circle(2), Circle(4), Circle(6)]
|
a6cea0616d279fb67fac02d7182e7be8c6833739 | Nadezhda-Sokolova/Practice-and-Home-work | /practice_2nd_episode.py | 732 | 3.703125 | 4 | # First excercise
a = 2
b = 3
a1 = str (a)
b1 = str (b)
c = a1 + b1
print (c)
d = int (a1 + b1)
print (d)
d1 = a + b
print (str(d1))
c1 = c * 2
print (c1)
# Second exercise
line = 'ABCDCDC'
sub = 'CDC'
n = line.count(sub)
print (n)
import re
print (len (re.findall('(?=CDC)', line)))
#Third exercise
text = 'It was the best of times it was the worst of times it was the age of wisdom it was the age of foolishness'
text = text.lower()
#print (text)
list_of_text = text.split(' ')
#print (list_of_text)
dictionary = dict()
for word in list_of_text:
if dictionary.get(word) == None:
dictionary[word] = 1
else:
dictionary[word] += 1
print (dictionary)
print (dictionary['IT'.lower()])
#print (help (str))
|
970861d1c278970e0fef6d706ffd18a4e8c50586 | Lzffancy/Aid_study | /fancy_month01/day12_fancy/12homework/stuff_manager_sys.py | 3,444 | 3.5625 | 4 | #公司员工管理系统
'''作业
1. 三合一
2. 当天练习独立完成
3. 员工信息管理系统
(1)录入员工信息
(2)显示员工信息
(3)删除员工信息
(4)修改员工信息
class Employee:
def __init__(self, eid, did, name, money):
self.eid = eid # 员工编号
self.did = did # 部门编号
self.name = name # 姓名
self.money = money # 薪资'''
class Employee_Model:
def __init__(self, eid=0, did=0, name='', money=0):
self.eid = eid # 员工编号
self.did = did # 部门编号
self.name = name # 姓名
self.money = money # 薪资
def __str__(self):
return str(self.__dict__)
class Employee_View:
def __init__(self):
self.__controller = Employee_Controller() #构建类间调用记得加() 桥
def __dispalay_menu(self):
print("按1键录入员工信息")
print("按2键显示员工信息")
print("按3键删除员工信息")
print("按4键修改员工信息")
def __select_menu(self):
sel = input("输入需要执行的操作:")
if sel == '1':
self.__input_emp()
elif sel == '2':
self.__show_emps()
elif sel == '3':
self.__delect_emp()
elif sel == '4':
self.__modfiy_emp()
def __input_emp(self):
emp_info = Employee_Model()
#self.eid = input('员工编号') # 员工编号
emp_info.did = int(input ("部门编号:")) # 部门编号
emp_info.name = input ('姓名:') # 姓名
emp_info.money = input ('薪资:') # 薪资
self.__controller.add_emp(emp_info)
print("添加成功")
def __show_emps(self):
for item in self.__controller.list_emps:
print(item) #表由model打包所以重写 model的__str__
def __delect_emp(self):
eid = int(input("删除:请输入员工的eid:"))
if self.__controller.remove(eid):
print("删除成功",eid)
else:
print("删除失败")
def __modfiy_emp(self):
emp = Employee_Model()
emp.eid = int(input("员工编号"))
emp.did = int(input("部门编号:")) # 部门编号
emp.name = input('姓名:') # 姓名
emp.money = input('薪资:') # 薪资
if self.__controller.update_emp(emp):
print("修改成功")
else:
print("修改失败")
def main(self):
while 1:
self.__dispalay_menu()
self.__select_menu()
class Employee_Controller:#核心 存储数据
def __init__(self):
self.__list_emps = []
self.__start_eid = 10000
@property
def list_emps(self):
return self.__list_emps
def add_emp(self, emp):
emp.eid = self.__start_eid
self.__start_eid += 1
self.__list_emps.append(emp)
def remove(self, eid):
for i in range(len(self.__list_emps)):
if self.__list_emps[i].eid == eid:
print('删除',self.__list_emps[i])
del self.__list_emps[i]
return True
return False
def update_emp(self, emp):
for each in self.__list_emps:
if each.eid == emp.eid:
each.__dict__=emp.__dict__
return True
return False
#-----------------------
view = Employee_View()
view.main() |
dcdf726e087b77002e0d8ed1769e7b7725547412 | ji-cc/MyPython | /函数/案例 控制终端.py | 142 | 3.828125 | 4 | endstr = "end"
str = ""
for line in iter(input, endstr):
str += line + "\n"
print(str) #在后台输入字符串,打印end结束程序 |
ba8fd1f5cd890944b47038ad489b34495f811e48 | ghoshorn/leetcode | /leet260.py | 2,512 | 3.984375 | 4 | # encoding: utf8
'''
Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
第一遍使用异或,得到只出现一次的两个数的异或值。
第二遍,根据之前的结果(某一位是否为1),将数分为两组,则必然是 每组中只有一个数出现一次,其他出现两次;
再根据Single Number I的解法,一次异或即可。
在Python中,因为不存在int的关系,需要对正负数分别对待。在C中不需要。
Python中,dif&=-dif,可以不需要区分正负数。为什么?
'''
import unittest
from pprint import pprint
import pdb
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
dif=0
for x in nums:
dif=dif ^ x
cnt=0
# print 'dif=',dif
# while dif>0:
# dif=dif>>1
# cnt+=1
# if cnt>1:
# dif=1<<(cnt-1)
# else:
# dif=1
dif&=-dif # bit hack, isolate the rightmost 1-bit
# print 'dif2=',dif
n1=0
n2=0
for x in nums:
if x & dif!=0:
n1=n1^x
else:
n2=n2^x
return [n1,n2]
class testCase(unittest.TestCase):
def setUp(self):
pass
self.a=Solution()
def testLeet(self):
self.assertEqual(self.a.singleNumber([1, 2, 1, 3, 2, 5]),[3,5])
self.assertEqual(self.a.singleNumber([43772400,1674008457,1779561093,744132272,1674008457,448610617,1779561093,124075538,-1034600064,49040018,612881857,390719949,-359290212,-812493625,124732,-1361696369,49040018,-145417756,-812493625,2078552599,1568689850,865876872,865876872,-1471385435,1816352571,1793963758,2078552599,-1034600064,1475115274,-119634980,124732,661111294,-1813882010,1568689850,448610617,1347212898,-1293494866,612881857,661111294,-1361696369,1816352571,-1813882010,-359290212,1475115274,1793963758,1347212898,43772400,-1471385435,124075538,-1293494866,-119634980,390719949]),[-145417756,744132272])
if __name__ == '__main__':
unittest.main() |
4e2f1456b6cf4eb1412b3fe12b1a140780321912 | HeywoodKing/mytest | /MyHello/person.py | 690 | 3.8125 | 4 | # -*- coding: utf-8 -*-
class Person(object):
def __init__(self, name, gender):
self.__name = name
self.__gender = gender
def get_gender(self):
return self.__gender
def set_gender(self, gender):
# if gender.strip() != '':
# self.__gender = gender
# else:
# raise ValueError('bad gender')
if gender.strip():
self.__gender = gender
else:
raise ValueError('bad gender')
def print_per(self):
print('%s, %s' % (self.__name, self.__gender))
lisa = Person('Linda', '女')
lisa.print_per()
lisa.set_gender('男')
lisa.print_per()
|
86304c58328b019f82bcd9f20a0ab4a6c4997400 | Paula-Bean/PaulaWords | /crosswords-guardian/cleanup.py | 1,142 | 3.640625 | 4 | #!/usr/bin/env python3
#
# Reads the file 'guardian-puzzlewords-withsees.txt' and removes unwanted
# material from it, combines clues when multiple clues for a word are
# present, and writes the result to 'guardian-puzzlewords.txt'.
#
# Words can have one or more clues:
#
# ACCREDITATION
# Granting of recognition (13)
#
# ACCREDITED
# Certified officially (10)
#
# ACCRUE
# Accumulate (6)
# Gather (6)
# Grow by addition (6)
#
import codecs
import collections
import re
resee = re.compile(".*See \d")
words = collections.defaultdict(set)
currentword = ""
for line in codecs.open("guardian-puzzlewords-withsees.txt", "rb", "utf8"):
line = line.rstrip()
if not line:
continue
if resee.match(line): # Skip clues like "See 1 down"
continue
if line[0] == " ":
clue = line.strip()
words[currentword].add(clue)
else:
currentword = line.strip()
with codecs.open("guardian-puzzlewords.txt", "wb", "utf8") as f:
for word in sorted(words):
f.write(word + "\n")
for clue in sorted(words[word]):
f.write(" " + clue + "\n")
f.write("\n")
|
247700ef4892d112a3be6b2fb6cd7b2acf116032 | Artur-STN/Curso-de-python | /ExerciciosCursoEmVideo/ex059 - Criando um Menu de opções.py | 1,718 | 3.65625 | 4 | from time import sleep
print('\033[31;1m▲▼\033[m'*10)
n1 = int(input('{}Primeiro valor: {}'.format('\033[32;1m', '\033[m')))
n2 = int(input('{}Segundo valor: {}'.format('\033[33;1m', '\033[m')))
print('\033[31;1m▲▼\033[m'*10)
sair = 0
maior = [n1, n2]
while sair != 5:
print('''{} [ 1 ] Somar{}
{}[ 2 ] Multiplicar{}
{}[ 3 ] Maior{}
{}[ 4 ] Novos Números{}
{}[ 5 ] Sair do Programa{}'''.format('\033[32;1m', '\033[m', '\033[33;1m', '\033[m', '\033[34;1m', '\033[m',
'\033[35;1m', '\033[m', '\033[36;1m', '\033[m'))
print('\033[31;1m▲▼\033[m' * 10)
opcao = int(input('{}Digite a sua opção: {}'.format('\033[30;1m', '\033[m')))
print('\033[31;1m▲▼\033[m' * 10)
if opcao == 1:
print('{}A soma é: {} + {} = {}{}'.format('\033[32;1m', n1, n2, n1 + n2, '\033[m'))
elif opcao == 2:
print('{}O produto de {} X {} = {}{}'.format('\033[33;1m', n1, n2, n1 * n2, '\033[m'))
elif opcao == 3:
print('{}Entre {} e {} o maior é {}{}'.format('\033[34;1m', n1, n2, max(maior), '\033[m'))
elif opcao == 4:
print('{}Informe os novos valores.{}'.format('\033[35;1m', '\033[m'))
n1 = int(input('{}Primeiro valor: {}'.format('\033[32;1m', '\033[m')))
n2 = int(input('{}Segundo valor: {}'.format('\033[33;1m', '\033[m')))
elif opcao > 5:
print('{}Opção inválida. Tente novamente.{}'.format('\033[31;1m', '\033[m'))
print('\033[31;1m▲▼\033[m' * 10)
if opcao == 5:
print('{}Finalizando...{}'.format('\033[36;1m', '\033[m')), sleep(2)
print('{}Fim do Programa! Volte Sempre!{}'.format('\033[36;1m', '\033[m'))
sair = 5
|
606d3ff1deb1fd76008077ae2a63824d97a5454f | vladGriguta/leetcode | /AugustChallenge/longest-palindrome.py | 732 | 3.703125 | 4 | # Day 14 - August Challenge
class Solution:
def longestPalindrome(self, s: str) -> int:
# idea: maximum palindrome is the size of the string minus the number of characters
# that appear an odd number of times plus 1
# if all characters with an even number of appearances, max palindrome is the length of the string
# convention: odd -> -1, even -> 1
mapEven = {}
for ch in s:
if ch not in mapEven:
mapEven[ch] = -1
else:
mapEven[ch] *= -1
if -1 in mapEven.values():
return len(s) - (sum(value == -1 for value in mapEven.values()) - 1)
else:
return len(s)
|
74e169a12769df77c2745d831596d16eccb2cebf | amogchandrashekar/Leetcode | /Medium/Last Stone Weight II.py | 1,575 | 3.8125 | 4 | """
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose any two rocks and smash them together. Suppose the stones have weights x and y with x <= y.
The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left.
Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.)
Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2 so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1 so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0 so the array converts to [1] then that's the optimal value.
Note:
1 <= stones.length <= 30
1 <= stones[i] <= 100
"""
from typing import List
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
total_sum = sum(stones)
max_sum = total_sum // 2
dp = [0 for i in range(max_sum + 1)]
for row_index in range(1, len(stones) + 1):
for col_index in range(len(dp) - 1, -1, -1):
if col_index - stones[row_index - 1] >= 0:
dp[col_index] = max(dp[col_index], dp[col_index - stones[row_index - 1]] + stones[row_index - 1])
return total_sum - 2 * dp[-1]
if __name__ == "__main__":
stones = [2,7,4,1,8,1]
print(Solution().lastStoneWeightII(stones)) |
3c33a83270457d165f7d36c2c34938028969a89b | denistsiupka/PythonLab1 | /Tsuipka__lab1_8.py | 926 | 4 | 4 | print(
"Програма, яка визначає значення цілої змінної number - від 1 до 7, в залежності від того,\nна який день тижня (від понеділка до неділі) припадає день (ціла змінна day) "
"невисокосного року, в якому 1 січня - понеділок (1 ≤ day ≤ 365). ")
day = int(input("Введіть номер вашого дня = "))
if day <= 0 or day > 365:
print("Невірно введені дані")
elif day % 7 == 0:
print("Неділя")
elif day % 7 == 1:
print("Понеділок")
elif day % 7 == 2:
print("Вівторок")
elif day % 7 == 3:
print("Середа")
elif day % 7 == 4:
print("Черверг")
elif day % 7 == 5:
print("П'ятниця")
elif day % 7 == 6:
print("Субота")
else:
print("Помилка")
|
a40ea79502f8ca49349f41b693c8fe0f65d490e5 | JMoVS/JUMP | /UserInput.py | 12,944 | 4.0625 | 4 | __author__ = 'Justin Scholz'
__copyright__ = "Copyright 2015 - 2017, Justin Scholz"
def recognize_user_input_yes_or_no(user_choice: str, default: bool):
user_input_understood = False
yes = str
no = str
user_choice_answer = "x"
if default:
yes = ""
no = "no"
elif not default:
yes = "yes"
no = ""
if user_choice == yes or user_choice == "y" or user_choice == "yes":
user_choice_answer = True
user_input_understood = True
elif user_choice == no or user_choice == "n" or user_choice == "no":
user_choice_answer = False
user_input_understood = True
return user_choice_answer, user_input_understood
def recognize_user_input_multi_choice(user_choice: str, user_options):
user_input_understood = False
user_choice_answer = int
for answer_index in range(user_options):
try:
if int(user_choice) == answer_index:
user_choice_answer = answer_index
user_input_understood = True
except ValueError:
user_input_understood = False
return user_choice_answer, user_input_understood
def parse_user_input_lower_upper_limit_with_interval(user_choice: float, lower_limit: float, upper_limit: float,
steplength: float):
user_input_understood = False
# First we check that the entered value is in the expected boundaries
if not (user_choice > upper_limit or user_choice < lower_limit):
# then we use mathematics to look whether it matches with our desired step length
reduced = ((user_choice - lower_limit) * steplength)
reduced = round(reduced, 4)
# And do stupid things because computers calculate in base 2 and not base 10
if reduced.is_integer():
user_input_understood = True
return user_choice, user_input_understood
def recognize_user_input(user_choice: str, possibilities: [], default_answer=None):
"""
:param default_answer: the default answer that is returned if user just hits enter
:param user_choice: what the user entered
:param possibilities: a list containing all valid answers, make sure to include "" if you want default answers
with "enter" key pressing
:return: user_chosen_answer: one value of the possibilities passed to this function; user_input_understood: Whether
there was an error parsing the answer or not. Returns true if the input was matched.
"""
user_input_understood = False
user_chosen_answer = str
for answer in possibilities:
try:
if int(user_choice) == answer:
user_chosen_answer = user_choice
user_input_understood = True
except ValueError:
user_input_understood = False
if user_choice == "":
user_chosen_answer = default_answer
user_input_understood = True
return user_chosen_answer, user_input_understood
def ask_user_for_input(question: dict):
"""
:param question: a dictionary as it comes from elsewhere, meaning that it has the keys: "question_title", "question_text",
"default_answer", "option_type" (can be "yes_no", "multi_choice", "free_choice"),
"valid_options" (only needed for multi_choice), "valid_options_lower_limit" and "valid_options_upper_limit" and
"valid_options_steplength" in case of the free_choice. The "default answer" key is in case of a yes/no question
either True or False, in case of free choice, it's a float and in case of multi_choice, it's the index of the answer
out of the valid_options.
:type question: dict
- a sample dictionary for multi_choice is:
question = {"question_title": "Measurement Mode",
"question_text": "Please choose which measurement mode to use",
"default_answer": 2,
"optiontype": "multi_choice",
"valid_options": ["2-point", "3-point", "4-point"]}
- a sample dictionary for yes/no is:
question = {"question_title": "Connection check",
"question_text": "Connection check wasn't performed but is optional. Do you want to check the "
"connections?",
"default_answer": True,
"optiontype": "yes_no"}
- a sample dictionary for interval is:
question = {"question_title": "Excitation voltage",
"question_text": "Please enter an excitation voltage between 0 and 3 V. Maximum accuracy is 0.1 V.",
"default_answer": 1.0,
"optiontype": "free_choice",
"valid_options_lower_limit": 0.0,
"valid_options_upper_limit": 3.0,
"valid_options_steplength": 1e1}
Note: Steplength is the inverse steplength. If 0.05 is the allowed steplength, enter 20 as steplength here
- a sample dictionary to ask for free text:
question = {"question_title": "Working directory",
"question_text": "Please choose a working directory for the following session with this program",
"default_answer": "C:\Data\DiBaMePro",
"optiontype": "free_text"}
- a sample dictionary to ask for two indeces:
question = {"question_title": "Same-level-merge selection",
"question_text": "Please enter the two indeces, (you will get two input prompts) for the "
"two which are to be merged.",
"default_answer": "0",
"optiontype": "2_indeces"}
- a sample dictionary to ask for multiple indeces:
question = {"question_title": "Same-level-merge selection",
"question_text": "Please enter one or more indeces separated only by a comma",
"default_answer": "0,4,8,12",
"optiontype": "multi_indeces"}
"""
result = question.copy()
# first we get the dictionarie's values into local variables to ease the handling
question_title = question["question_title"] # type: str
question_title = "-------------" + question_title + "-------------"
question_text = question["question_text"] # type: str
default_answer = question["default_answer"] # can be int or True or str
optiontype = question["optiontype"] # type: str
valid_options = None
valid_options_lower_limit = None
valid_options_upper_limit = None
valid_options_steplength = None
print(question_title)
print(question_text)
# valid_options and option specifics only exist if it's not a yes/no question
if optiontype != "yes_no":
# in case of multi_choice, key "valid_options" exist and we need to match it
if optiontype == "multi_choice":
valid_options = question["valid_options"] # type: []
elif optiontype == "free_choice":
valid_options_lower_limit = question["valid_options_lower_limit"]
valid_options_upper_limit = question["valid_options_upper_limit"]
valid_options_steplength = question["valid_options_steplength"]
# Now let's make different parsing for the (currently) three question types:
# Yes/No questions are mapped to Bool True or False
if optiontype == "yes_no":
# here we can easily centrally exchange this to some logic to talk to a potential GUI
answer_understood = False
user_chosen_answer = None # type: bool
default_literal_answer = ""
if default_answer:
default_literal_answer = "yes"
elif not default_answer:
default_literal_answer = "no"
while not answer_understood:
user_entered_response = input(
"Default answer is: " + default_literal_answer + ". What do you want? Type y, n or confirm default: ")
user_chosen_answer, answer_understood = recognize_user_input_yes_or_no(user_entered_response,
default_answer)
result['answer'] = user_chosen_answer
# Code Block for handling multi-option question type
elif optiontype == "multi_choice":
# we will later need a list of valid responses from the user
valid_answers = []
# enumerate yields the index AND the value, so we can use both then
for index, item in enumerate(valid_options):
print(str(index) + ": " + item)
valid_answers.append(index)
answer_understood = False
user_chosen_answer = None # type: str
while not answer_understood:
print("The default is option #" + str(default_answer))
user_entered_response = input("Confirm with enter or put in your own choice and confirm: ")
user_chosen_answer, answer_understood = recognize_user_input(user_entered_response, valid_answers,
default_answer)
result['answer'] = int(user_chosen_answer)
elif optiontype == "free_choice":
answer_understood = False
user_chosen_answer = None
while not answer_understood:
print("Default answer is: " + str(default_answer))
user_entered_response = input("Please enter your desired value with '.' as decimal separator: ")
try:
user_entered_response = float(user_entered_response)
user_chosen_answer, answer_understood = parse_user_input_lower_upper_limit_with_interval(
user_entered_response, valid_options_lower_limit, valid_options_upper_limit,
valid_options_steplength)
except ValueError:
try:
if user_entered_response == "":
user_chosen_answer = default_answer
answer_understood = True
except ValueError:
answer_understood = False
result['answer'] = user_chosen_answer
elif optiontype == "free_text":
answer_understood = False
user_chosen_answer = None
while not answer_understood:
print("Default answer is: " + str(default_answer))
user_chosen_answer = input("Type your own now or confirm default with enter: ")
if user_chosen_answer == "":
user_chosen_answer = default_answer
answer_understood = True
result['answer'] = user_chosen_answer
elif optiontype == "2_indeces":
answer1_understood = False
answer2_understood = False
index1 = None
index2 = None
print("Default answer is: " + str(default_answer))
while not answer1_understood:
user_chosen_answer = input("Index 1: ")
try:
index1 = int(user_chosen_answer)
answer1_understood = True
except ValueError:
print("Please make sure to only enter a number!")
while not answer2_understood:
user_chosen_answer = input("Index 2: ")
try:
index2 = int(user_chosen_answer)
answer2_understood = True
except ValueError:
print("Please make sure to only enter a number!")
result["answer"] = [index1, index2]
elif optiontype == "multi_indeces":
answer_understood = False
user_chosen_answer = default_answer
indeces = None
while not answer_understood:
indeces = []
print("Default answer is: " + str(default_answer))
user_chosen_answer = input("Type your own now or confirm default with enter: ") # type: str
user_chosen_answer_list = user_chosen_answer.split(",")
error_happened = False
for item in user_chosen_answer_list:
try:
indeces.append(int(item))
except ValueError:
error_happened = True
print("Please make sure to only enter integer numbers separated by commas.")
if not error_happened:
answer_understood = True
result["answer"] = indeces
else:
print("You are trying to use a question type that is not supported or have a typoo in your code.+")
return result # type: dict
def confirm_warning(warning_text: str,custom:bool=True):
# GUI code to make a window that just has an OK button
if custom:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(warning_text)
print("")
print("Confirm with Enter!")
input("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
def post_status(new_status: str):
# GUI code to show log messages that don't need confirmation!
print(str(new_status))
|
b66f4d4715286e19a184b0458cae819c01423168 | angelajiang/TensorFlow-Tutorials | /show_results.py | 3,304 | 3.75 | 4 | # Import a function from sklearn to calculate the confusion-matrix.
from sklearn.metrics import confusion_matrix
## HELPER FUNCTIONS FOR SHOWING RESULTS
def plot_confusion_matrix(cls_pred):
# This is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all images in the test-set.
# Get the confusion matrix using sklearn.
cm = confusion_matrix(y_true=cls_test, # True class for test-set.
y_pred=cls_pred) # Predicted class.
# Print the confusion matrix as text.
for i in range(num_classes):
# Append the class-name to each line.
class_name = "({}) {}".format(i, class_names[i])
print(cm[i, :], class_name)
# Print the class-numbers for easy reference.
class_numbers = [" ({0})".format(i) for i in range(num_classes)]
print("".join(class_numbers))
'''
This function calculates the predicted classes of images and also returns a
boolean array whether the classification of each image is correct. The
calculation is done in batches because it might use too much RAM otherwise. If
your computer crashes then you can try and lower the batch-size.
'''
batch_size = 256
def predict_cls(transfer_values, labels, cls_true):
# Number of images.
num_images = len(transfer_values)
# Allocate an array for the predicted classes which
# will be calculated in batches and filled into this array.
cls_pred = np.zeros(shape=num_images, dtype=np.int)
# Now calculate the predicted classes for the batches.
# We will just iterate through all the batches.
# There might be a more clever and Pythonic way of doing this.
# The starting index for the next batch is denoted i.
i = 0
while i < num_images:
# The ending index for the next batch is denoted j.
j = min(i + batch_size, num_images)
# Create a feed-dict with the images and labels
# between index i and j.
feed_dict = {x: transfer_values[i:j],
y_true: labels[i:j]}
# Calculate the predicted class using TensorFlow.
cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict)
# Set the start-index for the next batch to the
# end-index of the current batch.
i = j
# Create a boolean array whether each image is correctly classified.
correct = (cls_true == cls_pred)
return correct, cls_pred
'''
Calculate the predicated class for the test-set
'''
def predict_cls_test():
return predict_cls(transfer_values = transfer_values_test,
labels = labels_test,
cls_true = cls_test)
'''
This function calculates the classification accuracy given a boolean array
whether each image was correctly classified. E.g.
classification_accuracy([True, True, False, False, False]) = 2/5 = 0.4. The
function also returns the number of correct classifications.
'''
def classification_accuracy(correct):
# When averaging a boolean array, False means 0 and True means 1.
# So we are calculating: number of True / len(correct) which is
# the same as the classification accuracy.
# Return the classification accuracy
# and the number of correct classifications.
return correct.mean(), correct.sum()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.