blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1e666feea83a663bb021d98ade704d2fb69f0287 | gabrielvtan/ByteAcademy-FullStack | /Phase1/Week1/Python/1.3_4-Read-McNugget-Matrix-Hanoi/2-mcnugget-numbers/tempCodeRunnerFile.py | 263 | 3.71875 | 4 | for number in range(1, n+1):
for a in range(0,n):
for b in range(0,n):
for c in range(0,n):
if 6*a + 9*b + 20*c == number:
McNuggets.append(number)
|
e123a1450ec795a3ba1e560cdd8ecd30bfb7f609 | Little-Captain/py | /PyQt/ifelse4.py | 127 | 3.765625 | 4 | m = input("Enter marks: ")
if m.isdigit():
print("Entered data is numeric")
else:
print("Entered data is not numeric")
|
1579b499879033d4c06cdbf0aba92bc8fc3851ab | MakhmoodSodikov/tehnikum_telegram_course | /class_4/seminar_code/методы_строк.py | 378 | 3.984375 | 4 | a = 'Aziz' # Имя.
a = a.lower() # Мы приравниваем переменную типа str() к самой себе, но все буквы маленькие.
print(a) # Вывод имени.
a = 'aziz'
a = a.capitalize() # Мы приравниваем переменную типа str() к самой себе, но с заглавной буквы.
print(a) |
65efa7932ca61c23db6cc3de716769809ba7b515 | yosifnandrov/softuni-stuff | /list,advanced/heart delivery.py | 1,051 | 3.71875 | 4 | hood = input().split("@")
hood = [int(i) for i in hood]
jumps = input()
current_index = 0
counter = 0
while not jumps == "Love!":
action, index = jumps.split()
index = int(index)
current_index += index
if current_index > len(hood) - 1:
current_index = 0
if hood[current_index] == 0:
print(f"Place {current_index} already had Valentine's day.")
jumps = input()
continue
else:
hood[0] -= 2
else:
if hood[current_index] == 0:
print(f"Place {current_index} already had Valentine's day.")
jumps = input()
continue
else:
hood[current_index] -= 2
if hood[current_index] == 0:
print(f"Place {current_index} has Valentine's day.")
jumps = input()
print(f"Cupid's last position was {current_index}.")
for n in range(len(hood)):
if hood[n] > 0:
counter += 1
if counter > 0:
print(f"Cupid has failed {counter} places.")
if counter == 0:
print("Mission was successful.")
|
ba9f4246e10461a6a9ef13b1471a365b985a1d6a | brianhans/illuminati_tweet_generator | /markov/hashtable.py | 6,331 | 4.09375 | 4 | #!python
from linkedlist import LinkedList
class KeyValuePair:
def __init__(self, key, value):
self.key = key
self.value = value
def __eq__(self, other):
return other == self.key
class HashTable(object):
def __init__(self, init_size=8):
"""Initialize this hash table with the given initial size"""
self.buckets = [LinkedList() for i in range(init_size)]
def __repr__(self):
"""Return a string representation of this hash table
Returns:
hashtable: str
"""
return 'HashTable({})'.format(self.keys())
def _bucket_index(self, key):
"""Return the bucket index where the given key would be stored"""
return hash(key) % len(self.buckets)
def length(self):
"""Return the length of this hash table by traversing its buckets
Best case running time: Om(n) and
Worst case running time: O(n) because we have to loop through all
the elements.
Returns:
length: int
"""
total = 0
for bucket in self.buckets:
total += bucket.length()
return total
def contains(self, key):
"""Return True if this hash table contains the given key, or False
Returns:
isContained: Bool
"""
try:
self.get(key)
except KeyError:
return False
return True
def get(self, key):
"""Return the value associated with the given key, or raise KeyError
Best case running time: Om(1) if the bucket has only one or less elements
Worst case running time: O(n) if all the elements are in one bucket.
Returns:
value: Any
Throws:
KeyError: If key doesn't exist
"""
index = self._bucket_index(key)
item = self.buckets[index].find(lambda item: item == key)
if(item):
return item.value
raise KeyError
def set(self, key, value):
"""Insert or update the given key with its associated value
Best case running time: Om(1) if the bucket is empty
Worst case running time: O(n^2) if the bucket has many elements in it.
"""
index = self._bucket_index(key)
bucket_item = self.buckets[index].find(lambda item: item == key)
if(bucket_item):
bucket_item.value = value
else:
self.buckets[index].append(KeyValuePair(key, value))
def update_value(self, key, function):
"""Update the given key by applying the function
Best case running time: Om(1) if the bucket is empty
Worst case running time: O(n^2) if the bucket has many elements in it.
Keyword arguments:
key: the key that you want to update the value
function: lambda function which updates the value (ie x: x + 1)
"""
index = self._bucket_index(key)
bucket_item = self.buckets[index].find(lambda item: item == key)
if(bucket_item):
bucket_item.value = function(bucket_item.value)
else:
raise KeyError
def delete(self, key):
"""Delete the given key from this hash table, or raise KeyError
Best case running time: Om(1) if the bucket is empty
Worst case running time: O(n) if the bucket has all the elements in it.
Throws:
KeyError: If the key doesn't exist
"""
if not self.get(key):
raise KeyError
index = self._bucket_index(key)
self.buckets[index].delete(key)
def keys(self):
"""Return a list of all keys in this hash table
Best case running time: Om(n) and
Worst case running time: O(b+n) because it has to got through all the elements.
Returns:
keys: [Any]
"""
keys = []
for bucket in self.buckets:
bucket_keys = map(lambda x: x.key, bucket.as_list())
keys.extend(bucket_keys)
return keys
def values(self):
"""Return a list of all values in this hash table
Best case running time: Om(n) and
Worst case running time: O(b+n) bceause it has to got through all the elements.
Returns:
values: [Any]
"""
values = []
for bucket in self.buckets:
bucket_values = map(lambda x: x.value, bucket.as_list())
values.extend(bucket_values)
return values
def clear(self):
"""Remove all items from the dictionary.
Best case running time: Om(n) and
Worst case running time: O(n) because it has to got through all the buckets."""
self.buckets = [LinkedList() for i in range(len(self.buckets))]
def iteritems(self):
for bucket in self.buckets:
for item in bucket:
yield (item.key, item.value)
def __iter__(self):
for bucket in self.buckets:
for value in bucket.as_list():
yield value.value
def create_hashtable(amount):
hash_table = HashTable()
for i in range(0, amount):
hash_table.set('test' + str(i), 'none')
return hash_table
def lengthCheck(amount):
hash_table = create_hashtable(amount)
timer = Timer()
length = hash_table.length()
return timer.stop()
def setCheck(amount):
timer = Timer()
create_hashtable(amount)
return timer.stop()
def deleteCheck(amount):
hash_table = create_hashtable(amount)
keys = hash_table.keys()
timer = Timer()
for i in range(0, amount):
hash_table.delete(keys[i])
return timer.stop()
def getCheck(amount):
hash_table = create_hashtable(amount)
keys = hash_table.keys()
timer = Timer()
for i in range(0, amount):
hash_table.get(keys[i])
return timer.stop()
def performance_test(function, first_amount, second_amount):
first_test = function(first_amount)
second_test = function(second_amount)
print("Percent difference for " + function.__name__ + " " + str(second_test / first_test))
if __name__ == '__main__':
performance_test(setCheck, 100, 10000)
performance_test(deleteCheck, 100, 10000)
performance_test(lengthCheck, 100, 10000)
performance_test(getCheck, 100, 10000)
|
092fef4d6d5ab8220656f0859bec97f6f323e6f1 | AiZhanghan/Leetcode | /code/290. Word Pattern.py | 906 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 28 14:09:04 2019
@author: Administrator
"""
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
pattern_dict = {}
for i in range(len(pattern)):
if pattern[i] not in pattern_dict:
pattern_dict[pattern[i]] = (i, )
else:
pattern_dict[pattern[i]] = pattern_dict[pattern[i]] + (i, )
str_dict = {}
str_list = str.split()
for i in range(len(str_list)):
if str_list[i] not in str_dict:
str_dict[str_list[i]] = (i, )
else:
str_dict[str_list[i]] = str_dict[str_list[i]] + (i, )
return list(pattern_dict.values()) == list(str_dict.values())
if __name__ == '__main__':
pattern = "abba"
_str = "dog cat cat dog"
print(Solution().wordPattern(pattern, _str)) |
13945849aec8a776b7e712fd1fc6d9b60c58548b | LYXalex/Leetcode-PythonSolution | /tree/222. Count Complete Tree Nodes.py | 931 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# O(n)
def countNodes1(self, root: TreeNode) -> int:
if not root:
return 0
l = self.countNodes(root.left)
r = self.countNodes(root.right)
return l + r + 1
# since left hegiht always >= right hegiht
## time complexity: O(log(n)*log(n))
def countNodes(self, root: TreeNode) -> int:
def getDepth(node):
if not node:
return 0
return 1 + getDepth(node.left)
if not root:
return 0
l = getDepth(root.left)
r = getDepth(root.right)
if l == r:
return 2 ** l + self.countNodes(root.right)
else:
return 2 ** r + self.countNodes(root.left)
|
8a83556fb8fb512abda5bb0b8bc0f1466cd0baba | Dnurudeen/alx-higher_level_programming | /0x04-python-more_data_structures/10-best_score.py | 391 | 4.03125 | 4 | #!/usr/bin/python3
def best_score(a_dictionary):
"""
A function that returns a key with the biggest integer value.
"""
if a_dictionary:
my_list = list(a_dictionary.keys())
score = 0
leader = ""
for i in my_list:
if a_dictionary[i] > score:
score = a_dictionary[i]
leader = i
return leader
|
539c9f90699a649f21b1b6619c30edb090f6bcbc | Vjaiswal07/class-97 | /Main.py | 309 | 4.15625 | 4 | intro=input("enter your introduction: ")
print(intro)
characterCount=0
wordCount=1
for character in intro:
characterCount=characterCount+1
if(character==' '):
wordCount=wordCount+1
print("number of characters in intro")
print(characterCount)
print("number of words in intro")
print (wordCount) |
beae93793dd74e99d98d4ccfcceee49c88f03855 | Kim00n/PLParser | /src/tokenType.py | 649 | 3.515625 | 4 | import re
from src.token import Token
class TokenType():
# describe a type of token according a given pattern (regex)
# This class can test if a source match the pattern and return the relevant token
def __init__(self, type, pattern):
self.token_type = type
self.re_token = re.compile(pattern)
def match_token(self, source, startPos):
self.last_value = None
token_match = self.re_token.match(source, startPos)
if (token_match is not None and token_match.group() != ''):
token = Token(self.token_type, token_match.group(0), startPos)
return token
return None |
65dff0388e001708156035d18786cc8e1acee947 | indrajeet-droid/PythonPractice | /15_2D_list.py | 196 | 3.875 | 4 | #2D lists = a list of lists
drinks = ["coffee","soda","tea"]
dinner = ["pizza","hamburger","hotdog"]
dessert = ["cake","ice cream"]
food = [drinks,dinner,dessert]
print(food)
print(food[0][1])
|
7ad317e4a4e6625e29b8efba5a225fae1d4cf01e | ammuaj/CodeSignal-PySolutions | /leetCode_30DaysOfCode/day_7/counting_elements.py | 676 | 4.125 | 4 | """
problem:
Given an integer array arr, count element x such that x + 1 is also in arr.
If there're duplicates in arr, count them separately.
Ex:
Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
"""
def countElements(arr):
# use a set to store all unique elements in the array
in_arr = set(arr)
ans = 0
# loop through all elements in the array because duplicated are counted separately
for n in arr:
# if the number + 1 in the set (checking an element in a set takes O(1) time)
if n + 1 in in_arr:
ans += 1
return ans
print(countElements([1, 1, 2]))
|
392117ef0844d23c5c04ccd3e59f224484aef7ca | ahrav/Python-Django | /python_practice/interview_prep/string_compression.py | 866 | 3.8125 | 4 | def compress(word):
if len(word) == 1:
return word + str(1)
compressed_string = ''
count = 1
for letter in range(len(word)-1):
if word[letter] == word[letter + 1]:
count += 1
else:
compressed_string = compressed_string + word[letter] + str(count)
count = 1
return compressed_string + word[letter] + str(count)
word = 'a'
print (compress(word))
def compress_string(word):
compressed_string = ''
count = 1
for letter in range(len(word)-1):
if word[letter] == word[letter + 1]:
count += 1
else:
compressed_string = compressed_string + word[letter] + str(count)
count = 1
compressed_string = compressed_string + word[len(word)-1] + str(count)
return compressed_string
word = 'aaabbb'
print (compress_string(word)) |
e4400d62a3da7bcb97304269d3949272852cdb26 | GreenhillTeacher/Python2021 | /listAndTuples.py | 1,478 | 4.4375 | 4 | #MAria Suarez ctrl /
# We are learning about List and Tuples
# Learn their functions and looping with List
# HOw to use a module or library by oimporting
import random
myFruit=["apples","berries", "mangos", "banana"]
print(myFruit)
for fruit in myFruit:
print(fruit)
fruity=("apple", "kiwi", "banana")
print(fruity)
temp=list(fruity)
temp.insert(1,"papaya")
fruity= tuple(temp)
print(fruity)
for fruit in myFruit: # for each element of the array get the element
print(fruit, end=" , ")
print()
counter=len(myFruit) #the lenght of your list is one more than your last index
#finding a random number to be the index to select randint()
indx= random.randint(0,counter-1)
print(indx)
print("your lucky fruit is ", myFruit[indx] )
word=random.choice(myFruit)
print("your lucky fruit is ", word)
input()
#random method choice()
word=random.choice(myFruit)
print("Your random fruit is ", word)
for x in range(0,counter-1):
print(myFruit[x], end=" , ")
print(myFruit[counter-1]) #print the last element
if "apples" in myFruit:
print("Yes you got apples")
myFruit.remove("apples")
print(myFruit)
myFruit.insert(0,"kiwi")
myFruit.insert(2,"papaya")
myFruit.append("beets")
print(myFruit)
fruity=("apple", "pears", "banana") #tuple
print("tuple", fruity)
temp= list(fruity) #temp is a list
print("list",temp)
temp.insert(1,"kiwi")
fruity=tuple(temp)
print("tuple modified ", fruity)
print("list modified ",temp)
for element in fruity:
print(element) |
dbda71570fa32947216b8a4193736d750d7b1491 | 116dariya/PT-lab-1 | /lab1ex3.py | 210 | 3.859375 | 4 | # lab 1 ex 3
a = float(input())
b = float(input())
if a == 0 and b == 0:
print('INF')
elif a == 0 and b != 0:
print('NO')
else:
x = -b/a
x = int(x)
if x == 0:
print('NO')
else:
print(x)
|
9fb1821e8d6e9774b02e8313c29f43c34a49ec8a | yeswanth/Puzzles | /codechef/fctrl.py | 220 | 4.03125 | 4 | def factorial():
a=int(raw_input())
while(a!=0):
b=int(raw_input())
ans=find_factors(b)
print ans
a=a-1
def find_factors(b):
a=5
ans=0
while(b/a!=0):
ans=ans+(b/a)
a=a*5
return ans
factorial()
|
c3edafafddd19450bcacbb39cda079c3b4db5a74 | theOnlyHorst/SPG_1920-5bhif-pos-busch-python-practice | /Day5.py | 4,164 | 3.65625 | 4 |
def runComp():
F= open("Day5-Inputs.txt","r")
numbers = []
line = F.readline()
arr = line.split(",")
for it in arr:
numbers.append(int(it))
ptr =0
while True:
instruction = int(numbers[ptr])
code = instruction%100
instruction/=100
parmMode1 = int(instruction%10)
instruction/=10
parmMode2=int(instruction%10)
instruction/=10
parmMode3 = int(instruction%10)
print("Instruct: "+ str(code))
if code == 1:
num1=0
num2=0
if parmMode1==1:
num1=numbers[ptr+1]
else:
num1 = numbers[numbers[ptr+1]]
if parmMode2==1:
num2=numbers[ptr+2]
else:
num2 = numbers[numbers[ptr+2]]
if parmMode3==1:
numbers[ptr+3]=num1+num2
else:
numbers[numbers[ptr+3]]=num1+num2
ptr+=4
elif code == 2:
num1=0
num2=0
if parmMode1==1:
num1=numbers[ptr+1]
else:
num1 = numbers[numbers[ptr+1]]
if parmMode2==1:
num2=numbers[ptr+2]
else:
num2 = numbers[numbers[ptr+2]]
if parmMode3==1:
numbers[ptr+3]=num1*num2
else:
numbers[numbers[ptr+3]]=num1*num2
ptr+=4
elif code ==3:
numIn = int(input())
if parmMode1==1:
numbers[ptr+1] = numIn
else:
numbers[numbers[ptr+1]]= numIn
ptr+=2
elif code ==4:
if parmMode1==1:
print(numbers[ptr+1])
else:
print(numbers[numbers[ptr+1]])
ptr+=2
elif code ==5:
parm1=0
parm2=0
if parmMode1==1:
parm1 = numbers[ptr+1]
else:
parm1 = numbers[numbers[ptr+1]]
if parmMode2==1:
parm2=numbers[ptr+2]
else:
parm2=numbers[numbers[ptr+2]]
if parm1!=0:
ptr=parm2
else:
ptr+=3
elif code ==6:
parm1=0
parm2=0
if parmMode1==1:
parm1 = numbers[ptr+1]
else:
parm1 = numbers[numbers[ptr+1]]
if parmMode2==1:
parm2=numbers[ptr+2]
else:
parm2=numbers[numbers[ptr+2]]
if parm1==0:
ptr=parm2
else:
ptr+=3
elif code ==7:
parm1=0
parm2=0
if parmMode1==1:
parm1 = numbers[ptr+1]
else:
parm1 = numbers[numbers[ptr+1]]
if parmMode2==1:
parm2=numbers[ptr+2]
else:
parm2=numbers[numbers[ptr+2]]
if parm1<parm2:
if parmMode3==1:
numbers[ptr+3]=1
else:
numbers[numbers[ptr+3]]=1
else:
if parmMode3==1:
numbers[ptr+3]=0
else:
numbers[numbers[ptr+3]]=0
ptr+=4
elif code ==8:
parm1=0
parm2=0
if parmMode1==1:
parm1 = numbers[ptr+1]
else:
parm1 = numbers[numbers[ptr+1]]
if parmMode2==1:
parm2=numbers[ptr+2]
else:
parm2=numbers[numbers[ptr+2]]
if parm1==parm2:
if parmMode3==1:
numbers[ptr+3]=1
else:
numbers[numbers[ptr+3]]=1
else:
if parmMode3==1:
numbers[ptr+3]=0
else:
numbers[numbers[ptr+3]]=0
ptr+=4
elif code == 99:
break
else:
print("Error Illegal Opcode")
break
runComp() |
249836c577560361ff81acdc892e3ea5bedca8c3 | newstar123/Pythonlab_DEV | /Taining/Books/Core Python Programming 2nd Edition/Chapter 6/idcheck.py | 1,055 | 3.984375 | 4 | #!/usr/bin/env python
#coding:utf-8
import string
alphas = string.letters + '_'
nums = string.digits
print 'Welcome to the Identifier Checker v1.0'
print 'Testees must be at least 2 chars long.'
myInput = raw_input('Identifier to test? ')
if len(myInput) > 1:
if myInput[0] not in alphas:
print '''invalid: first symbol must be alphabetic'''
else:
for otherChar in myInput[1:]:
if otherChar not in alphas + nums:
print '''invalid: remaning symbols must be alphanumric'''
break
else:
print "okay as an identifier"
'''
运行结果:
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.
Identifier to test? abc
okay as an identifier
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.
Identifier to test? 123abc
invalid: first symbol must be alphabetic
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.
Identifier to test? abc%^
invalid: remaning symbols must be alphanumric
'''
|
da52eddd9aab7292162cca9f2e597172343cf8a8 | nishilab1226/sutikaiseki | /report_1/ensyu3.py | 527 | 3.53125 | 4 | from math import *
a = c = 1
b = 1.0e5
x1_b = lambda a,b,c:(-b+sqrt(b**2-a*c))/a
x2_b = lambda a,b,c:(-b-sqrt(b**2-a*c))/a
x1_a = lambda a,b,c:-c/(b+sqrt(b**2-a*c))
x2_a = lambda a,b,c:c/(-b+sqrt(b**2-a*c))
print("\nb>0 : ")
print(f"before_ans = ( x1 = {x1_b(a,b,c)} , x2 = {x2_b(a,b,c)} )")
print(f"after_ans = ( x1 = {x1_a(a,b,c)} , x2 = {x2_b(a,b,c)} )")
print("-"*80)
print("b<0 : ")
print(f"before_ans = ( x1 = {x1_b(a,-b,c)} , x2 = {x2_b(a,-b,c)} )")
print(f"after_ans = ( x1 = {x1_b(a,-b,c)} , x2 = {x2_a(a,-b,c)} )") |
432f6054388a6f682ac95889635fd2ca18b28b7f | qeedquan/challenges | /codeforces/1367B-even-array.py | 2,181 | 3.921875 | 4 | #!/usr/bin/env python
"""
You are given an array a[0…n−1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index.
More formally, an array is good if for all i (0≤i≤n−1) the equality i mod 2 =a[i] mod 2 holds, where x mod 2 is the remainder of dividing x by 2.
For example, the arrays [0,5,2,1] and [0,17,0,3] are good, and the array [2,4,6,7] is bad, because for i=1, the parities of i and a[i] are different: i mod 2 = 1 mod 2 = 1, but a[i] mod 2 = 4 mod 2 = 0.
In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).
Find the minimum number of moves in which you can make the array a good, or say that this is not possible.
Input
The first line contains a single integer t (1≤t≤1000) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1≤n≤40) — the length of the array a.
The next line contains n integers a0,a1,…,an−1 (0≤ai≤1000) — the initial array.
Output
For each test case, output a single integer — the minimum number of moves to make the given array a good, or -1 if this is not possible.
Example
input
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
output
2
1
-1
0
Note
In the first test case, in the first move, you can swap the elements with indices 0 and 1, and in the second move, you can swap the elements with indices 2 and 3.
In the second test case, in the first move, you need to swap the elements with indices 0 and 1.
In the third test case, you cannot make the array good.
"""
def goodable(values):
even, odd = 0, 0
for i in range(len(values)):
if i%2 == values[i]%2:
continue
if values[i]%2 == 0:
even += 1
else:
odd += 1
if even != odd:
return -1
return even
def main():
assert(goodable([3, 2, 7, 6]) == 2)
assert(goodable([3, 2, 6]) == 1)
assert(goodable([7]) == -1)
assert(goodable([4, 9, 2, 1, 18, 3, 0]) == 0)
main()
|
b55f37b98ec39a6ee3d61c8a48f1d7f6c9ae8bf3 | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc53_maximum_subarray.py | 1,997 | 3.6875 | 4 | """
https://leetcode.com/problems/maximum-subarray/
(Kadane's Algorithm)
"""
class Solution:
"""
Time complexity: O(n)
Space complexity: O(1)
"""
def maxSubArray(self, nums:[int]) -> int:
maxSumSoFar = -float('inf')
maxSumUpToN = 0
for i,n in enumerate(nums):
if maxSumUpToN + n > n:
maxSumUpToN = maxSumUpToN + n
else:
maxSumUpToN = n
maxSumSoFar = max(maxSumSoFar, maxSumUpToN)
return maxSumSoFar
def maxSubArray_getSubarray(self, nums):
maxSumSoFar = -float('inf')
maxSumUpToN = 0
startIdx = 0
endIdx = 0
for i,n in enumerate(nums):
if maxSumUpToN + n > n:
maxSumUpToN = maxSumUpToN + n
else:
maxSumUpToN = n
startIdx = i
if maxSumUpToN > maxSumSoFar:
maxSumSoFar = maxSumUpToN
endIdx = i
return maxSumSoFar, [startIdx, endIdx]
def test_maxSubArray_getSubarray(self):
a = [-2,1,-3,4,-1,2,1,-5,4] # expected: [4 -1 2 1]
res = self.maxSubArray_getSubarray(a)
print("res: ", res)
indices = res[1]
startIdx, endIdx = indices[0], indices[1]
subArray = a[startIdx: endIdx+1]
print("The actual subarray: ", subArray)
print("The sum: ", sum(subArray))
"""
Time complexity: O(n)
Space complexity: O(n)
"""
def maxSubArray2(self, nums: [int]) -> int:
maxSumUpTo = [0 for _ in range(len(nums))]
maxSumUpTo[0] = nums[0]
maxSoFar = nums[0]
for i in range(1, len(nums)):
n = nums[i]
maxSumUpTo[i] = max(n, maxSumUpTo[i-1]+n)
if maxSumUpTo[i] > maxSoFar:
maxSoFar = maxSumUpTo[i]
return maxSoFar
s = Solution()
s.test_maxSubArray_getSubarray() |
6881679bd7e3ce70926b18490361b12dc681079d | Yosolita1978/first-repository | /richie_rich.py | 1,043 | 3.859375 | 4 |
def make_palindrome(s, k):
"""
Returns a palyndrome version of S.
If more than k edits are needed, returns -1.
>>> make_palindrome("3943",1)
'3993'
>>> make_palindrome("092282",3)
'292292'
>>> make_palindrome("3973",2)
'3993'
>>> make_palindrome("3793",2)
'3993'
>>> make_palindrome("0011",1)
-1
>>> make_palindrome("378983",2)
'389983'
>>> make_palindrome("367873",2)
'378873'
>>> make_palindrome("378873",0)
'378873'
"""
new_word = ""
x = 0
y = len(s)-1
count = 0
while x < y:
if s[x] < s[y]:
new_word = new_word + s[y]
count = count +1
elif s[x] > s[y]:
new_word = new_word + s[x]
count = count + 1
else:
new_word = new_word + s[x]
x = x + 1
y = y - 1
if count > k:
return -1
return new_word + "".join(reversed(new_word))
if __name__ == "__main__":
import doctest
doctest.testmod()
|
b242760608f25e870e74c49c74cbd5b5bd64cde3 | YukaNakadomari/Sample_Object | /testmodule.py | 549 | 3.53125 | 4 | class Test:
def sayStr(self, str):
print(str)
if __name__ == '__main__': # testModule.pyを実行すると以下が実行される(モジュールとして読み込んだ場合は実行されない)
a = Test()
a.sayStr("Hello")
def fibo(n):
result = []
a = 2
b = 1
while b < n:
result.append(b)
val = a + b
b = a
a = val
return result
if __name__ == "__main__":
print("{0}".format(fibo(1000)))
def add(a, b):
return a + b
def sub(a, b):
return a - b
|
59379b54151471e8124b8eba9c1b8cb0d1eeeaf5 | Liam-Hearty/ICS3U-Unit5-03-Python | /convert_marks.py | 1,300 | 4.40625 | 4 | #!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: October 2019
# This program converts a number grade to a percent.
def convert_mark(grade):
# calculate area
new_mark = None
if grade == "4+":
new_mark = 97
elif grade == "4":
new_mark = 90
elif grade == "4-":
new_mark = 83
elif grade == "3+":
new_mark = 78
elif grade == "3":
new_mark = 75
elif grade == "3-":
new_mark = 71
elif grade == "2+":
new_mark = 68
elif grade == "2":
new_mark = 65
elif grade == "2-":
new_mark = 61
elif grade == "1+":
new_mark = 58
elif grade == "1":
new_mark = 55
elif grade == "1-":
new_mark = 51
elif grade == "R":
new_mark = 30
elif grade == "NE":
new_mark = 0
else:
new_mark = "-1"
return new_mark
def main():
# this function gets base and height
# input
grade_from_user = str(input("Enter your grade: "))
print("")
# call functions
new_mark = convert_mark(grade_from_user)
# show results
if new_mark == "-1":
print("Please make sure your number grade is valid or capitalized.")
else:
print("{}%".format(new_mark))
if __name__ == "__main__":
main()
|
c84bdc6bd8c441bd8a9186db9618a9bd47e812da | nezaj/interview-prep | /python/pangram.py | 631 | 4.15625 | 4 | # Pangramps
# https://www.hackerrank.com/challenges/pangrams
import re
NUM_ALPHA = 26 # Numer of letters in the alpha bet
def is_panagram(input):
regex = re.compile('[^a-zA-Z]')
stripped = regex.sub('', input)
transformed = [c.lower() for c in stripped]
if len(set(transformed)) == NUM_ALPHA:
return 'pangram'
else:
return 'not pangram'
t1 = 'We promptly judged antique ivory buckles for the next prize'
t2 = 'We promptly judged antique ivory buckles for the prize'
# print is_panagram(t1)
assert is_panagram(t1) == 'pangram'
assert is_panagram(t2) == 'not pangram'
print 'All tests pass!'
|
252b7e97b3a741d3cad01decc784b2d3e236ba9e | 0Magnetix0/GeeksForGeeksCode | /Data_Structures/Arrays/001Array_Rotations/005rotating_array_on_spot.py | 1,115 | 4.125 | 4 | # mid gives the length of the sub array.
# Dividing the array in half to equating one half to other half.
# The index is incremented by i to get the current index.
def reverse(array, i, j):
mid = j - i
mid //= 2
for k in range(mid):
array[k+i], array[j-1-k] = array[j-1-k] , array[k+i]
#Rotate the first sub array A[:d].
#Rotate the second sub array A[d:].
#Rotate the final array formed.
def rotate(array, n, d):
reverse(array, 0, d)
reverse(array, d, n)
reverse(array, 0, n)
#The size of the array.
print("Enter the size of the array", end = " ")
n = int(input())
#The elements are recoreded here.
print("Enter the array element :: ", end = "")
array = list(map(int,input().split()))
#The no of time's the array needs to be rotated.
print("Enter the time's to be rotated :: ", end = "")
d = int(input())
#performing mod of d with n.
d %= n
#rotate function called here.
rotate(array, n, d)
#printing the array elements after array rotation.
print("The array elements after performing the rotation operation is :: ", end = "")
for x in array:
print(x, end = " ")
print()
|
c1921819df5314ae27796b5b8795552a0b4e49bd | AbhiniveshP/DFS-3 | /MatchSticksToSquare.py | 2,127 | 3.578125 | 4 | '''
Solution:
1. First, check whether the total sum is divisible by 4, sort the array (reverse order).
2. For each sub-group, checking the base condition to be satisified, perform backtracking if the potential sum is
less than the target sum for that sub-group.
3. If the conditions for all 4 sub-groups aren't satisfied => return False, else return True
Time Complexity: O(N.logN + 4 ^ N) ~ O(4 ^ N) -- exponential
Space Complexity: O(H) for recursive stack space + O(1) -- maintain array of size 4 with the sum in each index getting updated by backtracking
~ O(H) where H is the Height of the Recursive Tree
--- Passed all testcases successfully on leetcode.
'''
class Solution:
def __checkHelper(self, nums: List[int], sides: List[int], cursor: int, target: int) -> bool:
# base case check and return true if satisfied
if (cursor == len(nums)):
baseCaseBool = True
for i in range(3):
baseCaseBool = baseCaseBool and (sides[i] == target)
return baseCaseBool
# for each group
for i in range(4):
# if the sum exceeds => continue
if (sides[i] + nums[cursor] > target):
continue
# otherwise, add the current number to the sum and perform backtracking
sides[i] += nums[cursor]
if (self.__checkHelper(nums, sides, cursor + 1, target)):
return True
sides[i] -= nums[cursor]
# return False as if reached here => condition not satisfied
return False
def makesquare(self, nums: List[int]) -> bool:
# edge case check
if (nums == None or len(nums) < 4):
return False
# sort the array and calculate the target for each group out of 4
nums.sort(reverse=True)
totalSum = sum(nums)
if (totalSum % 4 != 0):
return False
target = totalSum / 4
sides = [0 for i in range(4)]
# call backtracking
return self.__checkHelper(nums, sides, 0, target) |
ae79b08e0cd4fb64de63ed0de3fd8b0aea3e9e85 | lawtech0902/py_imooc_algorithm | /剑指offer/57_把二叉树打印成多行.py | 790 | 3.625 | 4 | # _*_ coding: utf-8 _*_
"""
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
__author__ = 'lawtech'
__date__ = '2018/5/9 下午9:56'
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, root):
# write code here
q, res = [root], []
if not root:
return res
while q:
new_q = []
res.append([node.val for node in q])
for node in q:
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
q = new_q
return res
|
9b5acd4612f1f376e66deb95e3bceb0c8b4c26fa | StandOutstar/learnPython | /python打怪之路/python文件读写/basic_csv.py | 314 | 3.734375 | 4 | import csv
question = []
answer = []
with open("newdata.csv", "r", encoding="utf-8") as csvfile:
# 读取csv文件,返回的是迭代类型
read = csv.DictReader(csvfile)
for i in read:
question.append(i['question'])
answer.append(i['answer'])
print(question)
print(answer)
|
23ab00fb5704520dc6bd99fabd951f3fdff77f8c | wickyou23/python_learning | /python3_learning/operators.py | 251 | 4.15625 | 4 | #####Python operators
# x1 = 3/2 #float div
# x2 = 3//2 #interger div
# x3 = 3**2
# x4 = 6%2
# print(x1, x2, x3, x4)
#####Operator Precedence
# x5 = 1+3*2
# print(x5)
#####Augmented Assignment Operator
# x6 = 1
# x6 += 1
# print(x6) |
f8bff257c7099570ce0bd2c09a4c3ec29f20bad3 | aminesabor/Hogeschool-Utrecht | /Opdrachten/les3/3_5.py | 199 | 3.859375 | 4 | # Schrijf een for-loop die over een lijst met getallen itereert, en alle even getallen print.
evens = [x for x in range(10) if x%2 == 0]
print (evens)
# or
for i in range(1, 100, 2):
print(i) |
90cda04073763b8a4bc9cbb165e4ba02fb05d25d | Hemanthtm2/codes | /oddevn.py | 123 | 4.15625 | 4 | #!/usr/bin/python
x=float(raw_input("Enter the input"))
if x%2==0:
print x,'is Even\n'
else:
print x,'is Odd\n'
|
5fda6d271ffc8e4542f4e15387ef49f142a97ecc | gandoufu/algorithms-and-datastructures | /graphs/dijkstra.py | 2,132 | 3.828125 | 4 | """
以下图为例:
A
/ ^ \
6 / | \ 1
/ | \
start 3 end
\ | /
2 \ | / 5
\ | /
B
说明:start(起点) 指向 A 和 B,A 和 B 指向 end(终点),B 指向 A
"""
# 构建图
graph = {}
# 记录各个节点的邻居 (由于要记录邻居是谁,即到达该邻居的开销,所以记录邻居时以字典的形式记录。例:{'start':{'A': 6, 'B': 2}})
graph['start'] = {}
graph['start']['a'] = 6
graph['start']['b'] = 2
graph['a'] = {}
graph['a']['end'] = 1
graph['b'] = {}
graph['b']['a'] = 3
graph['b']['end'] = 5
graph['end'] = {}
# 记录开销的散列表
infinity = float('inf') # 表示无穷大
costs = {}
costs['a'] = 6
costs['b'] = 2
costs['end'] = infinity # 由于初始时,start 到达不了 end,所以先用无穷大表示
# 记录父节点的散列表
parents = {}
parents['a'] = 'start'
parents['b'] = 'start'
parents['end'] = None
# 记录处理过的节点
processed = []
# 相关的数据准备完成,看一下算法执行过程
"""
1. 只要还有要处理的节点
2. 获取离起点最近的节点
3. 更新其邻居的开销
4. 如果有邻居的开销被更新,同时更新其父节点
5. 将第2步的节点标记为已处理
6. 重复以上过程
"""
def find_lowest_cost_node(costs):
lowest_cost = float('inf')
lowest_cost_node = None
for node, cost in costs.items():
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
def find_lowest_cost_path():
node = find_lowest_cost_node(costs)
while node:
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if new_cost < costs[n]:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
find_lowest_cost_path()
print(costs, parents)
|
722f7dcdc0147e6b5a067dca52d783074f8cf55c | Younggle/python_learn | /if test.py | 1,508 | 4.125 | 4 | #------ if test -----
#name=raw_input('Enter User ID:')
#name = 'yangle'
#if name == 'yangle':
# print("hello ,my dad")
#
#else:
# print('go away,')
# ---------------- user loading (if...elif & while)----------------------
# can input times
input_times=5
while input_times >=1:
name = raw_input("what's your name?'")
pass_wd = raw_input("press password:")
if name == 'yangle' and pass_wd == 'yl1234':
print("welcome!")
break
elif name != 'yangle' and pass_wd == 'yl1234':
print('name or password not current')
input_times=input_times-1
remaining_times = str(input_times)
print('you still have ' + remaining_times + ' times to input')
if input_times == 0:
print('you are not allow enter')
break
elif name =='yangle' and pass_wd !='yl1234':
print('name or password not current')
input_times = input_times - 1
remaining_times = str(input_times)
print('you still have '+ remaining_times + ' times to input')
if input_times == 0:
print('you are not allow enter')
break
else:
# print("fuck off!")
print('your password not current')
input_times = input_times - 1
remaining_times=str(input_times)
print('you still have ' + remaining_times + ' times to input')
if input_times == 0:
print('your input times is over,you are not allow enter')
#------------------- |
4545358da83d372f0a01410a0793dfcc6c6d12cd | ali-qdmz/exercises | /radiobutton.py | 277 | 3.703125 | 4 | from tkinter import*
root = Tk()
v = IntVar()
Label(root,text="chose one",justify = LEFT,padx = 20).pack()
Radiobutton(root,text="Python",padx = 20, variable=v,value=1).pack(anchor=W)
Radiobutton(root,text="php",padx = 20,variable=v,value=2).pack(anchor=W)
mainloop()
|
02364108f089e046e75c581832d409a9e2af2cdf | ibardi/PythonCourse | /session06/conditionals.py | 2,385 | 4.40625 | 4 | #THIS PRACTICE IS ABOUT CONDITIONAL STATEMENTS
#Simple if statement
age = 20
if age >= 18:
print('Your age is',age)
print('adult')
#If and else statements
age = 3
if age >= 18:
print("your age is", age)
print ('adult')
else:
print("Your age is", age)
print("teenager")
#Else if statements
age = 3
print('Your age is:', age)
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
#Nested condiitonals
x = 5
y = 10
print("The values specified are: X =", x, "and Y =", y)
if x == y:
print('x and y are equal')
else:
if x < y:
print("x is less than y")
else:
print('x is greater than y')
#Exercise 1
#Problem 1: BMI Calculator (Metric system). Weight in kilograms and height in meters
systemused = str(input("What system would you like to use: 'imperial' or 'metric'"))
if systemused == "imperial":
weight = float(input("Enter your weight in pounds"))
height = float(input("Enter your height in inches"))
bmi = 703 * (weight / (height**2))
roundbmi = round(bmi,2)
elif systemused == "metric":
weight = float(input("Enter your weight in kilograms"))
height = float(input("Enter your height in meters"))
bmi = weight / (height**2)
roundbmi = round(bmi,2)
else:
print("You entered an incorrect system. Check your spelling and make sure you do not use quotation marks!")
if roundbmi <= 18.5:
print("Underweight")
elif roundbmi < 25:
print("Normal weight")
elif roundbmi < 30:
print("Overweight")
else:
print("Obese")
#Problem 2:Two variables VarA and VarB
varA = "Troll"
varB = 55
if isinstance(varA,str) or isinstance(varB,str) == True:
print("String involvled")
else:
if varA > varB:
print("varA is larger than varB")
elif varA == varB:
print("varA and varB is equal")
else:
print("varA is smaller than varB")
#RECURSIONS
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
countdown(3)
def print_n(s,n):
if n<= 0:
return
print(s)
print_n(s, n-1)
print_n("Hello",3)
#This is an example of infinite recursion. BELOW.
def recurse():
recurse()
#ON PURPOSE I AM NOT RUNNING THIS CAUSE IT CAUSES ISSUES. |
006ca474634ab5baff01030f9e493a8078561168 | PhantomSpike/Python_edX | /Week 2/test6.py | 300 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 12:51:50 2019
@author: aleksandar
"""
def f(y):
x = 1
x += 1
print(x)
x = 5
f(x)
print(x)
def g(y):
print(x)
print(x+1)
x = 5
g(x)
print(x)
def h(y):
x = x + 1
x = 5
h(x)
print(x)
|
707ab4207ef5aac260cc6e72209c5fa33e9c49aa | harishramuk/python-handson-exercises | /134. Program for the requirement,input a4b3c2 and expected output aaaabbbcc.py | 171 | 3.546875 | 4 | s =input('enter input:')
output = ''
for x in s:
if x.isalpha():
ch = x
else:
d =int(x)
output=output+ ch*d
print(output)
|
a64b7c97b5f5c9c4ffed41ff0fbe8fa2116b7e75 | ashleymcm/AdventOfCode2017 | /4/4-2.py | 959 | 4.15625 | 4 | from collections import Counter
import itertools
def check_valid_passwords():
count = 0
# take the spreadsheet from the file and split it in an array of "passwords"
with open("input.txt") as password_list:
passwords = [passwords.split() for passwords in password_list]
# loop through all the passwords
for password in passwords:
valid = True
# use itertools to compare each array element to every other array element
for a, b in itertools.combinations(password, 2):
# Counter will count the instances of each char in the strings
if Counter(a) == Counter(b):
# if they are the same then it's an anagram and we set valid to False
valid = False
break # we also break out of the loop to save time
if valid:
# add to the count if it's valid
count = count + 1
return count
check_valid_passwords()
|
1967d27b53df37d26582fb4aef8af90ff8d8228b | omerl2322/Data2U | /models/timer.py | 380 | 3.515625 | 4 | from datetime import datetime
class Timer:
def __init__(self):
self._start_time = datetime.now()
self._duration = None
@property
def start_time(self):
return self._start_time
@property
def duration(self):
return self._duration
def set_duration(self):
self._duration = (datetime.now() - self.start_time).seconds
|
34b0672e53ccae72349a5401e094beeaa27e5d29 | TonyFlury/PythonSmartFormatting | /final.py | 2,231 | 4.09375 | 4 | class Temperature:
_units = {'C':'celsius','F':'fahrenheit'}
def __init__(self, initial):
"""Temperature in C or F with automatic translation between the two
initial : numeric or str. If numeric is assumed to be initial value in degrees C.
If str is assumed to be formatted with last letter C or F:
e.g. '212F' will be taken to be 212 degrees Farenheit.
raises ValueError if str is not formatted correctly (eg. no unit as last letter),
or numeric is not valid converted to a float.
"""
attribute = 'celsius'
try:
attribute = Temperature._units[initial[-1].upper()]
value = initial[:-1]
except KeyError:
raise ValueError(f'Invalid initial Temperature given: {initial}') from None
except TypeError:
value = initial
try:
setattr(self, attribute, float(value))
except (ValueError, TypeError):
raise ValueError(f'Invalid initial Temperature given: {initial}') from None
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
self._celsius = value
@property
def fahrenheit(self):
return 32+(self._celsius/5)*9
@fahrenheit.setter
def fahrenheit(self, value):
self._celsius = 5*(value-32)/9
def __format__(self, format_spec):
"""Addition to the format spec:
if the Type Character is F or C then format the Fahrenheit or Celsius respectively
The rest of the format spec is honoured by default
"""
attribute = Temperature._units.get(format_spec[-1],None)
if not attribute:
return format(self.celsius,format_spec)
else:
return format(getattr(self, attribute),format_spec[:-1]+'f')+'\u00B0'+format_spec[-1]
freezing = Temperature('0C')
boiling = Temperature(100)
print(freezing.fahrenheit, boiling.fahrenheit)
print('f{freezing:0.1C}, {freezing:0.1F}')
print('f{boiling:0.1C}, {boiling:0.1F}')
invalid = Temperature('fredF')
|
a5cf96ac89169261b34e8a14df052064c097b443 | sandhyachowdary/Python | /venv/Global Variable.py | 1,221 | 4.21875 | 4 | #Global Variable
#The variable which is declared inside the python file and outside the function or class are called as global variable
#The Global variable will get memory while running the program
# The scope of global variable is any where .It means we can use through at the python file and another python fine aslo
#Example
a = 100 # Global Variable
def show():
print("Hello")
b= 200 # Local Variable
print(a+b)
c = 300 #Global Variable
print(a+c)
show()
print(a+c)
print("-----------")
#Global and Local Variable
a = 300
def display():
a= 200
print(a)
print(a)
display()
print(a)
print("-----------")
#Declaring global variable inside a function
#To declare global variable inside a function we use "global" keyword
a = "sandhya" #Global Variable
def show():
print(a)
global b
b = 300
c = 400
print(b) #Global Variable
print(b+c) #Local Variable
print(a)
show()
print(a)
print(b)
print("---------")
#The global variable which is declared inside a function will get memory when function is called
#ex: modify global variable inside a function
a = 10
def display():
global a
a = 20
print(a)
print(a)
display()
print(a)
#parameters file after these
|
c349a49b5b090703818255c3abe1c3d3c8244803 | TigerTopher/PrismX | /Syntax.py | 2,001 | 3.78125 | 4 | import lex
class syntax():
def __init__(self):
self.text = ""
self.lex = lex.lexical_analysis()
self.input = []
self.parse = [0]
self.table = []
def set_input(self, temp):
temp = temp.rstrip().split("\n")
self.text = temp
def algorithm(self):
for x in self.text:
self.lex.set_text(list(x))
self.input = self.lex.main()
self.setup()
print self.input
temp = 0
while 1:
temp = self.input.pop(0)
temp1 = self.parse[-1:]
if temp == 11:
temp2 = self.table[temp1][0]
elif temp == 21:
temp2 = self.table[temp1][1]
elif temp == 23:
temp2 = self.table[temp1][2]
elif temp == 25:
temp2 = self.table[temp1][3]
elif temp == 26:
temp2 = self.table[temp1][4]
elif temp == 27:
temp2 = self.table[temp1][5]
else:
print "Error"
print temp, temp1
exit(1)
if temp2 >= 0:
self.parse.append(temp)
self.parse.append(temp2)
#elif temp2 < 0:
else:
print "Error"
print temp, temp1, temp2
exit(1)
def setup(self):
temp = [5, None, None, 4, None, None, 1, 2, 3]
self.table.append(temp)
temp = [None, 6, None, None, "accept", None, None, None]
self.table.append(temp)
temp = [None, -2, 7, None, -2, -2, None, None, None]
self.table.append(temp)
temp = [None, -4, -4, None, -4, -4, None, None, None]
self.table.append(temp)
temp = [5, None, None, 4, None, None, 8, 2, 3]
self.table.append(temp)
temp = [None, -6, -6, None, -6, -6, None, None, None]
self.table.append(temp)
temp = [5, None, None, 4, None, None, None, 9, 3]
self.table.append(temp)
temp = [5, None, None, 4, None, None, None, None, 10]
self.table.append(temp)
temp = [None, 6, None, None, 11, None, None, None, None]
self.table.append(temp)
temp = [None, -1, 7, -1, -1, None, None, None]
self.table.append(temp)
temp = [None, -3, -3, None, -3, -3, None, None, None]
self.table.append(temp)
temp = [None, -5, -5, None, -5, -5, None, None, None]
self.table.append(temp) |
6a7aedfb6093fd809d28efda3d667de7492a23f6 | pz325/ProjectEuler | /app/solutions/problem42.py | 1,207 | 4.03125 | 4 | '''
The nth term of the sequence of triangle numbers is given by, tn = 1/2 * n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?
'''
base = 64;
triangleNumber = [1, 3, 6, 10, 15, 21, 28,
36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210,
231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528,
561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990,
1035, 1081, 1128, 1176, 1225, 1275]
def main():
count = 0
words = [w[1:len(w)-1] for w in open('problem42.txt').read().split(',')]
for w in words:
score = sum([ord(ch) - base for ch in w])
if score in triangleNumber:
count += 1
print 'result: ', count
if __name__ == '__main__':
main()
|
ffdb430bdecbac30c00d752bca0df3cbedc435ad | tadhgcu/masters_projects | /graphs_and_networks/assignment3.py | 11,289 | 3.53125 | 4 |
# coding: utf-8
# ### Scale-free networks and attacks on networks
#
# 1. Generate a free scale network with 10000 nodes and add 10 nodes in each step (use the barabasi_albert_graph (n, m) routine ).
# 2. Calculate the values of L, C and the grade distribution of the nodes.
# 3. Generate a random network that has the same number of nodes and branches as the network that you have created, calculate your values.
#
# a) L
# b) C
# c) The degree distribution of the nodes
# d) Compare the values obtained
#
# In[1]:
import networkx as nx
from networkx import DiGraph
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import random
import numpy as np
import sys
# In[2]:
#Scale free network
def scale_free_L_C_degree(n,m):
scale_free = nx.barabasi_albert_graph(n, m)
L = nx.average_shortest_path_length(scale_free)
C = nx.average_clustering(scale_free)
max_degree = 0
node = ""
for n, d in scale_free.degree:
if d > max_degree:
max_degree = d
node = n
print("Scale free graph results:")
print("")
print("The average shortest path (L) is",L)
print("The clustering coefficient (C) is",C)
#print("")
#print("The node ",node, "has the highest degree in the scale free graph with a value of ",max_degree)
print("")
#Bar graph for the scale free graph
SF=nx.degree_histogram(scale_free)
plt.bar(range(len(SF)),SF, width=5, color='b')
plt.title("Degree distribution of the nodes for Scale free graph")
plt.ylabel("Count")
plt.xlabel("Degree")
plt.show()
###############################################################################################################################
#random network
def Random_L_C_degree(n,m):
random = nx.gnm_random_graph(n, m)
#characteristic path
#if the graph is connected, calculate the shortest path
try:
Lr = nx.average_shortest_path_length(random)
print("Random graph results:")
print("The average shortest path (L) is",Lr)
#if graph is disconnected
except:
Lr = []
path = nx.connected_component_subgraphs(random)
subgraph = []
for component in path:
L_sub = nx.average_shortest_path_length(component)
subgraph.append(L_sub)
Lr.append(max(subgraph))
print("Random graph results:")
print("")
print("The graph is disconnected however, the average shortest path (L) for the largest subgraph is",Lr)
Cr = nx.average_clustering(random)
r_max_degree = 0
node = ""
for n, d in random.degree:
if d > r_max_degree:
r_max_degree = d
node = n
print("The clustering coefficient (C) is",Cr)
#print("")
#print("The node ",node, "has the highest degree in the random network with a value of ",r_max_degree)
print("")
#Bar graph for the scale free graph
R=nx.degree_histogram(random)
plt.bar(range(len(R)),R, width=5, color='b')
plt.title("Degree distribution of the nodes for the Random graph")
plt.ylabel("Count")
plt.xlabel("Degree")
plt.show()
# In[3]:
n = 10000
m = 10
scale_free_L_C_degree(n,m)
Random_L_C_degree(n,m)
# ### Comparing the results from the Scale-free and Random networks
#
# ##### Clustering Ceofficient:
#
# 1) Scale free network (C) = 0.01
# 2) Random network (C) = 0.0
#
# The clustering ceofficient is slightly higher for the scale free graph compared to the Random network. In relation to the scale free network, the clustering coefficient also scales with network size following approximately a power law:
#
# C ~ N^-0.75
# ##### Average path length:
#
# 1) Scale free network (L) = 3.07
# 2) Random network (L) = 1.0
#
# The average path length is larger for the Scale free netwrok compared to the Random netwrok. This is due to the random network being disconnected
# ##### Degree Distribution:
#
# For the random netwrok, the distribution is very narrow, with the largest degree being 3. Comparing this to the scal free netwrok, the distribution is larger wider with the max degree being over 400.
#
#
# # Attack the Network
# 1. Implement a routine program random_attack (G, m) in Python that perform a random attack on m nodes of graph G.
#
# In[4]:
def Random_attack(G,m):
#Get a list of all the nodes
ListOfNodes = G.nodes()
NumberofNodesBefore = G.number_of_nodes()
#the number of nodes you want to remove
sample = m
#Select a sample of random numbers from your list of nodes
RandomSample = random.sample(ListOfNodes, sample)
#Remove the nodes
G.remove_nodes_from(RandomSample)
NumberofNodesafter = G.number_of_nodes()
# Calculate the largest clustering coefficient
path = nx.connected_component_subgraphs(G)
subgraph = []
L = []
for component in path:
L_sub = nx.average_shortest_path_length(component)
subgraph.append(L_sub)
L.append(max(subgraph))
random_size_component = max(subgraph)
return random_size_component
# 2. Use the previous routine to calculate the size of the largest component connected in
#
# a) random,
# b) small world and
# c) scale-free graphs
#
# Parameters: 1000 nodes and 4000 branches after attacks of 10%, 30%, 50%, 70% and 90% of the nodes of the graph
# In[13]:
n = 1000
m = 4000
m_less = 10 #Barabási–Albert network must have m >= 1 and m < n
k = 2
percentage_list = [10, 30, 50, 70, 90]
#Create a matrix to store the functions output
rows = len(percentage_list)
size = (3, rows)
Random_results=np.zeros(size)
#For each percentage, generate a new network and attack
i = 0
for percentage in percentage_list:
sys.stdout.write('.')
sys.stdout.flush()
#number of nodes to be removed
M = round((n/100)*percentage)
#attak the network
random_G = nx.gnm_random_graph(n, m)
scale_free_G = nx.barabasi_albert_graph(n, m_less)
small_world_G = nx.newman_watts_strogatz_graph(n, k, 1)
#store the resukts in a matrix
Random_results[0,i]= Random_attack(random_G, M)
Random_results[1,i]= Random_attack(scale_free_G, M)
Random_results[2,i]= Random_attack(small_world_G, M)
i = i+1
print("")
print(Random_results)
# # Now attack based on nodes with the highest degree
# 1. Implement a gram_schema program routine (G, m) in Python that performs an attack based on degrees to m nodes of graph G.
#
# In[6]:
def Gram_schema(G,M):
#Get a list of sorted nodes based on degree
ListOfNodes = sorted(G.degree, key=lambda x: x[1], reverse=True)
nodes = []
count = 0
for node, degree in ListOfNodes:
if count > M-1:
break
else:
nodes.append(node) # = degree
count = count+1
#Remove the nodes with the highest degree
G.remove_nodes_from(nodes)
#calculate the largest clustering coefficient
path = nx.connected_component_subgraphs(G)
subgraph = []
L = []
for component in path:
L_sub = nx.average_shortest_path_length(component)
subgraph.append(L_sub)
L.append(max(subgraph))
size_component = max(subgraph)
return size_component
# 2. Use the previous routine to calculate the size of the largest component connected in
#
# a) random,
# b) small world and
# c) scale-free graphs
#
# Parameters: 1000 nodes and 4000 branches after attacks of 10%, 30%, 50%, 70% and 90% of the nodes of the graph
#
# In[12]:
n = 1000
m = 4000
m_less = 10 #Barabási–Albert network must have m >= 1 and m < n
k = 2
percentage_list = [10, 30, 50, 70, 90]
rows = len(percentage_list)
size = (3, rows)
Gram_results=np.zeros(size)
i = 0
for percentage in percentage_list:
sys.stdout.write('.')
sys.stdout.flush()
M = round((n/100)*percentage)
random_G = nx.gnm_random_graph(n, m)
scale_free_G = nx.barabasi_albert_graph(n, m_less)
small_world_G = nx.newman_watts_strogatz_graph(n, k, 1)
Gram_results[0,i]= Gram_schema(random_G, M)
Gram_results[1,i]= Gram_schema(scale_free_G, M)
Gram_results[2,i]= Gram_schema(small_world_G, M)
i = i+1
print("")
print(Gram_results)
# # Compare the results of the two functions
# In[14]:
plt.figure(figsize=[15,7])
percentage_list = [10, 30, 50, 70, 90]
#plt.legend(handles=legend_handles, loc = 1)
plt.plot(percentage_list,Random_results[:][0], 'red', label="Random - random")
plt.plot(percentage_list,Gram_results[:][0], color = 'red', ls='--', label="Random - gram")
plt.plot(percentage_list,Random_results[:][1], 'blue', label="Scale_free - random")
plt.plot(percentage_list,Gram_results[:][1], color = 'blue', ls='--', label="Scale free - gram")
plt.plot(percentage_list,Random_results[:][2], 'green', label="Small_world - random")
plt.plot(percentage_list,Gram_results[:][2], color = 'green', ls='--', label="Small world - gram")
plt.xlabel('Percentage', size=15)
plt.ylabel('Largest component size', size=15);
plt.title('Comparing Network Attacks: Random vs Degree specific', size=20)
plt.legend()
plt.grid(True)
plt.show()
print("")
print("Random_attack:")
print(Random_results)
print("")
print("Gram_attack:")
print(Gram_results)
# As the random_attack is removing nodes at random and the Gram_attack is an intelligent attack, we would expect for the Gram_attack to perform better on the graphs however, this is topology dependent. The computational cost of each attack is also different. As the random attack is fairly simplistic, the cost is O(n) compared to the more complex intelligent attack. For the intelligent attack, we must also calculate the degree of every node. This increases the cost to O(n^2).
#
# The results are summarized below:
#
#
# ##### 1) Random Network:
#
# a) Random_attack - The network performed well against this attack. From the graph above, the clustering coefficient changes at a consistant rate. This is demonstrated by the solid red line in the graph above
#
# b) Gran_attack - Again, the change in clustering ceofficient reduces at a consistant rate.
#
# ##### 2) Scale Free Network:
#
# a) Random_attack - The network performed well against this attack.
#
# b) Gran_attack - Less resistant to the intelligent attack. From the graph above, you can see the the dotted blue line has a lower clustering coefficient for all the percentages compared to the random attack.
#
#
# ##### 3) Small World Network:
#
# a) Random_attack - The network performed well against this attack.
#
# b) Gran_attack - Again, the small world performed well against this attack
#
# ##### Best attack method against each graph:
# Random Network:<br>
# Gram_attack - As shown above, this performed better than the random_attack <br>
# Scale Free Network:<br>
# Gram_attack - As shown above, this network is less resistant to this type of attack<br>
# Small World Network:<br>
# Random Attack - Both attacks performed similar but the Random_attack costs less than the intelligent attack
|
90a4c627e81ea5cdd608e265d4014686b96ae85c | hirekatsu/MyNLTKBOOK | /ch02_03.py | 1,411 | 4.0625 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
print("""
----------------------------------------------------------------------
3 More Python: Reusing Code
3.1 Creating Programs with a Text Editor
----------------------------------------------------------------------
""")
print("----- no code -----")
print("""
----------------------------------------------------------------------
3.2 Functions
----------------------------------------------------------------------
""")
def lexical_diversity(my_text_data):
word_count = len(my_text_data)
vocab_size = len(set(my_text_data))
diversity_score = vocab_size / word_count
return diversity_score
from nltk.corpus import genesis
kjv = genesis.words('english-kjv.txt')
print(lexical_diversity(kjv))
print("-" * 40)
def plural(word):
if word.endswith('y'):
return word[:-1] + 'ies'
elif word[-1] in 'sx' or word[-2:] in ['sh', 'ch']:
return word + 'es'
elif word.endswith('an'):
return word[:-2] + 'en'
else:
return word + 's'
print(plural('fairy'))
print(plural('woman'))
print("-" * 40)
print("""
----------------------------------------------------------------------
3.3 Modules
----------------------------------------------------------------------
""")
print("----- skipped -----")
|
564d04c096de82d91078c2708de22f09b9521049 | EricLum/python-algos | /topological_sort.py | 1,708 | 3.59375 | 4 | # useful for dependencies
# the gist of the algo is to dfs a couple of times and then output leaf nodes to an order array.
# this order array may not be the same every time since ur node order can change depending on ur traversal + node selection.
# this only works on DAGs and it can't have any cycles so lets make a quick example with a depdency list
graph = {
'A' : ['D'],
'B' : ['D'],
'C' : ['A', 'B'],
'D' : ['H', 'G'],
'E' : ['A', 'D', 'F'],
'F' : ['K', 'J'],
'G' : ['I'],
'H' : ['I', 'J'],
'I' : ['L'],
'J' : ['M', 'L'],
'K' : ['J'],
'L' : [],
'M' : []
}
class TopologicalSort:
def __init__(self, graph):
self.graph = graph
self.visited = []
self.output = []
def solve(self):
# start with a loop here to ensure we traversed each node
for node in self.graph:
if node not in self.visited:
self.dfs(node)
##
##
print(self.output)
def dfs(self, node):
# using each node, DFS it until we hit a termination point. then pop off these bad boys into the output.
if len(graph[node]) == 0:
# its a terminal node
self.output.insert(0,node)
self.visited.append(node)
return
# termination condition should be theres no neighbors && not visited.
for neighbor in graph[node]:
if neighbor not in self.visited:
self.dfs(neighbor)
# once u have ur neighbors/children visited, append urself.
self.visited.append(node)
self.output.insert(0,node)
topsort = TopologicalSort(graph)
topsort.solve()
|
0f478534f7fcad7d99d58f79b2fc2d2cc39d3729 | abhijitdey/coding-practice | /fast-track/dynamic_programming/11_decode_ways.py | 1,238 | 4.375 | 4 | """
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways).
For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
Range of any letter: 1-26
"""
def decode_ways(s, dp, n):
if len(s[n - 1 :]) == 0:
return 1
if s[n - 1] == "0":
return 0
if len(s[n - 1 :]) == 1:
return 1
if dp[n] is not None:
return dp[n]
if int(s[n - 1]) <= 2 and int(s[n - 1 : n + 1]) <= 26:
# Two ways to decode
dp[n] = decode_ways(s, dp, n + 1) + decode_ways(s, dp, n + 2)
else:
# Only one way to decode
dp[n] = decode_ways(s, dp, n + 1)
return dp[n]
if __name__ == "__main__":
s = "226"
dp = [None] * (len(s) + 1)
dp[0] = 1
print(decode_ways(s, dp, n=1))
|
0808ea510032599c1df8b371c0ffaf92b092843a | alvin-the-programmer/Practice | /python/runningMedian.py | 953 | 3.609375 | 4 | from heapq import heappush
from heapq import heappop
from heapq import heappushpop
class median:
def __init__(self):
self.less = []
self.more = []
def add(self, n):
if not self.less and not self.more:
heappush(self.less, -n)
return
if n > -self.less[0]:
heappush(self.more, n)
else:
heappush(self.less, -n)
if (len(self.less) - len(self.more)) > 1:
heappush(self.more, -heappop(self.less))
elif (len(self.more) - len(self.less)) > 1:
heappush(self.less, -heappop(self.more))
def getMed(self):
if len(self.less) == len(self.more):
return (self.more[0] + -(self.less[0])) / 2.0
elif len(self.less) > len(self.more):
return -(self.less[0])
elif len(self.more) > len(self.less):
return self.more[0]
m = median()
m.add(10)
print m.getMed()
m.add(9)
print m.getMed()
m.add(11)
print m.getMed()
m.add(50)
print m.getMed()
m.add(7)
print m.getMed()
m.add(100)
print m.getMed()
m.add(101)
print m.getMed()
|
d78041298d13b948c3c9ba8fb46bee854145b6fe | bmasoumi/BioInfoMethods | /NaiveExactMatching.py | 4,395 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 11 10:31:09 2018
@author: Beeta
Implementation of exact matching algorithms
- Naive Exact Matching(Brute Force)
"""
def readFASTA(filename):
genome = ''
with open(filename, 'r') as f:
for line in f:
if not line[0] == '>':
genome += line.rstrip()
return genome
genome = readFASTA('phix.fa')
#=============================
# Naive exact matching
# aka Brute Force
#=============================
# returns offsets of pattern p in text t
def BruteForce(p, t):
occurrences = []
for i in range(len(t)-len(p)+1): # loop over alignment
match = True
for j in range(len(p)): # loop over characters
if t[i+j] != p[j]: # compare characters
match = False # mismatch
break
if match: # allchars matched
occurrences.append(i)
return occurrences
p = 'word'
t = 'this sentence contains a word'
occurrences = BruteForce(p, t)
print(occurrences) # 25 is the answer
min_no_comparisons = len(t)-len(p)+1
max_no_comparisons = len(p)*(len(t)-len(p)+1)
print(min_no_comparisons, max_no_comparisons) #answer is 26 & 104
p = 'AG'
t = 'AGCCCTTTGATAGTTTCAG'
BruteForce(p,t) # answer is [0, 11, 17]
# test the answer
print(t[:2], t[11:13], t[17:19])
# generate artifical reads from random positions in a given genome phix
import random
def generateReads(genome, numReads, readLen):
reads = []
for _ in range(numReads):
start = random.randint(0, len(genome)-readLen) - 1
reads.append(genome[start: start+readLen])
return reads
reads = generateReads(genome, 100, 100)
print(reads)
# matching artifical reads
# how many of these reads match the genome exactly
# obviously the answer should be all of them bc
# these are generated from this genome and there is no error involved
numMatched = 0
for r in reads:
matched = BruteForce(r ,genome)
if len(matched) > 0:
numMatched += 1
print('%d / %d reads matched the genome exactly' % (numMatched, len(reads)))
"""
# using python string methods
example = 'this sentence contains a word'
example.find('word') #find method returns the offset of the pattern (the leftmost)
# 'word' occurs at offset 25
"""
# matching real reads
# from a FASTQ file ERR266411_1.for_asm.fastq
# that has real reads from phix
def readFASTQ(filename):
sequences = []
qualities = []
with open(filename, 'r') as f:
while True:
f.readline()
seqs = f.readline().rstrip()
f.readline()
quals = f.readline().rstrip()
if len(seqs) == 0:
break
sequences.append(seqs)
qualities.append(quals)
return sequences, qualities
phix_reads, _ = readFASTQ('ERR266411_1.for_asm.fastq')
print(phix_reads, len(phix_reads))
numMatched = 0
total = 0
for r in phix_reads:
matched = BruteForce(r, genome)
total += 1
if len(matched) > 0:
numMatched += 1
print('%d / %d reads matched the genome' % (numMatched, total))
# answer is 502 / 10000 reads matched the genome
# bc of sequencing errors or
# bc the reference genome is double stranded and we checked only one
# now lets chnage it to matching only 30 first bases of reads
numMatched = 0
total = 0
for r in phix_reads:
r = r[:30]
matched = BruteForce(r, genome)
total += 1
if len(matched) > 0:
numMatched += 1
print('%d / %d reads matched the genome' % (numMatched, total))
# answer is 3563 / 10000 reads matched the genome
# still very low matching
# so lets do the same thing for the reverse complement of the read
def reverseComplement(s):
complement = {'A':'T', 'C':'G', 'T':'A', 'G':'C', 'N':'N'}
t = ''
for base in s:
t = complement[base] + t
return t
reverseComplement(phix_reads[1])
numMatched = 0
total = 0
for r in phix_reads:
r = r[:30]
matched = BruteForce(r, genome) # matches in forward strand
matched.extend(BruteForce(reverseComplement(r), genome)) # matches in reverse strand
total += 1
if len(matched) > 0:
numMatched += 1
print('%d / %d reads matched the genome' % (numMatched, total))
# answer is 8036 / 10000 reads matched the genome
# much better result
|
35fe792320bd66bae0f6b84e0c402d2232f2d9b8 | alankrit03/LeetCode_Solutions | /229. Majority Element II.py | 270 | 3.5 | 4 | class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
c = collections.Counter(nums)
ans = []
for x, y in c.most_common(2):
if y > (n // 3):
ans.append(x)
return ans |
f0d45a478bbbb806fcd58dce825e948c889dd3aa | karthikeya5608/python_2 | /countingwords.py | 186 | 3.59375 | 4 |
def fun():
inputc=input("enter:")
charactercount=0
for i in inputc:
words=inputc.split(" ")
charactercount=len(words)
print(charactercount)
fun() |
eeb7a430c831d0b5f3fd180bc502b72752eb0129 | michail82/TestMikl | /MIklTest2_Week2_8_Three_big.py | 757 | 4.03125 | 4 | a = int( input() )
b = int( input() )
c = int( input() )
if a >= b and a >= c:
print( a )
elif b >= a and b >= c:
print( b )
elif c >= a and c >= b:
print( c )
# eyes = int(input())
# legs = int(input())
# if eyes >= 8:
# if legs == 8:
# print("spider")
# else:
# print("scallop")
# else:
# if legs == 6:
# print("bug")
# else:
# print("cat")
# Даны три целых числа. Найдите наибольшее из них
# (программа должна вывести ровно одно целое число).
#
# Какое наименьшее число операторов сравнения
# (>, <, >=, <=) необходимо для решения этой задачи?
|
7b6e0e6bd195f69af5c37f42281e4b662a039e1f | joao-psp/Artificial-intelligence | /Perceptron/perceptron.py | 3,095 | 3.671875 | 4 | import numpy as np
class Perceptron(object):
"""Implements a perceptron network"""
def __init__(self, input_size, saida, epochs=10000, alpha=0.001):
# print("init")
self.W = np.random.rand(saida,input_size)
self.b = np.zeros(shape=(saida,1))
self.alpha = alpha
self.erro = 0
self.total = 0
self.epochs = epochs
# print('\n')
def step(self, x): # aplica a funcao degrau
# print("activation_fn")
# print(x.shape)
y = np.zeros(shape=(x.shape))
for i in range(0, x.shape[0]):
if(x[i] >=1):
y[i] = 1
else:
y[i] = 0
return y
def predict(self, x): # f(Wx+b)
z = np.matmul(self.W,x).reshape(3,1) + self.b
a = self.step(z)
return a
def perceptron(self, X, d): # algortmo para treino
t =0
E = 1
while t < self.epochs and E>0:
E = 0
for i in range(X.shape[0]):
x = X[i]
y = self.predict(x)
# print(" jh fds")
e = d[i].reshape(3,1) - y
aux = x.reshape(1,13)
e = e.reshape(3,1)
self.W = self.W + self.alpha* np.matmul(e,aux)
self.b = self.b + self.alpha*e
E = E + np.sum([value*value for value in e])
self.erro = E
t= t+1
def accuracy(self,actual,predicted): # verifica se a saida e igual a desejada
teste = 0
if(actual[0]==predicted[0] and actual[1]==predicted[1] and actual[2]==predicted[2]):
self.total +=1
def manipulaArquivo():
arq = open('wine.data','r') # Le arquivo de dados e sepaara em entrada e saida
saidas = []
entradas = []
for linha in arq:
linha = linha[:-1]
linha = linha.split(',')
saidas.append(int(linha[0]))
entradas.append([float(i) for i in linha[1:] ])
arq.close()
for i in range(0, len(saidas)):
s = []
if saidas[i] == 1:
saidas[i] = [1,0,0]
elif saidas[i] ==2:
saidas[i] = [0,1,0]
elif saidas[i] ==3:
saidas[i] = [0,0,1]
return np.array(entradas), np.array(saidas)
def main():
X, d = manipulaArquivo()
aux = np.mean(X,axis=0) # normaliza arquivo
aux2 = np.std(X, axis=0)
X = (X-aux)/aux2
treino = X[:115] #separa o banco em teste e treino
d_treino = d[:115]
teste = X[116:178]
d_teste = d[116:178]
perceptron = Perceptron(input_size=13, saida=3,epochs=10000) #treina a base
perceptron.perceptron(treino, d_treino)
for i in range(0,teste.shape[0]):
perceptron.accuracy(perceptron.predict(teste[i]),d_teste[i]) # testa a base
print("Alpha = 0.001, max_epochs = 10000")
print("\n Matrix W ")
print(perceptron.W)
print("\n bias")
print(perceptron.b)
print("\nAccuracy: ")
print(perceptron.total/teste.shape[0]) # mostra a accuracy
print("\nErro E")
print(perceptron.erro)
main()
|
859556619dc3532eacf59b363abc71179c97f08b | Elaina23/Simple-Linear-Regression | /Salary_Prediction_using_Simple_Linear_Regression.py | 2,175 | 3.828125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
from sklearn import linear_model
from sklearn.metrics import r2_score
# load datasets/import file
df = pd.read_csv(r'C:\Users\elena\Desktop\Salary_Data.csv') #read the csv file ('r' is put before the path string to address any special characters in the path, such as '\')
#print(df)
# to have a look at the dataset
df.head()
# summarize the data/descriptive exploration on the data
df.describe()
# plotting the features
plott = df[['YearsExperience','Salary']]
plott.hist()
plt.show()
# scatter plot to see how linear the relation is
plt.scatter(plott.YearsExperience, plott.Salary, color='cyan')
plt.xlabel("YearsExperience")
plt.ylabel("Salary")
plt.show()
# splitting the dataset into train and test sets, 80% for training and 20% for testing
# create a mask to select random rows using np.random.rand() function
msk = np.random.rand(len(df)) < 0.8
train = plott[msk]
test = plott[~msk]
# Train data distribution
plt.scatter(train.YearsExperience, train.Salary, color='red')
plt.xlabel("YearsExperience")
plt.ylabel("Salary")
plt.show()
# modelling data using sklearn package. Sklearn would estimate the intercept and slope
regr = linear_model.LinearRegression()
train_x = np.asanyarray(train[['YearsExperience']])
train_y = np.asanyarray(train[['Salary']])
regr.fit (train_x, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ', regr.intercept_)
# Plot outputs. Plot the fit line over the data
plt.scatter(train.YearsExperience, train.Salary, color='red')
plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')
plt.xlabel("YearsExperience")
plt.ylabel("Salary")
# Evaluate model accuracy by finding MSE
test_x = np.asanyarray(test[['YearsExperience']])
test_y = np.asanyarray(test[['Salary']])
test_y_hat = regr.predict(test_x)
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_hat - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_hat - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y_hat , test_y) )
|
a6a5cde359e29cbdc4c5ed00c9235ef13a24304f | sowmyananjundappa/Balancedbraces | /code.py | 694 | 4.03125 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
def is_matched(expr):
left_braces = "({["
right_braces = ")}]"
stack = []
for i in expr:
if i in left_braces:
stack.append(i) # push left delimiter on stack
elif i in right_braces:
if not stack:
return False # nothing to match with
if right_braces.index(i) != left_braces.index(stack.pop( )):
return False # mismatched
if not stack:
return True
else:
return False
value = int(input())
for number in range(value):
input_text = raw_input()
if (is_matched(input_text) == True):
print "Braces are balanced"
else:
print "Braces are not balanced"
|
e6018669c80d8687108ab8443d298a2b67d521ea | Cdt12233344446/ichw | /pyassign1/planets.py | 4,693 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: <utf-8> -*-
"""planets.py: An almost-to-scale simulation of the Solar System.
Only first six planets are included.
__author__ = "Cai Danyang"
__pkuid__ = "1700011774"
__email__ = "1700011774@pku.edu.cn"
"""
import math as m
import turtle
import random as ran
def obj_init():
"""defines objects
"""
turtle.setup(width=1.0, height=1.0, startx=None, starty=None)
turtle.screensize(canvwidth=1500, canvheight=1500, bg="black")
turtle.bgpic("Orrery.gif")
turtle.title("planets.py")
Sun = turtle.Turtle()
Mercury = turtle.Turtle()
Venus = turtle.Turtle()
Earth = turtle.Turtle()
Mars = turtle.Turtle()
Jupiter = turtle.Turtle()
Saturn = turtle.Turtle()
Sun.shape("circle")
Sun.shapesize(1.09, 1.09, 0)
Sun.color("yellow", "yellow")
return (Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn)
def para_init(Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn):
Sun = Sun
Mercury = Mercury
Venus = Venus
Earth = Earth
Mars = Mars
Jupiter = Jupiter
Saturn = Saturn
"""
A list of parameters needed for the following codes. Here
'i' is the index or 'self' parameter,
'rad' determines the size of the planet,
'col' is the designated color,
'φ' is the 'phase' that will be randomized later,
'a' is the semimajor axis,
'e' defines the eccentricity of the orbit,
'b' and 'c' are auxillary and will be assigned values immediately after.
"""
planets_and_parameters = [
{'i': Mercury,
'rad': 1.53,
'per': 24.1,
'col': "purple",
'φ': 0,
'a': 5.79,
'e': 0.206,
'b': 0,
'c': 0,
},
{'i': Venus,
'rad': 3.80,
'per': 61.5,
'col': "orange",
'φ': 0,
'a': 10.82,
'e': 0.007,
'b': 0,
'c': 0,
},
{'i': Earth,
'rad': 4.00,
'per': 100.0,
'col': "blue",
'φ': 0,
'a': 14.96,
'e': 0.016,
'b': 0,
'c': 0,
},
{'i': Mars,
'rad': 2.13,
'per': 188.0,
'col': "red",
'φ': 0,
'a': 22.79,
'e': 0.093,
'b': 0,
'c': 0,
},
{'i': Jupiter,
'rad': 11.2,
'per': 1186,
'col': "green",
'φ': 0,
'a': 77.84,
'e': 0.048,
'b': 0,
'c': 0,
},
{'i': Saturn,
'rad': 9.45,
'per': 2945,
'col': "brown",
'φ': 0,
'a': 142.67,
'e': 0.054,
'b': 0,
'c': 0,
},
]
return planets_and_parameters
def position_init(planets_and_parameters):
"""sends planets to their initial position
"""
planets_and_parameters = planets_and_parameters
for pls in planets_and_parameters:
pls['i'].shape("circle")
pls['i'].shapesize(pls['rad'] / 20, pls['rad'] / 20, 0)
pls['i'].color(pls['col'], pls['col'])
pls['i'].speed(0)
pls['φ'] = ran.uniform(-m.pi, m.pi)
pls['b'] = pls['a'] * m.sqrt(1 - pls['e'] ** 2)
pls['c'] = pls['a'] * pls['e']
pls['i'].up()
pls['i'].goto(
4 * (pls['a'] * m.cos(pls['φ']) - pls['c']),
4 * pls['b'] * m.sin(pls['φ']))
pls['i'].down()
def init():
print("Welcome to my Solar System Simulation!")
Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn = obj_init()
planets_and_parameters = para_init(Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn)
position_init(planets_and_parameters)
return (planets_and_parameters)
def main(planets_and_parameters):
planets_and_parameters = planets_and_parameters
try:
# keep the planets going
for t in range(1, 2000):
for pl in planets_and_parameters:
# use φ to simplify the expression, again
pl['φ'] = pl['φ'] + 2 * m.pi / pl['per']
pl['i'].goto(
4 * (pl['a'] * m.cos(pl['φ']) - pl['c']),
4 * pl['b'] * m.sin(pl['φ']))
# avoids redundant rendering by 'upping' the faster planets
if t == 100:
for pls in planets_and_parameters[:3]:
pls['i'].up()
# error handling
except:
print("Pity that you quit so early. See you next time!")
else:
print("Thanks for watching this simulaton. See you next time!")
if __name__ == '__main__':
planets_and_parameters = init()
main(planets_and_parameters)
|
1fad5a3592564ca676f7cbb59eef49adde775242 | ByunSungwook/B-Git | /PyDay/Day1.py | 530 | 4 | 4 | print "Enter your subject1 :"
sub1 = raw_input()
print "Enter your score of subject1 :"
score1 = input()
print "Enter your subject1 :"
sub2 = raw_input()
print "Enter your score of subject1 :"
score2 = input()
print "Enter your subject1 :"
sub3 = raw_input()
print "Enter your score of subject1 :"
score3 = input()
total = score1 + score2 + score3
avg = total/3.0
print sub1 + " : " + str(score1)
print sub2 + " : " + str(score2)
print sub3 + " : " + str(score3)
print "total : " + str(total)
print "average : " + str(avg)
|
0046565b3438028a510fb46bbcb15ffb2d6f583c | mary-tano/python-programming | /python_for_kids/book/Projects/grafik0.py | 372 | 3.640625 | 4 | # Графика
from tkinter import *
# Функция события
def buttonClick() :
pass
# Основная программа
Window = Tk()
Window.title("Графика")
Window.config(width=500, height=330)
Button = Button(Window, text="Давай посмотрим!", command=buttonClick)
Button.place(x=190, y=150, width=120, height=30)
Window.mainloop()
|
c3f2095351e081acc970b334f9432f02cc398698 | willrogers/euler | /python/p037.py | 564 | 3.78125 | 4 | '''
Find the sum of all 11 truncatable primes (that is, both ways).
Single-digit primes don't count.
'''
from utils import is_prime
import itertools
TOTAL = 11
def truncatable(p):
s = str(p)
l = len(s)
for i in range(1, l):
if not is_prime(int(s[i:])):
return False
if not is_prime(int(s[:i])):
return False
return True
truncs = []
for i in itertools.count(11, 2):
if is_prime(i):
if truncatable(i):
truncs.append(i)
if len(truncs) == TOTAL:
break
print sum(truncs)
|
068d45b035add739242761896b323e647fe06782 | Gray-Tu/Practice | /quick_sort.py | 2,093 | 3.921875 | 4 | #Quick sort
import random
import time
def randomNumber(st, ed, N):
"""
Return length == N random numbers list
"""
reList = []
for i in range(N):
reList.append(random.randint(st, ed))
return reList
###
def partition(List, left_index, right_index, selected_index):
"""
[5, 6, 4, 2, 7, 8, 1]
left_index
| right_index
|
selected
"""
#1
#print("1:My List\t",List)
select_value = List[selected_index] #4
List[right_index], List[selected_index] = List[selected_index], List[right_index]
#print("2:SWAP(Prov,R)\t",List,"Prove:",List[right_index])
#[5, 6, 1, 2, 7, 8, 4]
# ^ SI
SI = left_index
#print("3:SI",SI)
for i in range(left_index, right_index, 1):
# print("i=",i,"SI",SI, List)
if List[i] <= select_value: #需要放到左邊的情況
List[i], List[SI] = List[SI], List[i]
#List[i] == 1 (i == 2
SI += 1
#[1, 6, 5, 2, 7, 8, 4]
# ^ SI
#--------
#List[i] == 2 (i == 3
#[1, 2, 5, 6, 7, 8, 4]
# ^ SI
#[1, 2, 5, 6, 7, 8, 4]
# ^ SI
List[SI], List[right_index] = List[right_index], List[SI]
#[1, 2, 4, 6, 7, 8, 5]
# ^ SI
#print("End","SI",SI, List)
return SI #NEW index of selected_value
def quick_sort(AList, left_index, right_index):
if left_index < right_index: #else: end of sort
New_SI = partition(AList, left_index, right_index, right_index-1)
#left sort
quick_sort(AList, left_index, New_SI-1)
#right sort
quick_sort(AList, New_SI+1, right_index)
return
if __name__ == "__main__":
aList = randomNumber(0,50000, 40000)#[5, 6, 4, 2, 7, 8, 1,23,442,3,2,2,11,2,3,5]
#print(aList)
tStart = time.time()
#quick_sort(aList, 0, len(aList)-1)
aList.sort()
tEnd = time.time()
#print(aList)
print("It cost %f sec" % (tEnd - tStart)) |
2ddec3cffb4d80515ed0841d324bfbb2aaba58a0 | siberian122/kyoupuro | /practice/WaterBottle.py | 219 | 3.6875 | 4 | import math
a, b, x = map(int, input().split())
cap = a*a*b
if cap/2 < x: # 半分より多い
print(math.degrees(math.atan(2*b/a - 2*x/a/a/a)))
else: # 半分以下
print(math.degrees(math.atan(a*b*b/2/x)))
|
c343b157993b02019616e35b0c0cd898faca5f83 | hanchengge/csce470 | /HW1/pytut.py | 4,615 | 4.34375 | 4 | #!/usr/bin/env python
import re
import unittest
# To run the code in this file, run this command:
# > python pytut.py
# You will need to replace all of the places wher you see a "FIXME" to get this
# code working. You should look over the documentation on data structures before
# staring on this:
# http://docs.python.org/tutorial/datastructures.html
class TestSimpleEnv(unittest.TestCase):
def test_a_list(self):
print '\n\tlist'
# A list works like an ArrayList in Java or std:vector in C++. The items
# in the list do not have to have the same type, but they generally do.
primes = [2,3,5,7,11]
self.assertEqual( primes[0], 2 )
self.assertEqual( len(primes), 5 )
self.assertEqual( sum(primes), "FIXME" )
# Let's print out a few of them:
for prime in primes:
if prime<6:
print prime
# Let's add something to the end of the list.
primes.append(13)
self.assertEqual( primes[-1], 13)
# Now you can make a list of names. Make sure the third one is
# 'Charlie'.
names = "FIXME"
self.assertEqual( names[2], 'charlie' )
def test_dict(self):
print '\n\tdict'
# A dict works like HashMap in Java or std:map in C++. It maps
# keys to values.
fav_foods = {
'vegetable': 'spinach',
'fruit': 'apple',
'meat': 'steak',
'ice cream': 'mint chocolate chip',
"FIXME": "FIXME",
}
for kind,label in fav_foods.iteritems():
print "favorite %s : %s"%(kind,label)
self.assertEqual( fav_foods['fruit'], 'apple' )
# you need to add your favorite type of nut to fav_foods:
self.assertTrue( 'nut' in fav_foods )
def test_dict_of_lists(self):
print '\n\tdicts of lists'
# Here's some things I want to get at the grocery store. It is a dict
# that maps department names to lists of items I want to buy in that
# department:
groceries = {
'fruits': ['apple','banana'],
'vegetables': ['avocado','onion','tomato','okra'],
'cereal': ['granola','raisin bran','musli'],
'dairy': ['skim milk','buttermilk'],
'bulk foods': ['peanuts','black beans'],
'meats':[],
}
self.assertEqual( groceries.get('fruits'), ['apple','banana'] )
self.assertEqual( groceries.get('baking'), None )
self.assertEqual( groceries['fruits'], ['apple','banana'] )
# What happens when you uncomment the next line?
# self.assertEqual( groceries['baking'], None )
# iterating over a dictionary returns the keys
for dept in groceries:
print "%s: %r"%(dept,groceries[dept])
# Let's sort the list of departements by the number of items we are
# buying in each section. The department with the smallest nuber of
# foods (meat) should be first, and the department with the most foods
# (vegetables) should be last.
# http://docs.python.org/library/functions.html#sorted may help you
# decode this.
sorted_keys = sorted(
groceries,
key=lambda label:len(groceries[label])
)
self.assertEqual( sorted_keys[-1], 'vegetables' )
self.assertEqual( sorted_keys[0], 'meats' )
self.assertEqual( groceries[sorted_keys[0]], "FIXME" )
# Now try counting how many leters are in each department's list.
counts = {
dept:sum(len(word) for word in items)
for dept,items in groceries.iteritems()
}
self.assertEqual( counts['meats'], 0 )
self.assertEqual( counts['fruits'], "FIXME" )
def _vowel_ending(self, word):
# A method whose name begins with an underscore is treated like it is
# private by convention.
# This method should return True if word ends with a vowel, and false
# otherwise.
# Big hint: http://docs.python.org/library/re.html
# The functions search, match, split, findall, and sub could be useful
# in this course.
return "FIXME"
def test_regexes(self):
print '\n\tregular expressions'
self.assertFalse( self._vowel_ending('book') )
self.assertTrue( self._vowel_ending('movie') )
self.assertFalse( self._vowel_ending('song') )
self.assertTrue( self._vowel_ending('YMCA') )
if __name__ == '__main__':
unittest.main()
|
cc10167f5ab9936e572f75f981ac151d93e1b9a3 | jpjagt/prisonerds | /graph.py | 3,942 | 3.640625 | 4 | """
A graph is a representation of a strategy for prisoners dilemma.
Here, the action C is represented by digit 1, the action D by digit 2.
This makes indexing next state easier.
"""
import numpy as np
# np.array([
# [1, 0, 1],
# [1, 0, 2],
# [2, 2, 2]
# ])
class Graph:
def __init__(self, data=None):
if data is None:
self.data = np.array([[1, 0, 0]])
self.mutate()
self.mutate()
self.mutate()
else:
self.data = data
self.validate()
def __getitem__(self, item):
return self.data.__getitem__(item)
def clone(self, mutate=False):
cloned = self.__class__(data=self.data)
if mutate:
cloned.mutate()
return cloned
def validate(self):
assert set(self.data[:, 0]) <= {
1,
2,
}, "actions column contains forbidden values"
n_nodes = self.data.shape[0]
assert (
self.data[:, 1].max() < n_nodes
), "reference to non-existing node"
assert self.data[:, 1].min() >= 0, "reference to non-existing node"
assert (
self.data[:, 2].max() < n_nodes
), "reference to non-existing node"
assert self.data[:, 2].min() >= 0, "reference to non-existing node"
def __random_node(self):
return np.random.randint(self.data.shape[0])
def mutate_flip_action(self):
"flip one of the actions in actions column"
index = self.__random_node()
self.data[index, 0] = 3 - self.data[index, 0]
def mutate_moveto_random_if_c(self, new_node_index=None):
"move to a random node if cooperate on some random node"
if new_node_index is None:
new_node_index = self.__random_node()
index = self.__random_node() # node to be mutated
self.data[index, 1] = new_node_index
def mutate_moveto_random_if_d(self, new_node_index=None):
"move to a random node if defect on some random node"
if new_node_index is None:
new_node_index = self.__random_node()
index = self.__random_node() # node to be mutated
self.data[index, 2] = new_node_index
def mutate_create_node(self):
action = np.random.choice([1, 2])
new_node = np.array(
[[action, self.__random_node(), self.__random_node()]]
)
self.data = np.concatenate((self.data, new_node))
# should we update existing nodes to reference to this node?
new_index = self.data.shape[0] - 1
self.mutate_moveto_random_if_c(new_index)
self.mutate_moveto_random_if_d(new_index)
def mutate_remove_node(self):
if not len(self.data) > 1:
return
index = self.__random_node()
self.data = np.delete(self.data, index, axis=0)
# cleanup
mask_above = self.data > index
mask_equal = self.data == index
mask_above[:, 0] = 0
mask_equal[:, 0] = 0
# shift indices
self.data[mask_above] -= 1
# update nodes that referenced to deleted node
x, y = np.where(mask_equal)
new_indices = [self.__random_node() for _ in range(len(x))]
self.data[x, y] = new_indices
def mutate_swap_nodes(self):
i1 = self.__random_node()
i2 = self.__random_node()
n1 = self.data[i1, :]
self.data[i1, :] = self.data[i2, :]
self.data[i2, :] = n1
def mutate_if(self, func, prob):
if np.random.rand() < prob:
func()
def mutate(self):
self.mutate_if(self.mutate_flip_action, 0.35)
self.mutate_if(self.mutate_moveto_random_if_c, 0.35)
self.mutate_if(self.mutate_moveto_random_if_d, 0.35)
self.mutate_if(self.mutate_create_node, 0.2)
self.mutate_if(self.mutate_remove_node, 0.15)
self.mutate_if(self.mutate_swap_nodes, 0.2)
self.validate()
|
dd55de4fc69c59bceb65e68060a9dfc1ce780273 | M0673N/Programming-Basics-with-Python | /exam_preparation/05_mock_exam/04_problem_solution.py | 485 | 3.859375 | 4 | p1 = int(input())
p2 = int(input())
command = input()
while command != "End of battle":
if command == "one":
p2 -= 1
else:
p1 -= 1
if p1 == 0:
print(f"Player one is out of eggs. Player two has {p2} eggs left.")
break
if p2 == 0:
print(f"Player two is out of eggs. Player one has {p1} eggs left.")
break
command = input()
else:
print(f"Player one has {p1} eggs left.")
print(f"Player two has {p2} eggs left.")
|
4b1ced67911ad8316b65b9d4dbc7ff36b12a0a58 | krishnakrib/wer | /disply prime.py | 204 | 3.875 | 4 | a=20
b=100
print("number between",a,"and",b,"are")
for num in range(a,b+1):
if (num>1):
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
|
d4995bc7e2718707ac94fd5480736646b25fc051 | gabrielsalesls/curso-em-video-python | /ex065.py | 577 | 4 | 4 | maior = menor = 0
soma = 0
digitados = 0
sair = 'Ss'
while sair in 'Ss':
num = int(input('Digite o numero: '))
soma += num
digitados += 1
if menor == 0 and maior == 0:
menor = maior = num
else:
if num > maior:
maior = num
if num < menor:
menor = num
sair = str(input('Deseja continuar?[S/N] '))
media = soma / digitados
print('Foram digitados {} numeros. A media entre eles é {}'.format(digitados, media))
print('O maior numero digitado foi {}, o menor foi {}'.format(maior, menor))
|
32b9ad0c90c584924b37cd75ca632ae67097f92a | sakshigarg22/python-lab | /pattern2.py | 101 | 3.765625 | 4 | l1 = [1,2,4,5]
l2 = [1,3,9,8]
l3 = l1+l2
[l3.remove(i) for i in l3 if i in l2 and i in l1]
print(l3)
|
c2860a05ee2a98f8a2f938581fe588266f6c535a | jimibarra/cn_python_programming | /miniprojects/loops_test.py | 1,057 | 3.984375 | 4 | my_list = [1, 2, 3, 4, 5]
# 'break' ends the execution of the loop, skipping anything after
for num in my_list:
if num % 3 == 0:
break
print(num)
print("finished 'break' part")
for num in my_list:
if num % 3 == 0:
continue
print(num)
print("finished 'continue' part")
n = 10
while True:
if n <= 0:
print("Blastoff")
break
else:
print(n)
n -= 1
people = [
['Bilbo', 'Baggins'],
['Gollum'],
['Tom', 'Bombadil'],
['Aragorn']
]
# Change everything below here to use while loops instead
for person in people:
to_print = ""
for name in person:
to_print += name + " "
print(to_print)
count = 0
total = len(people)
while count < total:
name_list = people[count]
if len(name_list) == 2:
to_print = name_list[0] + " " + name_list[1]
print(to_print)
count += 1
if len(name_list) == 1:
to_print = name_list[0]
print(to_print)
count += 1
print("We are done!")
|
948627c3831c9e40c4a55b0aa6e47f9965cac45e | LouisLuFin/Finite-Difference | /Python code/HeatFDGrid.py | 8,091 | 3.671875 | 4 |
# %%
import numpy as np
import matplotlib.pyplot as plt
import warnings
class HeatFDGrid:
"""
A Python class to solve Heat Partial Differenial Equation with Finite Difference method.
This class could implement all three common Schemes of Finite Difference method: Explicit, Implicit, and Crank-Nicolson method
Pleae find the the details of the three methods in the readme file
The main part of this class is a numpy matrix that represents the grid,
and solution at every discreted time point could be exacted by 1-demension or 2-demonstion index, but only after the instance has completed calculation.
With 1-D index x, the HeatFDGRid object returns the solution at time x
With 2-D index specified as list [x,y], the HeatFDGrid object returns the solution at time y and the xth boundary condition
This class supports users to input upper, lower and initial boundary conditions with self written function,
this file contains a sample initial boundary condition function, and upper and lower boundary condition are 0 if not specified
This class could be directly demonstrated with print() function, it would show the entire grid
With Emplicit method, the solution may have unstable solutions, in this case, there will be a warning
The file contains no error checking
Sample code to use these codes:
a = HeatFDGrid(0, dx, 1, dt, 1000*dt)
a.SetBoundaryConditions(demo_fun_explict)
a.CalGrid()
Author: Ruinan Lu
References:
[1]Brandimarte P. Numerical methods in finance and economics: a MATLAB-based introduction[M]. John Wiley & Sons, 2013.
[2]Seydel R, Seydel R. Tools for computational finance[M]. Berlin: Springer, 2006.
[3]Ramalho L. Fluent python: Clear, concise, and effective programming[M]. " O'Reilly Media, Inc.", 2015.
"""
typecode = 'd'
def __init__(self, xmin, dx, xmax, dt, tmax):
"""
The constructor of the class specifies the following variables to initialise a Finite Difference grid:
1) xmin: the minimum x, which is the number that will appear at the [0,0] location of the grid
2) dx: boundary condition step scale
3) xmax: the maximum x, which is the number that will appear at the [-1,0] location of the grid
4) dt: time step scale
5) tmax: the maximum time in the grid
"""
self.xmin = xmin
self.dx = dx
self.xmax = xmax
self.dt = dt
self.tmax = tmax
self.N = round((self.xmax-self.xmin)/self.dx)
self.xmax = self.xmin+self.N*self.dx
self.M = round(self.tmax/self.dt)
self.__FDGrid = np.zeros((self.N+1, self.M+1))
def __getitem__(self, idx_list):
"""Special method to realise extract solution by index.
Supports either 1 or 2-D indexing"""
if isinstance(idx_list, int):
x = idx_list
return self.FDGrid_full[:, x]
if len(idx_list) == 2:
x, y = idx_list
return self.FDGrid_full[x, y]
def __repr__(self):
"""Special method to output the grid with print() function"""
self.FDGrid_repr = self.__FDGrid
return np.array_str(self.FDGrid_repr)
def SetBoundaryConditions(self, f_init, f_ub=0, f_lb=0):
"""
Class method to input boundary conditions
the first input is the initial consition of the equation, and is a must for the grid
the second input is the upper bound of the grid, could be user specified function or number, would be 0 if not specified
the third input is the lower bound of the grid, could be user specified function or number, would be 0 if not specified
"""
self.rho = self.dt/(self.dx**2)
if callable(f_ub):
self.__FDGrid[0, :] = np.array(
list(map(f_ub, np.arange(0, self.tmax+self.dt, self.dt))))
else:
self.__FDGrid[0, :] = f_ub
if callable(f_lb):
self.__FDGrid[-1, :] = np.array(list(map(f_lb,
np.arange(0, self.tmax+self.dt, self.dt))))
else:
self.__FDGrid[-1, :] = f_ub
self.__FDGrid[:, 0] = np.array(
list(map(f_init, np.arange(self.xmin, self.xmax+self.dx, self.dx))))
self.FDGrid_ViewBoundary = self.__FDGrid
def CalGrid(self, method='CrankNicolson'):
"""
The method to calculate the grid, specify method by 'Explicit' 'Implicit' or 'CrankNicolson', use Crank-Nocolson method by default
"""
if method == 'Explicit':
"""
Explicit method calculation process
"""
di = (1-2*self.rho)*np.ones((1, self.N-1))
rho_arr = self.rho*np.ones((1, self.N-2))
self.A = np.diagflat(di)+np.diagflat(rho_arr, 1) + \
np.diagflat(rho_arr, -1)
stability_test(self.A)
for jdx in range(0, self.M):
gj = self.cal_gj(jdx)
self.__FDGrid[1:self.N, jdx +
1] = self.A.dot(self.__FDGrid[1:self.N, jdx]+gj)
if method == 'Implicit':
"""
Implicit method calculation process
"""
di = (1+2*self.rho)*np.ones((1, self.N-1))
rho_arr = -self.rho*np.ones((1, self.N-2))
self.B = np.diagflat(di)+np.diagflat(rho_arr, 1) + \
np.diagflat(rho_arr, -1)
for jdx in range(0, self.M):
gj = self.cal_gj(jdx)
self.__FDGrid[1:self.N, jdx+1] = np.linalg.inv(
self.B).dot(self.__FDGrid[1:self.N, jdx]+gj)
if method == 'CrankNicolson':
"""
Crank-Nicolson method calculation process
"""
diC = 2*(1+self.rho)*np.ones((1, self.N-1))
rho_arrC = -self.rho*np.ones((1, self.N-2))
self.C = np.diagflat(diC)+np.diagflat(rho_arrC, 1) + \
np.diagflat(rho_arrC, -1)
diD = 2*(1-self.rho)*np.ones((1, self.N-1))
rho_arrD = self.rho*np.ones((1, self.N-2))
self.D = np.diagflat(diD)+np.diagflat(rho_arrD, 1) + \
np.diagflat(rho_arrD, -1)
for jdx in range(0, self.M):
gj = self.cal_gj(jdx)
gj_plus_one = self.cal_gj(jdx+1)
self.__FDGrid[1:self.N, jdx+1] = np.linalg.inv(self.C).dot(
(self.D.dot(self.__FDGrid[1:self.N, jdx])+self.rho*(gj+gj_plus_one)))
self.FDGrid_full = self.__FDGrid
def cal_gj(self, idx):
"""
Inner function in the calculation process
"""
gj = np.concatenate(([self.__FDGrid[0, idx]], np.zeros(
(self.N-3)), [self.__FDGrid[self.N, idx]]))
return gj
def stability_test(A):
"""
A function to perform stability test for Explicit method
"""
if np.linalg.norm(A, np.inf) <= 1:
print("Convergence analysis show that this method is stable")
else:
print("Stability of this explict method cannot be granteened")
warnings.warn("Stability of this explict method cannot be granteened")
def demo_fun_explict(x):
"""
This is a demo function of specifing boundary conditions
please indicate Piecewise functions by if else statements
"""
if 0 <= x <= 0.5:
return 2*x
elif x >= 0.5 or x <= 1:
return 2*(1-x)
# %%
if __name__ == "__main__":
"""
main function to test code while writing the code
"""
dx = 0.1
dt = 0.001
a = HeatFDGrid(0, dx, 1, dt, 1000*dt)
a.SetBoundaryConditions(demo_fun_explict)
a.CalGrid()
plt.subplot(221)
plt.plot(np.arange(0, 1+dx, dx), a[1])
plt.axis([0, 1, 0, 1])
plt.subplot(222)
plt.plot(np.arange(0, 1+dx, dx), a[:, 10])
plt.axis([0, 1, 0, 1])
plt.subplot(223)
plt.plot(np.arange(0, 1+dx, dx), a[:, 50])
plt.axis([0, 1, 0, 1])
plt.subplot(224)
plt.plot(np.arange(0, 1+dx, dx), a[:, 100])
plt.axis([0, 1, 0, 1])
print(a)
# %%
|
37e5ffffe6565e845e4bd7e536d78b0431c3b9f0 | JaspreetSAujla/Rock_Paper_Scissors | /Python/RockPaperScissors.py | 4,021 | 4.0625 | 4 | import random
import time
import sys
class RockPaperScissors:
"""
A class which stores the code for a game of rock paper scissors.
The game is ran for as long as the user wants to play.
Class Variables:
OPTION_LIST = Stores a list of possible options the computer
can pick.
Methods:
__init__ = Defines the initial variables of the game.
run = Runs the main code for the game.
get_valid_user_choice = Asks the player for a choice and checks
to see if it is valid or not.
determine_winner = Uses if statements to determine the winner
of the game.
"""
OPTION_LIST = ["rock", "paper", "scissors"]
def __init__(self):
"""
Defines the inital variables of the game.
Variables:
self.user_choice = Stores the choice the user makes.
self.computer_choice = Stores the choice the computer makes.
self.play_again = Stores whether the user wants to play again.
"""
self.user_choice = None
self.computer_choice = None
self.play_again = "yes"
def run(self):
"""
Used to run the game.
Game keeps running until the user decides to stop.
"""
print("Welcome to rock paper scissors.")
time.sleep(2)
# Loop over for as long as the user wants to play.
while self.play_again == "yes":
# Computer picks a choice at random.
self.computer_choice = random.choice(RockPaperScissors.OPTION_LIST)
# Ask user for a choice, and check if valid or not.
self.get_valid_user_choice()
print(f"I picked {self.computer_choice}")
time.sleep(2)
#Compares the choices made and works out the winner.
self.determine_winner()
time.sleep(2)
#Asks the user if they want to play again.
self.play_again = input("Would you like to go again? \n(yes/no) \n")
input("ok then, press enter to exit \n")
sys.exit()
def get_valid_user_choice(self):
"""
Asks the user for a choice and performs while loop to see
if the choice is valid or not.
Variables:
valid_choice = Stores whether the user made a valid
choice.
"""
valid_choice = False
while valid_choice == False:
self.user_choice = input("What is your choice? \n(rock/paper/scissors) \n")
if self.user_choice in RockPaperScissors.OPTION_LIST:
valid_choice = True
else:
print("Invalid choice selected, try again.")
def determine_winner(self):
"""
Uses if statements to determine who won the game.
Compares the choices and uses the rules of rock paper scissors
to determine the winner.
"""
if self.user_choice == "rock":
if self.computer_choice == "rock":
print("It's a draw...")
elif self.computer_choice == "paper":
print("Yes, I win!")
elif self.computer_choice == "scissors":
print("There's always next time.")
elif self.user_choice == "paper":
if self.computer_choice == "rock":
print("Which means you win...")
elif self.computer_choice == "paper":
print("Therefore we draw.")
elif self.computer_choice == "scissors":
print("I win!")
elif self.user_choice == "scissors":
if self.computer_choice == "rock":
print("You lose!")
elif self.computer_choice == "paper":
print("You win...")
elif self.computer_choice == "scissors":
print("Hmm a draw.")
if __name__ == "__main__":
rps = RockPaperScissors()
rps.run() |
2f30303fa848bdc4f81678a704e07326ae742985 | rainman011118/python | /new.py | 461 | 3.78125 | 4 | import random
print(dir(random))
print(random.randint(1,100))
print(random.randint(1,100))
print(random.randint(1,100))
print(random.random())
print(random.random())
print(random.random())
arr = []
for i in range(10):
r = random.randint(1,100)
arr.append(r)
print(arr)
print('max = ', max(arr))
print('min = ', min(arr))
for e in arr:
print(e, end=',')
first = "Jack"
last = "Sparrow"
print("{} {}".format(first, last))
print(f'{first} {last}')
|
b8c54987b9c15fd90e1d03d7c449c7a92c39db6a | AlexeyZavar/informatics_solutions | /5 раздел/Задача E.py | 560 | 3.5 | 4 | # С начала суток прошло \(H\) часов, \(M\) минут, \(S\) секунд (\(0\le H <12\), \(0\le M < 60\), \(0\le S < 60\)).
# По данным числам \(H\), \(M\), \(S\) определите угол (в градусах), на который повернулаcь часовая стрелка
# с начала суток и выведите его в виде действительного числа.
import math
h = int(input())
m = int(input())
s = int(input())
n = 3600 * 12 / 360
print((h * 3600 + m * 60 + s) / n)
|
2177cf36111f4195edb2d2a9476715610c953e01 | onuryarartr/trypython | /fonksiyon_problem2.py | 848 | 4.03125 | 4 | """Kullanıcıdan 2 tane sayı alarak bu sayıların en büyük ortak bölenini (EBOB) dönen bir tane fonksiyon yazın.
Problem için şu siteye bakabilirsiniz;
http://www.matematikciler.com/6-sinif/matematik-konu-anlatimlari/1020-en-kucuk-ortak-kat-ve-en-buyuk-ortak-bolen-ebob-ekok"""
print("""*************************************
EBOB Bulucu Uygulama
*************************************
""")
def ebob_bul(sayı1,sayı2):
x = 1
ebob = 1
while(x <= sayı1 and x<= sayı2):
if (not (sayı1 % x) and not (sayı2 % x)):
ebob = x
x += 1
return ebob
sayı1 = int(input("1. Sayıyı girin:"))
sayı2 = int(input("2. Sayıyı girin:"))
print(sayı1,"ve",sayı2,"sayıları için EBOB:",ebob_bul(sayı1,sayı2))
print("\nProgramı kullandığınız için teşekkürler...") |
4d8f2db55ade8cd71415a3e7565cb31371583f1d | dxz6228/Code-Examples | /Python Projects/printedWords.py | 2,227 | 4 | 4 | """
file: printedWords.py
language: python3
author: Denis Zhenilov
description: this program calculates the total amount of printed words per year and proceeds to create a graph plotting the trend for the amount of printed words.
"""
import wordData
from rit_lib import *
def printedWords(words):
"""
This function creates a dictionary, mapping years to the amount of words in them. It then uses the dictionary to produce a list of YearCount classes.
input: dictionary
output: list
"""
wordsPerYear={}
for yearData in words.values():
for year in yearData:
if not (year.year in wordsPerYear):
wordsPerYear[year.year]=wordData.YearCount(year.year,year.count)
else:
wordsPerYear[year.year].count=wordsPerYear[year.year].count+year.count
yearlist=[]
year=1900
while year<=2008:
if (year in wordsPerYear):
yearlist=yearlist+[wordsPerYear[year]]
year=year+1
else:
year=year+1
return yearlist
def wordsForYear(year, yearlist):
"""
This function returns the amount of words that were printed in a given year. If the year is not present in the list of years, it returns 0.
Input: integer, list
output: integer
"""
for el in yearlist:
if el.year==year:
return el.count
return 0
def main():
"""
This is the "main" function which prompts the user for the name of the word file and the year and outputs the total amount of printed words in a given year.
It then constructs a trend graph, showing the amount of printed words, over the whole period of time.
"""
wordfile=input("Enter word file: ")
year=int(input("Enter year: "))
yrlist=printedWords(wordData.readWordFile(wordfile))
total=wordsForYear(year,yrlist)
print("Total printed words in",year,":",total)
import simplePlot
labels = 'Year', 'Total Words'
plot = simplePlot.plot2D('Number of printed words over time', labels)
for yc in yrlist:
point = yc.year, yc.count
plot.addPoint(point)
plot.display()
if __name__ == '__main__':
main() |
f75c6e4894c46bda962a9f89aeee1a9ede2aaffa | Seila2009/Basic_Python | /Lesson_2/HW_2_2.py | 191 | 3.6875 | 4 | My_list = list(input("Введите какое-нибудь число: "))
for i in range(0, len(My_list) - 1, 2):
My_list[i], My_list[i + 1] = My_list[i + 1], My_list[i]
print(My_list) |
0bbd10c4c64b2122a70c71c8d8cedd4f2701bae5 | Jorgelsl/batchroja | /ejercicio 2.py | 1,243 | 3.859375 | 4 | x = int(input("Ingresa un numero X \n"))
y = int(input("Ingresa un numero Y \n"))
z = x % y
print(z)
if z == 0:
print("Exacta")
else:
print("No")
a = int(input("Ingresa un numero X \n"))
b = int(input("Ingresa un numero Y \n"))
if a > b:
print("El primero es el numero mayo")
elif b > a:
print("El primero es el numero menor")
elif a == b:
print ("El valor es el mismo")
e = int(input("Ingresa el año actual\n"))
f = int(input("Ingresa el año que prefieras \n"))
if e > f:
print("Faltan " + str(e - f))
else:
print("Ya pasaron " + str(f - e))
h = int(input("Ingresa un numero porfis\n"))
i = int(input("Ingresa otro numero \n"))
j = int(input("El ultimo y nos vamos\n"))
if h > i and i > j:
print("el numero mayoes es " + str(h))
elif i > h and h > j:
print("el numero mayor es " + str(i))
elif j > h and h > i:
print("el numero mayor es " + str(j))
h = int(input("Ingresa un numero\n"))
i = int(input("Ingresa un numero\n"))
j = int(input("Ingresa un numero\n"))
if h == i and i == j:
print(("todos son iguales"))
elif h == i and i != j:
print("el diferente es " + str(j))
elif j == i and i != h:
print("la obeja negra es " + str(h))
elif h == j and j != i:
print("la obeja negra es " + str(i))
|
eff32d964071467e5dbd6adb8f7878356eb5ed45 | Magreken/Hangman | /Hangman/task/hangman/hangman.py | 1,489 | 3.796875 | 4 | # Write your code here
import random as rd
words = ["python", "java", "kotlin", "javascript"]
print("H A N G M A N")
game = ""
val = rd.randint(0, 3)
word = words[val]
helping = ""
taken = ""
for i in range(len(word)):
helping += "-"
i = 0
while game != "exit":
game = input("""Type "play" to play the game, "exit" to quit: """)
print()
if game == "exit" or game != "play":
continue
while i < 8:
print(helping)
if not ("-" in helping):
break
s = input("Input a letter: ")
tmp = ""
if len(s) != 1:
print("You should input a single letter")
tmp = helping
elif not s.isascii() or s.upper() == s:
print("It is not an ASCII lowercase letter")
tmp = helping
elif s in taken:
print("You already typed this letter")
tmp = helping
elif s in word:
taken += s
for j in range(len(word)):
if word[j] == s:
tmp += s
else:
tmp += helping[j]
else:
print("No such letter in the word")
taken += s
tmp = helping
i += 1
if i == 8:
break
helping = tmp
print()
if i == 8:
print("You are hanged!")
print()
else:
print(f"You guessed the word {helping}!")
print("You survived!")
print()
|
9f5eb849f6428e66c9cf993bf0e43410c29246e3 | dhairyakataria/Data-Structure-and-Algorithms | /Algorithmic Toolbox/week6_dynamic_programming2/2_partitioning_souvenirs/partition3.py | 1,764 | 3.546875 | 4 | # Python3 program for the above approach
dp = {}
# Function to check array can be
# partition into sum of 3 equal
def checkEqualSumUtil(arr, N, sm1, sm2, sm3, j):
s = str(sm1) + "_" + str(sm2) + str(j)
# Base Case
if j == N:
if sm1 == sm2 and sm2 == sm3:
return 1
else:
return 0
# If value at particular index is not
# -1 then return value at that index
# which ensure no more further calls
if s in dp:
return dp[s]
# When element at index
# j is added to sm1
l = checkEqualSumUtil(arr, N, sm1 + arr[j],
sm2, sm3, j + 1)
# When element at index
# j is added to sm2
m = checkEqualSumUtil(arr, N, sm1,
sm2 + arr[j], sm3,
j + 1)
# When element at index
# j is added to sm3
r = checkEqualSumUtil(arr, N, sm1,
sm2, sm3 + arr[j],
j + 1)
# Update the current state and
# return that value
dp[s] = max(l, m, r)
return dp[s]
# Function to check array can be
# partition to 3 subsequences of
# equal sum or not
def checkEqualSum(arr, N):
# Initialise 3 sums to 0
sum1 = sum2 = sum3 = 0
# Function Call
if checkEqualSumUtil(arr, N, sum1,
sum2, sum3, 0) == 1:
print("1")
else:
print("0")
# Driver code
# Given array arr[]
N = int(input())
arr = list(map(int, input().split()))
# Function call
checkEqualSum(arr, N) |
b91f8090178a1a82abbfd024e9df3f6940ff0b4d | synertia/The-Arena | /gladiator.py | 1,670 | 3.65625 | 4 | # gladiator.py
# A betting game allowing the player to bet on one of two randomly generated
# warriors. Winnings will be based on odds generated by the character's stats
# and equipment.
from battle import Battle
from player import Player
import string
from text import printIntro,announceWarriors
def main():
player = Player()
printIntro()
choice = 'yes'
no = ['no','n']
yes = ['yes','y','ye']
while player.getPurse() > 0 and choice not in no:
print "You have", player.getPurse(),"in your pouch.\n"
battle = Battle()
print "\nThe next battle is between %s and %s.\n" % (battle.warrior1.getName(),battle.warrior2.getName())
announceWarriors(battle.warrior1,battle.odds1,battle.warrior2,battle.odds2)
print "\nDo you want to bet?\n\n"
player.getChoice(battle.warrior1,battle.warrior2)
winner, odds = battle.battle()
if winner == player.getPick():
player.updatePurse("win",player.getBet(),odds)
else:
player.updatePurse("lose",player.getBet(),odds)
print "\nWould you like to bet on the next battle?\n"
while True:
try:
choice = string.lower(str(raw_input(">> ")))
if choice in yes:
break
elif choice in no:
choice = 'no'
break
else:
print "\nPlease choose yes or no.\n"
continue
except ValueError:
print "\nPlease choose yes or no.\n"
continue
print "\nThank you so much for playing!\n"
if player.getPurse() > 1:
print "\nYou leave the Colosseum with %d coins in your purse.\n" % player.getPurse()
elif player.getPurse() == 1:
print "\nYou leave the Colosseum with one coin, not even another to rub it against.\n"
else:
print "\nYou're leaving dead broke!\n"
main()
|
b9743952b423e0708fe95ff3303c9a6b9d18fb87 | GusRigor/Sistema-e-Sinais | /Atividade 6/aula10.py | 2,573 | 3.65625 | 4 | import matplotlib.pyplot as plt
def verifica_entrada(str,*args):
entrada = input(str).upper()
for x in args:
if x == entrada:
return entrada
print('Entrada inválida. Insira novamente um dos comandos.')
return verifica_entrada(str,args)
def verifica_entrada_num(str):
entrada = input(str)
if any(chr.isdigit() for chr in entrada):
return float(entrada)
print('Entrada inválida. Insira novamente um valor válido.')
return verifica_entrada_num(str)
def plot_grafico(t,x,y, delta_t):
plt.subplot(2,2,1)
plt.plot(t, x, label='x(t)')
plt.legend()
plt.subplot(2,2,2)
plt.stem(t,x, label='x(T)')
plt.legend()
plt.subplot(2,2,3)
plt.stem(t,y, label='y(T)')
plt.legend()
plt.subplot(2,2,4)
plt.plot(t, y, label='y(t)')
plt.legend()
plt.show()
r_or_p = True if "R"==verifica_entrada('Reta ou Parábola? [R/P]','R', 'P') else False
if r_or_p:
print('Você selecionou RETA, insira os valores de A e B ( y(x) = Ax + B )')
a = verifica_entrada_num('Insira o valor de A: ')
b = verifica_entrada_num('Insira o valor de B: ')
Tm = verifica_entrada_num('Insira o valor de T mín [coloque 0 para o valor padrão]: ')
T = verifica_entrada_num('Insira o valor de T máx [coloque 0 para o valor padrão]: ')
T = 2 if T==0 else T
delta_t = verifica_entrada_num('Insira o valor de delta t [coloque 0 para o valor padrão]: ')
delta_t = 0.5 if delta_t==0 else delta_t
t = [Tm]
x = [a*t[-1] + b]
y = [0]
while t[-1] <= T:
t.append(t[-1]+delta_t)
x.append(a*t[-1] + b)
y.append((x[-1] - x[-2])/delta_t)
plot_grafico(t,x,y,delta_t)
else:
print('Você selecionou PARÁBOLA, insira os valores de A, B e C ( y(x) = Axˆ2 + Bx + C )')
a = verifica_entrada_num('Insira o valor de A: ')
b = verifica_entrada_num('Insira o valor de B: ')
c = verifica_entrada_num('Insira o valor de C: ')
Tm = verifica_entrada_num('Insira o valor de T mín [coloque 0 para o valor padrão]: ')
T = verifica_entrada_num('Insira o valor de T máx[coloque 0 para o valor padrão]: ')
T = 2 if T==0 else T
delta_t = verifica_entrada_num('Insira o valor de delta t [coloque 0 para o valor padrão]: ')
delta_t = 0.05 if delta_t==0 else delta_t
t = [Tm]
x = [a*t[-1]*t[-1] + b*t[-1] + c]
y = [0]
while t[-1] <= T:
t.append(t[-1]+delta_t)
x.append(a*t[-1]*t[-1] + b*t[-1] + c)
y.append((x[-1] - x[-2])/delta_t)
plot_grafico(t,x,y, delta_t)
|
a35fd9f3ff45bcd10259832c3b2a842a976326b8 | rsamit26/InterviewBit | /Python/GreedyAlgorithm/Highest Product.py | 1,235 | 3.875 | 4 | """
Given an array of integers, return the highest product possible by multiplying 3 numbers from the array
Input:
array of integers e.g {1, 2, 3}
NOTE: Solution will fit in a 32-bit signed integer
Example:
[0, -1, 3, 100, 70, 50]
=> 70*50*100 = 350000
"""
class Solution:
# T = O(nlogn)
def highest_product(self, arr):
arr.sort()
n = len(arr)
return max(arr[0] * arr[1] * arr[n - 1], arr[n - 1] * arr[n - 2] * arr[n - 3])
# T = O(n)
def method_02(self, arr):
if len(arr) < 3:
return 0
import sys
min1 = min2 = sys.maxsize
max1 = max2 = max3 = -sys.maxsize
for item in arr:
if item > max1:
max3 = max2
max2 = max1
max1 = item
elif item > max2:
max3 = max2
max2 = item
elif item > max3:
max3 = item
if item < min1:
min2 = min1
min1 = item
elif item < min2:
min2 = item
return max(min1 * min2 * max1, max1 * max2 * max3)
s = Solution()
ar = [-10000000, 1, 2, 3, 4]
print(s.highest_product(ar))
print(s.method_02(ar))
|
087f951330ce914732907e8ae6101e37a8ad7f89 | mikefgalvin/cs_py_linked_lists | /src/stack/stack_deque.py | 422 | 3.796875 | 4 | from collections import deque
class Stack:
def __init__(self):
self.storage = deque()
def __len__(self):
return len(self.storage)
def push(self, value):
self.storage.append(value)
def pop(self):
# if deque is empty,
if len(self.storage) == 0:
# then attempting to pop below would throw an error
return
return self.storage.pop()
|
b89c8ddbd1ead560d3b37037d74e35f77fbfccf0 | q42355050/260201026 | /lab04/example4.py | 149 | 3.78125 | 4 | # Power
a = int(input("a = "))
b = int(input("b = "))
result = 1
if(a == 0):
result = 1
else:
for i in range (b):
result *= a
print(result) |
2d35a386b2443aedfe6e2d858bb5a423973a2f8b | Drewleks/learn-python-the-hard-way | /ex16/ex16.py | 907 | 3.609375 | 4 | from sys import argv
script, filename = argv
print(f"Я собираюсь стереть файл {filename}.")
print("Если вы не хотите стирать его, нажмите сочетание клавиш CTRL+C (^C).")
print("Если хотите стереть файл, нажмите клавишу Enter.")
input("?")
print("Открытие файла...")
target = open(filename, 'w')
print("Очистка файла. До свидания!")
target.truncate()
print("Теперь я запрашиваю у вас три строки.")
line1 = input("строка 1: ")
line2 = input("строка 2: ")
line3 = input("строка 3: ")
print("Это я запишу в файл.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("И наконец, я закрою файл.")
target.close()
|
26e3092ff4fbaecff61e12109680eda6ebffe198 | kabeerchhillar/FirstPy | /BooksWithSql.py | 2,587 | 4 | 4 | import DataSql
#
# MyBook Schema :
# id integer PRIMARY KEY
# name text NOT NULL
# author text
# year integer
# doIHaveIt boolean
def add_books(conn,book):
sql = ''' INSERT INTO my_book (name,author,year,DoIHaveIt)
VALUES(?,?,?,?); '''
cur = conn.cursor()
cur.execute(sql,book)
return cur.lastrowid
def create_my_book_table(conn):
sql_create_books_table = """
CREATE TABLE IF NOT EXISTS my_book (
id integer PRIMARY KEY,
name text NOT NULL,
author text,
year integer,
DoIHaveIt text ); """
if conn is not None:
DataSql.create_table(conn,sql_create_books_table)
else:
print("Error! cannot create the database connection.")
def input_destinations(user_input,connection):
if user_input == "0":
create_my_book_table(connection)
if user_input == "1":
# book_name = str(input("Name the Book "));
# book_author = str(input("Name the Author "));
# book_year = int(input(" Give the year of book "));
# book_Ihave = str(input(" Do i have the book "));
# book = (book_name, book_author, book_year, book_Ihave);
book = ("abcd", "xxaqws", 1999, "yes");
add_books(connection,book);
def main():
main_input = 0
connection = DataSql.create_database("myBooks.db")
while main_input != 10:
print("What do you like to do \n "
" 0. Create Database and Table"
" 1. Add a Name\n "
" 2. find a name \n "
" 3. print the list \n "
" 4. delete a name \n "
" 5. Find book with substring \n "
" 6. find book using year \n "
" 7. find year of publishment \n "
" 8. find how many times kabeer has read the book \n "
" 9. find if kabeer has the book or not \n "
" 10. exit");
main_input = input(": ")
# print(type(main_input))
input_destinations(str(main_input),connection)
book = ("abcd", "xxaqws", 1999, "yes");
add_books(connection, book);
return
if __name__ == '__main__':
main() |
387d8c54f238ea62da11426d7c3f7709bc7a09ea | sonal2706/traffic-congestion-detector | /detect.py | 1,595 | 3.734375 | 4 | # OpenCV Python program to detect cars in video frame
# import libraries of python OpenCV
import cv2
# capture frames from a video
cap = cv2.VideoCapture('dataset/video1.avi')
# Trained XML classifiers describes some features of some object we want to detect
car_cascade = cv2.CascadeClassifier('cars.xml')
def rotate(image,angle):
(h, w) = image.shape[:2]
center = (w / 2, h)
# rotate the image by 180 degrees
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
def count_cars(image,ind):
# convert to gray scale of each frames
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detects cars of different sizes in the input image
cars = car_cascade.detectMultiScale(gray, 1.1, 1)
# To draw a rectangle in each cars
for (x,y,w,h) in cars:
cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)
cv2.namedWindow("Channels"+str(ind))
cv2.imshow('Channels'+str(ind), image)
return len(cars)
# loop runs if capturing has been initialized.
while True:
# reads frames from a video
ret, frames = cap.read()
north_up = rotate(frames,12)
north_down = north_up[20:330, 0:150]
north_up = north_up[20:300, 150:300]
south_up =frames[300:550,0:300]
cnt1 = count_cars(north_down,1)
cnt2 = count_cars(north_up,2)
cnt3 = count_cars(south_up,3)
print (cnt1,cnt2,cnt3)
# Wait for Esc key to stop
if cv2.waitKey(33) == 27:
break
# De-allocate any associated memory usage
cv2.destroyAllWindows()
|
47373b580d2abdd0a1bd2c8b53b22cae4e45f380 | Aiyane/aiyane-LeetCode | /1-50/两数相加.py | 1,505 | 3.6875 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python3
# File Name: 两数相加.py
# Created Time: Sun 29 Apr 2018 11:14:52 PM CST
"""
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
"""
"""
思路: 只改一个链表, 只改指针, 知道divmod的用法
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# 保留头节点
l = l1
# 不存在 l2
if not l2:
return l
# 不存在 l1
if not l1:
return l2
# 简单相加
ne, l1.val = divmod(l1.val + l2.val, 10)
while l1.next and l2.next:
l1, l2 = l1.next, l2.next
ne, l1.val = divmod(l1.val + l2.val + ne, 10)
# 连接
if l2.next:
l1.next = l2.next
# 还有进位
while l1.next and ne > 0:
l1 = l1.next
ne, l1.val = divmod(l1.val + ne, 10)
# 末尾进位
if ne:
l1.next = ListNode(ne)
return l
|
3902382bc721e73ae5773e70f72d75f6da0fd824 | ayrra/python_practice | /5-user_interfaces_database/bookstore_script.py | 3,809 | 3.578125 | 4 | from tkinter import *
from backend import Database
database=Database()
class Window:
def __init__(self,window):
self.window=window
self.window.wm_title("Bookstore Database App")
title_label=Label(window,text="Title")
title_label.grid(row=0,column=0)
self.title_value=StringVar()
self.title_entry=Entry(window,textvariable=self.title_value)
self.title_entry.grid(row=0,column=1)
author_label=Label(window,text="Author")
author_label.grid(row=0,column=2)
self.author_value=StringVar()
self.author_entry=Entry(window,textvariable=self.author_value)
self.author_entry.grid(row=0,column=3)
year_label=Label(window,text="Year")
year_label.grid(row=1,column=0)
self.year_value=StringVar()
self.year_entry=Entry(window,textvariable=self.year_value)
self.year_entry.grid(row=1,column=1)
isbn_label=Label(window,text="ISBN")
isbn_label.grid(row=1,column=2)
self.isbn_value=StringVar()
self.isbn_entry=Entry(window,textvariable=self.isbn_value)
self.isbn_entry.grid(row=1,column=3)
self.lb = Listbox(window,height=6,width=35)
self.lb.grid(row=2,column=0,rowspan=6,columnspan=2)
sb=Scrollbar(window)
sb.grid(row=2,column=2, rowspan=6)
self.lb.configure(yscrollcommand=sb.set)
sb.configure(command=self.lb.yview)
self.lb.bind('<<ListboxSelect>>',self.get_selected_row)
viewall_button=Button(window,text="View All",width=12,command=self.view_db)
viewall_button.grid(row=2,column=3)
searchentry_button=Button(window,text="Search Entry",width=12,command=self.search_db)
searchentry_button.grid(row=3,column=3)
addentry_button=Button(window,text="Add Entry",width=12,command=self.add_db)
addentry_button.grid(row=4,column=3)
update_button=Button(window,text="Update",width=12,command=self.update_db)
update_button.grid(row=5,column=3)
delete_button=Button(window,text="Delete",width=12,command=self.delete_db)
delete_button.grid(row=6,column=3)
close_button=Button(window,text="Close",width=12,command=window.destroy)
close_button.grid(row=7,column=3)
def get_selected_row(self,event):
if len(self.lb.curselection()) > 0:
index=self.lb.curselection()
self.selected_item=self.lb.get(index)
self.title_entry.delete(0,END)
self.title_entry.insert(END,self.selected_item[1])
self.author_entry.delete(0,END)
self.author_entry.insert(END,self.selected_item[2])
self.year_entry.delete(0,END)
self.year_entry.insert(END,self.selected_item[3])
self.isbn_entry.delete(0,END)
self.isbn_entry.insert(END,self.selected_item[4])
def view_db(self):
self.lb.delete(0,END)
for row in database.view():
self.lb.insert(END,row)
def search_db(self):
self.lb.delete(0,END)
for row in database.search(self.title_value.get(),self.author_value.get(),self.year_value.get(),self.isbn_value.get()):
self.lb.insert(END,row)
def add_db(self):
self.lb.delete(0,END)
database.insert(self.title_value.get(),self.author_value.get(),self.year_value.get(),self.isbn_value.get())
self.lb.insert(END,(self.title_value.get(),self.author_value.get(),self.year_value.get(),self.isbn_value.get()))
def update_db(self):
database.update(self.selected_item[0],self.title_value.get(),self.author_value.get(),self.year_value.get(),self.isbn_value.get())
def delete_db(self):
database.delete(self.selected_item[0])
window=Tk()
Window(window)
window.mainloop() |
dd904c382cb9bd5cb027a73a984f584a087c32fb | Cherry93/coedPractices | /demos/W1/day4/00Homework2.py | 1,155 | 3.9375 | 4 | '''
·求当前时间距离1970年0时逝去了多少秒
·求当前时间距离1970年0时逝去了多少分钟
·求当前时间距离1970年0时逝去了多少小时
·求当前时间距离1970年0时逝去了多少天
·求当前时间距离1970年0时逝去了多少年
·求当前时分秒
'''
import time
# 求当前时间距离1970年0时逝去了多少秒
seconds = int(time.time())
print(seconds)
# 求当前时间距离1970年0时逝去了多少分钟
minutes = seconds // 60
print(minutes)
# ·求当前时间距离1970年0时逝去了多少小时
hours = seconds // (60*60)
print(hours)
# ·求当前时间距离1970年0时逝去了多少天
days = seconds // (60*60*24)
print(days)
# ·求当前时间距离1970年0时逝去了多少年
years = seconds // (60*60*24*365)
print(years)
# ·求当前时分秒
todaySeconds = seconds % (60*60*24)
timeHours = todaySeconds // 3600 + 8
timeMinutes = todaySeconds % 3600 // 60
timeSeconds = todaySeconds % 60
# print(timeHours,timeMinutes,timeSeconds)
# print("当前时间:",timeHours,":",timeMinutes,":",timeSeconds)
print("当前时间:%d:%d:%d"%(timeHours,timeMinutes,timeSeconds))
|
f68b1120870966cf0148dbba8c609b6bfa361eb8 | NikiDimov/SoftUni-Python-Basics | /exam/grandpa_stavri.py | 510 | 3.953125 | 4 | days = int(input())
total_degrees = 0
total_litters = 0
for day in range(days):
litter = float(input())
total_litters += litter
current_degree = float(input())
total_degrees += current_degree*litter
middle_degrees = total_degrees / total_litters
print(f"Liter: {total_litters:.2f}")
print(f"Degrees: {middle_degrees:.2f}")
if middle_degrees < 38:
print(f"Not good, you should baking!")
elif 38 <= middle_degrees <= 42:
print("Super!")
else:
print("Dilution with distilled water!")
|
47ce1fa46945e0d9bbbd4dc18658af38becf4f8e | brianwgoldman/Analysis-of-CGPs-Mechanisms | /problems.py | 15,207 | 3.578125 | 4 | '''
Defines each of the benchmark problems used as well as the function sets
for those problems.
'''
from operator import or_, and_, add, sub, mul, div, xor
import itertools
import random
import math
def nand(x, y):
'''
Simple Nand function for inclusion in function sets.
'''
return not (x and y)
def nor(x, y):
'''
Simple Nor function for inclusion in function sets.
'''
return not (x or y)
def and_neg_in(x, y):
return (not x) and y
def protected(function):
'''
Decorator that ensures decorated functions always have a valid output.
If an exception occurs or infinity is returned, the first argument of the
function will be returned.
Parameters:
- ``function``: The function to be decorated.
'''
def inner(*args):
try:
# Call the function on the arguments
value = function(*args)
if math.isinf(value):
return args[0]
return value
except (ValueError, OverflowError, ZeroDivisionError):
return args[0]
inner.__name__ = function.__name__
return inner
def arity_controlled(desired):
'''
Decorator used to make functions take any number of inputs while only
using the first ``desired`` number of arguments. For example, you can
pass 10 arguments to a function that takes only 1 if ``desired=1`` and
the first of the arguments will actually be used. Currently unused.
Parameters:
- ``desired``: The actual arity of the wrapped function.
'''
def wrap(function):
def inner(*args):
return function(*args[:desired])
inner.__name__ = function.__name__
return inner
return wrap
# Standard lists of operators for different problems to use
binary_operators = [or_, and_, nand, nor]
regression_operators = [add, sub,
mul, div]
# Ensures all regression operators are numerically protected
regression_operators = [protected(op) for op in regression_operators]
class Problem(object):
'''
The abstract base of a problem
'''
def __init__(self, config):
'''
Designed to force children of this class to implement this function.
Children use this function to set up problem specific initialization
from configuration information.
'''
raise NotImplementedError()
def get_fitness(self, individual):
'''
Designed to force children of this class to implement this function.
Children use this function evaluate an individual and
return its fitness.
'''
raise NotImplementedError()
class Bounded_Problem(object):
'''
Base object for any problem with a known set of test cases. Stores a
map for all possible inputs to their correct outputs so they only
have to be evaluated once.
'''
def __init__(self, config):
'''
Create a new problem.
Parameters:
- ``config``: A dictionary containing the configuration information
required to fully initialize the problem. Should include values
for:
- Any configuration information required to construct the problem
range.
- ``epsilon``: The amount of allowed error on each test.
'''
self.config = config
self.training = [(inputs, self.problem_function(inputs))
for inputs in self.data_range(config)]
self.epsilon = config['epsilon']
def get_fitness(self, individual):
'''
Return the fitness of an individual as applied to this problem.
Parameters:
- ``individual``: The individual to be evaluated.
'''
score = 0
for inputs, outputs in self.training:
answers = individual.evaluate(inputs)
# Finds the average number of outputs more than epsilon away from
# the correct output
score += (sum(float(abs(answer - output) > self.epsilon)
for answer, output in zip(answers, outputs))
/ len(outputs))
# Returns the percentage of correct answers
return 1 - (score / float(len(self.training)))
def problem_function(self, _):
'''
Designed to force children of this class to implement this function.
Children use this function to define how to translate an input value
into an output value for their problem.
'''
raise NotImplementedError()
def binary_range(config):
'''
Given a dictionary specifying the ``input_length``, returns all binary
values of that length.
'''
return itertools.product((0, 1), repeat=config['input_length'])
def single_bit_set(config):
'''
Creates the list of all possible binary strings of specified length
with exactly one set bit. ``config`` should specify the ``input_length``.
'''
return [tuple(map(int,
'1'.rjust(i + 1, '0').ljust(config['input_length'], '0')
)
)
for i in range(config['input_length'])]
def float_samples(config):
'''
Returns random samples of the input space.
Parameters:
- ``config``: A dictionary containing information about the input space.
- ``min``: The minimum valid value in the space.
- ``max``: The maximum valid value in the space.
- ``input_length``: The number of input variables.
- ``samples``: The number of samples to draw.
'''
return ([random.uniform(config['min'], config['max'])
for _ in xrange(config['input_length'])]
for _ in xrange(config['samples']))
def float_range(config):
'''
Returns a incremental range of a floating point value. Like range() for
floats.
Parameters:
- ``config``: A dictionary containing information about the input space.
- ``min``: The minimum valid value in the space.
- ``max``: The maximum valid value in the space.
- ``step``: The distance between sample points.
'''
counter = 0
while True:
value = counter * config['step'] + config['min']
if value > config['max']:
break
yield value
counter += 1
def n_dimensional_grid(config):
'''
Returns a multidimensional grid of points in the input space.
Parameters:
- ``config``: A dictionary containing information about the input space.
- All configuration information required by ``float_range``.
- ``input_length``: How many dimensions are in the input space.
'''
return itertools.product(float_range(config),
repeat=config['input_length'])
class Binary_Mixin(object):
'''
Inheritance mixin useful for setting the class attributes of
binary problems.
'''
data_range = staticmethod(binary_range)
operators = binary_operators
max_arity = 2
class Regression_Mixin(object):
'''
Inheritance mixin useful for setting the class attributes of
regression problems.
'''
data_range = staticmethod(float_range)
operators = regression_operators
max_arity = 2
class Neutral(Problem):
'''
Defines the Neutral problem, in which all individuals receive the same
fitness. The only operator in this function is 'None', meaning only
connection genes actually evolve.
'''
operators = [None]
max_arity = 2
def __init__(self, _):
'''
Doesn't require initialization, but must implement.
'''
pass
def get_fitness(self, _):
'''
Returns the fitness of passed in individual, which is always 0.
'''
return 0
class Even_Parity(Bounded_Problem, Binary_Mixin):
'''
Defines the Even Parity problem.
'''
def problem_function(self, inputs):
'''
Return the even parity of a list of boolean values.
'''
return [(sum(inputs) + 1) % 2]
class Binary_Multiply(Bounded_Problem, Binary_Mixin):
'''
Defines the Binary Multiplier problem.
'''
def problem_function(self, inputs):
'''
Return the result of performing a binary multiplication of the first
half of the inputs with the second half. Will always have the same
number of output bits as input bits.
'''
# convert the two binary numbers to integers
joined = ''.join(map(str, inputs))
middle = len(joined) / 2
a, b = joined[:middle], joined[middle:]
# multiply the two numbers and convert back to binary
multiplied = bin(int(a, 2) * int(b, 2))[2:]
# pad the result to have enough bits
extended = multiplied.rjust(len(inputs), '0')
return map(int, extended)
class Binary_Multiply_Miller(Binary_Multiply):
operators = [and_, and_neg_in, xor, or_]
class Binary_Multiply_Torresen(Binary_Multiply):
operators = [and_, xor]
class Multiplexer(Bounded_Problem, Binary_Mixin):
'''
Defines the Multiplexer (MUX) Problem.
'''
def problem_function(self, inputs):
'''
Uses the first k bits as a selector for which of the remaining bits to
return.
'''
k = int(math.log(len(inputs), 2))
index = int(''.join(map(str, inputs[:k])), 2) + k
return [inputs[index]]
class Demultiplexer(Bounded_Problem, Binary_Mixin):
'''
Defines the Demultiplexer (DEMUX) Problem.
'''
def problem_function(self, inputs):
'''
Returns the last input bit on the output line specified by the binary
index encoded on all inputs except the last bit.
'''
k = int(math.log(len(inputs) - 1, 2))
index = int(''.join(map(str, inputs[:k])), 2) + k
return [inputs[index]]
class Binary_Encode(Bounded_Problem, Binary_Mixin):
'''
Defines the Binary Encode problem.
'''
# Set the data range to be all possible inputs with a single set bit.
data_range = staticmethod(single_bit_set)
def problem_function(self, inputs):
'''
Returns the binary encoding of which input line contains a one.
'''
oneat = inputs.index(1)
binary = bin(oneat)[2:]
width = math.log(len(inputs), 2)
return map(int, binary.zfill(int(width)))
class Binary_Decode(Bounded_Problem, Binary_Mixin):
'''
Defines the Binary Decode problem.
'''
def problem_function(self, inputs):
'''
Returns a 1 on the output line specified by the binary input index
'''
combined = ''.join(map(str, inputs))
width = 2 ** len(inputs)
base = [0] * width
base[int(combined, 2)] = 1
return base
class Breadth(Bounded_Problem, Binary_Mixin):
'''
Defines the Breadth problem.
'''
# Set the data range to be all possible inputs with a single set bit.
data_range = staticmethod(single_bit_set)
# Set the list of possible operators to just be OR.
operators = [or_]
def problem_function(self, inputs):
'''
Returns true as long as at least one input is true.
'''
return [sum(inputs) > 0]
class TwoFloor(Bounded_Problem, Binary_Mixin):
'''
Defines the Two Floor Problem.
'''
# Set the data range to be all possible inputs with a single set bit.
data_range = staticmethod(single_bit_set)
# Set the list of possible operators to just be OR.
operators = [or_]
def problem_function(self, inputs):
'''
Returns a string of bits half as long as the input string, where
the only set output bit is at the index // 2 of the set input bit.
'''
results = [0] * (len(inputs) // 2)
results[inputs.index(1) // 2] = 1
return results
class Depth(Problem):
'''
Defines the Depth problem.
'''
# Set the list of possible operators to just be just min(X, Y) + 1.
operators = [lambda X, Y: min(X, Y) + 1]
max_arity = 2
def __init__(self, config):
'''
Saves configuration for use during evaluation.
'''
self.config = config
def get_fitness(self, individual):
'''
Returns the fitness of the individual as a percentage of maximum
fitness.
'''
score = individual.evaluate((0,))[0]
return score / float(self.config['graph_length'])
class Flat(Problem):
'''
Defines the Flat problem, in which all individuals receive fitness
based on how many connection genes are connected to the input.
The only operator in this function is 'None', meaning only
connection genes actually evolve.
'''
operators = [None]
max_arity = 2
def __init__(self, _):
'''
Doesn't require initialization, but must implement.
'''
pass
def get_fitness(self, individual):
'''
Returns the percentage of connection genes connected to the input.
'''
correct, total = 0, 0
for gene in individual.genes:
if gene is not None:
if gene < 0:
correct += 1
total += 1
return correct / float(total)
class Novel(Problem, Binary_Mixin):
'''
Defines the Novel problem, which evaluates individuals based on how many
unique semantics the individual can create.
'''
def __init__(self, config):
complete = float(2 ** 2 ** config['input_length'])
self.best = float(min(complete, config['graph_length']))
def get_fitness(self, individual):
for inputs in binary_range(self.config):
individual.evaluate(inputs)
return len(set(individual.semantics)) / self.best
class Active(Problem):
'''
Defines the Active problem, in which all individuals receive fitness
based on how many active nodes they have.
The only operator in this function is 'None', meaning only
connection genes actually evolve.
'''
operators = [None]
max_arity = 2
def __init__(self, config):
'''
Saves configuration for use during evaluation.
'''
self.config = config
def get_fitness(self, individual):
'''
Returns the percentage of nodes that are active.
'''
return len(individual.active) / float(self.config['graph_length'])
class Koza_1(Bounded_Problem, Regression_Mixin):
'''
Defines the Koza-1 problem.
'''
def koza_quartic(self, inputs):
'''
Return the result of Koza-1 on the specified input. Expects the input
as a single element list and returns a single element list.
'''
x = inputs[0]
return [x ** 4 + x ** 3 + x ** 2 + x]
class Pagie_1(Bounded_Problem, Regression_Mixin):
'''
Defines the Pagie-1 problem.
'''
# Set the data range to be an n dimensional grid.
data_range = staticmethod(n_dimensional_grid)
def pagie(self, inputs):
'''
Returns the result of Pagie-1 on the specified inputs.
'''
x, y = inputs
return [1.0 / (1 + x ** -4) + 1.0 / (1 + y ** -4)]
|
14081cd964d121a754c42302b5998d53397b69b3 | padack/Practice | /Practice_연산자.py | 3,702 | 3.765625 | 4 | '''
1.산술 연산자
+
-
*
/ : 두값을 나눈 결과를 반환(실수 값)
// : 두 값을 나눈 결과의 몫 반환(정수 값)
% : 두 값을 나눈 결과의 나머지 반환
** : 거듭 제곱의 결과 바환
== : 두 피 연산자 값을 비교하여 동일하면 True, 동일하지 않으면 False
예) 3==3 (True) , 3==4(False)
!= : 두 피 연산자 값을 비교하여 동일하면 False, 동일하지 않으면 True(연산자 '=='와 반대개념)
> : 두 피 연산자 값을 비교하여 왼쪽의 값이 크면 True, 그렇지 않으면 False
< : 오른쪽의 값이 크면 True, 그렇지 않으면 False
>= : 두 피 연산자 값을 비교하여 왼쪽의 값이 크거나 같으면 True, 그렇지 않으면 False
<= : 오른쪽의 값이 크거나 같으면 True, 그렇지 않으면 False
* 파이썬에 True == 1 => True *
'''
x=input('정수 혹은 문자1 : ')
y=input('정수 혹은 문자2 : ')
print('x는 {}이고, y는 {}일때.'.format(x,y))
print('x==y는 {}'.format(x==y))
# 같음과 다름은 숫자, 문자끼리 비교가 가능하며 숫자와 문자도 비교 가능하고, type(int,float)과 type(str)도 비교 가능
print('x!=y는 {}'.format(x != y))
print('x<y는 {}'.format(x<y))
print('x>y는 {}'.format(x>y))
print('x<=y는 {}'.format(x<=y))
print('x>=y는 {}'.format(x>=y))
print('{:-^50}'.format('-'))
'''
2.논리 연산자
and : 두 피 연산자가 전부 True인 경우에만 Trud(논리곱)
or : 두 피 연산자가 전부 False인 경우에만 False(논리합)
not : 오른쪽 피 연산자에 대한 부정
'''
print("x=3,y=5,a='a',b='b'일때")
x=3
y=5
a='a'
b='b'
print('x<y는 {}'.format(x<y)),print('a!=b는 {}'.format(a!=b))
print(' x<y and a!=b는 {}'.format(x<y and a!=b))
print(' x>y and a==b는 {}'.format(x<y and a==b))
print('x>y or a!=b는 {}'.format(x<y and a!=b))
print('not x<y는 {}'.format(x<y))
print('{:-^50}'.format('-'))
'''
3.멤버 연산자
in : 왼쪽 피 연산자 값이 오른쪽 피 연산자 멤버 중 일치하는 값이 존재 하면
not in : 왼쪽 피 연산자 값이 오른쪽 피 연산자 멤버 중 일치하는 값이 존재 하지 않으면 True
4.식별 연산자
is : 두 피 연산자의 식별 값을 비교하였을 때 동일한 객체이면 True
is not : 두 피 연산자의 식별 값을 비교하였을 때 동일한 객체이면 False
'''
print(1 in (1,2,3,4))
print(2 in (1,3,5,7))
print(1 is type(str))
print(1 is not type(str))
print('{:-^50}'.format('-'))
'''
4.비트 연산자
& : 두 피 연산자의 and 비트 연산을 수행함
0&0 -> 0
0&1 -> 0
1&0 -> 0
1&1 -> 1
| : 두 피 연산자의 or 비트 연산을 수행함
0 | 0 -> 0
0 | 1 -> 1
1 | 0 -> 1
1 | 1 -> 1
^ : 두 피 연산자의 xor 비트 연산을 수행함
0^0 -> 0
0^1 -> 1
1^0 -> 1
1^1 -> 0
[자석의 N극 S극 개념과 비슷]
<< : 왼쪽 피 연산자의 비트를 왼쪽으로 2개 비트 이동
비트 2배 증가
>> : 왼쪽 피 연산자의 비트를 오른쪽로 2개비트 이동
비트 2배 감소
'''
print(bin(10))
print(bin(5))
print(10&5)
'''
10=1010
& 5=0101
----------
0000 = 0
'''
print(10 | 5)
'''
10=1010
| 5=0101
-----------
1111 = 15
'''
print(10^5)
'''
10=1010
^ 5=0101
------------
1111 = 15
'''
print(10<<2)
'''
10 = 1010
10<<2 = 101000 = 40 => 1010'00' : 2개 오른쪽으로 이동
'''
print(bin(10<<2)) # 10<<2 를 비트 값으로 출력
print('{:b}'.format(10<<2)) # 10<<2 를 2진수 값으로 출력
print(10>>2)
'''
10 = 1010
10>>2 = 10 = 2 (1010 이 왼쪽으로 2칸 이동하면서 오른쪽 '10'삭제)
'''
print(bin(10>>2))
print('{:b}'.format(10>>2))
|
fb57042cee22e7c9a9d30de59e850d4ebbf597da | azad-2021/python | /Data_science/pandas/reading_csv.py | 369 | 3.640625 | 4 | import pandas as pd
#reading csv file
data = pd.read_csv('data.csv')
x = data.head() #prints first five data set.
print(x,'\n')
a = data.head(10) #prints first 10 data set.
print(a,'\n')
#reading excel file
df = pd.read_excel('data.xlsx')
z = df.head() #returns first five rows
print(z,'\n')
b = df.head(10) #returns first ten rows
print(b,'\n') |
c0bbcceca4de90a0aa057b9e5abd1e069583e500 | namth2015/python | /1.DataScience/2.BigO/Green18/lec7_check_numeric_character.py | 120 | 3.546875 | 4 | a = input()
b = ''
for i in range(len(a)):
if ord(a[i]) >= 48 and ord(a[i]) <=57:
b = b + a[i]
print(len(b)) |
2ffce4d1e0fec81b2dacd54d535a13a83f5ab85c | ldmgogogo1995/python | /day01/inputAndOutput.py | 145 | 3.5 | 4 | print('the quick brown fox', 'jumps over', 'the lazy dog')
输出表达式
print('100+200=', 100+200)
input
name = input()
print('Hello,', name)
|
e9afdb66392322be689424b9c5e2267d2d0fdc1c | BgLoveXixi/algorithm011-class02 | /Week_02/homework.py | 3,052 | 3.890625 | 4 | ##NO.1 N叉树的前序遍历
##给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
##你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
##给定一个 N 叉树,返回其节点值的前序遍历。
##例如,给定一个 3叉树 :
## 1
## 3 2 4
## 5 6
##返回其前序遍历: [1,3,5,6,2,4]。
# 直接递归
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if root is None: #直至为空
return []
result = [root.val] #存为链表
for node in root.children:
result.extend(self.preorder(node)) #根节点后添加子节点的值,前序遍历
return result
# 迭代法
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if root is None:
return []
s = [root]
result = []
while s:
node = s.pop()
result.append(node.val)
s.extend(node.children[::-1]) #添加所有孩子的值
return result
##NO.2 N叉树的层序遍历
# 给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
# 例如,给定一个 3叉树 :
# 1
# 3 2 4
# 5 6
#返回其层序遍历:
#
#[
# [1],
# [3,2,4],
# [5,6]
#]
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root is None:
return []
result = []
queue = collections.deque([root]) ##双向列表
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
queue.extend(node.children)
result.append(level)
return result
##NO.3 丑数
#我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
#
#示例:
#输入: n = 10
#输出: 12
#解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
#说明:
#1 是丑数。
#n 不超过1690。
#动态规划解
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
dp, a, b, c = [1] * n, 0, 0, 0
for i in range(1, n):
n2, n3, n5 = dp[a] * 2, dp[b] * 3, dp[c] * 5
dp[i] = min(n2, n3, n5)
if dp[i] == n2:
a += 1
if dp[i] == n3:
b += 1
if dp[i] == n5:
c += 1
return dp[-1] |
0b85ebd5333b361896e9ac31c675fcd1432a751a | csdms/bmi-live | /bmi_live/diffusion.py | 1,682 | 3.546875 | 4 | """A model of temperature diffusion over a rectangular plate."""
import numpy as np
import yaml
class Diffusion(object):
"""Model of temperature diffusion on a plate."""
def __init__(self, config_file=None):
"""Initialize the model."""
if config_file is not None:
with open(config_file, 'r') as fp:
parameters = yaml.safe_load(fp)
for key, value in parameters.items():
setattr(self, key, value)
else:
self.nx = 8
self.ny = 6
self.dx = 1.0
self.dy = 1.0
self.alpha = 0.9
self.time = 0.0
self.dt = min(self.dx, self.dy) ** 2.0 / (4.0 * self.alpha)
self.dt /= 2.0
self.temperature = np.zeros((self.ny, self.nx))
self.new_temperature = self.temperature.copy()
def advance(self):
"""Advance the model by one time step."""
self.solve()
self.time += self.dt
def solve(self):
"""Solve the diffusion equation."""
dx2, dy2 = self.dx**2, self.dy**2
coef = self.alpha * self.dt / (2.0*(dx2 + dy2))
for i in range(1, self.ny-1):
for j in range(1, self.nx-1):
self.new_temperature[i,j] = \
self.temperature[i,j] + coef * (
dx2*(self.temperature[i,j-1] + self.temperature[i,j+1]) +
dy2*(self.temperature[i-1,j] + self.temperature[i+1,j]) -
2.0*(dx2 + dy2)*self.temperature[i,j])
self.new_temperature[(0, -1), :] = 0.0
self.new_temperature[:, (0, -1)] = 0.0
self.temperature[:] = self.new_temperature
|
d16b8c531f302e83083ecfeabae98ca56659d141 | j-ckie/htx-immersive-08-2019 | /01-week/3-thursday/labs/hello.py | 152 | 3.796875 | 4 | # import time module
import time
# Exercise 1: Hello, you!
name_input = input("What is your name? ")
time.sleep(0.3)
print("Hello " + name_input + "!") |
4365612a54febfc65554f68ded04c6ee3fee5a17 | chinmaya-dev/ttbdonation | /venv/Lib/python3.6/site-packages/Tree/utils.py | 2,137 | 4.21875 | 4 | """
Helper module.
"""
from math import atan2, cos, sin, pi, sqrt
def convert_color(color):
"""Convert color tupel(r, g, b) to string("rgb({r}, {g}, {b}").
Args:
color (tupel): RGB color. e.g. (134, 8, 45)
Returns:
string: "rgb({r}, {g}, {b}"
"""
return "rgb({}, {}, {})".format(color[0], color[1], color[2])
class Node(object):
"""A node.
Attributes:
pos (tupel): The position of the node. (x, y)
"""
def __init__(self, pos):
self.pos = pos
def make_new_node(self, distance, angle):
"""Make a new node from an existing one.
This method creates a new node with a distance and angle given.
The position of the new node is calculated with:
x2 = cos(-angle)*distance+x1
y2 = sin(-angle)*distance+y1
Args:
distance (float): The distance of the original node to the new node.
angle (rad): The angle between the old and new node, relative to the horizont.
Returns:
object: The node with calculated poistion.
"""
return Node((cos(-angle)*distance+self.pos[0],
sin(-angle)*distance+self.pos[1]))
def get_node_angle(self, node):
"""Get the angle beetween 2 nodes relative to the horizont.
Args:
node (object): The other node.
Returns:
rad: The angle
"""
return atan2(self.pos[0]-node.pos[0], self.pos[1]-node.pos[1]) - pi / 2
def get_distance(self, node):
"""Get the distance beetween 2 nodes
Args:
node (object): The other node.
"""
delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1])
return sqrt(delta[0]**2+delta[1]**2)
def get_tuple(self):
"""Get the position of the node as tuple.
Returns:
tupel: (x, y)
"""
return self.pos
def move(self, delta):
"""Move the node.
Args:
delta (tupel): A tupel, holding the adjustment of the position.
"""
self.pos = (self.pos[0]+delta[0], self.pos[1]+delta[1])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.