blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4cf6e8b0263178be722a6e2efe85420da3db09c8 | JiJibrto/lab_rab_5 | /individual/individual_1.py | 537 | 3.984375 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
# Дано предложение. Вывести все имеющиеся в нем буквосочетания нн.
if __name__ == '__main__':
in_file = str(input("Введите предложение> "))
in_file.lower()
temp = 0
temp = in_file.count('нн')
if temp == 0:
print("Буквосочетания \"нн\" не найденны")
else:
print(f"Количество буквосочетаний \"нн\" = {temp}")
|
f6cc45759b2a35c48c6db99e231f1baa7b3e510d | a-jennings/EDX_Midterm | /EX5.py | 333 | 3.96875 | 4 | #items_price takes quantity (list a) and multiplies with cost (list b)
# to give a total cost of items. Lists are assumed to be equal length.
def items_price(a,b):
total = 0
for x in range(len(a)):
total = a.pop(0)*b.pop(0) + total
return(total)
a = [4, 6, 3, 1, 10]
b = [5, 6, 2, 4, 1]
items_price(a,b)
|
0bd7d806e9ad2057d04f29938e3329a2e6d7dab3 | bcjordan/python | /lab01/Song.py | 695 | 3.875 | 4 | class Song:
"""Class for representing information about a song"""
def __init__(self, title, artist, album):
self.title = title
self.artist = artist
self.album = album
def output(self):
print('Title: "{0}"').format(self.title)
print('Artist: {0}').format(self.artist)
print('Album: {0}\n').format(self.album)
if __name__ == "__main__":
songs = []
songs.append(Song("Between Two Points", "The Glitch Mob", "Drink the Sea"))
songs.append(Song("Ghosts 'n' Stuff (Sub Focus Remix)", "Deadmau5", "Ghosts Album"))
songs.append(Song("All the Cash", "Evil Nine", "All the Cash (Single)"))
for song in songs: song.output() |
ac3b0aa52b800aa5efa7a91221ade6697592b4e2 | oliviagoo/movie-rater-python-assessment | /old components/movie program search frame.py | 1,083 | 3.578125 | 4 | #version 5 - setting up the search frame
from tkinter import *
RATINGS = ["No Rating", "1", "2", "3", "4", "5"]
class MovieRaterGUI:
def __init__(self, parent):
self.search_rate = StringVar()
search_frame = Frame(parent)
search_label = Label(search_frame, text = "Search for movies with a rating of: ")
search_label.grid(row = 0, column = 0)
search_rb_frame = Frame(search_frame)
for rating in RATINGS:
rb = Radiobutton(search_rb_frame, text = rating, value = rating, variable = self.search_rate)
rb.grid(row = 0, column = RATINGS.index(rating))
search_rb_frame.grid(row = 1, column = 0, padx = 10, pady = 10)
self.search_but = Button(search_frame, text = "Go!", command = self.printsearch)
self.search_but.grid(row = 2, column = 0)
search_frame.grid(row = 0, column = 0)
def printsearch(self):
print(self.search_rate.get())
#main routine
if __name__ == "__main__":
root = Tk()
MovieRater = MovieRaterGUI(root)
root.mainloop()
|
1c0caaffdef74eb1911756360307908310c811b2 | laviniabivolan/Spanzuratoarea | /MyHangman.py | 2,394 | 4.125 | 4 | import random
def guess_word():
list_of_words = ["starwards", "someone", "powerrangers", "marabu", "mypython", "wordinthelist", "neversurrender"]
random_word = random.choice(list_of_words)
return random_word
def hangman_game():
alphabet = 'abcdefghijklmnoprstuvwxyqz'
word = guess_word()
lifes = 5
guesses = []
print('The word contains {} letters'.format(len(word)))
game_over = False
while game_over == False and lifes > 0:
print('-' * 25)
print('You have {} tries'.format(lifes))
print('-' * 25)
user_word = input('Introduce one letter or entire word: ').lower()
print('-' * 25)
if len(user_word) == 1:
if user_word not in alphabet:
print('Your input is not correct, must to be alphabetic!')
elif user_word in guesses:
print('You have already introduced that letter')
elif user_word not in word:
print('Was not the right guess!')
guesses.append(user_word)
lifes -= 1
elif user_word in word:
print('You got it!')
guesses.append(user_word)
else:
print('Try again...')
elif len(user_word) == len(word):
if user_word == word:
print('Your guessed was ok!')
game_over = True
else:
print('Your guessed was not ok!')
lifes -= 1
else:
print('Your length of input is not ok')
strcuture_of_word = ''
for letter in word:
if letter in guesses:
strcuture_of_word += letter
else:
strcuture_of_word += '_'
print(strcuture_of_word)
if strcuture_of_word == word:
print('Congrat! You won the game!')
game_over = True
try_again()
elif lifes == 0:
print('You lost the game!!!!!')
game_over = True
try_again()
def try_again():
user_choose = input('Do you want to play again? y/n: ')
print('-' * 25)
if user_choose == 'y':
hangman_game()
else:
print('Have a nice day!')
quit()
if __name__ == '__main__':
hangman_game()
|
7c30f6b2be5904401f1981135e8cfab6b1999c4c | NickRojckov/lab_1.1 | /задание 1.py | 200 | 3.546875 | 4 | a = int(input())
b = int(input())
c = int(input())
X = 0
Y = 0
if a>0:
X+=1
elif a<0:
Y+=1
if b>0:
X+=1
elif b<0:
Y+=1
if c>0:
X+=1
elif c<0:
Y+=1
print(X,Y)
|
fa6057a380c53fda8b1607094f29dce90f2f510e | dgu12/Fakespeare | /genPoem.py | 6,472 | 3.828125 | 4 | from hyphen import Hyphenator
import numpy as np
import random
import sys
from visualize import *
from rhyme import *
''' This file contains functions for generating poems from an HMM description
'''
def hmmGenerate(A_Mat, O_Mat, tokens, startP = None):
''' Generates a poem from a HMM's A matrix and O matrix
Inputs:
A_Mat: np matrix representing state transition probabilities
O_Mat: np matrix representing observation emission probabilities
tokens: Array of words, used to translate tokens into words
*startP: Optional array of start state probabilities
'''
# Allows you prompt the user to generate more poems
user_input = 'y'
while (user_input != 'n'):
# pyHyphen object that allows you to separate words into syllables
h_en = Hyphenator('en_US')
numStates = len(A_Mat)
numObs = np.shape(O_Mat)[1]
state = 0
statePath = []
# If no start probs, assume uniform start distribution
if startP == None:
state = random.randint(0, numStates-1)
else:
# Use startP to determine the start base
sumP = 0
prob = random.random()
index = 0
for p in startP:
sumP += p
if sumP > prob:
state = index
break
index += 1
poem = []
capitalize = False
# A sonnet is 14 lines
for l in range(0,14):
numSyl = 0
line = []
stateTemp = [state]
# Keep number of syllables per line about 10
while numSyl < 10:
prob = random.random()
ind = 0
sumP = 0
if numSyl == 0:
capitalize = True
while ind < numObs:
sumP += O_Mat[state][ind]
if sumP > prob:
# Emit this observation
if capitalize == True:
line.append(tokens[ind].capitalize())
capitalize = False
else:
# Capitalize I
if tokens[ind] == "i":
line.append("I")
else:
line.append(tokens[ind])
# Capitalize after ending punctuation
if tokens[ind].endswith(".") or \
tokens[ind].endswith("?") or \
tokens[ind].endswith("!"):
capitalize = True
# Default to one syllable
if len(h_en.syllables(unicode(tokens[ind]))) == 0:
numSyl += 1
else:
numSyl += len(h_en.syllables(unicode(tokens[ind])))
break
ind += 1
if numSyl < 10:
# Transition to the next state
prob = random.random()
ind = 0
sumP = 0
while ind < numStates:
sumP += A_Mat[state][ind]
if sumP > prob:
stateTemp.append(ind)
state = ind
break
ind += 1
poem.append(line)
statePath.append(stateTemp)
#Print poem
for line in poem:
print ' '.join(line)
print '\n'
# Verbose option to print analytics
if user_input == 'v':
print 'State sequence'
for l in statePath:
print l
print '\n'
# Print part of speech visualization info
visualize( O_Mat, tokens)
# Prompt to generate more poems
user_input = raw_input('Generate a another poem? [y/n/v]')
def genFromFile(f, rhyme):
data = open(f)
isO = False
hasStart = False
S_Mat = None
temp = data.readline()
numStates = int(data.readline())
numObs = int(data.readline())
if temp.strip() == "true":
hasStart = True
S_Mat = np.zeros(numStates)
A_Mat = np.zeros((numStates, numStates))
O_Mat = np.zeros((numStates, numObs))
tokens = []
Arow = 0
Acol = 0
Orow = 0
Ocol = 0
Srow = 0
Trow = 0
isTokens = True
for line in data:
line = line.strip()
if line == "":
continue
if hasStart == True:
if line == "Start" :
continue
S_Mat[Srow] = float(line)
Srow += 1
if Srow == numStates:
hasStart = False
continue
if isTokens == True:
if line == "Tokens":
continue
tokens.append(line)
Trow += 1
if Trow == numObs:
isTokens = False
continue
if line == "A":
continue
if line == "O":
isO = True
continue
if isO == True:
O_Mat[Orow][Ocol] = float(line)
Ocol += 1
if Ocol == numObs:
Ocol = 0
Orow += 1
else:
A_Mat[Arow][Acol] = float(line)
Acol += 1
if Acol == numStates:
Acol = 0
Arow += 1
if Arow == numStates:
isO = True
data.close
if rhyme == 1:
hmmGenerate(A_Mat, O_Mat, tokens, S_Mat)
else:
rhyme1 = rhymingDict("shakespeare.txt")
rhyme2 = rhymingDict("spenser.txt")
rhyme = rhyme1 + rhyme2
rhymeLim = rhymeDictLim(tokens, rhyme)
rhymeGen(A_Mat, O_Mat, tokens, rhymeLim)
def main():
''' Run this program from the command to generate a poem from an HMM
train file'''
if len(sys.argv) != 3:
# Use 1 to generate an unrhyming poem
# Use 0 to generate a rhyming poem
print 'Usage: python', sys.argv[0], \
'[file name] [1 - naive, 0 - rhyme]'
return -1
else:
file = sys.argv[1]
rhyme = int(sys.argv[2])
genFromFile(file, rhyme)
if __name__ == '__main__':
main() |
efcb63ba80b697680a8b907923bcbcdc609ae94e | Wmeng98/Leetcode | /Easy/merge_2_sorted_lists.py | 1,295 | 4.21875 | 4 | # Solution 1 - Recursive Approach
# Recursivelly define the merge of two lists as the following...
# Smaller of the two head nodes plus to result of the merge on the rest of the nodes
# Time 0(n+m) and Space O(n+m) -> first recursive call doesn't return untill ends of l1 && l2 have been reached
# Solution 2 - Iterative Approach
# Can achieve the same idea via iteration
# Insert elements of l2 in necessary places of l1
# Need to setup...
# A false prehead to return the head of merged list
# prev - node we will be adjusting the next ptr of
# Stop comparison until one of l1 or l2 points to null
# Time O(n+m) Space O(1) - only alloc a few pointers
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val < l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
# connect non-null list to end of merged list
prev.next = l1 if l1 is not None else l2
return prehead.next
|
911b133099fdc39a5c0fee6eeb32ee9f3d1dc044 | Wmeng98/Leetcode | /CTCI/Python/functions.py | 1,232 | 3.921875 | 4 | '''
Python Inner/Nested Functions
# Has access to variables and names defined in the enclosing function
# Encapsulation, hide from external access
In Python, Functions are **first-class citizens**
Means on par with any other object such as numbers, strings, lists, tuples, modules, etc.
You can dynamically create or destroy them, store them in data structures, pass them as arguments to other functions, use them as return values, and so forth.
- can be stored in variables and data structures
- can be passed as a parameter to a subroutine
- can be returned as the result of a subroutine
- can be constructed at runtime
- has intrinsic identity (independent of any given name)
'''
# Closure Factory Functions
# NOTE: Higher-order functions are functions that operate on other functions by taking them as arguments, returning them, or both
# Closures are dynamically created functions that are returned by other functions.
# Their main feature is that they have full access to the variables and names defined in the local namespace (SNAPSHOT) where the closure was created
# powers.py
def generate_power(exponent):
def power(base):
return base ** exponent
return power |
1f858c8755bb4c927e9269b9b01871f4d2b15e24 | Wmeng98/Leetcode | /CTCI/Python/notes.py | 5,949 | 3.8125 | 4 | # Python
'''
Note Python 3's int doesn't have a max size (bounded by memory)
float('inf') is for infinity, guaranteed to be higher than any other int value
range vs. xrange (deprc in python3)
If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecated in Python 3
range() is faster if iterating over the same sequence multiple times.
xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however)
Python - Pass by Value or Reference
Neither of these 2 concepts applicable
Values are sent to functions by means of object reference
Pass-by-object-reference
Almost everything in Python is an object
Values passed to functions by object-reference
If immutable, modified value NOT available outside scope of function
Mutable objects
list, dict, set, byte array
Immutable objects
int, float, complex, string, tuple, frozen set, bytes
Deque
Double ended queue (impl probably a DOUBLY LINKED LIST - Bidirectional)
`from collections import deque `
append(), appendLeft, pop(), popLeft()
index(ele, beg, end), insert(i,a), remove(), count()
Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container,
as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
'''
'''
Python Mutable Data Types
Id - unique identifier for object -> points to location in memory
In python all data stored as object with 3 things:
id, type, value
Mutable Objects (changeable)
list, dict, set
Immutable objects:
Integer, float, string, tuple, bool, frozenset
STRINGS ARE NOT MUTABLE in PYTHON!!!
Passing arguments
[MUTABLE] If a mutable object is called by reference in a function, the original variable may be changed. If you want to avoid changing the original variable, you need to copy it to another variable.
[IMMUTABLE] When immutable objects are called by reference in a function, its value cannot be changed.
None
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None
Comparing 2 objects in Python
compare for EQUALITY or IDENTITY
== for equality
is for identity
__eq__ to compare 2 class instances
Even if two class instances have the same attribute values,
comparing them using == will return False
You have to tell python how exactly you want equality be defined.
do so by defining a special method __eq__ like this
NOTE: because two different objects can sometimes compare equal
(if not then don't bother overloading it). In this case the return id(self)
hash function is BROKEN (EQUAL OBJECTS MUST HASH THE SAME)
List Comprehension
- List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list
SYNTAX
- `newlist = [expression for item in iterable if condition == True]`
- NOTE: The return value is a new list, leaving the old list unchanged
- NOTE:
- The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome
- `newlist = [x if x != "banana" else "orange" for x in fruits]`
DefaultDict
- Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dict class
that returns a dictionary-like object. The functionality of both dictionaries and defualtdict are almost same except for the
fact that defualtdict never raises a KeyError. It provides a default value for the key that does not exists.
- from collections import defaultdict
Complexity of "in"
- Here is the summary for in:
list - Average: O(n)
set/dict - Average: O(1), Worst: O(n)
The O(n) worst case for sets and dicts is very uncommon, but it can happen if __hash__ is implemented poorly.
This only happens if everything in your set has the same hash value.
operator.itemgetter
- dict.items() -> array of tuples
- Return a callable object that fetches item from its operand using the operand’s __getitem__() method.
If multiple items are specified, returns a tuple of lookup values. For example
'''
'''
Sorting
lists have built-in list.sort() method, modifies list in place
sorted() function builds a new sorted list from an iterable
[KEY]
key param to specify a function (or other callable) to be called on each list prior to
making comparisons
sorted("This is a test string from Andrew".split(), key=str.lower)
value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes
LAMBDAS are a good candidate here!!!
NOTE: Common pattern is to sort complex objects using some of the objects indices as keys
sorted(student_tuples, key=lambda student: student[2])
sorted(student_objects, key=lambda student: student.age)
[OPERATOR MODULE FUNCTIONS]
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster
***** from operator import itemgetter, attrgetter *****
sorted(student_tuples, key=itemgetter(2))
sorted(student_objects, key=attrgetter('age'))
multiple levels of sorting. For example, to sort by grade then by age
sorted(student_tuples, key=itemgetter(1,2))
sorted(student_objects, key=attrgetter('grade', 'age'))
'''
|
7210057fb5068f880b93a09ebfda8e00a8f9b0b6 | Wmeng98/Leetcode | /Dynamic Programming/pramp_number_of_paths.py | 2,306 | 4 | 4 | # Like leetcode unique paths but restriction that car can't cross diagonal border
def num_of_paths_to_dest(n):
# recursive approach
# return num_paths(0,0,n)
# [MEMOIZATION] is top-down
# Bottom up would be Tabulation
# init to -1 to indicate uncomputed
memo = [[-1]*n for _ in range(n)]
def num_paths(x,y):
# consider special cases
# invalid x or y
if x < 0 or y < 0:
return 0
# crossed the border to upper half
if x < y:
memo[x][y] = 0 # invalid path
elif x == 0 and y == 0:
memo[x][y] = 1
elif memo[x][y] != -1:
return memo[x][y]
else:
memo[x][y] = num_paths(x-1,y) + num_paths(x,y-1)
return memo[x][y]
return num_paths(n-1,n-1)
# destination always (n-1,n-1)
'''
Bottom up not as intuitive as top down approach...
at every point, car can either go 1 up or 1 right
'''
# Hmm - generally top down recursion is more intuitive
# paths(i,j) = paths(i-1,j) + path(i,j-1)
def num_paths(x, y, n):
if x == n-1 and y == n-1:
print('found base case')
return 1
# catch case where x,y is on the border
# cannot cross but can still touch the border
if x != 0 and x > y or (x >= n or y >= n):
print('border passed',x,y)
return 0
# sum the paths
print(x,y)
# WRONG - We should be building sol'n from sol'n of subproblems
# Start from x=n-1,y=n-1
return num_paths(x,y+1,n) + num_paths(x+1,y,n)
print('huuh')
print(num_of_paths_to_dest(4))
# Can this be memoized?
# dp[x][y] are num paths to get from x,y to n-1,n-1
# Pseudo for Tabulation on lower half of the grid
function numOfPathsToDest(n):
if (n == 1):
return 1
lastRow = []
for i from 1 to n-1:
lastRow[i] = 1 # base case - the first row is all ones
currentRow = []
# IMPORTANT NOTE: We're only calculating every square south-east to the diagonal
for j from 1 to n-1:
for i from j to n-1:
if (i == j):
# this makes sense if you draw out the grid, then currentRow[i] on the border and
# same number of paths as lastRow[i]
currentRow[i] = lastRow[i]
else:
currentRow[i] = currentRow[i-1] + lastRow[i]
lastRow = currentRow
return currentRow[n-1]
|
54e1ec09fd057b7e7f37e1d2f8e209459ad26e19 | Wmeng98/Leetcode | /CTCI/Python/types.py | 516 | 3.6875 | 4 | '''
List
Tuple
- collection which is ordered and unchangeable, and allows duplicate values
- written with round brackets
- Can be indexed
- NOTE: use when want list of constants, Tuples can also be used as key in dict
Dictionary
- key value pairs
Sets
- set items are unordered, unchangeable, and do not allow duplicate values.
- sets are written with curly brackets
- thisset = {"apple", "banana", "cherry"}
- NOTE: You can use python set() function to convert list to set
''' |
6479f78c861a015b6dd42adbae231014b6a4f53d | layan21-meet/meetyl1 | /inheritance.py | 957 | 3.828125 | 4 | from turtle import Turtle
import turtle
class Ball(Turtle):
def __init__(self,r,color,dx,dy):
Turtle.__init__(self)
self.penup()
self.dx = dx
self.dy = dy
self.shape("circle")
self.color(color)
self.r = r
self.shapesize(r/10)
def move(self,screen_width,screen_height):
current_x = self.xcor()
newX = current_x + self.dx
current_y = self.ycor()
newY =current_y + self.dy
right_side_ball = newX + self.r
left_side_ball = newX + self.r
upper_side_ball = newY + self.r
lower_side_ball = newY + self.r
if right_side_ball >screen_width:
newX = newX
if left_side_ball< -screen_width:
newX = newX
if lower_side_ball< -screen_height:
newY = newY
if upper_side_ball>screen_height:
newY = newY
self.goto(newX, newY)
screen_width = turtle.getcanvas().winfo_width()/2
screen_height = turtle.getcanvas().winfo_height()/2
ball_1 = Ball(10,"red",10,10)
while 1==1:
ball_1.move(screen_width, screen_height)
|
cfcd01b620080975032453d307479bc8016a7f8e | Jelowis/DEBER15 | /Cola.py | 1,302 | 4.03125 | 4 | # Leonardo Altamirano Retto
# 3 Semestre Software
class Cola_1:
def __init__(self,tamanio):
self.lista=[]
self.size=tamanio
self.top=0
def push(self,dato):
if self.top <self.size:
self.lista = self.lista + [dato]
self.top += 1
return True
else:
return False
def pop(self):
if self.empty():
return None
else:
top = self.lista[0]
self.lista = self.lista[1:]
self.top -= 1
return top
def show(self):
for top in range(self.top):
print("[{}]".format(self.lista[top]))
def longitud(self):
return self.top
def empty(self):
if self.top == 0:
return True
else:
return False
# cola=Cola_1(3)
# print(cola.push(20))
# print(cola.push(25))
# print(cola.push(30))
# print(cola.push(35))
# cola.show()
# dato=cola.pop()
# if dato: print("El dato eliminado es: {}".format(dato))
# else: print("La lista esta vacia")
# input("Presione una tecla para continuar...")
# dato=cola.pop()
# if dato: print("El dato eliminado es: {}".format(dato))
# else: print("La lista esta vacia")
# input("Presione una tecla para continuar...")
# cola.show() |
1ab21a736cafc0550e8dc579170f939ae03e0bae | idixon2/csc221 | /hw/hw4/hw4_solution.py | 309 | 4.03125 | 4 |
def is_odd(number):
return number%2==1
def is_even(number):
return not is_odd(number)
def is_mult_of_four(number):
return number4 == 0
def is mult_of_divisor(number,divisor):
return number%divisor
def both_ ends(s):
if len(s) < 2:
return ''
else:
return s[:2] +[-2 |
ff234acf470b12fe21ee41df3d2a2cf69bd0af91 | tejalbangali/HackerRank-Numpy-Challenge | /Arrays.py | 502 | 4.40625 | 4 | # Task:
# --> You are given a space-separated list of numbers. Your task is to print a reversed NumPy array with the element type float.
# -> Input Format: A single line of input containing space-separated numbers.
# -> Sample Input: 1 2 3 4 -8 -10
# -> Sample Output: [-10. -8. 4. 3. 2. 1.]
import numpy
def arrays(arr):
arr=numpy.array(arr)
arr=arr.astype(float)
result=arr[::-1]
return result
arr = input().strip().split(' ')
result = arrays(arr)
print(result)
|
0833af795b79bc5ba21775f472cf16c5a1aa7cf6 | BhaskarSrinivasK/PythonZone | /PasswordGenerator(Using only random library).py | 553 | 3.921875 | 4 | import random
print("Want a Secure a password?")
length = int(input("Enter the length of password required!! : "))
lower = []
for i in range(65,91):
lower.append(chr(i))
upper = []
for i in range(97,123):
upper.append(chr(i))
symbols = []
for i in range(33,48):
symbols.append(chr(i))
num = [0,1,2,3,4,5,6,7,8,9]
all = lower + upper + num + symbols
temp = random.sample(all, length)
password = ""
for i in range(length):
password = password + str(temp[i])
print(password)
print("Go! Go! Go! Use this secure one!!!")
|
1da880569a546ff5a0ab841952173e1810a3527d | SybelBlue/SybelBlue | /main/maze_maker.py | 2,307 | 3.71875 | 4 | import random
directions = ['up', 'down', 'left', 'right']
class Cell:
def __init__(self, i, j):
self.pos = i, j
self.visited = False
self.walls = {x: True for x in directions}
def move_to(self, other):
if self.pos[0] < other.pos[0]:
self.walls['right'] = False
other.walls['left'] = False
elif self.pos[0] > other.pos[0]:
other.walls['right'] = False
self.walls['left'] = False
elif self.pos[1] < other.pos[1]:
self.walls['down'] = False
other.walls['up'] = False
elif self.pos[1] > other.pos[1]:
other.walls['down'] = False
self.walls['up'] = False
cols, rows = 10, 10
grid = [[Cell(i, j) for j in range(cols)] for i in range(rows)]
def neighbor(cell):
out = []
def safe_add(a, b):
if a < 0 or b < 0:
return
if a >= cols or b >= rows:
return
item = grid[a][b]
if not item.visited:
out.append(item)
i, j = cell.pos
safe_add(i - 1, j)
safe_add(i, j - 1)
safe_add(i + 1, j)
safe_add(i, j + 1)
if not out:
return None
return random.choice(out)
current = grid[0][0]
stack = [current]
def print_grid():
def get_str_at(i, j):
def safe_check(a, b, s):
if a < 0 or b < 0:
return False
if a >= cols or b >= rows:
return False
return grid[a][b].walls[s]
center = grid[i][j]
# up = center.walls['up'] or safe_check(i - 1, j, 'down')
# right = center.walls['right'] or safe_check(i - 1, j, 'left')
left = center.walls['left'] or safe_check(i - 1, j, 'right')
down = center.walls['down'] or safe_check(i, j + 1, 'up')
s = '|' if left else ' '
s += '_' if down else ' '
# s += '|' if right else '_'
return s
for i in range(rows):
for j in range(cols):
print(get_str_at(i, j), end='')
print()
while stack:
current.visited = True
next = neighbor(current)
if next is not None:
current.move_to(next)
stack.append(current)
current = next
print_grid()
else:
current = stack.pop()
print_grid()
|
8fc4be8aa0b68e0aabb63686cf41d514c92e8a36 | Tanukiii/Keras-Functional-and-Sequential-API | /Keras Functional and Sequential API.py | 11,189 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Keras Functional and Sequential APIの使い方
# ## Preparcing Tensorflow2.x and Dataset MNIST
# In[1]:
import tensorflow as tf
import keras
# Mnist
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalization 0-255の値が入っているので、0-1に収まるよう正規化します
x_train, x_test = x_train / 255.0, x_test / 255.0
# Check the data
# Now, each row has one data
print(x_train.shape, x_test.shape)
# # Sequential の場合の書き方
# ### ・keras.models.Sequential()にlistで与える
#
# ### ・model.add()で1層ずつ足してくかしてモデルをつくる
#
# ### 最期に学習条件を決めてcompileすれば完成です。
#
# In[2]:
# Sequentialモデルを定義します
model = keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape =(28, 28)))
model.add(tf.keras.layers.Dense(128, activation ='relu'))
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(10, activation ='softmax'))
# モデルをcompileします
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
display(model.summary())
# 学習します
hist = model.fit(x_train, y_train, validation_split=0.1, epochs=5)
# テストデータの予測精度を計算します
print(model.evaluate(x_test, y_test))
# # Functional の場合の書き方
# ## ①入力が1つの場合
# ### 上記のSequentialの場合とまったく同じモデルをfunctional APIで書くと次のようになります。
# Sequentialだと入力数と出力数がどちらも1つと決まってるのでSequentialでネットワーク構造を定義したら完成でしたが、functional APIだと入力と出力をどちらも複数設定できますので、ネットワーク構造をkeras.layersで定義する部分の2つを書いておいて、入力と出力がいくつあるのかkeras.Model()で定義して完成となります。
# In[3]:
# モデル構造を定義します
inputs = tf.keras.layers.Input(shape=(28, 28))
x = tf.keras.layers.Flatten()(inputs)
x = tf.keras.layers.Dense(128, activation='relu')(x)
x = tf.keras.layers.Dropout(0.2)(x)
predictions = tf.keras.layers.Dense(10, activation='softmax')(x)
# 入出力を定義します
model = keras.Model(inputs=inputs, outputs=predictions)
# モデルをcompileします
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
display(model.summary())
# 学習します
hist = model.fit(x_train, y_train, validation_split=0.1, epochs=5)
# テストデータの予測精度を計算します
print(model.evaluate(x_test, y_test))
# (Note)
#
# 学習データとテストデータのようにkerasの外からkerasモデルに渡すデータは必ず最初にkeras.layers.Input()で受け取り、そこから加える層の右にその層への入力を()付きで与えるように書いて、1層ずつ増やしていくという書き方になります。
#
# 下の例だとpredictionsに入力から出力までのInput => Flatten => Dense(128, relu) => Dropout => Dense(10, softmax)までのネットワークが全部入ってますので、Sequentialで書いたmodelと同じ内容になります
# ## ② 入力が2つある場合(出力は1つ)
# 入力が複数ある場合はinputが複数あるネットワークを書いて、keras.Model()にlistでinputを与えるようにします。下の例はmnistデータを2つに分けてkeras model内で結合してから同じネットワークに通すようにしたものです。
# In[4]:
# 複数入力のテストの為にxを分割してみます
# 全ての行、392
x_train2_1 = x_train.reshape(60000, 784)[:,:392] # (60000, 392)
x_train2_2 = x_train.reshape(60000, 784)[:,392:] # (60000, 392)
x_test2_1 = x_test.reshape(10000, 784)[:,:392] # (10000, 392)
x_test2_2 = x_test.reshape(10000, 784)[:,392:] # (10000, 392)
# Functional APIでモデルを定義します
input1 = tf.keras.layers.Input(shape=(392,))
input2 = tf.keras.layers.Input(shape=(392,))
inputs = tf.keras.layers.concatenate([input1, input2])
x = tf.keras.layers.Dense(128, activation='relu')(inputs)
x = tf.keras.layers.Dropout(0.2)(x)
predictions = keras.layers.Dense(10, activation='softmax')(x)
# 入出力を定義します
model = tf.keras.Model(inputs=[input1, input2], outputs=predictions)
# モデルをcompileします
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
display(model.summary())
# 学習します
hist = model.fit([x_train2_1, x_train2_2], y_train, validation_split=0.1, epochs=5)
# テストデータの予測精度を計算します
print(model.evaluate([x_test2_1, x_test2_2], y_test))
# ## ③ 入力と出力が2つある場合(損失関数は1つ)
# 分岐を加えて出力が2つあるmodelに変えてみました。x1とx2の2つの経路に分岐していて、prediction1とprediction2がそれぞれの出力までのネットワーク情報をもっています。出力段が2つになったのでkeras.Model()に与える出力段も2つになります。
# In[5]:
# 複数入力のテストの為にxを分割してみます
x_train2_1 = x_train.reshape(60000, 784)[:,:392]
x_train2_2 = x_train.reshape(60000, 784)[:,392:]
x_test2_1 = x_test.reshape(10000, 784)[:,:392]
x_test2_2 = x_test.reshape(10000, 784)[:,392:]
# Functional APIでモデルを定義します
input1 = keras.layers.Input(shape=(392,))
input2 = keras.layers.Input(shape=(392,))
# Prediction 1
inputs1 = keras.layers.concatenate([input1, input2])
x1 = keras.layers.Dense(128, activation='relu')(inputs1)
x1 = keras.layers.Dropout(0.2)(x1)
prediction1 = keras.layers.Dense(10, activation='softmax')(x1)
# Prediction 2
inputs2 = keras.layers.concatenate([input1, input2])
x2 = keras.layers.Dense(128, activation='relu')(inputs2)
x2 = keras.layers.Dropout(0.2)(x2)
prediction2 = keras.layers.Dense(10, activation='softmax')(x2)
# 入出力を定義します
model = keras.Model(inputs=[input1, input2], outputs=[prediction1, prediction2])
# モデルをcompileします
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
display(model.summary())
# 学習します
hist = model.fit([x_train2_1, x_train2_2], [y_train, y_train],
validation_split=0.1, epochs=5)
# テストデータの予測精度を計算します
print(model.evaluate([x_test2_1, x_test2_2], [y_test, y_test]))
# # ④ 入力、出力、損失関数が2つある場合
# せっかく出力を分けたので損失関数も別々に入れてみます。
#
# modelを作るときにname=''で名付けておいて、compile()するときにlossを辞書型で渡せば出力ごとに異なる損失関数を使うことができます。下の例だと同じ損失関数を使ってますが、ぜんぜん違う損失関数を指定しても構いません。
#
# 学習はトータルの損失関数を最小化するように進めますがデフォルトでは単純に合計するようです。加算比率をloss_weightsに辞書型で渡すことで指定することもできるので、以下では0.5ずつで加算するようにしています。
# In[6]:
# 複数入力のテストの為にxを分割してみます
x_train2_1 = x_train.reshape(60000, 784)[:,:392]
x_train2_2 = x_train.reshape(60000, 784)[:,392:]
x_test2_1 = x_test.reshape(10000, 784)[:,:392]
x_test2_2 = x_test.reshape(10000, 784)[:,392:]
# Functional APIでモデルを定義します
input1 = keras.layers.Input(shape=(392,))
input2 = keras.layers.Input(shape=(392,))
# Prediction 1
inputs1 = keras.layers.concatenate([input1, input2])
x1 = keras.layers.Dense(128, activation='relu')(inputs1)
x1 = keras.layers.Dropout(0.2)(x1)
prediction1 = keras.layers.Dense(10, activation='softmax', name='prediction1')(x1)
# Prediction 2
inputs2 = keras.layers.concatenate([input1, input2])
x2 = keras.layers.Dense(128, activation='relu')(inputs2)
x2 = keras.layers.Dropout(0.2)(x2)
prediction2 = keras.layers.Dense(10, activation='softmax', name='prediction2')(x2)
# 入出力を定義します
model = keras.Model(inputs=[input1, input2], outputs=[prediction1, prediction2])
# モデルをcompileします
model.compile(optimizer='adam',
loss={'prediction1': 'sparse_categorical_crossentropy',
'prediction2': 'sparse_categorical_crossentropy'},
loss_weights={'prediction1': 0.5,
'prediction2': 0.5},
metrics=['accuracy'])
display(model.summary())
# 学習します
hist = model.fit([x_train2_1, x_train2_2], [y_train, y_train],
validation_split=0.1, epochs=5)
# テストデータの予測精度を計算します
print(model.evaluate([x_test2_1, x_test2_2], [y_test, y_test]))
# ## ⑤ 学習済みmodelを組み込む
# 学習済みmodelを部品として組み込むことも出来ます。
#
# 使い方はkeras.layersの代わりに学習済みmodelを置くだけですし、組み込んだら1つのkeras modelとして使えますのでアンサンブルモデルも簡潔に書けて便利です。
# 下の例では上半分で学習しで作ったmodelを下半分で部品として組み込んだmodel2を作っています。
#
# In[7]:
# Functional APIでモデルを定義します
inputs = keras.layers.Input(shape=(28, 28))
x = keras.layers.Flatten()(inputs)
x = keras.layers.Dense(128, activation='relu')(x)
x = keras.layers.Dropout(0.2)(x)
predictions = keras.layers.Dense(10, activation='softmax')(x)
# 入出力を定義します
model = keras.Model(inputs=inputs, outputs=predictions)
# モデルをcompileします
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
display(model.summary())
# 学習します
hist = model.fit(x_train, y_train, validation_split=0.1, epochs=5)
# テストデータの予測精度を計算します
print(model.evaluate(x_test, y_test))
# ######################################################
# In[8]:
# モデルを再利用するモデルを定義します
inputs = keras.layers.Input(shape=(28, 28))
predictions = model(inputs)
# モデルをcompileします
model2 = keras.Model(inputs=inputs, outputs=predictions)
model2.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
display(model2.summary())
# テストデータの予測精度を計算します
print(model2.evaluate(x_test, y_test))
# ## Appendix: Slice
# In[9]:
import numpy as np
data = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90,])
data2=np.array(data).reshape(3,3) #3×3の配列を作成
data2
# In[10]:
data2[:2,] #0~1行目、すべての列
# In[11]:
data2[:,:1] # 全ての行、1列目以降
# In[12]:
data2[:,1:] #すべての行、1列目以降
# In[13]:
data2[1:,1:] #1行目以降、1列目以降
|
bea6d1297b379920ae263850f2eb40a3397c1159 | sundnes/solving_odes_in_python | /docs/src/appendix1/interest_v2.py | 551 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import datetime
x0 = 100 # initial amount
p = 5 # annual interest rate
r = p / 360.0 # daily interest rate
date1 = datetime.date(2017, 9, 29)
date2 = datetime.date(2018, 8, 4)
diff = date2 - date1
N = diff.days
index_set = range(N + 1)
x = np.zeros(len(index_set))
x[0] = x0
for n in index_set[1:]:
x[n] = x[n - 1] + (r / 100.0) * x[n - 1]
plt.plot(index_set, x)
plt.xlabel('days')
plt.ylabel('amount')
plt.show()
|
52706c76dbdab396370d5491bc574b3ef0bca6f3 | sundnes/solving_odes_in_python | /docs/src/chapter1/forward_euler_class.py | 1,997 | 4 | 4 | """
Forward Euler class implementation for systems of ODEs.
"""
import numpy as np
class ForwardEuler:
def __init__(self, f):
"""Initialize the right-hand side function f """
self.f = lambda t, u: np.asarray(f(t, u), float)
def set_initial_condition(self, u0):
"""Store the initial condition as
an instance attribute.
"""
self.u0 = np.asarray(u0)
self.neq = self.u0.size
def solve(self, t_span, N):
"""Compute solution for
t_span[0] <= t <= t_span[1],
using N steps.
Returns the solution and the
time points as arrays.
"""
t0, T = t_span
self.dt = (T - t0) / N
self.t = np.zeros(N + 1)
self.u = np.zeros((N + 1, self.neq))
msg = "Please set initial condition before calling solve"
assert hasattr(self, "u0"), msg
self.t[0] = t0
self.u[0] = self.u0
for n in range(N):
self.n = n
self.t[n + 1] = self.t[n] + self.dt
self.u[n + 1] = self.advance()
return self.t, self.u
def advance(self):
"""Advance the solution one time step."""
u, dt, f, n, t = self.u, self.dt, self.f, self.n, self.t
return u[n] + dt * f(t[n], u[n])
class Logistic:
def __init__(self, alpha, R):
self.alpha, self.R = alpha, R
def __call__(self, t, u):
return self.alpha * u * (1 - u / self.R)
if __name__ == '__main__':
"""
Demonstrate how the class is used,
by solving the logistic growth problem.
To test the class for a system of ODEs,
run pendulum.py
"""
import matplotlib.pyplot as plt
problem = Logistic(alpha=0.2, R=1.0)
solver = ForwardEuler(problem)
u0 = 0.1
solver.set_initial_condition(u0)
T = 40
t, u = solver.solve(t_span=(0, T), N=400)
plt.plot(t, u)
plt.title('Logistic growth, Forward Euler')
plt.xlabel('t')
plt.ylabel('u')
plt.show()
|
83243d09a2140da62c7a572d2d887e879801e104 | victordity/PythonExercises | /PythonInterview/binarySearch.py | 1,029 | 4.21875 | 4 | import bisect
def bisect_tutorial():
fruits = ["apple", "banana", "banana", "banana", "orange", "pineapple"]
print(bisect.bisect(fruits, "banana"))
print(bisect.bisect_left(fruits, "banana"))
occurrences = bisect.bisect(fruits, "banana") - bisect.bisect_left(fruits, "banana")
print(occurrences) # Number of occurrences of the word banana
bisect.insort_left(fruits, "kiwi")
print(fruits)
def binary_iterative(elements, search_item):
"""Return the index of the search_item element."""
left, right = 0, len(elements) - 1
while left <= right:
middle_idx = (left + right) // 2
middle_element = elements[middle_idx]
if middle_element == search_item:
return middle_idx
if middle_element < search_item:
left = middle_idx + 1
elif middle_element > search_item:
right = middle_idx - 1
return None
if __name__ == '__main__':
elements = [3, 4, 5, 5, 9]
a = binary_iterative(elements, 5)
print(a)
|
22a28e41992b8d36c2b5b676a0ba17cc70eb7696 | justdharmik/Python-Things | /5. Search.py | 560 | 3.921875 | 4 | def search(text, word, count):
lst = list(text.split(" "))
if word in lst:
result = f"Word found! '{word}'' in '{text}'"
for i in lst:
if i == word:
count += 1
else:
result = "Word not found!"
print(f"Instances: {count}")
return result
#text = input("Enter the text: ")
#word = input("Enter the word: ")
text = "Dharmik Says Hello there" #comment this for using input text
word = "Hello" #comment this for using input word
count = 0
lst = []
print(search(text, word, count))
|
38200fdf05a7f80e7bce3773a0f954ec8e3e67f0 | vfperez1/AdivinaNumero | /entrada/menu.py | 744 | 4.125 | 4 | """
Módulo que agrupa todas las funcionalidades
que permiten pedir entrada de números
"""
import sys
def pedirNumeroEntero():
correcto = False
num = 0
while (not correcto):
try:
num = int(input("Eliga una opción del 1 al 4: "))
correcto = True
except ValueError:
print('Error, introduce un número entero',
file=sys.stderr)
return num
def pedirNumeroJuego():
correcto = False
num = 0
while (not correcto):
try:
num = int(input("Introduzca un número: "))
correcto = True
except ValueError:
print('Error, introduce un número entero',
file=sys.stderr)
return num
|
cee42d7413ad30fcfe67437b706ee14b889f0aae | loide/MITx-6.00.1x | /lessThan4.py | 365 | 3.84375 | 4 | '''
This function returns the sublist of strings in input list that contains
fewer than 4 caracters.
'''
def lessThan4(a_list):
lessThan4List = []
for x in a_list:
if len(x) < 4:
lessThan4List.append(x)
return lessThan4List
if __name__ == '__main__':
a_list = ["apple", "cat", "dog", "banana"]
print lessThan4(a_list)
|
4d51b16c7673470425579525742dd537470e48b9 | loide/MITx-6.00.1x | /myLog.py | 841 | 4.46875 | 4 | '''
This program computes the logarithm of a number relative to a base.
Inputs:
number: the number to compute the logarithm
base: the base of logarithm
Output:
Logarithm value [ log_base (number) ]
'''
def myLog(number, base):
if ( (type(number) != int) or (number < 0)):
return "Error: Number value must be a positive integer."
if ( (type(base) != int) or (base < 2)):
return "Error: Base value must be an integer greater than or equal 2."
return recursiveRad(number, base)
def recursiveRad(number, base):
if base > number:
return 0
if number <= 1:
return 0
else:
return 1 + recursiveRad(number/base, base)
if __name__ == "__main__":
number = int(raw_input('Insert a number: '))
base = int(raw_input('Insert the base value: '))
print myLog(number, base)
|
80c19732e0851baa74bd4e103ecd3c4a7090c15f | raphaelassor/snake-python- | /snake.py | 1,185 | 3.71875 | 4 | from turtle import Turtle
STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
DIRECTIONS = {
"right": 0,
"up": 90,
"down": 270,
"left": 180
}
class Snake:
def __init__(self):
self.segments = []
self.__create_snake()
self.head = self.segments[0]
def __create_snake(self):
for position in STARTING_POSITION:
self.create_segment(position)
def move(self):
for i in range(len(self.segments) - 1, 0, -1):
next_x = self.segments[i - 1].xcor()
next_y = self.segments[i - 1].ycor()
self.segments[i].goto(next_x, next_y)
self.head.forward(MOVE_DISTANCE)
def change_direction(self, direction):
angle = DIRECTIONS[direction]
if abs(self.head.heading() - angle) != 180:
self.head.setheading(angle)
def add_segment(self):
last = self.segments[-1]
self.create_segment((last.xcor(),last.ycor()))
def create_segment(self,position):
segment = Turtle(shape="square")
segment.color("white")
segment.penup()
segment.goto(position)
self.segments.append(segment)
|
7e9c4dd4ecbfdb8419acd37044c0aeb41bc0a408 | zupph/CP3-Supachai-Khaokaew | /Lecture53_Supachai_K.py | 159 | 3.84375 | 4 | def vatCalculate(totalPrice):
result = totalPrice * 1.07
return result
totalPrice = int(input("enter total price : "))
print(vatCalculate(totalPrice))
|
4b2d0491033d18d00e87c1602fdeffea62d01abe | valeriacavalcanti/IP-2019.1 | /Lista 01/lista_01_questao_02.py | 115 | 3.640625 | 4 | raio = float(input("Informe o valor do raio: "))
comprimento = 2 * 3.14 * raio
print ("Comprimento =", comprimento) |
f24127377952c8a659f4d40e86da704c9bc4b020 | SpencerOfwiti/software-testing | /prime/primes.py | 625 | 4.0625 | 4 | import math
def is_prime(a):
"""
Return True if number is prime
:param a:
:return:
"""
if isinstance(a, int):
if a <= 1:
return False
for i in range(2, math.floor(math.sqrt(a) + 1)):
if a % i == 0:
return False
return True
return 'IsPrime only takes integer parameters.'
def print_next_prime(a):
"""
Print the closest prime number larger than number
:param a:
:return:
"""
index = a
while True:
index += 1
if is_prime(index):
return index
def sum_of_primes(arg):
"""
Print sum of prime numbers in parameter
:param arg:
:return:
"""
return sum([x for x in arg if is_prime(x)])
|
6902980b86ed30978f16b6f9ee21495e8b9cc5e9 | AdarshNamdev/Python-Practice-Files | /ExampleOOP.py | 935 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 10:40:20 2021
@author: adars
"""
class student(object):
def __init__(self, name, marks = 0):
self.name = name
self.marks = marks
def display_student_details(self):
print("Hi {}".format(self.name))
print("Your marks are: {}".format(self.marks))
def compute_grade(self):
if self.marks >= 600:
return "You got first grade!"
elif self.marks >= 500:
return "You got second grade!"
elif self.marks >= 350:
return "You got third grade!"
else:
return "You failed !!!"
nos = int(input("How many students you have: "))
while nos:
student_obj = student(input("Enter Student Name: "), int(input("Marks Secured: ")))
student_obj.display_student_details()
print(student_obj.compute_grade())
nos -= 1 |
00fd86dd9f3dbf758c6c0a86407e6b1e3d8ffadc | AdarshNamdev/Python-Practice-Files | /gcdRecursion.py | 322 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 10 23:14:57 2019
@author: adars
"""
def gcdRecur(a, b):
if b == 0:
return a
else:
return gcdRecur(b, a%b)
print(gcdRecur(2, 12))
print(gcdRecur(6, 12))
print(gcdRecur(9, 12))
print(gcdRecur(17, 12))
print(gcdRecur(13,17)) |
395b88dc71c7c358a6867bbad74dfb63b83aea5d | AdarshNamdev/Python-Practice-Files | /getter_setter_@property.py | 510 | 4.0625 | 4 |
class celsius(object):
def __init__(self, temperature = 0):
self.temperature = temperature
def to_fahrenheit(self):
return (self.temperature * 1.8) + 32
"""
basic method of setting and getting the attribute in python
"""
human = celsius()
print(human.temperature)
# setting the temperature
human.temperature = 37
# getting the temperature attribute
print(human.temperature)
# Get the to_fahrenheit method
print("to fahrenheit: ", human.to_fahrenheit())
print(human.__dict__) |
a5c8a5b1a6cdb1852e1e404f1a970230f5d27384 | AdarshNamdev/Python-Practice-Files | /Regex2-GroupCapturing-BackReferencing.py | 1,386 | 3.578125 | 4 | """
Regular Expression Group Capturing and Back Referencing!
"""
import re
with open(r"C:\Users\adars\Desktop\random.txt", "r") as handle1:
content1 = handle1.read()
print("Actual Content:\n", content1,"\n####################################################\n")
print("obtaining the phone numbers in the format: 123-xxx-1234")
print("---------------------------------------------------------")
redact_ph = re.sub(r"(\d{3})-\d{3}-(\d{4})", r"\1-xxx-\2", content1)
print(redact_ph)
print("obtaining date format from mm dd yyyy to mm dd, yyyy")
print("-------------------------------------------------------")
mm_dd_yyyy = re.sub(r"(\d{1,2})\s?([a-zA-Z]{3})\s?(\d{4})", r"\2 \1, \3", content1)
print(mm_dd_yyyy)
"""
Output:
``````
Actual Content:
19 Jan 1965
Judy Foster
912-576-7052
02 Aug 1984
John Nash
717-852-7391
30 Jun 1989
Baba Sikandar
750-715-7178
####################################################
obtaining the phone numbers in this format 123-xxx-1234
---------------------------------------------------------
19 Jan 1965
Judy Foster
912-xxx-7052
02 Aug 1984
John Nash
717-xxx-7391
30 Jun 1989
Baba Sikandar
750-xxx-7178
obtaining date format from mm dd yyyy to mm dd, yyyy
-------------------------------------------------------
Jan 19, 1965
Judy Foster
912-576-7052
Aug 02, 1984
John Nash
717-852-7391
Jun 30, 1989
Baba Sikandar
750-715-7178
"""
|
a6b745c310326cd42e26225a55507fd8dbd9c842 | AdarshNamdev/Python-Practice-Files | /AbstractClasses-AbstractMethod-2.py | 3,075 | 4.6875 | 5 |
"""
Note:
a.) Concrete Method: Are methods that has a body
"""
from abc import ABC, abstractmethod
class Car(ABC):
def __init__(self, regno):
self.regno = self.regno
def fillfuel(self):
"""
'fillfuel' method is a Concrete Method because here we are assuming that every car has the same fuel filling mechanism
"""
print("""\n1. Unlock the fuel lock\n2. Take the fuel tank cap out\n3. Fill Fuel\n""")
@abstractmethod
def transmission(self):
"""
Method 'transmission' is an Abstract Method becasue not every car has same type of gear transmission,
some are Automatic, some semi-automatic and some manual
"""
pass
@abstractmethod
def engine(self):
"""
Method 'engine' is an Abstract Method becasue not every car has same type of engine,
some are Diesel Engine and some Petrol Engine.
"""
pass
@abstractmethod
def braking(self):
"""
Method 'braking' is an Abstract Method becasue not every car has same kind of breaking mechanism, some have Hydraulic breaking
and some have Electromagnetic breaking system.
"""
pass
class BMW(Car):
speed = 6
def __init__(self, model, year, regno):
self.model = model
self.year = year
self.regno = regno
def transmission(self):
if self.year > 1991:
print("BMW model {} has {} speed Automatic Transmission".format(self.model, BMW.speed))
else:
print("BMW model {} has Manual {} speed Transmission".format(self.model, BMW.speed))
def engine(self):
print("BMW model {} comes in with both Petrol and Diesel Engine".format(self.model))
def braking(self):
if self.year > 2005:
print("BMW model {} has Electromagnetic braking mechanism".format(self.model))
else:
print("BMW model {} has Hydraulic braking mechanism".format(self.model))
class Hyundai(Car):
speed = 5
def __init__(self, model, year, regno):
self.model = model
self.year = year
self.regno = regno
def transmission(self):
if self.year > 2005:
print("Hyundai model {} has {} speed Automatic Transmission".format(self.model, BMW.speed))
else:
print("Hyundai model {} has Manual {} speed Transmission".format(self.model, BMW.speed))
def engine(self):
print("Hyundai model {} comes in with both Petrol and Diesel Engine".format(self.model))
def braking(self):
if self.year > 2009:
print("Hyundai model {} has Electromagnetic braking mechanism".format(self.model))
else:
print("Hyundai model {} has Hydraulic braking mechanism".format(self.model))
beamer = BMW('720i', 2018, 'MH09MI3084')
beamer.fillfuel()
beamer.transmission()
beamer.engine()
beamer.braking()
verna = Hyundai(model = 'Verna', regno = 'ABCD6508A', year = 2017)
verna.fillfuel()
verna.transmission()
verna.engine()
verna.braking()
|
9f29473c50937834567deb43dca531addc1c8094 | MarlonVictor/pyRepo | /Aula02/at04.py | 450 | 4.09375 | 4 | ## Faça um programa que leia dois números e mostre qual o maior dos dois. O programa deve informar caso sejam iguais.
valor1 = int(input('Digite um número: '))
valor2 = int(input('Agora digite um segundo número: '))
print()
if valor1 > valor2:
print('{0} é maior que {1}'.format(valor1, valor2))
elif valor2 > valor1:
print('{0} é maior que {1}'.format(valor2, valor1))
else:
print(' Os dois números digitados são iguais!') |
0d2d71708e8e72392171a4d6b88684ed13c95455 | warrya/atcoder | /bigginer/180121/a.py | 207 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 21 21:40:47 2018
@author: Yuki
"""
a, b = map(int,input().split())
product = a*b
if product%2 == 0:
print('Even')
else:
print('Odd')
|
6cd16833434bc2664faf13966458bc1796f50710 | warrya/atcoder | /bigginer/171118/A.py | 254 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 9 01:16:26 2017
@author: Yuki
"""
num = input()
if num[0] == num[1] and num[0] ==num[2]:
print('Yes')
elif num[1] == num[2] and num[2] ==num[3]:
print('Yes')
else:
print('No')
|
dc185924d79662ba00817e5fd37ddb8dab5eaf50 | shafiul-haque-johny/Data-Science-in-Python-Assignment-Solution-Coursera | /Assignment1.py | 3,226 | 4.3125 | 4 |
def example_word_count():
# This example question requires counting words in the example_string below.
example_string = "Amy is 5 years old"
# YOUR CODE HERE.
# You should write your solution here, and return your result, you can comment out or delete the
# NotImplementedError below.
result = example_string.split(" ")
return len(result)
# raise NotImplementedError()
# ## Part A
#
# Find a list of all of the names in the following string using regex.
import re
def names():
simple_string = """Amy is 5 years old, and her sister Mary is 2 years old.
Ruth and Peter, their parents, have 3 kids."""
# YOUR CODE HERE
name = re.findall('[A-Z][\w]*', simple_string)
return name
raise NotImplementedError()
names()
print(names())
assert len(names()) == 4, "There are four names in the simple_string"
# ## Part B
#
# The dataset file in [assets/grades.txt](assets/grades.txt) contains a line separated list of people with their grade in
# a class. Create a regex to generate a list of just those students who received a B in the course.
import re
def grades():
with open ("grades.txt", "r") as file:
grades = file.read()
return re.findall('([A-Z]\S+ [A-Z]\S+): B', grades)
# YOUR CODE HERE
namesB = []
for item in re.finditer('(?P<name>.*)(\: B)', grades):
namesB.append(item.group('name'))
return namesB
raise NotImplementedError()
grades()
print(grades())
assert len(grades()) == 16
# ## Part C
#
# Consider the standard web log file in [assets/logdata.txt](assets/logdata.txt). This file records the access a user makes when visiting a web page (like this one!). Each line of the log has the following items:
# * a host (e.g., '146.204.224.152')
# * a user_name (e.g., 'feest6811' **note: sometimes the user name is missing! In this case, use '-' as the value for the username.**)
# * the time a request was made (e.g., '21/Jun/2019:15:45:24 -0700')
# * the post request type (e.g., 'POST /incentivize HTTP/1.1' **note: not everything is a POST!**)
#
# Your task is to convert this into a list of dictionaries, where each dictionary looks like the following:
# ```
# example_dict = {"host":"146.204.224.152",
# "user_name":"feest6811",
# "time":"21/Jun/2019:15:45:24 -0700",
# "request":"POST /incentivize HTTP/1.1"}
# ```
import re
def logs():
with open("logdata.txt", "r") as file:
logdata = file.read()
# YOUR CODE HERE
logsdict = []
pattern = """
(?P<host>.*)
(\ -\ )
(?P<user_name>.*)
(\ \[)
(?P<time>.*)
(\]\ \")
(?P<request>.*)
(\")"""
for item in re.finditer(pattern, logdata, re.VERBOSE):
logsdict.append(item.groupdict())
return logsdict
raise NotImplementedError()
logs()
print(logs())
assert len(logs()) == 979
one_item={'host': '146.204.224.152',
'user_name': 'feest6811',
'time': '21/Jun/2019:15:45:24 -0700',
'request': 'POST /incentivize HTTP/1.1'}
assert one_item in logs(), "Sorry, this item should be in the log results, check your formating"
|
6bd4ae3ab2f3486e1e468a7af7b091d1a6647a83 | rerapony/Stepik | /Algorithms/Methods/GreedyAlgorithms/HuffmanEncoding.py | 1,123 | 3.734375 | 4 | from queue import PriorityQueue
from collections import defaultdict
def make_code(queue):
code = defaultdict(str)
while queue.qsize()>1:
left, right = queue.get(), queue.get()
for letter in left[1]:
code[letter] = '0' + code[letter]
for letter in right[1]:
code[letter] = '1' + code[letter]
queue.put((left[0] + right[0], left[1] + right[1]))
return code
s = input()
freq = defaultdict(int)
freq_q = PriorityQueue()
count=0
for char in s:
freq[char]+=1
if len(freq)==1:
print(len(freq), len(s), sep = ' ')
for key in freq.keys():
print(key, '0', sep=': ', end='\n')
for ch in s:
print('0', sep='', end='')
else:
for key, value in freq.items():
freq_q.put((value, [key]))
huffman_code = make_code(freq_q)
for ch in s:
count+=len(huffman_code[ch])
print(len(freq), count, sep = ' ')
for (char, code) in huffman_code.items():
print(char, code, sep=': ', end='\n')
for ch in s:
if ch in huffman_code.keys():
print(huffman_code[ch], end='')
|
3a79946632f8c31aa3ec6872a483d7f2e11d7efd | rerapony/Stepik | /Algorithms/Methods/DivideAndConquer/DotsAndSections.py | 888 | 3.59375 | 4 | from sys import stdin
import random
import bisect
def quicksort(array, l, r):
if l >= r: return
i, j = l, r
pivot = array[random.randint(l, r)]
while i <= j:
while array[i] < pivot: i += 1
while array[j] > pivot: j -= 1
if i <= j:
array[i], array[j] = array[j], array[i]
i += 1
j -= 1
quicksort(array, l, j)
quicksort(array, i, r)
n_sections, n_dots = map(int, stdin.readline().split())
begins = []
ends = []
for i in range(n_sections):
fst, lst = map(int, stdin.readline().split())
begins.append(fst)
ends.append(lst)
dots = list(map(int, stdin.readline().split()))
quicksort(begins, 0, n_sections-1)
quicksort(ends, 0, n_sections-1)
for dot in dots:
count1 = bisect.bisect_right(begins, dot)
count2 = bisect.bisect_left(ends, dot)
print(abs(count1-count2), end = ' ')
|
38299b6fc562f4b1d28588f243823b01d7fb0bf0 | rerapony/Stepik | /Algorithms/Methods/DivideAndConquer/QuickSort_InPlace.py | 367 | 3.90625 | 4 | def quicksort(array, l, r):
if l >= r: return
i, j = l, r
pivot = array[random.randint(l, r)]
while i <= j:
while array[i] < pivot: i += 1
while array[j] > pivot: j -= 1
if i <= j:
array[i], array[j] = array[j], array[i]
i += 1
j -= 1
quicksort(array, l, j)
quicksort(array, i, r)
|
6193bcd6421b4ea1cee6d23555b79a87d5557beb | anweshachakraborty17/Python_Bootcamp | /P55_Get the length of a set.py | 96 | 3.546875 | 4 | #Get the length of a set
thisset = {"apple", "banana", "cherry"}
print(len(thisset)) #3
|
839ab1c41846f5584b6cb10fd4d9a63fedbb0522 | anweshachakraborty17/Python_Bootcamp | /P63_Print all values in a dictionary, one by one.py | 197 | 4.03125 | 4 | #Print all values in a dictionary, one by one
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
#Ford
#Mustang
#1964 |
3f8bf3c96fb585dec8b5d7130132d7dadaa7f6a4 | anweshachakraborty17/Python_Bootcamp | /P96_Lambda Function Problem2.py | 135 | 3.703125 | 4 | #Lambda Function Problem3
#A lambda function that sums argument a, b, and c
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
#13 |
579e0da0253ec03a4583ba2288b552b72c0d5ced | anweshachakraborty17/Python_Bootcamp | /P48_Delete a tuple.py | 295 | 4.15625 | 4 | #Delete a tuple
thistuple1 = ("apple", "banana", "mango")
del thistuple1
print(thistuple1) #this will raise an error because the tuple no longer exists
#OUTPUT window will show:
#Traceback (most recent call last): File "./prog.py", line 3, in NameError: name 'thistuple1' is not defined |
cf9975b6ae797b5e2eacbe1c63f55d784ebe18a6 | anweshachakraborty17/Python_Bootcamp | /P45_Loop through a tuple.py | 133 | 4.25 | 4 | #loop through a tuple
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
#apple
#banana
#cherry |
5cf51d431c50db3886d1daa7c5dc07ea19e133f7 | harsh4251/SimplyPython | /practice/oops/encapsulation.py | 543 | 4.4375 | 4 | class Encapsulation():
def __init__(self, a, b, c):
self.public = a
self._protected = b
self.__private = c
print("Private can only be accessed inside a class {}".format(self.__private))
e = Encapsulation(1,2,3)
print("Public & protacted can be access outside class{},{} ".format(e.public,e._protected))
"""Name
Notation
Behaviour
name Public
Can be accessed from inside and outside
_name Protected
Like a public member, but they shouldn't be directly accessed from outside.
__name Private
Can't be seen and accessed from outside"""
|
e19c95a226506a3e23d9a5771eb17daa2b7b771c | kumarhegde76/Scripting-Language | /SL_Final/9/A/9a.py | 424 | 3.609375 | 4 | class Student:
name=''
age=''
lst=[]
mylst=[]
def __init__(self,name,age,lst):
self.name=name
self.age=age
self.lst=lst
def Display(self):
print(self.name,'',self.age,'',self.lst)
def accept(self):
myname=input("Enter Name\n")
myage=input("Enter Age\n")
mymarks=list(map(str,input().split()))
p=Student(myname,myage,mymarks)
p.Display()
obj=Student('a','12',[12,15,16])
obj.Display()
obj.accept()
|
e638c537565c9d8dcf1895f248b572c3e7550000 | kumarhegde76/Scripting-Language | /SL Lab/SL_Lab_Test1/aut.py | 546 | 4.0625 | 4 | dict = {1:'Hydrogin',2:'Lithium',3:'Boran',4:'Helium'}
def AutomicDict():
while True:
num=int(input("Enter Automic value Enter 0 to Exit"))
if(num==0):
break;
else:
nam=str(input("Enter The Name of an automic:"))
dict.update({num:nam})
print(dict)
print("Number of Automic values:",len(dict))
sea=str(input("Enter The Elements to search:"))
flag=0;
for i in dict:
if(dict[i].lower()==sea.lower()):
print("Search Found")
print({i,dict[i]})
flag=1
break;
if(flag!=1):
print("Not Found")
AutomicDict() |
6dee0da4be450881bb638d7b2d4163887dee29b7 | stelaseldano/advent_of_code_2017 | /9/stream_processing.py | 1,915 | 3.9375 | 4 | import sys
def stream_processing(file_path):
"""
Day 9 | Part 1 & 2
http://adventofcode.com/2017/day/9
Removes garbage blocks from a stream (string of chars)
and finds how many valid blocks of data there are in the stream.
Takes a file as argument and
creates 'output_91' containing the result for Part 1
and 'output_92' with the result for Part 2
"""
with open(file_path, 'r') as f:
# prepares the date from the file
for line in f:
old_stream = line.strip()
# a string with the cancelled chars removed
cleaner_stream = ''
#
cleanest_stream = ''
# cancelled chars flag
skip_next = False
# garbage flag
skip_while = False
# nesting info for counting the groups
nesting = 0
# groups
groups = 0
# Part 2
# garbage chars counter
garbage_count = 0
# removes the '!' and the next char from the stream
for char in range(0, len(old_stream)):
if skip_next:
skip_next = False
continue
if old_stream[char] == '!':
skip_next = True
else:
cleaner_stream += old_stream[char]
# removes the garbage
for char in range(0, len(cleaner_stream)):
# while skip_while is True if the char is not '>' the iteration continues
if skip_while:
if cleaner_stream[char] == '>':
skip_while = False
else:
garbage_count += 1
continue
# if the char is '<', skip while is set to True
if cleaner_stream[char] == '<':
skip_while = True
elif cleaner_stream[char] == '>':
continue
else:
cleanest_stream += cleaner_stream[char]
# counts the groups
for char in cleanest_stream:
if char == '{':
nesting += 1
if char == '}':
groups += nesting
nesting -= 1
with open('output_91', 'w') as f:
f.write(str(groups))
with open('output_92', 'w') as f:
f.write(str(garbage_count))
if __name__ == '__main__':
stream_processing(sys.argv[-1]) |
9f9aa4b4aa4cc6b293043e036b2a8a73ab2ec07b | qzhou0/SoftDevSpr19WS | /temp/util/dbOperator.py | 1,237 | 3.859375 | 4 | import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
#==========================================================
DB_FILE="./data/<intended_name>" #<SUBSTITUTE FILE NAME>
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
#==========================================================
#INSERT YOUR POPULATE CODE IN THIS ZONE
cmd = "CREATE TABLE table_name(name TEXT, age INTEGER, id INTEGER)"
"""INSERT"""
#cmd = "INSERT INTO [{}] VALUES(?,?)".format(user)
"""SELECT"""
#cmd = "SELECT name FROM sqlite_master WHERE name = '{}'".format(storyName)
"""how to extract table names"""
#cmd = "SELECT * FROM '{}' WHERE authors = '{}'".format(storyname, username)
# 'SELECT name FROM sqlite_master WHERE type = "table" '
#result = c.execute(cmd).fetchall() #listyfy
"""
if result:#list is not empty
return True
# Otherwise, the user has not contributed. (Return false).
return False
"""
#build SQL stmt, save as string
c.execute(cmd) #run SQL statement
#==========================================================
db.commit() #save changes
db.close() #close database
|
91005dad8a02f97f1487323daf79e6e3fccdc59a | hillbs/Trigonometry-Programlets | /arclength_radian.py | 482 | 3.84375 | 4 | # Calculate length of an arc using radius and radian angle measurement
import math
from stdutils import prettyFunction, inputAsDict
vals = inputAsDict(('radians','radius'))
# Calculate arc length
vals['len'] = vals['radians']*vals['radius']
# Calculations with pi
vals['lenp'] = vals['rap']*vals['radius']
vals['rap'] = vals['radians']*math.pi
print('')
print(prettyFunction("{len}{pi} = {radians}{pi} x {radius}", vals))
print(prettyFunction("{len}{pi} {approx} {lenp}", vals))
|
f5983e465d80e3ed54b995418c902f65ceb5eb79 | joopeed/pywizard | /classes/dragon.py | 5,880 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import pygame
pygame.init()
images = {}
images["dragonR"] = pygame.image.load("./images/dragonR.png").convert_alpha()
images["dragonL"] = pygame.image.load("./images/dragonL.png").convert_alpha()
images["dragonU"] = pygame.image.load("./images/dragonU.png").convert_alpha()
images["dragonD"] = pygame.image.load("./images/dragonD.png").convert_alpha()
images["sombra"] = pygame.image.load("./images/sombra.png").convert_alpha()
pygame.font.init()
font_of_life = pygame.font.Font(None, 17)
class Dragon:
"""
Class to create Dragões/Dragons
"""
def __init__(self, posInitial,screen):
self.life = 200
self.position = self.x, self.y = posInitial
self.color_of_life = (0, 200,200)
self.dragon= images["dragonD"]
self.screen = screen
self.velocity = 1
self.tipo = "Dragon"
#self.chao = pygame.sprite.Sprite() .rect
self.chao = pygame.Rect(self.x+60, self.y+114, 45,10)
# Angulo de visão do dragon
self.visao = pygame.Rect(self.x+50, self.y+134, 60,60)
# Laterais possiveis
self.chaoright = pygame.Rect(self.x+60+self.velocity, self.y+114, 45,10)
self.chaoleft = pygame.Rect(self.x+60-self.velocity, self.y+114, 45,10)
self.chaoup = pygame.Rect(self.x+60, self.y+114-self.velocity, 45,10)
self.chaodown = pygame.Rect(self.x+60, self.y+114+self.velocity, 45,10)
self.frozen = False
def lower(self,value):
if self.life-value>0:
self.life -=value
else:
self.life =0
if self.life > 40: # If at least 40%, its green
self.color_of_life = (0, 200,0)
else:
self.color_of_life = (200, 0,0)
def upper(self,value):
if self.life <=100-value:
self.life +=value
else:
self.life +=100-self.life
if self.life > 40: # If at least 40%, its green
self.color_of_life = (0, 200,0)
else:
self.color_of_life = (200, 0,0)
def moveright(self,mago):
if not self.frozen:
self.position = self.x, self.y = self.x+self.velocity,self.y
self.dragon = images["dragonR"]
self.chao = pygame.Rect(self.x+60, self.y+114, 45,10)
self.chaoright = pygame.Rect(self.x+60+self.velocity, self.y+114, 45,10)
self.chaoleft = pygame.Rect(self.x+60-self.velocity, self.y+114, 45,10)
self.chaoup = pygame.Rect(self.x+60, self.y+114-self.velocity, 45,10)
self.chaodown = pygame.Rect(self.x+60, self.y+114+self.velocity, 45,10)
self.visao = pygame.Rect(self.x+100, self.y+87, 60,60)
if mago.chao.colliderect(self.visao) and not mago.invisible and not self.isdead():
mago.lower(2)
def moveleft(self,mago):
if not self.frozen:
self.position = self.x, self.y = self.x-self.velocity,self.y
self.dragon = images["dragonL"]
self.chao = pygame.Rect(self.x+60, self.y+114, 45,10)
self.chaoright = pygame.Rect(self.x+60+self.velocity, self.y+114, 45,10)
self.chaoleft = pygame.Rect(self.x+60-self.velocity, self.y+114, 45,10)
self.chaoup = pygame.Rect(self.x+60, self.y+114-self.velocity, 45,10)
self.chaodown = pygame.Rect(self.x+60, self.y+114+self.velocity, 45,10)
self.visao = pygame.Rect(self.x+20, self.y+87, 60,60)
if mago.chao.colliderect(self.visao) and not mago.invisible and not self.isdead():
mago.lower(2)
def moveup(self,mago):
if not self.frozen:
self.position = self.x, self.y = self.x,self.y-self.velocity
self.dragon = images["dragonU"]
self.chao = pygame.Rect(self.x+60, self.y+94, 45,45)
self.chaoright = pygame.Rect(self.x+60+self.velocity, self.y+114, 45,10)
self.chaoleft = pygame.Rect(self.x+60-self.velocity, self.y+114, 45,10)
self.chaoup = pygame.Rect(self.x+60, self.y+114-self.velocity, 45,10)
self.chaodown = pygame.Rect(self.x+60, self.y+114+self.velocity, 45,10)
self.visao = pygame.Rect(self.x+50, self.y+20, 60,60)
if mago.chao.colliderect(self.visao) and not mago.invisible and not self.isdead():
mago.lower(2)
def movedown(self,mago):
if not self.frozen:
self.position = self.x, self.y = self.x,self.y+self.velocity
self.dragon = images["dragonD"]
self.chao = pygame.Rect(self.x+60, self.y+94, 45,45)
self.chaoright = pygame.Rect(self.x+60+self.velocity, self.y+114, 45,10)
self.chaoleft = pygame.Rect(self.x+60-self.velocity, self.y+114, 45,10)
self.chaoup = pygame.Rect(self.x+60, self.y+114-self.velocity, 45,10)
self.chaodown = pygame.Rect(self.x+60, self.y+114+self.velocity, 45,10)
self.visao = pygame.Rect(self.x+50, self.y+134, 60,60)
if mago.chao.colliderect(self.visao) and not mago.invisible and not self.isdead():
mago.lower(2)
def isdead(self):
return self.life == 0
def frozen(self):
self.frozen = True
def update(self):
# print chao.top
#self.chao = pygame.sprite.Sprite() .rect
#self.chao = pygame.Rect(self.x+60, self.y+114, 45,10)
#self.chao.image = pygame.image.load("bola.png")
# Laterais possiveis
#self.chaoright = pygame.Rect(self.x+62, self.y+114, 45,10)
#self.chaoleft = pygame.Rect(self.x+58, self.y+114, 45,10)
#self.chaoup = pygame.Rect(self.x+60, self.y+112, 45,10)
#self.chaodown = pygame.Rect(self.x+60, self.y+116, 45,10)
self.position = self.x, self.y
self.chao = pygame.Rect(self.x+60, self.y+94, 45,45)
"""Deixa o chão visível"""
#pygame.draw.rect(self.screen, (255,255,255),self.chao)
#pygame.draw.rect(self.screen, (255,255,50),self.visao)
# Update of Dragon
self.screen.blit(self.dragon,self.position)
# Update of Life
textlife = font_of_life.render("%.2f"%(self.life)+"%", True, (255,255, 255)) #self.color_of_life) white default
textRectlife = self.x+60,self.y-22,self.x,self.y
barralife = pygame.Rect(self.x+62, self.y-8, 36.0/200*self.life ,6)
borda = pygame.Rect(self.x+60, self.y-10, 40,10)
# Drawing the group of borda, bar of life and text of percent
self.screen.blit(images['sombra'],(self.x+58, self.y-12))
pygame.draw.rect(self.screen, (255,255,255), borda)
pygame.draw.rect(self.screen, self.color_of_life, barralife)
self.screen.blit(textlife, textRectlife)
|
055de77fe286c3e14c5869e9e04fbcd2a9922103 | elizabethmuirhead-toast/python-eliz | /fractal_tree.py | 4,802 | 4.21875 | 4 | """
CSC 111, Lab 9
Author: Sara Mathieson (modified from Lab 8 solution)
Author: Elizabeth Muirhead and Maddy Kulke
A program to draw a fractal tree using recursion.
"""
from graphics import *
import math
import random
# GLOBALS
theta = 0.7 # angle of each branch away from its trunk
petal_color = "magenta4" # color of the petals
center_color = "yellow" # color of the center of the flower
sky_color = "light pink" # color of the sky/background
ground_color = "dark green" # color of the ground
branch_color = "navy" # color of the branches
flower_lst = [] #global
# CLASSES
# Creases flower object
class Flower:
#initializes instance variable
def __init__(self, x, y):
# make a yellow center for the flower
center = Circle(Point(x,y),2)
center.setFill(center_color)
center.setOutline(center_color)
# set petal length and pick a random orientation for the flower
petal_len = 18
angle = random.uniform(0,2*math.pi)
# make four petals using helper function
petal1 = self.make_petal(x, y, petal_len,angle)
petal2 = self.make_petal(x, y, petal_len,angle+math.pi/2)
petal3 = self.make_petal(x, y, petal_len,angle+math.pi)
petal4 = self.make_petal(x, y, petal_len,angle+3*math.pi/2)
# list with all the components iof the flower
self.part_lst = [center, petal1, petal2, petal3, petal4]
# builds and returns a petal
def make_petal(self, x, y, length, angle):
# first point closest to the center
p1 = Point(x,y)
# left-most point
dx2 = length/2*math.cos(angle-0.3)
dy2 = length/2*math.sin(angle-0.3)
p2 = Point(x+dx2,y+dy2)
# furthest point from the center
dx3 = length*math.cos(angle)
dy3 = length*math.sin(angle)
p3 = Point(x+dx3,y+dy3)
# right-most point
dx4 = length/2*math.cos(angle+0.3)
dy4 = length/2*math.sin(angle+0.3)
p4 = Point(x+dx4,y+dy4)
# create the diamond-shaped petal
petal = Polygon(p1,p2,p3,p4)
petal.setFill(petal_color)
petal.setOutline(petal_color)
return petal
# draws all parts in part list of flower
def draw(self, window):
for part in self.part_lst:
part.draw(window)
# moves all parts in part list
def move(self, dx, dy):
for part in self.part_lst:
part.move(dx, dy)
# gets center of circle in part list, returns true if flower center is less than height
def is_above_ground(self, y):
flower_center = self.part_lst[0].getCenter()
y_height = flower_center.getY()
if y_height < y:
return True
else:
return False
# HELPER FUNCTIONS
# recursively draws a fractal tree
def draw_tree(window, order, x, y, length, angle):
# compute the coordinates of end of the current branch
dx = length * math.cos(angle)
dy = length * math.sin(angle)
x2 = x + dx
y2 = y + dy
# draw current branch
branch = Line(Point(x,y), Point(x2,y2))
branch.setFill(branch_color)
branch.setWidth(order) # make the higher order branches thicker
branch.draw(window)
# base case: at the leaves, draw a flower
if order == 0:
flower = Flower(x2,y2)
flower.draw(window)
flower_lst.append(flower)
# recursion case: if order > 0, draw two subtrees
else:
new_len = length*0.7
draw_tree(window, order-1, x2, y2, new_len, angle-theta) # "left" branch
draw_tree(window, order-1, x2, y2, new_len, angle+theta) # "right" branch
# MAIN
def main():
# set up the graphics window
width = 800
height = 600
win = GraphWin("Fractal Tree", width, height)
win.setBackground(sky_color)
# draws the ground
ground = Rectangle(Point(0,height-80), Point(width,height))
ground.setFill(ground_color)
ground.setOutline(ground_color)
ground.draw(win)
# set up parameters for our call to the recursive function
order = 6
x_start = width/2 # middle of the window
y_start = height-10 # close to the bottom of the window
angle = -math.pi/2 # initial branch (trunk) pointing *upwards*
length = 200 # length of initial branch (trunk)
# calls recursive function to draw tree
draw_tree(win, order, x_start, y_start, length, angle)
# loops through the flowers
for f in flower_lst:
# while loop checks to see if flower_Center y is less than height-20
while f.is_above_ground(height-(random.randint(20,70))):
# while true, flower continues to move down by 10
f.move(0, 10)
# close on click
win.getMouse()
win.close()
main()
|
259e6161b173cb9975c55427158b13f76750e059 | c42-arun/coding-challenges-python | /src/max_product_of_3_ints/solution_2.1.py | 1,772 | 4.125 | 4 | '''
Greedy approach
- 1 loops
- O(1) space (or O(n)?)
- O(n) time
- considers only +ve ints
'''
def pushDownValues(items, fromIndex):
print(f"Before push: {items[0]}, {items[1]}, {items[2]}: {fromIndex}")
for i in range(len(items) - 1, fromIndex, -1):
print(f"{i - 1} -> {i}")
items[i] = items[i-1]
print(f"After push: {items[0]}, {items[1]}, {items[2]}: {fromIndex}")
int_list = [-15, -10, 7, 8, 5, 11, 12, 9]
max_list = int_list[:3]
max_list.sort(reverse = True)
print(f"Initial values: {max_list[0]}, {max_list[1]}, {max_list[2]}")
print("-------------------------------------")
for i in range(len(int_list)):
current_value = int_list[i]
print(f"Begin iteration values: {max_list[0]}, {max_list[1]}, {max_list[2]}; {current_value}")
# if we already have the number in the max list then skip
if (current_value in max_list):
continue
# we cannot use >= because if the item is already in max_list (for eg the initial values)
# then we'll still push down values
# if we use > then make sure we check for 'current_value in max_list' above - otherwise
# when current_value equals one of the values it is checked against next one and might
# be added again
if (current_value > max_list[0]):
pushDownValues(max_list, 0)
max_list[0] = current_value
elif (current_value > max_list[1]):
pushDownValues(max_list, 1)
max_list[1] = current_value
elif (current_value > max_list[2]):
max_list[2] = current_value
print(f"End iteration values: {max_list[0]}, {max_list[1]}, {max_list[2]}; {current_value}")
print("-------------------------------------")
print(f"Final values: {max_list[0]}, {max_list[1]}, {max_list[2]}")
|
cb03be569b14995c4e68e6a32112fa021f4c2b7f | c42-arun/coding-challenges-python | /src/apple-stocks/solution_2.py | 1,294 | 4.0625 | 4 | prices = [15, 10, 7, 8, 5, 11, 12, 9]
# prices.sort(reverse = True)
# print(prices)
max_profit = None
# here we are seeing for each price (buy price) the maximum price
# that occurs after (sell price)
# Space complexity: O(1)
# Time complexity: O(n) - only one loop (not sure about taking max() at each iteration?)
for i in range(len(prices) - 1):
buy_price = prices[i]
sell_price = max(prices[i+1:])
if (max_profit is None):
max_profit = sell_price - buy_price
elif((sell_price - buy_price) > max_profit):
max_profit = (sell_price - buy_price)
print('Max profit is ' + str(max_profit))
'''
Follow up:
1. You can't just take the difference between the highest price and the lowest price,
because the highest price might come before the lowest price. And you have to buy before you can sell.
Satisfied
2. What if the price goes down all day? In that case, the best profit will be negative.
SATISFIED - there's no need to check for +ve profit in line 11
3. Done in O(1) space and O(n) time
O(1) space - yes (assuming its the additional space taken by algorithm which is always those temp vars max_profit, buy_price etc)
O(n) time - yes but unsure about running the max() function everytime?
'''
|
0b2deb15577ba07a878f00d91eee617d48605bec | beekalam/fundamentals.of.python.data.structures | /ch02/counting.py | 583 | 4.15625 | 4 | """
File: counting.py
prints the number of iterations for problem sizes
that double, using a nested loop
"""
if __name__ == "__main__":
problemSize = 1000
print("%12s%15s" % ("Problem Size", "Iterations"))
for count in range(5):
number = 0
#The start of the algorithm
work = 1
for j in range(problemSize):
for k in range(problemSize):
number += 1
work += 1
work -= 1
# the end of the algorithm
print("%12d%15d" % (problemSize, number))
problemSize *= 2
|
db92a53991353d177176207c73e506de02723010 | rodrigoadfaria/playground | /algorithms/analog_cutting_machinery.py | 1,111 | 3.609375 | 4 | import numpy as np
def optimal_log_cutting(p, l):
'''
Analog Cutting Machinery - given an array p with cutting points p1, p2, ..., pk of
an analog and l which is its length, computes the minimal cost based on the best
cutting arrangement.
'''
p.insert(0, 0)
p.insert(len(p), l)
n = len(p)
c = [[-1 for j in range(n)] for i in range(n)] # initializing the c matrix of size n+1 x n
for i in range(0, n-1):
c[i][i+1] = 0
for k in range(1, n):
for i in range(0, n-k-1):
j = i+k+1
c[i][j] = float('inf')
m = i+1
while m < j:
aux = c[i][m] + c[m][j]
if aux < c[i][j]:
c[i][j] = aux
m += 1
c[i][j] = c[i][j] + p[j] - p[i]
return c, c[0][n-1]
def main():
#p = [25,50,75]
#l = 100
#p = [2,4,7]
p = [4,5,7,8]
l = 10
print
print '==============================================='
print 'Analog cutting machinery'
print '==============================================='
print 'p = ', p
print 'l = ', l
c, cost = optimal_log_cutting(p, l)
c = np.array(c)
print 'c = '
print c
print 'The minimal cost is ', cost
if __name__=="__main__":
main() |
4e4a76cd1c3146b7bc8e16a1dd85f7e712a71cfb | rodrigoadfaria/playground | /algorithms/longest_common_subsequence.py | 5,046 | 3.859375 | 4 | import numpy as np
import quicksort as qs
def lcs_length(X, Y):
'''
Computes the longest common subsequence of two vectors X and Y, keeping
the size of those subsequences in a matrix c and the path to the longest
subsequence in another matrix of same size b.
We sum up 1 to m and n due to indexing of the original algorithm.
The characters are:
D - diagonal
U - upper
L - left
Based on CLRS 2ed p353.
'''
m = len(X) + 1
n = len(Y) + 1
c = [[None for j in range(n)] for i in range(m)] # initializing the c matrix of size mxn
b = [[None for j in range(n)] for i in range(m)] # initializing the b matrix of size mxn
for i in range(1, m):
c[i][0] = 0
for j in range(0, n):
c[0][j] = 0
for i in range(1, m):
for j in range(1, n):
if X[i-1] == Y[j-1]: # once we use the the length m and n, we have to subtract 1 to get all values in X, Y vectors
c[i][j] = c[i-1][j-1] + 1
b[i][j] = 'D'
elif c[i-1][j] >= c[i][j-1]:
c[i][j] = c[i-1][j]
b[i][j] = 'U'
else:
c[i][j] = c[i][j-1]
b[i][j] = 'L'
return c, b
def lcs_max_sum_length(X, Y):
'''
Computes the longest common subsequence of two vectors X and Y, keeping
the size of those subsequences in a matrix c and the path to the longest
subsequence in another matrix of same size b.
We sum up 1 to m and n due to indexing of the original algorithm.
The characters are:
D - diagonal
U - upper
L - left
Based on CLRS 2ed p353.
'''
m = len(X) + 1
n = len(Y) + 1
c = [[None for j in range(n)] for i in range(m)] # initializing the c matrix of size mxn
b = [[None for j in range(n)] for i in range(m)] # initializing the b matrix of size mxn
for i in range(1, m):
c[i][0] = 0
for j in range(0, n):
c[0][j] = 0
for i in range(1, m):
for j in range(1, n):
if X[i-1] == Y[j-1]: # once we use the the length m and n, we have to subtract 1 to get all values in X, Y vectors
c[i][j] = c[i-1][j-1] + X[i-1]
b[i][j] = 'D'
elif c[i-1][j] >= c[i][j-1]:
c[i][j] = c[i-1][j]
b[i][j] = 'U'
else:
c[i][j] = c[i][j-1]
b[i][j] = 'L'
return c, b
def print_lcs(b, X, i, j):
'''
Prints out the longest common subsequence of X and Y in the proper, forward
order, recursively.
Pay attention in line 'print X[i-1]' where we had to subtract 1 due to
algorithm indexing.
Based on CLRS 2ed p355.
'''
if i == 0 or j == 0:
return
if b[i][j] == 'D':
print_lcs(b, X, i-1, j-1)
print X[i-1],
elif b[i][j] == 'U':
print_lcs(b, X, i-1, j)
else:
print_lcs(b, X, i, j-1)
def build_longest_increasing_subsequence(v, n):
'''
Given a array v of integers, copies it in an auxiliary array u and
sorts it using a comparison sort algorithm (n lg n).
After that, it uses the LCS algorithm strategy to prints out the longest
common subsequence between v and u (the original array v in increasing order).
'''
u = [None] * n
for i in range(n):
u[i] = v[i]
qs.quicksort(u, 0, len(u)-1)
c, b = lcs_length(v, u)
print_lcs(b, v, len(v), len(u))
def get_lcs_max_sum(X, m, n, b, max_length):
'''
Retrieve the longest common subsequence of maximum sum of X and Y in the proper, forward
order, recursively.
Pay attention in line 'print X[i-1]' where we had to subtract 1 due to
algorithm indexing.
Based on CLRS 2ed p355.
'''
k = max_length
i = m
j = n
Z = [None] * k
l = 0
print Z
while i > 0 and j > 0:
if b[i][j] == 'D':
print X[i-1]
print k
Z[k-1] = X[i-1]
k = k-1
i = i-1
j = j-1
l = l+1
elif b[i][j] == 'L':
i = i-1
else:
j = j-1
return Z, l
def build_max_sum_lcs(X, n):
'''
Given a array v of integers, copies it in an auxiliary array u and
sorts it using a comparison sort algorithm (n lg n).
After that, it uses the LCS algorithm strategy to prints out the longest
common subsequence between v and u (the original array v in increasing order).
'''
Y = [None] * n
for i in range(n):
Y[i] = X[i]
qs.quicksort(Y, 0, len(Y)-1)
c, b = lcs_max_sum_length(X, Y)
print np.array(c)
print np.array(b)
print 'Length of the LCS max sum '
print get_lcs_max_sum(X, len(X), len(Y), b, len(X))
def main():
X = ['A', 'B', 'C', 'B', 'D', 'A', 'B']
Y = ['B', 'D', 'C', 'A', 'B', 'A']
c, b = lcs_length(X, Y)
print '==============================================='
print 'Longest Common Subsequence'
print '==============================================='
print 'X = ', X
print 'Y = ', Y
print 'c = '; print np.array(c)
print 'b = '; print np.array(b)
print_lcs(b, X, len(X), len(Y))
X = [2,4,5,7,1,3,8,6,15]
print
print '==============================================='
print 'Longest Common Subsequence'
print '==============================================='
print 'X = ', X
build_longest_increasing_subsequence(X, len(X))
#X = [42,4,5,7,1]
X = [2,4,7,5,9]
print
print '==============================================='
print 'Max Sum Longest Common Subsequence'
print '==============================================='
print 'X = ', X
build_max_sum_lcs(X, len(X))
if __name__=="__main__":
main() |
ae674ff0b38d7c061fae09e8666072e62e95c82b | rodrigoadfaria/playground | /algorithms/binary_sum.py | 1,067 | 4 | 4 | def binary_sum(A, B, n):
'''
CLRS - 3 ed. Problem 2.1-4
Add two n-bit binary integers, stored in two n-element arrays A and B
'''
C = [0]*(n+1)
carry = 0
# do the summation from the least significant to most significant bit
for i in range(n-1, -1, -1):
sum_ = A[i] + B[i] + carry
C[i+1] = int(sum_ % 2)
carry = int(sum_ / 2)
C[0] = carry
return C
def main():
#A=[1,1,0] # 6
#B=[0,1,0] # 2
A=[0,1,1,0,1] # 13
B=[1,0,1,1,1] # 23
#A = [0,1,1,0,1,1,1,0] # 110
#B = [0,0,0,1,0,1,1,1] # 23
C = binary_sum(A, B, len(A))
C_concat = ''
A_concat = ''
B_concat = ''
for x in A:
A_concat += str(x)
for x in B:
B_concat += str(x)
for x in C:
C_concat += str(x)
# parse the arrays to int values for better seeing the summation
A_ = int(A_concat, 2)
B_ = int(B_concat, 2)
C_ = int(C_concat, 2)
print ('A = ', A, A_)
print ('B = ', B, B_)
print ('A + B = ', C, C_)
if __name__=="__main__":
main() |
647b520d0ab13328a9a834a4c74da8c7a6beca4d | leopen-hu/python-web-demo | /base-demo/python-advanced-features/Iteration.py | 854 | 3.796875 | 4 | from collections import Iterable
print('string iterable?', isinstance('abc', Iterable))
print('list iterable?', isinstance([1, 2, 3], Iterable))
print('int iterable?', isinstance(123, Iterable))
for i, value in enumerate(['1', 'b', '-']):
print('enumerate', i, value)
def findMinAndMax(source_list):
if len(source_list) == 0:
return (None, None)
max = source_list[0]
min = source_list[0]
for x in source_list:
if x > max:
max = x
if x < min:
min = x
return (min, max)
# 测试
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
|
ddb75e2eefe1cc045ca3047ee2fb97617135b84d | bubnicbf/essay_grader | /Spellings/Spellings.py | 1,396 | 4.0625 | 4 |
##
# SPELL CHECKER
# -- module has a function to check and grade spellings
#
# @author Apoorva Rao @date 14 March 2012
#
##
import enchant
import re
# @brief function which checks spellings
# INPUT : essay
# OUTPUT: returns the number of misspelt words AND key-value pairs of missplet words and suggestions to correct them
def spellCheck(text):
#choose the dictionary
d = enchant.Dict("en_US")
#keep track of the number of misspelt words
numIncorrect=0
#split the text into words
wordList = re.findall(r'\w+', text)
misspelt = {}
#Checking for misspelt words...
for word in wordList:
#print word, d.check(word)
if d.check(word)==False:
misspelt[word] = d.suggest(word) #store the word and its suggestions as a key value pair
numIncorrect += 1
return numIncorrect, misspelt
#test driver to independently test the module
if __name__ == '__main__' :
text = "Hi lets see fi iti cahn check miy sepllings?? Apoorva\n"
#incorr1, misspelt1 = spellChecker(text)
#print "\n\nIncorrectly spelled count: ", incorr1
############################
#open essay
sourceFileName = "../Sample_Essays/essay4.txt"
sourceFile = open(sourceFileName, "r")
#read essay
text = sourceFile.read()
incorr2, misspelt2 = spellCheck(text)
print "\n\nIncorrectly spelled count: ", incorr2, "\n"
for key in misspelt2:
print key, " :: ", misspelt2[key], "\n\n"
|
8e19018571298372b73695afb9139596e1524464 | MITRE-South-Florida-STEM/ps1-summer-2021-luis-c465 | /ps1c.py | 1,706 | 4.125 | 4 | annual_salary = float(input("Enter the starting salary: "))
total_cost = 1_000_000
semi_annual_raise = .07
portion_down_payment = 0.25
r = 0.04 # Return on investment
total_months = 0
current_savings = 0.0
def down_payment(annual_salary: int, portion_saved: float, total_cost: int,
portion_down_payment: float, r: float, semi_annual_raise: float,
semi_annual_raise_after = 6
) -> int:
total_months = 0
current_savings = 0.0
while total_cost * portion_down_payment > current_savings:
if total_months != 0 and (total_months % semi_annual_raise_after) == 0:
annual_salary *= 1 + semi_annual_raise
return_on_investment = current_savings * (r / 12)
investment = (annual_salary / 12) * portion_saved
current_savings += return_on_investment + investment
total_months += 1
return total_months
moths = 36
bisections = 0
low = 0
high = 10_000
high_before = high
# ! Lower this value for a more accurate answer / more bisections !
# ! Must be greater than 1 !
epsilon = 3
while abs(low - high) >= epsilon:
guess = (high + low) // 2
payment_guess = down_payment(annual_salary, guess / high_before, total_cost, portion_down_payment, r, semi_annual_raise)
# print(f"Bisections: {bisections}")
# print(f"Payment guess months: {payment_guess}")
# print(f"Guess: {guess}\tLow/High: {low}/{high}\n")
if moths < payment_guess: low = guess
else: high = guess
bisections += 1
if high == high_before:
print(f"It is not possible to pay the down payment in {moths / 12} years.")
else:
print(f"Best savings rate: {guess / high_before}")
print(f"Steps in bisection search: {bisections}")
|
aeca74f1e637228b4d7e0bffcdf0f3c9dab35143 | imclab/fatiando | /fatiando/inversion/datamodule.py | 3,430 | 3.625 | 4 | """
Base DataModule class with the format expected by all inverse problem solvers.
See the docs for the :mod:`fatiando.inversion` package for more information on
the role of the data modules.
----
"""
import numpy
class DataModule(object):
"""
A generic data module.
Use this class as a skeleton for building custom data modules for a specific
geophysical data set and interpretative model, like gravity anomaly for
right rectangular prism models, travel time residuals for epicenter
calculation, etc.
Data modules are how each inverse problem solver knows how to calculate
things like:
* Predicted data
* Data-misfit function
* Gradient of the data-misfit function
* Hessian of the data-misfit function
Not all solvers use all of the above. For examples, heuristic solvers don't
require gradient and hessian calculations.
This class has templates for all of these methods so that all solvers know
what to expect.
Normally, all data modules should store the value of the latest residual
vector calculated.
Constructor parameters common to all methods:
* data : array
The observed data.
"""
def __init__(self, data):
self.data = data
def get_misfit(self, residuals):
"""
Returns the value of the data-misfit function for a given residual
vector
Parameters:
* residuals : array
The residual vector
Returns:
* misfit : float
Scalar value of the data-misfit
"""
return numpy.linalg.norm(residuals)
def get_predicted(self, p):
"""
Returns the predicted data vector for a given parameter vector.
Parameters:
* p : array
The parameter vector
Returns:
* pred : array
The calculated predicted data vector
"""
raise NotImplementedError("get_predicted method not implemented")
def sum_gradient(self, gradient, p=None, residuals=None):
"""
Sums the gradient vector of this data module to *gradient* and returns
the result.
Parameters:
* gradient : array
The old gradient vector
* p : array
The parameter vector
* residuals : array
The residuals evaluated for parameter vector *p*
.. note:: Solvers for linear problems will use ``p = None`` and
``residuals = None`` so that the class knows how to calculate
gradients more efficiently for these cases.
Returns:
* new_gradient : array
The new gradient vector
"""
raise NotImplementedError("sum_gradient method not implemented")
def sum_hessian(self, hessian, p=None):
"""
Sums the Hessian matrix of this data module to *hessian* and returns
the result.
Parameters:
* hessian : array
2D array with the old Hessian matrix
* p : array
The parameter vector
.. note:: Solvers for linear problems will use ``p = None`` so that the
class knows how to calculate gradients more efficiently for these
cases.
Returns:
* new_hessian : array
2D array with the new Hessian matrix
"""
raise NotImplementedError("sum_hessian method not implemented")
|
ab872a4d32586fe8cb30a77bf6e212a8512d9c11 | Andrew7891-kip/python_for_intermediates | /copying.py | 918 | 4.21875 | 4 | import copy
# shallow copy
# interferes the original
org = [[0,1,2,3],[5,6,7,8]]
cpy=copy.copy(org)
cpy[0][1]=9
print(cpy)
print(org)
# shallow func copy
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
p1=Student('Andrew',19)
p2 = copy.copy(p1)
p2.age=20
print(p1.age)
print(p2.age)
# deep copy
# not interfere the original
orgy = [[0,1,2,3],[5,6,7,8]]
cpyi=copy.deepcopy(orgy)
cpyi[0][1]=9
print(cpyi)
print(orgy)
# deep copy func
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
class Company:
def __init__(self,boss,employee):
self.boss=boss
self.employee=employee
p1=Student('Andrew',19)
p2 = copy.copy(p1)
p2.age=20
# shallow copy
company=Company(p1,p2)
# deep copy
company_clone=copy.deepcopy(company)
company_clone.boss.age=50
print(company_clone.boss.age)
print(company.boss.age)
|
ff141f26969b510c1d7a03b29d2bfea0e84aa57d | Andrew7891-kip/python_for_intermediates | /process_exp.py | 408 | 3.515625 | 4 | # process : is an instance of a program
from multiprocessing import Process
import os
import time
def square_num():
for i in range(10):
i*i
time.sleep(0.1)
processes = []
num_process = os.cpu_count()
for i in range(num_process):
p=Process(target=square_num)
processes.append(p)
# start
for p in processes:
p.start()
for p in processes:
p.join()
print('end main')
|
7835d172de44fdcaa38cba0a3c716e6b342863d0 | Dragonair28/My-projects | /Stone paper scissors/Guessing game.py | 246 | 4.0625 | 4 | print("GAME: Guessing game")
a = input("Enter your guessing number up to 100:")
if a == "69":
print("Well Done ! , Your guess is right")
elif a == "hint":
print("it's between 50 to 70 ")
else:
print("Your guess is wrong , Try Again")
|
19eb343bbdee6be18dbf77f01ad02db9cd17350c | nigelandrewquinn/Kattis | /dasblinkenlights.py | 245 | 3.6875 | 4 | def gcd(a,b):
if b == 0:
return a
remainder = a % b
return gcd(b,remainder)
def lcm(a, b):
return int( (a*b) / gcd(a,b))
p, q, s = map(int, input().split())
if lcm(p,q) <= s:
print('yes')
else:
print('no') |
4681d2bde1224f48fa6f6cd85a32b89ee7063d0d | nigelandrewquinn/Kattis | /guessthedatastructure.py | 1,397 | 3.796875 | 4 | from collections import deque
from sys import stdin
import heapq
class Stack:
def __init__(self):
self.s = deque()
def add(self, n):
self.s.append(n)
def pop(self):
return self.s.pop() if self.s else None
def ds_type(self):
return 'stack'
class Queue:
def __init__(self):
self.q = deque()
def add(self, n):
self.q.append(n)
def pop(self):
return self.q.popleft() if self.q else None
def ds_type(self):
return 'queue'
class PQ:
def __init__(self):
self.pq = []
def add(self, n):
heapq.heappush(self.pq, -n)
def pop(self):
return -heapq.heappop(self.pq) if self.pq else None
def ds_type(self):
return 'priority queue'
while 1:
try:
ds = [Stack(), Queue(), PQ()]
for _ in range(int(input())):
a, b = map(int, input().split())
for i in range(len(ds) - 1, -1, -1):
if a == 1:
ds[i].add(b)
else:
if ds[i].pop() != b:
del ds[i]
if len(ds)>1:
print('not sure')
elif len(ds) == 0:
print('impossible')
else:
print(ds[0].ds_type())
except EOFError:
break
|
65b80fb12e43b9fd616015f6a3e1ccc2e521243f | nigelandrewquinn/Kattis | /snowflakes.py | 377 | 3.609375 | 4 | from sys import stdin, stdout
for _ in range(int(stdin.readline())):
seen= set()
count = 0
longest = 0
for i in range(int(stdin.readline())):
sf = int(stdin.readline())
if sf not in seen:
seen.add(sf)
count+=1
longest = max(longest, count)
else:
count = 0
print(longest) |
57c185df5b31ccf64519fcfb0e580fd4e402710b | johnconnor77/holbertonschool-higher_level_programming | /0x03-python-data_structures/8-multiple_returns.py | 123 | 3.53125 | 4 | #!/usr/bin/python3
def multiple_returns(sentence):
return (len(sentence), sentence[0] if sentence is not '' else None)
|
c91499c701088dc38d55595d10c81c0ef5b19aee | johnconnor77/holbertonschool-higher_level_programming | /0x11-python-network_1/1-hbtn_header.py | 343 | 3.65625 | 4 | #!/usr/bin/python3
"""
Python script that takes in a URL, sends a request
to the URL and displays the value of the X-Request-Id
"""
import urllib.request
from sys import argv
if __name__ == "__main__":
with urllib.request.urlopen(argv[1]) as response:
dict_info = response.info()
print(dict_info['X-Request-Id'])
|
b915168a6b9ad8c6c44e5c1fa6565688a44efb0f | johnconnor77/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-from_json_string.py | 260 | 4.09375 | 4 | #!/usr/bin/python3
import json
def from_json_string(my_str):
"""From JSON string to Object
Returns an object (Python data structure) represented by a JSON string
Args:
my_str: JSON string being used
"""
return(json.loads(my_str))
|
a4473c948e409ac384a583620829bff08dab3646 | burnettk/origin | /Python/BuckysCodeExamples/RangeWhile.py | 193 | 3.984375 | 4 | for x in range(10):
print(x)
for y in range(5, 12):
print(y)
for z in range(10, 40, 5):
print(z)
mrh_scalar = 5
while mrh_scalar < 10:
print(mrh_scalar)
mrh_scalar += 1
|
49371bccaacbff19fbb745348679df95941f1b5e | burnettk/origin | /Python/BuckysCodeExamples/ExceptionHandling.py | 456 | 4.09375 | 4 | #tuna = int(input("What's your favorite number?\n"))
# throws exception if string entered
#print(tuna)
while True:
try:
number = int(input("What's your favorite number?\n"))
print(18/number)
break
except ValueError:
print("Make sure and enter a number.")
except ZeroDivisionError:
print("Can't enter zero.")
# Not a good idea
except:
break
finally:
print("loop is complete")
|
f3db99c9ac7fdb7cadb6d025103c7d66d5d10d9b | sw2-team/sw2-team | /first_homework/20171705-조경상-assignment2.py | 191 | 3.71875 | 4 | while True:
n = int(input("Enter a number: "))
f = 1
if n <= -1:
exit()
if n == 0 :
print("0! = 1")
if n >= 1 :
for i in range(1,n+1):
f = f*i
print("%d! = %d"%(n,f))
|
2838e84d4a11ddfae046220ceb8951f48d742742 | nickruta/stupidlang | /stupidlang/run.py | 2,380 | 3.84375 | 4 | from .parser import parse
from .evaluator import eval_ptree, Program
def backtolang(exp):
"""
Takes a expression list and converts it back into a
stupidlang expression.
Parameters
----------
exp : list
A list representing a parsed stupidlang expression
Returns
-------
str
A string with the corrsponding stupidlang code
Examples
--------
>>> backtolang(None)
nil
>>> backtolang(True)
#t
>>> backtolang()
"""
boolmap={True:'#t', False:'#f'}
if isinstance(exp, list):
return '(' + ' '.join(map(backtolang, exp)) + ')'
elif isinstance(exp, bool):
return boolmap[exp]
elif exp is None:
return 'nil'
else:
return str(exp)
def repl(env, prompt='SL> '):
"""
A REPL for the stupidlang language
Parameters
----------
env : Environment
a concrete implementation instance of the Environment interface
prompt : str, optional
a string for the prompt, default SL>
"""
try:
import readline
except:
pass
while True:
try:
val = eval_ptree(parse(input(prompt)), env)
except (KeyboardInterrupt, EOFError):
break
if val is not None:
print(backtolang(val))
def run_program_asif_repl(program, env):
"""
Runs code with output as-if we were in a repl
Parameters
----------
program: str
a multi-line string representing the stupidlang program
env : Environment
a concrete implementation instance of the Environment interface
Returns
-------
str:
The output of the program as if it were being run in a REPL
"""
prog=Program(prpgram, env)
for result in prog.run():
print(backtolang(result))
def run_program(program, env):
"""
Runs code without output until the last line where output is provided.
Parameters
----------
program: str
a multi-line string representing the stupidlang program
env : Environment
a concrete implementation instance of the Environment interface
Returns
-------
str:
The last output of the program as if it were being run in a REPL
"""
prog=Program(program, env)
endit = None
for result in prog.run():
endit = result
return backtolang(endit) |
e04ea4abc905d69bac5ae6bf65ab123a7e8f28ce | leal26/pyfi | /auxiliary_functions.py | 5,699 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 21:15:49 2016
@author: Pedro
"""
from datetime import datetime
def output_reader(filename, separator='\t', output=None, rows_to_skip=0,
header=0, type_data = None):
"""
Function that opens files of any kind. Able to skip rows and
read headers if necessary.
Inputs:
- filename: just the name of the file to read.
- separator: Main kind of separator in file. The code will
replace any variants of this separator for processing. Extra
components such as end-line, kg m are all eliminated.
- output: defines what the kind of file we are opening to
ensure we can skip the right amount of lines. By default it
is None so it can open any other file.
- rows_to_skip: amount of rows to initialy skip in the file. If
the output is different then None, for the different types of
files it is defined as:
- Polar files = 10
- Dump files = 0
- Cp files = 2
- Coordinates = 1
- header: The header list will act as the keys of the output
dictionary. For the function to work, a header IS necessary.
If not specified by the user, the function will assume that
the header can be found in the file that it is opening.
- type_data: if defined, has the same length of the number of
columns in the file and tells output_reader how to process
the data. 'time' will return datetime objects, 'float' will
return floats.
Output:
- Dictionary with all the header values as keys
Created on Thu Mar 14 2014
@author: Pedro Leal
"""
# In case we are using an XFOIL file, we define the number of rows
# skipped
if output == 'Polar' or output == 'Alfa_L_0':
rows_to_skip = 10
elif output == 'Dump':
rows_to_skip = 0
elif output == 'Cp':
rows_to_skip = 2
elif output == 'Coordinates':
rows_to_skip = 1
# n is the amount of lines to skip
Data = {}
if header != 0:
header_done = True
for head in header:
Data[head] = []
else:
header_done = False
count_skip = 0
with open (filename, "r") as myfile:
# Jump first lines which are useless
for line in myfile:
if count_skip < rows_to_skip:
count_skip += 1
# Basically do nothing
elif header_done == False:
# If the user did not specify the header the code will
# read the first line after the skipped rows as the
# header
if header == 0:
# Open line and replace anything we do not want (
# variants of the separator and units)
line = line.replace(separator + separator + separator +
separator + separator + separator, ' ').replace(separator
+ separator + separator + separator + separator,
' ').replace(separator + separator + separator +
separator, ' ').replace(separator + separator + separator,
' ').replace(separator + separator, ' ').replace("\n",
"").replace("(kg)", "").replace("(m)", "").replace("(Pa)",
"").replace("(in)", "").replace("#", "").replace(separator,
' ')
header = line.split(' ')
n_del = header.count('')
for n_del in range(0, n_del):
header.remove('')
for head in header:
Data[head] = []
# To avoid having two headers, we assign the False
# value to header which will not let it happen
header_done = True
# If the user defines a list of values for the header,
# the code reads it and creates libraries with it.
elif type(header) == list:
for head in header:
Data[head] = []
header_done = True
else:
line = line.replace(separator + separator + separator,
' ').replace(separator + separator, ' ').replace(separator,
' ').replace("\n", "").replace('---------', '').replace(
'--------', '').replace('-------', '').replace('------',
'')
line_components = line.split(' ')
n_del = line_components.count('')
for n in range(0, n_del):
line_components.remove('')
if line_components != []:
if type_data == None:
for j in range(0, len(line_components)):
Data[header[j]].append(float(line_components[j]))
else:
for j in range(0, len(line_components)):
if type_data[j] == 'float':
Data[header[j]].append(float(line_components[j]))
elif type_data[j] == 'time':
time_object = datetime.strptime(line_components[j],'%Y-%m-%d')
Data[header[j]].append(time_object)
# else DO NOTHING!
return Data
if __name__ == '__main__':
data = output_reader('history_BOND.csv', separator = ',', type_data = ['time',
'float', 'float', 'float', 'float', 'float', 'float']) |
5f21d23c5e0d090078a61c2e07103fce8dcfc595 | parkseohui/git | /DashInsert.py | 483 | 3.875 | 4 | #Dash Insert
#입력: 숫자를 입력받기
#출력: 홀수가 연속되면 두 수 사이에 - 를 추가하고, 짝수가 연속되면 * 를 추가한 문자열
a=input("숫자를 입력해주세요")
b=list()
for i in range(len(a)-1):
b.append(a[i])
if int(a[i])%2==1 and int(a[i+1])%2==1:
b.append('-')
if int(a[i])%2==0 and int(a[i+1])%2==0:
b.append('*')
b.append(a[i+1])
print(b)
b = ''.join(str(e) for e in b) #how to list to string
print(b)
|
fb3c128f7b232eda2fea37853247a0aa1544c8f4 | parkseohui/git | /List comprehension.py | 107 | 3.5 | 4 | a=[1,2,3,4]
result=[]
for num in a:
result.append(num*3)
#리스트내포
result=[num*3 for num in a]
|
22ae7593d42eb116cf4739471a01200a7a3ec8c5 | parkseohui/git | /dictest.py | 461 | 3.515625 | 4 | #딕셔너리표현하기!!
ha={'나':1 , '너':2 , '우리':3}
for h in ha:
print(h) #이렇게하면 키값만 나오네!
for h in ha.keys():
print(h) #위와 똑같군
for h in ha.values():
print(h) #이건 밸류값만 나오는군
for h in ha.keys():
print('{}의 숫자는 {}입니다.'.format(h,ha[h])) #키와 밸류
for key,value in ha.items():
print('{}의 숫자는 {}입니다.'.format(key,value)) #키와 밸류
|
9fbbdf6e7ddc220e5468eadaf4acefbfb56141d1 | daaniel3232/dio-introducao-ao-python | /aula07_calculadora3.py | 569 | 4 | 4 | # como não vai inicializar nada não é necessário usar o método "__init__"
class Calculadora:
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplicacao(self, valor_a, valor_b):
return valor_a * valor_b
def divisao(self, valor_a, valor_b):
return valor_a / valor_b
calculador = Calculadora()
print(calculador.soma(10, 2))
print(calculador.subtracao(5, 3))
print(calculador.divisao(100, 2))
print(calculador.multiplicacao(10, 5))
|
315ace2527ebf89d6e80aea2a47047f0484f5b40 | Owensb/SnapCracklePop | /snapcrackle.py | 457 | 4.125 | 4 | # Write a program that prints out the numbers 1 to 100 (inclusive).
# If the number is divisible by 3, print Crackle instead of the number.
# If it's divisible by 5, print Pop.
# If it's divisible by both 3 and 5, print CracklePop. You can use any language.
i = []
for i in range (1, 101):
if (i % 3 ==0) & ( i % 5 ==0) :
print ('CracklePop')
elif (i % 5 == 0):
print ('Pop')
elif (i % 3 ==0) :
print ('Crackle')
else:
print(i) |
f704e93b06d68c404ffd82852902911ada4d167c | SREEHARI1994/Bioinformatics_specialization | /pattern_count_honors.py | 372 | 3.8125 | 4 |
def pattern_count(text,pattern):
count=0
for letter_index in range(len(text)-len(pattern)):
if text[letter_index:letter_index+len(pattern)]==pattern:
count=count +1
return count
f=open('data.txt')
inp=f.read()
t=inp.split('\n')
text=t[0]
pattern=t[1]
print(pattern_count(text, pattern))
#correct solution for all datasets in challenge |
3f1aa1041c78f7daa41ec99ea09fe69943d2139c | BDRave/Univer | /untitled3/ClothingAccessories.py | 540 | 3.625 | 4 | from Clothes import Clothes
class ClothingAccessories(Clothes):
carried=""
warm=""
def __init__(self, color, size, material, carried, warm):
super(ClothingAccessories, self).__init__(color, size, material)
self.carried=carried
self.warm=warm
def getcolor(self):
return self.color
def getsize(self):
return self.size
def getmaterial(self):
return self.material
def getcarried(self):
return self.carried
def getwarm(self):
return self.warm
|
71be5f13b1e86c0006e7522813dce857eed54bbd | alex-fu/pytest | /http_test/debug.py | 318 | 3.5 | 4 | from functools import wraps
def debug_entry(func):
'''
Decorator that print entry of function
:param func:
:return:
'''
@wraps(func)
def wrapper(*args, **kwargs):
print("=> Enter " + func.__name__)
result = func(*args, **kwargs)
return result
return wrapper
|
0d12dd8d6f4796bd920de55a2e2dab71252caa89 | ruthmd/Data_Structures_Algorithms | /LRU/Cache.py | 846 | 3.515625 | 4 | from collections import deque
class LRU:
def __init__(self, capacity):
self.Q = deque(maxlen=capacity)
def put(self, key):
if key in self.Q:
# if key exists push to the top
self.Q.remove(key)
self.Q.appendleft(key)
def get(self, key):
if key not in self.Q:
return False
# move recetly used key to the top
self.Q.remove(key)
self.Q.appendleft(key)
return True
def refer(self, key):
if not self.get(key):
self.put(key)
def display(self):
print(self.Q)
if __name__ == "__main__":
cache = LRU(5)
cache.refer(1)
cache.refer(11)
cache.refer(14)
cache.refer(1)
cache.refer(18)
cache.refer(17)
cache.refer(15)
cache.refer(14)
cache.refer(13)
cache.display() |
eda726b6a912150ecbb24caade07080ae98a10ad | tyuno123/python-thw | /ex5.py | 627 | 3.71875 | 4 | # More Variables and Printing
my_name = 'William Y.'
my_age = 22
my_height = 173
my_weight = 75
my_eyes = 'Black'
my_teeth = 'White'
my_hair = 'Black'
print "Let's talk about %s." %my_name
print "He's %d cm tall." %my_height
print "He's %d kg heavy." %my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." %(my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." %my_teeth
#This line is tricky, try to get it exactly right.
print "If I add %d, %d and %d I get %d." %(my_age, my_height, my_weight,
my_age + my_height + my_weight)
|
475e858695c7dde18e0b30bc141d644edf3cd98f | chichutschang/6.00.1x-2T2016 | /Week 2/Exercise eval quadratic.py | 336 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 7 21:32:02 2016
@author: chi-chu tschang
"""
def evalQuadratic(a, b, c, x):
'''
a, b, c: numerical values for the coefficients of a quadratic equation
x: numerical value at which to evaluate the quadratic.
'''
# Your code here
return (a * x**2) + (b * x) + c |
b69eef742a8b9c5298ca6780e2796b9e8958cd45 | chichutschang/6.00.1x-2T2016 | /Week 2/Functions Exercise 2.py | 317 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 7 21:46:54 2016
@author: chi-chu tschang
"""
def a(x):
return x + 1
def b(x):
return x + 1.0
def c(x,y):
return x + y
def d(x,y):
return x > y
def e(x, y, z):
return x >= y and x <= z
def f(x, y):
x + y - 2 |
74e94e99cd388035508406b63f184ce8b5c1e8ec | chichutschang/6.00.1x-2T2016 | /Week 1/Exercise 4.4.py | 239 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 2 22:43:35 2016
@author: chi-chu tschang
"""
num = 10
while True:
if num < 7:
print('Breaking out of loop')
break
print(num)
num -= 1
print('Outside of loop') |
5addf368b2b02b23a8e77d314486794a387b9fdc | chichutschang/6.00.1x-2T2016 | /Week 2/Exercise 4.py | 237 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 7 21:59:48 2016
@author: chi-chu tschang
"""
a = 10
def f(x):
return x + a
a = 3
f(1)
x = 12
def g(x):
x = x + 1
def h(y):
return x + y
return h(6)
g(x) |
f09c97c150ae9c1661ed595ed6ca40bde2b4b4b5 | chichutschang/6.00.1x-2T2016 | /Week 1/Exercise for exercise 2.py | 184 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 3 14:52:20 2016
@author: chi-chu tschang
"""
num = 12
print ("Hello!")
for num in range(12, 2, -2):
num -= 2
print (num)
|
51ffc1a8b36f6fc10b3910ecc0c594a4ada317f5 | Olegidse/dead-or-alive | /deadoralive/deadoralive.py | 4,825 | 3.578125 | 4 | import random
import time
import sys
def printM(matr):
for i in range(len(matr)):
for j in range(len(matr[i])):
print(matr[i][j], end = ' ')
if j == len(matr[i])-1:
print('\n')
#Случайное заполнение поля размером a*b
def initDesk(a,b):
Desk = []
random.seed()
for i in range(a):
Desk.append([0] * b)
for i in range(a):
for j in range(b):
Desk[i][j] = random.randint(0,1)
return Desk
#a = 1 - ввод целого числа, a = 0 - ввод строки
def input1(errortext, prompt, a ):
try:
if a == 1:
return int(input(prompt))
if a == 0:
return input(prompt)
except:
print(errortext)
time.sleep(5)
sys.exit()
#Считает количество единиц вокруг одного элемента, проверяет каждый случай его возможного расположения на поле
def count(matr, i, j):
N = len(matr) - 1
M = len(matr[0]) -1
sum = 0
if i == 0 and not (j == M or j == 0):
sum = matr[0][j-1] + matr[0][j+1] + matr[1][j-1] + matr[1][j] + matr[1][j+1]
elif i == N and not (j == 0 or j == M):
sum = matr[N][j-1] + matr[N][j+1] + matr[N-1][j-1] + matr[N-1][j] + matr[N-1][j+1]
elif j == 0 and not (i == 0 or i == N):
sum = matr[i-1][0] + matr[i+1][0] + matr[i-1][1] + matr[i][1] + matr[i+1][1]
elif j == M and not (i == 0 or i == N):
sum = matr[i-1][M] + matr[i+1][M] + matr[i-1][M-1] + matr[i][M-1] + matr[i+1][M-1]
elif i == 0 and j == 0:
sum = matr[0][1] + matr[1][0] + matr[1][1]
elif i == 0 and j == M:
sum = matr[0][M-1] + matr[1][M-1] + matr[1][M]
elif i == N and j == 0:
sum = matr[N][1]+ matr[N-1][0]+ matr[N-1][1]
elif i == N and j == M:
sum = matr[N][M-1] + matr[N-1][M] + matr[N-1][M-1]
else:
sum = matr[i-1][j-1] + matr[i-1][j] + matr[i-1][j+1] + matr[i][j-1]+ matr[i][j+1] + matr[i+1][j-1] + matr[i+1][j] + matr[i+1][j+1]
return sum
#создаёт считает кол-во единиц вокруг каждого элемента, создаёт новое изменённое состояние и передаёт его в эту же функцию
def loop(N,M,Desk,counter):
counter += 1
print()
NewDesk = []
for i in range(N):
NewDesk.append([0] * M)
for i in range(N):
for j in range(M):
if Desk[i][j] == 1:
if count(Desk,i,j) < 2 or count(Desk,i,j) > 3:
NewDesk[i][j] = 0
else: NewDesk[i][j] = 1
if Desk[i][j] == 0:
if count(Desk,i,j) == 3:
NewDesk[i][j] = 1
else: NewDesk[i][j] = 0
print('Состояние ',counter,': ')
print()
printM(NewDesk)
time.sleep(1)
loop(N,M,NewDesk,counter)
print('Выберите способ получения стартового состояния:')
print('0 - случайное стартовое состояние')
print('1 - считывание из файла')
A = input1('Неверный ввод!','',1)
if A == 0: #случайное заполненение с вводом размеров поля
N = input1('Неверный ввод!', 'Введите количество строк: ',1)
M = input1('Неверный ввод!', 'Введите количество столбцов: ',1)
Desk = initDesk(N,M)
print('Состояние 1:')
print()
printM(Desk)
time.sleep(1)
loop(N,M,Desk,1)
if A == 1: #считывание стартового состояния из файла
file = input1('Неверный ввод!','Введите имя файла: ',0)
try:
f = open(file, 'r')
except:
print('Неверное имя файла!')
time.sleep(5)
sys.exit
N = 0
M = len(f.readline())-1 #количество столбцов
print(M)
f.seek(0)
for line in f: #Считаем кол-во строк
N += 1
Desk = [] #создаём поле размером N*M, заполненное нулями
for i in range(N):
Desk.append([0] * M)
i = -1
j = -1
f.seek(0)
for line in f: #Заполняем поле числами из файла
i+=1
for symb in line:
j+=1
if not symb == '\n':
try:
Desk[i][j] = int(symb)
except:
print('Неверно задано поле')
time.sleep(5)
sys.exit()
else: j = -1
f.close()
print('Состояние 1:')
print()
printM(Desk)
time.sleep(1)
loop(N,M,Desk,1)
|
bee754461d6e09c17c20690040a74775a3720a87 | LucasGuimar/Atividade---Linguagem-de-Programa-o-Python | /04.py | 335 | 3.78125 | 4 | #coding: utf-8
'''Atividade 4: Implementar uma função que retorne verdadeiro se o número for primo
(falso caso contrário). Testar de 1 a 100.'''
num = int(input('Digite um número: '))
tdiv = 0
for c in range(1, num + 1):
if num % c == 0:
tdiv += 1
if tdiv == 2:
print('VERDADEIRO!')
else:
print('FALSO!')
|
672da5248da9a9a9ede263382231f9dd4707a88f | mr-shubhamsinghal/Data-Structure | /insetion_sort_test.py | 214 | 3.5 | 4 | arr = [7, 5, 4, 2, 3, 1]
n = len(arr)
for i in range(1, n):
num = arr[i]
hole = i
while hole > 0 and arr[hole-1] > num:
arr[hole] = arr[hole-1]
hole -= 1
arr[hole] = num
print(arr)
|
da0aeaaac4388f01fee9cff8930e882700c1e867 | Ganesh658/Snake_Game | /python-game-updated.py | 8,322 | 3.5625 | 4 | # turtle
import turtle
import time
import random
delay = 0.1
delay_2 = 0.1
# Score
score = 0
high_score = 0
score_2 = 0
high_score_2 = 0
# Set up the screen
wn = turtle.Screen()
wn.title("Snake Game by @Team 3")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0) # Turns off the screen updates
wn_2 = turtle.Screen()
wn_2.title("Snake Game by @Team 3")
wn_2.bgcolor("green")
wn_2.setup(width=600, height=600)
wn_2.tracer(0) # Turns off the screen updates
# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("turtle")
head.color("black")
head.penup()
head.goto(30,10)
head.direction = "stop"
head_2 = turtle.Turtle()
head_2.speed(0)
head_2.shape("turtle")
head_2.color("yellow")
head_2.penup()
head_2.goto(0,0)
head_2.direction = "stop"
# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)
food_2 = turtle.Turtle()
food_2.speed(0)
food_2.shape("circle")
food_2.color("orange")
food_2.penup()
food_2.goto(0,100)
segments = []
segments_2 = []
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0", align="center", font=("Courier", 24, "normal"))
pen_2 = turtle.Turtle()
pen_2.speed(0)
pen_2.shape("square")
pen_2.color("white")
pen_2.penup()
pen_2.hideturtle()
pen_2.goto(0, 230)
pen_2.write("Score: 0", align="center", font=("Courier", 24, "normal"))
# Functions
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
def go_up_2():
if head_2.direction != "down":
head_2.direction = "up"
def go_down_2():
if head_2.direction != "up":
head_2.direction = "down"
def go_left_2():
if head_2.direction != "right":
head_2.direction = "left"
def go_right_2():
if head_2.direction != "left":
head_2.direction = "right"
def move_2():
if head_2.direction == "up":
y_2 = head_2.ycor()
head_2.sety(y_2 + 20)
if head_2.direction == "down":
y_2 = head_2.ycor()
head_2.sety(y_2 - 20)
if head_2.direction == "left":
x_2 = head_2.xcor()
head_2.setx(x_2 - 20)
if head_2.direction == "right":
x_2 = head_2.xcor()
head_2.setx(x_2 + 20)
# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
wn_2.listen()
wn_2.onkeypress(go_up_2, "i")
wn_2.onkeypress(go_down_2, "k")
wn_2.onkeypress(go_left_2, "j")
wn_2.onkeypress(go_right_2, "l")
# Main game loop
while True:
wn.update()
wn_2.update()
# Check for a collision with the border
if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
time.sleep(1)
head.goto(30,10)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
pen.clear()
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
if head_2.xcor()>290 or head_2.xcor()<-290 or head_2.ycor()>290 or head_2.ycor()<-290:
time.sleep(1)
head_2.goto(0,0)
head_2.direction = "stop"
# Hide the segments
for segment_2 in segments_2:
segment_2.goto(1000, 1000)
# Clear the segments list
segments_2.clear()
# Reset the score
score_2= 0
# Reset the delay
delay_2 = 0.1
pen_2.clear()
pen_2.write("Score: {}".format(score_2), align="center", font=("Courier", 24, "normal"))
# Check for a collision with the food
if head.distance(food) < 20:
# Move the food to a random spot
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x,y)
# Add a segment
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("turtle")
new_segment.color("black")
new_segment.penup()
segments.append(new_segment)
# Shorten the delay
delay -= 0.001
# Increase the score
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
if head_2.distance(food_2) < 20:
# Move the food to a random spot
x_2 = random.randint(-290, 290)
y_2 = random.randint(-290, 290)
food_2.goto(x_2,y_2)
# Add a segment
new_segment_2 = turtle.Turtle()
new_segment_2.speed(0)
new_segment_2.shape("turtle")
new_segment_2.color("magenta")
new_segment_2.penup()
segments_2.append(new_segment_2)
# Shorten the delay
delay_2 -= 0.001
# Increase the score
score_2 += 10
if score_2 > high_score_2:
high_score_2 = score_2
pen_2.clear()
pen_2.write("Score: {}".format(score_2), align="center", font=("Courier", 24, "normal"))
# Move the end segments first in reverse order
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
# Move segment 0 to where the head is
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x,y)
for index in range(len(segments_2)-1, 0, -1):
x_2 = segments_2[index-1].xcor()
y_2 = segments_2[index-1].ycor()
segments_2[index].goto(x_2, y_2)
# Move segment 0 to where the head is
if len(segments_2) > 0:
x_2 = head_2.xcor()
y_2 = head_2.ycor()
segments_2[0].goto(x_2,y_2)
move()
move_2()
# Check for head collision with the body segments
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
# Update the score display
pen.clear()
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
for segment_2 in segments_2:
if segment_2.distance(head_2) < 20:
time.sleep(1)
head_2.goto(0,0)
head_2.direction = "stop"
# Hide the segments
for segment_2 in segments_2:
segment_2.goto(1000, 1000)
# Clear the segments list
segments_2.clear()
# Reset the score
score_2 = 0
# Reset the delay
delay_2 = 0.1
# Update the score display
pen_2.clear()
pen_2.write("Score: {} ".format(score_2), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
time.sleep(delay_2)
wn.mainloop()
|
20db204b1fb6db98751c9fa3c74acab9e95ae1d7 | Byhako/python | /scripts/calendario.py | 5,951 | 3.9375 | 4 | """
Me das una fecha y te digo si sera año bifiesto, cuantos dias an
pasado desde el 15/10/1582, y la fecha en el calendario juliano.
Ruben E Acosta
2016-02-27
"""
import time
print('**************************************************')
print('Enter a date after 14/10/1582 and before 1/1/3700')
print('**************************************************')
A=int(input('Enter the year: '))
if A<1582: print('WRONG YEAR')
M=int(input('Enter the month: '))
if M>12: print('WRONG MONTH')
D=int(input('Enter the day: '))
inicio=time.time()
if D<1 or D>31: print('WRONG DAY')
if A==1582 and M<=9: print('WRONG DATE')
m=M
if A>1582:
a=A-1583
else:
a=0
if m==9:
dm1=0
elif m==10:
dm1=16
elif m==11:
dm1=46
da=int(a*365.242198074) #dias en el numero de años
#dias en meses
if m==1:
dm=0
elif m==2:
dm=31
elif m==3:
dm=59
elif m==4:
dm=90
elif m==5:
dm=120
elif m==6:
dm=151
elif m==7:
dm=181
elif m==8:
dm=212
elif m==9:
dm=243
elif m==10:
dm=273
elif m==11:
dm=304
elif m==12:
dm=334
if A==1582:
if m==10:
dm=0
elif m==11:
dm=16
elif m==12:
dm=46
#verifico si es bisiesto
bi=0
if A%4==0:
if A%400==0:
bi=1
elif A%100!=0:
bi=1
if bi==1:
dm=dm+1
print('Gregorian Leap year')
print('')
else:
print('')
##**************************************************
#numero de dias total desde fecha hasta 15/10/1582
if A>1582:
dg=da+dm+D+77
elif A==1582 and m==10:
dg=da+dm+D-15
else:
dg=da+dm+D
print('Gregorian Days:',dg)
if A<3000:
d=int(dg*365.248/365.246599+1)
else:
d=int(dg*365.248/365.246599)
print('Julian Days: ',d)
###*************************************************
#Calculamos el ano juliano
if d<149:
ano=1582
anos=0
else:
anos=int((d-148)/365.25)
ano=anos+1583
if ano%4!=0:
ban=1
else:
ban=0
print('Julian year: ',ano)
#dias restantes en ano
if ano==1582:
dr=217+d
else:
dr=d-148-int(anos*365.25)
#DETERMINO EL MES
if dr>0 and dr<32:
mes=1
elif dr>31 and dr<62:
mes=2
elif dr>61 and dr<93:
mes=3
elif dr>92 and dr<123:
mes=4
elif dr>122 and dr<152:
mes=5
elif dr>152 and dr<183:
mes=6
elif dr>182 and dr<214:
mes=7
elif dr>213 and dr<244:
mes=8
elif dr>243 and dr<275:
mes=9
elif dr>274 and dr<305:
mes=10
elif dr>304 and dr<336:
mes=11
elif dr>335:
mes=12
#hallo cantidad de dias en esos meses
if mes==1:
dm2=0
elif mes==2:
dm2=31
elif mes==3:
dm2=61
elif mes==4:
dm2=92
elif mes==5:
dm2=122
elif mes==6:
dm2=152
elif mes==7:
dm2=182
elif mes==8:
dm2=213
elif mes==9:
dm2=243
elif mes==10:
dm2=274
elif mes==11:
dm2=304
elif mes==12:
dm2=335
df=int(dr-dm2)
print('')
print('*************************')
print('Gregorian calendar date: ')
print('D:',D,'M:',m,'Y:',A,'\n')
print('Julian calendar date: ')
print('D:',df,'M:',mes,'Y:',ano)
print('*************************','\n')
"""
El calendario juliano es usado entre 46 ac y el 4 de octubre de 1582
El calendario juliano toma el año como de 325.25 dias exactos. Este desface hace que se adelante 11.23 minutos por año y entre el año 325dc y 1582dc se acumula un desface de 9.87 dias entre el año tropical y el calendario juliano, pero se aproxima a 10 dias de desface.
Únicamente en el año 46 ac, se contaron 445 días, en vez de los 365 normales, para corregir los desfases del calendario anterior, y se le llamó año de la confusión. Para ello, se agregaron dos meses, entre noviembre y diciembre, uno de 33 días y otro de 34, además del mes intercalado en febrero.
Luego pasaron muchas cosas con la iglesia y el calendario se modifico mucho hasta que se estandarizo en el 44 dc!
Antes de 153dc al año comenzaba el 1 de marzo, pero a partir de este año comienza el 1 de enero.
En el año 321 d. C., el emperador Constantino I el Grande implantó la semana de siete días.
El calendario juliano cuenta como bisiestos uno de cada cuatro años, incluso los seculares. Con este calendario se comete un error de 3 días cada 400 años.
El año tropico dura 365.242198074 dias o 365 dias, 5 horas, 48 minutos, 45.25 segundos.
El calendario gragoriano aproxima el año a 365.2425 dias.
Calendario gregoriano desde el 15 de octubre de 1582.
El primer año bisiesto en calendario gregoriano es 1584.
Un año es bisiesto si es divisible entre 4, excepto el último de cada siglo (aquel divisible por 100), salvo que este último sea divisible por 400.
El papa Gregorio XIII, asesorado por el astrónomo jesuita Christopher Clavius promulgó,el 24 de febrero de 1582, la bula Inter gravísimas en la que establecía que tras el, jueves 4 de octubre de 1582 seguiría el viernes 15 de octubre de 1582. Por tal razón, las fechas del 5 de octubre de 1582 al 14 de octubre de 1582 no existen.
Hay 77 dias entre el 15/10/1582 y 1/1/1583
ya que los meses estan en diferente orden, trabajo por separado para el año 1582 y para los demas.
Primero determino el numero de dias total que hay entre la fecha dada y el 15/10/1582
En el total de dias (d) sumo 77, porque hay 77 dias desde el 15/10/1582 hasta fin de año en gregoriano, y el calculo de las otras cantidades es desde fecha hasta el 1/1/1583.
En linea 68 pongo d<149, porque en calendario juliano fantan 148 dias para acabar el año desde el 4/10 por eso mismo lo resto en la linea 72 y en la 79.
En linea 77 sumo 217 pues hay 217 dias desde inicio de año hasta 4/10.
df, son los dias que quedan luego de restar la cantidad de dias en meses acumulados al total de dias que teniamos en el año (dias restantes.)
"""
fin=time.time()
print('Tiempo de ejecucion: ', fin-inicio) |
f08a569896e35f58a043cef6eff1414cb1a73300 | Byhako/python | /scripts/factores_primos.py | 1,002 | 3.6875 | 4 | n = int(input('Ingresa un número natural: '))
print('\nLos fatores primos para los números ente 2 y',n,'son:\n')
primos = [2]
def addPrimo():
"""
agrego le siguiente primo a la lista primos
"""
numero = primos[-1] # last primo
while True:
numero += 1
for primo in primos:
if not numero%primo:
break
if not numero % primo:
continue
else:
primos.append(numero)
break
for i in range(2,n+1):
numero = i
lista = []
while True:
for primo in primos:
while numero%primo==0:
lista.append(primo)
numero = numero/primo
if numero==1: break
if numero==1:
print(i,'-->',lista)
break
else:
addPrimo()
"""
Verifico que el numero pueda ser dividido entre primo(29), si es asi, agrego ese
primo a la lista(30), y continuo con el resultado de la division.
Si numero/primo = 0 entonces ya termine y salgo(32,34), si no, entonces agrego
el siguiente primo a la lista y repito el proceso.
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.