blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
ca96436efca7c0b171625683d122951b8ba4b833 | YashMeh/HCI-Project | /image_operations.py | 739 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 28 19:25:56 2018
@author: yash
"""
import numpy as np
import cv2
#Usually people perform analysis on grayscale image
#then export the result on coloured image
img=cv2.imread('tejas.jpg',cv2.IMREAD_COLOR)
###Referencing a particular pixel
px=img[55,55]
print(px)
###Changing the value of pixel
img[55,55]=[255,255,255]
px=img[55,55]
print(px)
##ROI=region of image
roi=img[100:150,100:150]
print(roi)
##Changing the region
img[100:150,100:150]=[255,255,255]
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
##Copying a region and pasting it
face=img[37:111,107:194]
img[0:74,0:87]=face
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
37940d1160cc5a78595a58676589eca91d3d7fdc | AlanaMina/CodeInPlace2020 | /Assignment1/TripleKarel.py | 1,268 | 4.28125 | 4 | from karel.stanfordkarel import *
"""
File: TripleKarel.py
--------------------
When you finish writing this file, TripleKarel should be
able to paint the exterior of three buildings in a given
world, as described in the Assignment 1 handout. You
should make sure that your program works for all of the
Triple sample worlds supplied in the starter folder.
"""
def main():
# Pre-condition: Three building with white walls
# Post-condition: Three buildings with painted walls
for i in range(3):
paint_building()
turn_right()
turn_left()
# Pre-condition: Karel is facing certain point
# Post-condition: Karel will turn three times anticlockwise the initial point
def turn_right():
turn_left()
turn_left()
turn_left()
# Pre-condition: One of the buildings has white walls
# Post-condition: One of the buildings gets all its walls painted
def paint_building():
for i in range(2):
paint_wall()
turn_left()
move()
paint_wall()
# Pre-condition: A wall is white
# Post-condition: The wall is painted
def paint_wall():
while left_is_blocked():
put_beeper()
move()
# There is no need to edit code beyond this point
if __name__ == "__main__":
run_karel_program()
|
3da0242e36ee059b8471559ae4491a435b90e234 | AlanaMina/CodeInPlace2020 | /Assignment5/word_guess.py | 2,881 | 4.1875 | 4 | """
File: word_guess.py
-------------------
Fill in this comment.
"""
import random
LEXICON_FILE = "Lexicon.txt" # File to read word list from
INITIAL_GUESSES = 8 # Initial number of guesses player starts with
def play_game(secret_word):
"""
Add your code (remember to delete the "pass" below)
"""
nro = INITIAL_GUESSES
guess = ""
aux = []
for i in range(len(secret_word)):
guess += "-"
for i in range(len(secret_word)):
aux.append("-")
while ("-" in guess) and (nro > 0):
print("The word now looks like this: " + str(guess))
print("You have " + str(nro) + " guesses left")
letter = input("Type a single letter here, then press enter: ")
if len(letter) != 1:
print("Guess should only be a single character.")
else:
letter = letter.upper()
if letter in secret_word:
print("That guess is correct")
res = []
for idx, val in enumerate(secret_word):
if val in letter:
res.append(idx)
for j in range(len(guess)):
aux[j] = guess[j]
if len(res) > 1:
for m in range(len(res)):
aux[res[m]] = str(letter)
else:
i = secret_word.index(letter)
aux[i] = str(letter)
guess = ""
for n in range(len(aux)):
guess += aux[n]
else:
print("There are no " + str(letter) + "'s in the word")
nro -= 1
if nro == 0:
print("Sorry, you lost. The secret word was: " + str(secret_word))
elif "-" not in guess:
print("Congratulations, the word is: " + str(secret_word))
def get_word():
"""
This function returns a secret word that the player is trying
to guess in the game. This function initially has a very small
list of words that it can select from to make it easier for you
to write and debug the main game playing program. In Part II of
writing this program, you will re-implement this function to
select a word from a much larger list by reading a list of words
from the file specified by the constant LEXICON_FILE.
"""
aux = []
with open(LEXICON_FILE) as file:
for line in file:
line = line.strip()
aux.append(line)
index = random.randrange(122000)
return str(aux[index])
def main():
"""
To play the game, we first select the secret word for the
player to guess and then play the game using that secret word.
"""
secret_word = get_word()
play_game(secret_word)
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == "__main__":
main()
|
fbd5d7800af041a8e69102609f84bba5d8b6c63f | AlanaMina/CodeInPlace2020 | /Assignment5/credit_card_total.py | 1,036 | 3.984375 | 4 | """
File: credit_card_total.py
--------------------------
This program totals up a credit card bill based on
how much was spent at each store on the bill.
"""
INPUT_FILE = 'bill1.txt'
def main():
"""
Add your code (remember to delete the "pass" below)
"""
dict = {}
name = ""
num = ""
with open(INPUT_FILE) as file:
for line in file:
line = line.strip()
ini = line.index('[')
end = line.index(']')
for i in range(ini + 1, end):
name += line[i]
for j in range(end + 3, len(line)):
num += line[j]
if name not in dict:
dict[name] = num
else:
add = str(int(num) + int(dict[name]))
dict[name] = add
name = ""
num = ""
for name in dict:
print(name, "-> $", dict[name])
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
|
46f4a78818e9ff35199700107f193ce49587569c | SpiralBL0CK/Programming-solutions-from-codeforces | /asu_3_cup.py | 230 | 3.53125 | 4 | x = int(raw_input())
y = int(raw_input())
command = raw_input()
for i in command:
if i == 'U':
y = y + 1
if i == 'D':
y = y -1
if i == 'L':
x = x-1
if i == 'R':
x = x+1
print(x,y)
|
6033405dc1913c086c43a57b8ed06e70a481a8c1 | mrahmed0116/Practise1 | /sortbasedonvalues.py | 429 | 4.28125 | 4 | '''
Sort dictionary based on keys
'''
dict1= {'x':4,'y':3,'z':2,'a':1,'b':1, 'c':0}
s1 = sorted(dict1.keys())
print(s1)
output={}
for s in s1:
for i in dict1:
if i == s:
output[i] = dict1[i]
print(output)
'''
Sort dictionary based on values
'''
s2 = sorted(dict1.values())
print(s2)
output1={}
for j in s2:
for i in dict1:
if j == dict1[i]:
output1[i] = dict1[i]
print(output1) |
6946898e4785bc0dca8b2f0e4284a9bd51b4b24d | ckid/LeetCode | /AddTwo.py | 1,405 | 3.921875 | 4 |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
@staticmethod
def addTwoNumbers( l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
datareturn = ListNode(0)
curNodeReturn = datareturn
curNode = l1
c = 0
if (l1 and l2) is None:
return l1 or l2
while curNode is not None:
var,c = Solution.nodeAdd(l1,l2,c)
curNodeReturn.next = ListNode(val)
curNodeReturn = curNodeReturn.next
curNode = curNode.next
l1 = l1.next
l2 = l2.next
#如果l1为空 则将l2连接到curNodeReturn
if l1 is None:
if c ==1:
curNodeReturn.next = l2
break
if l2 is None:
curNodeReturn.next = l1
break
return datareturn.next
@staticmethod
def nodeAdd(n1, n2, c):
if n1 and n2 is None:
node = n1 or n2
if !None and
var = n1.var + v2.val + c
if var >9:
return var -10, 1
else:
return var , 0
if __name__ == "__main__":
l1 = ListNode(5)
l1.next=ListNode(8)
l2 = ListNode(0)
a = Solution.addTwoNumbers(l1, l2)
print(a)
|
0857fa157a39ff743884d00466b885fadb02e17d | cduhaney1/ubiquitous-fiesta | /prompt_user.py | 154 | 3.953125 | 4 | print("hello")
user_input = int(input("Give me a number! "))
result = int (user_input) * int(user_input)
print (result)
name = input ('What is your name') |
bb91dc84c3520303d5ccc1dfc29615d6a85a3dd9 | cduhaney1/ubiquitous-fiesta | /Hello.py | 70 | 3.625 | 4 | user_name = input('What is your name?')
print('hello, %s' %user_name)
|
cf7a0769baca60bd80d8fe5c6e1af2eb07c1273c | li-MacBook-Pro/li | /static/Mac/play/调用/累加/累加.py | 401 | 3.890625 | 4 | def sum_numbers(num):
if num == 1:
return 1
temp = sum_numbers(num - 1)
return num + temp
print(sum_numbers(3))
def sum_numbers(num):
if num == 3:
return 3
temp = sum_numbers(num + 1)
return num + temp
print(sum_numbers(1))
def my_sum(i):
if i < 0:
raise ValueError
elif i <= 1:
return i
else:
return i + my_sum(i - 1)
print(my_sum(10))
print(my_sum(100)) |
51adf901afcf2ff68f2b82d4c28c19e8074bd715 | li-MacBook-Pro/li | /static/Mac/play/调用/器/迭代器.py | 1,016 | 4.09375 | 4 | # 可迭代对象
# 可通过for…in 进行遍历的数据类型包括 list,tuple, dict, set, str;以及生成器generator,及带yield的生成器函数
# 这些可直接作用于for循环的对象统称为可迭代对象:Iterable
# from collections import Iterable
# print(isinstance('abc',Iterable))
# print(isinstance((x for x in range(10)),Iterable))
# print(isinstance(100,Iterable))
# 迭代器
# Iterator,无限大数据流,内部定义__next__( )方法,返回下一个值的对象
# 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
print('done')
g = fib(5)
print(next(g))
next(g)
next(g)
next(g)
print(next(g))
g = fib(10)
for item in g:
print(item)
g = fib(20)
while True:
try:
x = next(g)
print('g: ', x)
except StopIteration as e:
print('Generation return value: ', e.value)
break |
347c26e4de6383598ea3a21ca20ff027713b3e8f | li-MacBook-Pro/li | /static/Mac/play/调用/二分树/小偷偷钱.py | 1,101 | 3.828125 | 4 | #定义一个二叉房子类,包括当前节点、左节点和右节点
class House():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
#定义一个函数,返回根节点最后的偷值和不偷值较大那个
def rob(root):
a = helper(root)
print(max(a[0], a[1]))
#定义一个辅助函数,递归算出根节点偷值和不偷值
def helper(root):
if(root == None):
return [0, 0]
left = helper(root.left)
right = helper(root.right)
#当前节点偷值等于当前节点的偷值加上左右子节点的不偷值
robValue = root.value + left[1] + right[1]
#当前节点不偷值等于左右子节点的偷值与不偷值中较大的那个值
skipValue = max(left[0], left[1]) + max(right[0], right[1])
#返回偷值和不偷值
return [robValue, skipValue]
node1 = House(3)
node2 = House(4)
node3 = House(5)
node4 = House(1)
node5 = House(3)
node7 = House(1)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.right = node7
DLR(node1)
rob(node1)
|
5612738c34956713a04a55923765d1718fdcd934 | li-MacBook-Pro/li | /static/Mac/play/调用/长方体/changfangxing.py | 2,251 | 3.8125 | 4 | #第一种
import random
class cube:
def define(self):
global x,y,z
x=self.x = random.randint(1,5)
y=self.y = random.randint(1,5)
z=self.z = random.randint(1,5)
return x,y,z
def Cuboid_Area(self):
global Area
Area=(2*(self.x * self.y + self.x * self.z + self.y * self.z))
return Area
def Cuboid_volume(self):
global svolume
svolume=(self.x*self.y*self.z)
return svolume
class z_cobe(cube):
def side(self):
global a
a=self.a=random.randint(1,5)
return a
def side_superficial_area(self):
global cobe_area
cobe_area=(6*(self.a**2))
return cobe_area
def cobe_volume(self):
global vvlume
vvlume=(self.a**3)
return vvlume
ALL=cube()
ALL.define()
ALL.Cuboid_Area()
ALL.Cuboid_volume()
print(('the long of cube is ' + str(x)))
print(('the wide of cube is ' + str(y)))
print(('the high of cube is ' + str(z)))
print('the Cuboid_Area of cube is ' + str(Area))
print('the Cuboid_svolume of cube is ' + str(svolume))
all=z_cobe()
all.side()
all.side_superficial_area()
all.cobe_volume()
print()
print('the side_superficial_area of cube is ' + str(cobe_area))
print('the cobe_volume of cube is ' + str(vvlume))
#第二种
class Cube:
def __init__(self,L,W,H):
self.L = L
self.W = W
self.H = H
def surface(self):
global result1
result1 = (L*W+W*H+H*L)*2
return result1
def volume(self):
global result2
result2 = L*W*H
return result2
L = 2
W = 3
H = 4
a = Cube(L,W,H)
a.surface()
a.volume()
print ('the surface of cube is '+str(result1))
print ('the volume of cube is '+str(result2))
#第三种
class Cube:
def __init__(self,l,w,h):
self.l = l
self.w = w
self.h = h
def surface(self):
global result3
result3 = (l*w+w*h+h*l)*2
return result3
def volume(self):
global result4
result4 = l*w*h
return result4
l = int(input('长:'))
w = int(input('宽:'))
h = int(input('高:'))
a = Cube(l,w,h)
a.surface()
a.volume()
print ('the surface of cube is '+str(result3))
print ('the volume of cube is '+str(result4)) |
e93fdc9cee0fa4388f92877ceaee733624c3900a | tveebot/organizer | /tveebot_organizer/matcher.py | 1,919 | 3.75 | 4 | import re
from tveebot_organizer.dataclasses import Episode, TVShow
class Matcher:
"""
The Matcher is one of the sub-components of the *Organizer*. An organizer is associated with a
single matcher. The matcher is used to match an episode name, using some pre-defined format,
to an episode object.
Supported formats:
- TV.Show.Name.S01E02.720p -> Episode("TV Show Name", season=1, number=2)
"""
# An episode pattern corresponds to a 'word' of the form S01E01
# Where S01 indicates the episode corresponds to season 1
# and E01 indicates the episode is the first episode of the season
_episode_pattern = re.compile('S(?P<season>\d+)E(?P<number>\d+)\Z')
def match(self, name: str) -> Episode:
"""
Takes an episode name, parses it, and returns the corresponding episode object.
The format of the episode name must follow the list of support formats specified in the
*Matcher*'s class documentation.
:raise ValueError: if it can not match *name* to an episode
"""
# The character '.' divides words
# Take each word
words = name.split('.')
# Look for an episode pattern
episode = None
for index, word in enumerate(words):
match = self._episode_pattern.match(word)
if match:
# The words before the episode pattern compose the tv show name.
tvshow_name = " ".join(words[:index])
# Capitalize the first letter of each word of the tvshow name
tvshow_name = tvshow_name.title()
season = int(match.group('season'))
number = int(match.group('number'))
episode = Episode(TVShow(tvshow_name), season, number)
if episode is None:
raise ValueError(f"could not match name '{name}' to an episode")
return episode
|
46a808d1c32ca99e7672ed19389480728ee21b6b | CooperNederhood/spring2018_project | /data_processing/model0.py | 1,663 | 3.734375 | 4 | from keras import layers
from keras import models
'''
From Chapter 5, create a simple CNN model from scratch
'''
model = models.Sequential()
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(128, 128, 3)))
model.add(layers.MaxPooling2D( (2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
model.add(layers.MaxPooling2D( (2,2)))
model.add(layers.Conv2D(128, (3,3), activation='relu'))
model.add(layers.MaxPooling2D( (2,2)))
model.add(layers.Conv2D(128, (3,3), activation='relu'))
model.add(layers.MaxPooling2D( (2,2)))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(3, activation='softmax'))
from keras import optimizers
model.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc'])
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_dir = "lagos/training"
validation_dir = "lagos/validation"
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(128, 128),
batch_size=20,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(128, 128),
batch_size=20,
class_mode='categorical')
history = model.fit_generator(
train_generator, steps_per_epoch=100, epochs=30,
validation_data=validation_generator, validation_steps=50)
model.save('first_lum_model.h5')
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc)+1)
|
662afa79e92cac1dab547c962292fa42efca4e57 | MrCordero/testgithub2 | /ejercicio_7.py | 410 | 4 | 4 | #Contador de numeros
cont_num = 0
#Contador de vueltas
cont_vueltas = 0
#Acumulador de numeros
acu_num = 0
while(True):
num = int(input("Ingrese numero : "))
#Suma
acu_num += num
cont_vueltas = cont_vueltas + 1}
prom = acu_num / cont_vueltas
if(cont_vueltas == -1):
break
print("La suma de los numeros es :", acu_num)
print("El promedio de los numeros es" , prom) |
712b6de931dcfe6fcdce13e16c4edf5e16b7fc94 | KontextuellEnergivisualisering/Priority-Calculations | /Algorithms.py | 1,521 | 3.6875 | 4 | import time
# Calculates the minimum power in the combined list with old data ('points') and new data ('lastHourData')
def min(points, lastHourData):
min = -1
# Check if points are from database
if not isinstance(points[0][1], int):
# If points come from database, loop through every point until a point with 'min'
# is found, this points value will be the current minimum to compare to
for a in points:
if a[1].find("min") != -1:
min = a[0]
if min == -1:
min = lastHourData[0][2]
change = 0
for n in lastHourData:
if n[2] < min:
min = n[2]
change = 1
if change == 1:
return [min, "min", 3, int(time.time())]
else:
return []
# Calculates the minimum power in the combined list with old data ('points') and new data ('lastHourData')
def max(points, lastHourData):
max = -1
# Check if points are from database
if not isinstance(points[0][1], int):
# If points come from database, loop through every point until a point with 'max'
# is found, this points value will be the current maximum to compare to
for a in points:
if a[1].find("max") != -1:
max = a[0]
if max == -1:
max = lastHourData[0][2]
change = 0
for n in points:
if n[2] > max:
max = n[2]
change = 1
if change == 1:
return [max, "max", 3, int(time.time())]
else:
return []
|
a2942eea4bbccc41c49f0a87b00324f23b93fb40 | pisa-engine/pisa | /script/bp/generate_config.py | 1,394 | 3.703125 | 4 | #!/usr/bin/env python
import argparse
import sys
def generate_recursive(lvl, first, last, out):
if last - first < 2:
return
left_range = (first, first + (last - first) // 2)
right_range = (left_range[1], last)
print(lvl, 20, left_range[0], left_range[1],
right_range[0], right_range[1],
0, file=out)
generate_recursive(lvl + 1, left_range[0], left_range[1], out)
generate_recursive(lvl + 1, right_range[0], right_range[1], out)
def generate(ndoc, out):
"""
Generates nodes (one per line) in format:
LVL I FL FR SL SR C
where
- LVL is integer defining level (depth) in recursion tree
- I is iteration count
- FL first range's beginning
- FR first range's end
- SL second range's beginning
- SR second range's end
- 0 or 1 (cache gains or not)
"""
generate_recursive(0, 0, ndoc, out);
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate BP config file.')
parser.add_argument('ndoc', type=int,
help='Number of document in collection.')
parser.add_argument('-o', '--output',
type=argparse.FileType('w'), default=sys.stdout,
help='Ouptut config file (if absent, write to stdout)')
args = parser.parse_args()
generate(args.ndoc, args.output)
|
7b16f62b068e3f5de037781f496881846d025fa3 | XiaoyuZhou1106/CSC108-Introduction-to-Computer-Programming | /a3/tweets.py | 14,057 | 3.953125 | 4 | """Assignment 3: Tweet Analysis"""
from typing import List, Dict, TextIO, Tuple
HASH_SYMBOL = '#'
MENTION_SYMBOL = '@'
URL_START = 'http'
# Order of data in the file
FILE_DATE_INDEX = 0
FILE_LOCATION_INDEX = 1
FILE_SOURCE_INDEX = 2
FILE_FAVOURITE_INDEX = 3
FILE_RETWEET_INDEX = 4
# Order of data in a tweet tuple
TWEET_TEXT_INDEX = 0
TWEET_DATE_INDEX = 1
TWEET_SOURCE_INDEX = 2
TWEET_FAVOURITE_INDEX = 3
TWEET_RETWEET_INDEX = 4
# Helper functions.
def first_alnum_substring(text: str) -> str:
"""Return all alphanumeric characters in text from the beginning up to the
first non-alphanumeric character, or, if text does not contain any
non-alphanumeric characters, up to the end of text."
>>> first_alnum_substring('')
''
>>> first_alnum_substring('IamIamIam')
'iamiamiam'
>>> first_alnum_substring('IamIamIam!!')
'iamiamiam'
>>> first_alnum_substring('IamIamIam!!andMore')
'iamiamiam'
>>> first_alnum_substring('$$$money')
''
"""
index = 0
while index < len(text) and text[index].isalnum():
index += 1
return text[:index].lower()
def clean_word(word: str) -> str:
"""Return all alphanumeric characters from word, in the same order as
they appear in word, converted to lowercase.
>>> clean_word('')
''
>>> clean_word('AlreadyClean?')
'alreadyclean'
>>> clean_word('very123mes$_sy?')
'very123messy'
"""
cleaned_word = ''
for char in word.lower():
if char.isalnum():
cleaned_word = cleaned_word + char
return cleaned_word
# Required functions
def extract_mentions(text: str) -> List[str]:
"""Return a list of all mentions in text, converted to lowercase, with
duplicates included.
>>> extract_mentions('Hi @UofT do you like @cats @CATS #meowmeow')
['uoft', 'cats', 'cats']
>>> extract_mentions('@cats are #cute @cats @cat meow @meow')
['cats', 'cats', 'cat', 'meow']
>>> extract_mentions('@many @cats$extra @meow?!')
['many', 'cats', 'meow']
>>> extract_mentions('No valid mentions @! here?')
[]
"""
b = ''
result_mentions = []
for a in range(len(text)):
if text[a] == '@':
b = first_alnum_substring(text[a + 1:])
result_mentions.append(b)
if result_mentions == ['']:
return []
return result_mentions
def extract_hashtags(text: str) -> List[str]:
"""Return a list of all hashtags in text, converted to lowercase, without
duplicates included.
>>> extract_hashtags('#qwe tweet #ASD hahahah #zxc')
['qwe', 'asd', 'zxc']
>>> extract_hashtags('haha #Qwer hahaha #Qwer')
['qwer']
>>> extract_hashtags('lalalala #qwe hahahha #qwe lalala #asd')
['qwe', 'asd']
>>> extract_hashtags('#QWE lalala #qWe hehehehe #QWe')
['qwe']
"""
c = ''
result_hashtags = []
for d in range(len(text)):
if text[d] == '#':
c = first_alnum_substring(text[d + 1:])
if not c in result_hashtags:
result_hashtags.append(c)
if result_hashtags == ['']:
return[]
return result_hashtags
def find_words(text: str) -> List[str]:
"""Return the seperate words from the text.
>>> find_words('#UofT Nick Frosst: Google Brain re-searcher by day, singer
@goodkidband by night!')
['nick', 'frosst', 'google', 'brain', 'researcher', 'by', 'day',
'singer', 'by', 'night']
"""
e = ''
new_text = ' ' + text + ' '
result_wordslist = []
g = ''
h = 0
for f in range(len(new_text) - 1):
if new_text[f] == ' ':
g = new_text[f + 1:]
h = g.index(' ')
e = g[:h]
if e[0] != '@' and e[0] != '#':
result_wordslist.append(first_alnum_substring(clean_word(e)))
return result_wordslist
def count_words(text: str, words_times: Dict[str, int]) -> None:
"""Return the number of words in text. If a word is not the dictionary yet,
it should be added.
>>> words = {'nick': 1, 'google': 1, 'by': 1}
>>> count_words('#UofT Nick Frosst: Google Brain re-searcher by day, singer
@goodkidband by night!', words)
>>> words
{'nick': 2, 'google': 2, 'by': 3, 'frosst': 1, 'brain': 1, 'researcher': 1,
'day': 1, 'singer': 1, 'night': 1}
"""
new_list = find_words(text)
for i in range(len(new_list)):
if new_list[i] in words_times:
words_times[new_list[i]] = words_times[new_list[i]] + 1
else:
words_times[new_list[i]] = 1
def invert_dict(words_times: Dict[str, int]) -> Dict[int, List[str]]:
"""invert the keys and values of words_times.
>>> invert_dict({'key': 2, 'words': 3, 'mind': 4, 'google': 3})
{2: ['key'], 3: ['words', 'google'], 4: 'mind'}
"""
result_dict = {}
for words in words_times:
times = words_times[words]
if not (times in result_dict):
result_dict[times] = [words]
else:
result_dict[times].append(words)
return result_dict
def common_words(words_times: Dict[str, int], words_num: int) -> None:
"""Keep no more than words_number words in the words_times. If after
adding the number of tie words , the number is over words_number,
delet all tie words.
>>> words = {'key': 2, 'words': 3, 'mind': 4, 'google': 3}
>>> common_words(words, 1)
>>> words
{'mind': 4}
>>> common_words(words, 3)
>>> words
{'words': 3, 'mind': 4, 'google': 3}
>>> common_words(words, 2)
>>> words
{'mind': 4}
"""
new_dict = invert_dict(words_times)
h = []
for j in new_dict:
h.append(j)
h.sort()
h.reverse()
m = 0
n = [] #the list of words will in the new dict
o = [] #the list of num whose words will in the new dict
while m < len(h) and len(n) < words_num:
n.extend(new_dict[h[m]])
o.append(h[m])
m = m + 1
if len(n) > words_num:
o.pop(-1)
p = []
for num in o:
p.extend(new_dict[num])
nnew_list = []
for q in words_times:
if q not in p:
nnew_list.append(q)
for it in nnew_list:
del words_times[it]
def read_tweets(file_name: TextIO) -> Dict[str, List[tuple]]:
"""Return the context of file_name into dictionary. The key will be the user
name and write other information in the list of tuple.
"""
#find the username and manage them into str
big_users = []
users = []
text_list1 = []
text_list2 = []
date_list1 = []
date_list2 = []
source_list2 = []
favourite_list1 = []
retweet_list2 = []
source_list1 = []
favourite_list2 = []
retweet_list1 = []
fline = 0
index_b = 0
index_a = 0
text0 = ''
tweets = {}
tuple1 = ()
tuple_list = []
file_list = []
for lines in file_name:
file_list.append(lines)
for line in range(len(file_list)):
if len(file_list[line]) >= 2 and file_list[line][-2] == ':':
big_users = file_list[line][:-2].lower()
users.append(big_users)
fline = line + 1
while fline < len(file_list) and len(file_list[fline]) >= 2 and file_list[fline][-2] != ':':
if file_list[fline][:13].isdigit():
date_list1.append(int(file_list[fline][0:14]))
index_b = file_list[fline][15:].index(',') + 15
index_a = file_list[fline][index_b + 1:].index(',') + index_b + 1
source_list1.append(file_list[fline][index_b + 1:index_a])
index_b = file_list[fline][index_a + 1:].index(',') + index_a + 1
favourite_list1.append(int(float(file_list[fline]
[index_a + 1:index_b])))
retweet_list1.append(int(float(file_list[fline]
[index_b + 1:])))
fline = fline + 1
while fline < len(file_list) and '<<<EOT' not in file_list[fline]:
text0 = text0 + file_list[fline].rstrip()
fline = fline + 1
text_list1.append(text0)
text0 = ''
fline = fline + 1
text_list2.append(text_list1)
text_list1 = []
date_list2.append(date_list1)
date_list1 = []
source_list2.append(source_list1)
source_list1 = []
favourite_list2.append(favourite_list1)
favourite_list1 = []
retweet_list2.append(retweet_list1)
retweet_list1 = []
for zz in range(len(users)):
for xx in range(len(text_list2[zz])):
tuple1 = (text_list2[zz][xx], date_list2[zz][xx],
source_list2[zz][xx], favourite_list2[zz][xx],
retweet_list2[zz][xx])
tuple_list.append(tuple1)
tweets[users[zz]] = tuple_list
tuple_list = []
return tweets
def most_popular(tweets: Dict[str, List[tuple]], first_date: int,
last_date: int) -> str:
"""Return the username of the most popular tweet which between the first
date and the last date. The first date and the last date are inclusive. If
there is no tweet between the dates or the number of the favourable are tie,
just return the string 'tie'.
Precondition: first_date and last_date should be an int with 14 digits.
>>> most_popular({'uoftcompsci': [('hahahaha', 20181103091833, 'Twitter
for Android', 3, 1), ('hahaha', 20181107051833, 'Twitter for Android',
7, 3)], 'uoft': [('haha', 20181105091933, 'Twitter for Android', 3, 8)]},
20181031211000, 20181231091100)
'uoft'
>>> most_popular({'uoftcompsci': [('hahahaha', 20181103091833, 'Twitter
for Android', 3, 1), ('hahaha', 20181107051833, 'Twitter for Android',
7, 3)], 'uoft': [('haha', 20181105091933, 'Twitter for Android', 2, 8)]},
20181031211000, 20181231091100)
'tie'
>>> most_popular({'uoftcompsci': [('hahahaha', 20181103091833, 'Twitter
for Android', 3, 1), ('hahaha', 20181107051833, 'Twitter for Android',
7, 3)], 'uoft': [('haha', 20181105091933, 'Twitter for Android', 2, 8)]},
20181031211000, 20181106091100)
'uoft'
>>> most_popular({'uoftcompsci': [('hahahaha', 20181103091833, 'Twitter
for Android', 3, 1), ('hahaha', 20181107051833, 'Twitter for Android',
7, 3)], 'uoft': [('haha', 20181105091933, 'Twitter for Android', 2, 8)]},
20180131211000, 20180106091100)
'tie'
"""
num1 = 0
mostlove = []
list1 = []
list2 = []
user1 = []
favourite_user = []
for r in tweets:
for s in tweets[r]:
if first_date <= s[1] <= last_date:
num1 = s[3] + s[4]
list1.append(num1)
list1.sort()
if len(list1) >= 1:
list2.append(list1[-1])
list1 = []
if list2 == []:
return 'tie'
for u in range(len(list2)):
if list2[u] == max(list2):
mostlove.append(u)
if len(mostlove) > 1:
return 'tie'
for v in tweets:
user1.append(v)
favourite_user = user1[mostlove[0]]
return favourite_user
def find_hashtags(tweets: Dict[str, List[tuple]], username: str) -> List[str]:
"""Retrun the hashtags which the user use.
>>> find_hashtags({'uoftcompsci': [('#hah ahaha #has', 20181103091833,
'Twitter for Android', 3, 1), ('hahaha #has', 20181107051833, 'Twitter for
Android', 7, 3)], 'uoft': [('haha #1', 20181105091933, 'Twitter for
Android', 3, 8)]}, 'uoftcompsci')
["#hah', '#has']
"""
#text2 = ''
#num2 = 0
tag = ''
tag_list = []
new_username = username.lower()
tweets1 = tweets[new_username]
for w in tweets1:
tag = extract_hashtags(w[0])
if tag[0] not in tag_list:
tag_list.extend(tag)
tag = ''
return tag_list
def detect_author(tweets: Dict[str, List[tuple]], aim_word: str) -> str:
"""Retrun the more like username in the tweets dictionary who write about
the aim_word. If there are more that one person use the hashtag, return the
string 'unknown'.
>>> detect_author({'uoftcompsci': [('#hah ahaha', 20181103091833, 'Twitter
for Android', 3, 1), ('hahaha #has', 20181107051833, 'Twitter for Android',
7, 3)], 'uoft': [('haha #1 lalala #hah', 20181105091933, 'Twitter for
Android', 3, 8)]}, '#1 lala')
'uoft'
>>> detect_author({'uoftcompsci': [('#hah ahaha', 20181103091833, 'Twitter
for Android', 3, 1), ('hahaha #has', 20181107051833, 'Twitter for Android',
7, 3)], 'uoft': [('haha #1 lalala #hah', 20181105091933, 'Twitter for
Android', 3, 8)]}, '#3')
'unknown'
>>> detect_author({'uoftcompsci': [('#hah ahaha', 20181103091833, 'Twitter
for Android', 3, 1), ('hahaha #has', 20181107051833, 'Twitter for Android',
7, 3)], 'uoft': [('haha #1 lalala #hah', 20181105091933, 'Twitter for
Android', 3, 8)]}, '#hah kjdfhi'
'unknown'
"""
aim_user = []
text_tag = []
find_tag = []
text_tag.extend(extract_hashtags(aim_word))
if len(text_tag) == 0:
return 'unknown'
for x in tweets:
for y in text_tag:
if y in find_hashtags(tweets, x):
aim_user.append(x)
find_tag.append(y)
find_tag = []
if x in aim_user and find_tag != text_tag:
aim_user.remove(x)
if len(aim_user) == 1:
return aim_user[0]
else:
return 'unknown'
if __name__ == '__main__':
pass
|
a2c11f8cdd280ce12b1d56ad3745fff0b19f456c | osamaawadallah/AlgorithmicToolbox | /week1_programming_challenges/2_maximum_pairwise_product/max_pairwise_product.py | 1,028 | 3.875 | 4 | # python3
from random import randrange
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def max_pairwise_product_fast(numbers):
temp = numbers[:]
max_product = 0
max1 = max(temp)
temp.remove(max1)
max2 = max(temp)
max_product = max1 * max2
return max_product
while True:
n = randrange(10) + 2
numbers = []
print(n)
for num in range(n):
numbers.append(randrange(100000))
print(numbers)
res1 = max_pairwise_product(numbers)
res2 = max_pairwise_product_fast(numbers)
if res1 == res2:
print(f"OK, result is {res1}")
else:
print(f"Error: {res1} != {res2}")
break
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
|
e7a2aeeaece89d8091827c210ba333275b31c263 | Xudoge/PythonStudy | /Python/BaseKnowledge/inherit/inherit.py | 433 | 3.71875 | 4 |
class A:
def __init__(self,value,name):
self.value=value
self.name=name
print("这是一个父类方法")
def hihi():
print(self.name)
class B(A):
def __init__(self,value,name):
#A.__init__(self,value=1,name="a")
super().__init__(value,name)
print("这是一个子类类方法1")
b=B(1,"nameB")
print(b.name)
c=B(1,"nameC")
print(c.name)
print(b.name) |
15a0cde2ab30d5ed1d4eaf04cac7af6d6f3faf31 | bjmyers/prtp | /Combination.py | 15,540 | 3.75 | 4 | import numpy as np
from prtp.Rays import Rays
import astropy.units as u
import prtp.transformationsf as trans
class Combination:
'''
Class Combination:
A combination object is a group of several components that the user wants to
group together
When Rays are traced to a Combination Object, they will be traced to each
Component individually and only those components who missed every
component will be removed
Tracing to Combinations will also give detailed information about how each
Component affected the overall efficiency
'''
def __init__(self):
self.componentlist = []
def addComponent(self,comp,index=None):
'''
Function addComponent:
Adds a Component to the componentlist
Inputs:
comp - The component to add
index - Where in the list you want to add the component, if None, it
will be added to the end
'''
if index is None:
self.componentlist.append(comp)
else:
self.componentlist.insert(index,comp)
def applyToAll(self, func, **kwargs):
'''
Function applyToAll:
Applies a function to each component in the Combination Object
(e.g: applyToAll(self,FlatComponent.UnitRotate,theta=.1*u.rad,axis=2)
will rotate each component in the Combination .1 radians about the
y-axis
Inputs:
func - The function you want to apply to each element
**kwargs - Any other arguments that func requires
Outputs:
None
'''
for c in self.componentlist:
func(c,**kwargs)
def setAttribute(self, name, value):
'''
Function setAttribute:
Changes the value of a parameter for every Component in the Combination
Inputs:
name - The name of the parameter
value - The value that you would like to set the parameter to
Notes:
- This function cannot check for astropy units, check what form the
parameter should be in before you call this function.
'''
for c in self.componentlist:
setattr(c,name,value)
def getSubComponents(self):
'''
Function getSubComponents:
Returns a list of the components in this Combination. If one of the
components is a Combination itself, the components that make up this
Combination will be returned instead. This process is repeated
until every component of every Combination in self has been returned
Inputs:
Nothing
Output:
- A list containing every subcomponent
'''
output = []
combinations = []
for c in self.componentlist:
if isinstance(c,Combination):
combinations.append(c)
else:
output.append(c)
while len(combinations) > 0:
comb = combinations.pop()
for c in comb.componentlist:
if isinstance(c,Combination):
combinations.append(c)
else:
output.append(c)
return output
## Movement Functions:
@u.quantity_input(x=u.mm,y=u.mm,z=u.mm)
def defineRotationPoint(self,x=0*u.mm,y=0*u.mm,z=0*u.mm):
'''
Function defineRotationPoint:
Defines the point about which the entire Stack can rotate
Inputs:
x,y,z - The Coordinates of the Rotation Point, must be astropy units of
length
Outputs:
None
Notes:
Calling this function is required if you try to rotate the whole stack.
Using Combination.applyToAll and a rotation function will rotate each
Grating about their centers, rather than rotating the whole stack about
this point
'''
self.rx = x.to(u.mm)
self.ry = y.to(u.mm)
self.rz = z.to(u.mm)
@u.quantity_input(theta=u.rad)
def unitrotate(self,theta=0*u.rad,axis=1):
'''
Function unitrotate:
Rotates the entire Graint Stack about the rotationpoint and about a
unit axis
Inputs:
theta - The amount by which you want to rotate, must be an astropy unit
of angle
axis - integer input of 1, 2, or 3 to rotate about the x, y, or z axes,
respectively.
Outputs:
None
Notes:
- Theta can be a single value or an array/list. If it is array-like, it
must have the same length as the component list as it specifies the
rotation angle of each component
'''
theta = theta.to(u.rad)
try:
len(theta)
if (len(theta) != len(self.componentlist)):
raise ValueError('Theta Array must be the same length as the component list')
else:
arr = True
except:
arr = False
# arr is True if theta is an array, False otherwise
if (arr):
for i in range(len(self.componentlist)):
g = self.componentlist[i]
# Rotates the Grating's two vectors
g.unitrotate(theta[i],axis)
# Move the Grating's so the rotation point is about the origin
g.translate(-self.rx,-self.ry,-self.rz)
# Rotate the Grating's position
g.x,g.y,g.z = trans.rotatevector(g.x,g.y,g.z,theta[i],axis)
# Translate the origin back down
g.translate(self.rx,self.ry,self.rz)
else:
for g in self.getSubComponents():
# Rotates the Grating's two vectors
g.unitrotate(theta,axis)
# Move the Grating's so the rotation point is about the origin
g.translate(-self.rx,-self.ry,-self.rz)
# Rotate the Grating's position
g.x,g.y,g.z = trans.rotatevector(g.x,g.y,g.z,theta,axis)
# Translate the origin back down
g.translate(self.rx,self.ry,self.rz)
@u.quantity_input(theta=u.rad)
def rotate(self,theta=0*u.rad,ux=1,uy=0,uz=0):
'''
Function unitrotate:
Rotates the entire Graint Stack about the rotationpoint and about a
user-defined axis
Inputs:
theta - The amount by which you want to rotate, must be an astropy unit
of angle
ux,uy,uz - The x, y, and z components of the vector about which you want
to rotate
Outputs:
None
Notes:
- Theta can be a single value or an array/list. If it is array-like, it
must have the same length as the component list as it specifies the
rotation angle of each component
'''
theta = theta.to(u.rad)
try:
len(theta)
if (len(theta) != len(self.componentlist)):
raise ValueError('Theta Array must be the same length as the component list')
else:
arr = True
except:
arr = False
# arr is True if theta is an array, False otherwise
if (arr):
for i in range(len(self.componentlist)):
g = self.componentlist[i]
# Rotates the Grating's two vectors
g.rotate(theta[i],ux,uy,uz)
# Move the Grating's so the rotation point is about the origin
g.translate(-self.rx,-self.ry,-self.rz)
# Rotate the Grating's position
g.x,g.y,g.z,q1,q2,q3 = trans.rotateaxis(g.x.value,g.y.value,g.z.value,ux,uy,uz,theta[i].value)
# Restore units
g.x *= u.mm
g.y *= u.mm
g.z *= u.mm
# Translate the origin back down
g.translate(self.rx,self.ry,self.rz)
else:
for g in self.getSubComponents():
# Rotates the Grating's two vectors
g.rotate(theta,ux,uy,uz)
# Move the Grating's so the rotation point is about the origin
g.translate(-self.rx,-self.ry,-self.rz)
# Rotate the Grating's position
g.x,g.y,g.z,q1,q2,q3 = trans.rotateaxis(g.x.value,g.y.value,g.z.value,ux,uy,uz,theta.value)
# Restore units
g.x *= u.mm
g.y *= u.mm
g.z *= u.mm
# Translate the origin back down
g.translate(self.rx,self.ry,self.rz)
@u.quantity_input(theta=u.rad)
def unitrotateinplace(self,theta,axis=1):
'''
Function unitrotateinplace:
Rotates each of the components in this combination about a unit axis.
Unlike unitrotate which rotates each component about a single point,
this function rotates each component about their center. Leaving them
"in place" and not changing the position of their centers.
Inputs:
theta - The amount by which you want to rotate, must be an astropy unit
of angle. Can be a single value or array-like
axis - integer input of 1, 2, or 3 to rotate about the x, y, or z axes,
respectively.
Outputs:
None
'''
if isinstance(theta.value, (list, tuple, np.ndarray)):
if (len(theta.value) != len(self.componentlist)):
raise ValueError('Theta Array must be the same length as the component list')
for i in range(len(self.componentlist)):
self.componentlist[i].unitrotate(theta[i],axis)
else:
for i in range(len(self.componentlist)):
self.componentlist[i].unitrotate(theta,axis)
@u.quantity_input(theta=u.rad)
def rotateinplace(self,theta,ux=1,uy=0,uz=0):
'''
Function unitrotateinplace:
Rotates each of the components in this combination about a user-defined
axis. Unlike unitrotate which rotates each component about a single point,
this function rotates each component about their center. Leaving them
"in place" and not changing the position of their centers.
Inputs:
theta - The amount by which you want to rotate, must be an astropy unit
of angle. Can be a single value or array-like
ux,uy,uz - Components of the vector about which you want to rotate, does
not need to be a unit vector (can have any length)
Outputs:
None
'''
if isinstance(theta.value, (list, tuple, np.ndarray)):
if (len(theta.value) != len(self.componentlist)):
raise ValueError('Theta Array must be the same length as the component list')
for i in range(len(self.componentlist)):
self.componentlist[i].rotate(theta[i],ux,uy,uz)
else:
for i in range(len(self.componentlist)):
self.componentlist[i].rotate(theta[i],ux,uy,uz)
@u.quantity_input(x=u.mm,y=u.mm,z=u.mm)
def translate(self,dx=0*u.mm,dy=0*u.mm,dz=0*u.mm):
'''
Function translate
Translates the GratingStack in three-dimensions
Inputs:
dx,dy,dz - The amount to move in x, y, and z, respectively, must be
astropy units of length
Outputs:
None
Notes:
- This move is relative, not absolute. That is, you will move BY dx, dy, and z, you will not move TO dx, dy, and dz
'''
for g in self.getSubComponents():
g.translate(dx,dy,dz)
## Trace Function:
def trace(self,rays,considerweights=False,eliminate='remove'):
'''
Function trace:
Traces rays to each component in the Combination, keeps the photons
which hit either component
Inputs:
rays - The Rays object you want to trace
considerweights - If True, the weighting of rays will be used when
trying to remove rays based on a probability, with reflectivity,
for example.
eliminate - If 'remove', photons that miss will be removed from the
Rays object. If it is anything else, the photons which miss will
be given NaN for their x-position
Outputs:
Efficiency information about the combination
'''
# Store the length of the incoming rays
l = rays.length(considerweights)
# Initialize a list in which efficiencies will be stored
effs = []
# Make a Rays object to store the Rays that make it
finalrays = rays.copy()
finalrays.x[:] = np.nan
# Keep track of the input rays for when we're finished with one Mirror
temprays = rays.copy()
# This array will keep track of which rays have been successfully traced
success = np.zeros(len(rays)).astype(bool)
# Iterate through each Mirror Object
for r in self.componentlist:
# Through each pass we need to ensure that the rays that make it are
# placed into a final rays object
# All those that miss are passed to the next Mirror
eff = r.trace(temprays,considerweights=considerweights,eliminate='nan')
# Some components return a list of efficiencies, check if this is the case
if type(eff) == list:
effs.extend(eff)
else:
effs.append(eff)
# Find the Rays which hit the component
tarray = np.logical_not(np.isnan(temprays.x))
# Save the Rays which hit this component in finalrays, if they
# haven't hit any other component first
finalrays.pullrays(temprays,np.logical_and(tarray,np.logical_not(success)))
# Update success to include the rays which just hit
success = np.logical_or(success,tarray)
# Back remaining rays up to their original position
temprays = rays.copy()
# If there are no rays left, we can stop
if len(temprays) == 0:
break
# Make it so that the original rays now contain the output
rays.makecopy(finalrays)
# Remove NaNs, if needed
if eliminate == 'remove':
rays.remove(np.isnan(rays.x))
# Sort efficiency outputs into rays lost by missing the components and
# rays lost through other effects
# hit_but_lost stores the number of rays which hit a component but were
# lost through other effects
hit_but_lost = 0
for e in effs:
# All missed efficiencies start with "Missed"
if e[0][:6] != 'Missed':
hit_but_lost += e[2] - e[1]
eff1 = ('Missed Combination',l,rays.length(considerweights)+hit_but_lost)
eff2 = ('Lost By Combination - Other',
rays.length(considerweights)+hit_but_lost,rays.length(considerweights))
return [eff1,eff2]
|
692e4f7a9df5800599d2492b20a732b65e7e7c60 | keerthz/luminardjango | /Luminarpython/collections/listdemo/prgmforsearching.py | 232 | 3.84375 | 4 | lst=[10,12,13,14,15]
element=int(input("enter the element for search"))
flg=0
for i in lst:
if(i==element):
flg=1
break
else:
flg=0
if(flg==1):
print("element found")
else:
print("not found") |
ff64e2214caf2f674365a5cacd003b9afe7b1d0d | keerthz/luminardjango | /Luminarpython/languagefundamentals/sumof6.py | 87 | 4.0625 | 4 | num=int(input("enter the num"))
sum=0
for i in range(0,num+1):
sum=sum+i
print(sum) |
6ed8de9512fcf7f26e356d1e8def736dfe7e5051 | keerthz/luminardjango | /Luminarpython/languagefundamentals/secondlargest.py | 353 | 4.1875 | 4 | num1=int(input("enter num1"))
num2=int(input("enter num2"))
num3=int(input("enter num3"))
if((num2>num1) & (num1>num3)):
print("num1 is largest",num1)
elif((num3>num2) & (num2>num1)):
print("num2 is largest",num2)
elif((num1>num3) & (num3>num2)):
print("num3 is largest",num3)
elif((num1==num2) & (num2==num3)):
print("they are equall")
|
8c9824e79adaffc0d82b70faf2fbf5cd8b5fc11e | keerthz/luminardjango | /Luminarpython/collections/listdemo/pattern.py | 170 | 3.65625 | 4 | lst=[3,5,8]#output[13,11,8]
#3+5+8=16
#16-3=13
#16-5=11
#16-8=8
output=[]
total=sum(lst)
for item in lst:
num=total-item#16-3=13
output.append(num)
print(output)
|
b83ddc757ec963dbe30a142285ed68655fbc93b5 | keerthz/luminardjango | /Luminarpython/languagefundamentals/vowels.py | 167 | 3.734375 | 4 | string=input("enter a word")
list=["a","e","i","o","u"]
count=0
for i in list:
if(i in string):
count+=1
print(count,i)
else:
break
|
009248f4014b9f8ce04bf4701c45e2ec4ecd46c2 | keerthz/luminardjango | /Luminarpython/oops/polymorphism/empl1.py | 484 | 3.859375 | 4 | class employee:
def __init__(self,id,name,salary):
self.id=id
self.name=name
self.salary=int(salary)
#def printValues(self):
# print(self.id)
# print(self.name)
# print(self.salary)
obj=employee(1001,"ayay",25000)
obj2=employee(1002,"arun",30000)
obj3=employee(1003,"jinu",35000)
lst=[]
lst.append(obj)
lst.append(obj2)
lst.append(obj3)
for employee in lst:
if(employee.salary>=35000):
print(employee.name)
|
832f2cb1ee730068f1865f9c0655e38472a9fab0 | keerthz/luminardjango | /Luminarpython/regularexpression/quantifiers.py | 251 | 4 | 4 | import re
#pattern="a+"
#pattern="a*"
#pattern="a?"
#pattern="a{2}"
pattern="a{2,3}"
matcher=re.finditer(pattern,"aabaaaabbaaaaaabaaabb")
count=0
for match in matcher:
print(match.start())
print(match.group())
count+=1
print("count",count) |
d15700beffef5f6f30597d848d67c736c9673182 | Yuji-Takai/switchIn | /website/switchinweb/modules/utility.py | 708 | 4.03125 | 4 | from datetime import datetime
""" converts the string extracted from text to date
:param date: string representing the date
:returns: datetime for the string
"""
def convertDateFormat(date):
if (len(date) == 8):
month = date[0:2]
day = date[3:5]
year = date[6:len(date)]
year = "19" + year if int(year) > 50 else "20" + year
date = year + "-" + month + "-" + day
return datetime.strptime(date, '%Y-%m-%d')
return ""
def str_to_num(money):
if (money):
money = money.split(",")
new_money = ""
for num in money:
new_money = new_money + num
return int(new_money[1:len(new_money)])
return 0
|
4f06365db3bb2fdfa5e6c62e722e03f1ca916a7b | twillis209/algorithmsAndDataStructures | /arraySearchAndSort/insertionSort/insertionSort.py | 422 | 4.125 | 4 | def insertionSort(lst):
"""
Executes insertion sort on input.
Parameters
----------
lst : list
List to sort.
Returns
-------
List.
"""
if not lst:
return lst
sortedLst = lst[:]
i = 1
while i < len(sortedLst):
j = i - 1
while j >= 0 and sortedLst[j] > sortedLst[j+1]:
temp = sortedLst[j]
sortedLst[j] = sortedLst[j+1]
sortedLst[j+1] = temp
j -= 1
i +=1
return sortedLst
|
18290f2b984ca71bdbc4c147ec052ba17e246ad0 | twillis209/algorithmsAndDataStructures | /arraySearchAndSort/timsort/timsort.py | 1,029 | 4.25 | 4 | import pythonCode.algorithmsAndDataStructures.arraySearchAndSort.insertionSort as insertionSort
def timsort():
pass
def reverseDescendingRuns(lst):
"""
Reverses order of descending runs in list.
Modifies list in place.
Parameters
---------
lst : list
List to sort.
Returns
-------
List.
"""
runStack = getRunStack(lst)
while runStack:
start, stop = runStack.pop()
lst = reverseSubsequence(lst, start, stop)
return lst
def reverseSubsequence(lst, start, stop):
"""
"""
if start >= stop:
return lst
else:
lst[start], lst[stop] = lst[stop], lst[start]
return reverseSubsequence(lst, start+1,stop-1)
def getRunStack(lst):
"""
Identifies all runs of descending elements.
Parameters
----------
lst : list
List to sort.
Returns
-------
List.
"""
runStack = []
i = 0
while i < len(lst)-1:
# Descending
if lst[i] > lst[i+1]:
j = i+1
while j < len(lst)-1 and lst[j] > lst[j+1]:
j += 1
runStack.append((i,j))
i = j+1
else:
i += 1
return runStack
|
e47c62abda3b57756034c72860b47ebeef96f4dc | luoyun/LuoYunCloud | /lyweb/lib/SQLAlchemy-0.8.2/examples/association/__init__.py | 922 | 3.515625 | 4 | """
Examples illustrating the usage of the "association object" pattern,
where an intermediary class mediates the relationship between two
classes that are associated in a many-to-many pattern.
This directory includes the following examples:
* basic_association.py - illustrate a many-to-many relationship between an
"Order" and a collection of "Item" objects, associating a purchase price
with each via an association object called "OrderItem"
* proxied_association.py - same example as basic_association, adding in
usage of :mod:`sqlalchemy.ext.associationproxy` to make explicit references
to "OrderItem" optional.
* dict_of_sets_with_default.py - an advanced association proxy example which
illustrates nesting of association proxies to produce multi-level Python
collections, in this case a dictionary with string keys and sets of integers
as values, which conceal the underlying mapped classes.
""" |
227ffd15cf6fd13ac446c356d96c0761e1932f4d | ruteshr/python | /string_palindraome.py | 243 | 4.15625 | 4 | #String is Palindrome
string=list(str(input("enter a String :")))
a=""
for i in string:
a=i+a
if("".join(string)==a):
print('{} is palindrome'.format("".join(string)) )
else:
print('{} is not palindrome'.format("".join(string)) )
|
a7947ff5b7e90e1996753e5c05c0fbe3ff0f582d | ruteshr/python | /pattern_diamond.py | 2,697 | 3.75 | 4 | n=5
for i in range(n):
for j in range(n-i-1):
print(end=" ")
for j in range(2*i+1):
print("*",end="")
print()
for i in range(1,n):#for i in range(n)-->for 10 line
for j in range(i):
print(end=" ")
for j in range(2*n-(2*i+1)):
print("*",end="")
print()
'''
OUTPUT:
*
***
*****
*******
*********
*******
*****
***
*
'''
#============================================
n=5
for i in range(n):
for j in range(n-i-1):
print(end=" ")
for j in range(2*i+1):
print(j+1,end="")
print()
for i in range(1,n):
for j in range(i):
print(end=" ")
for j in range(2*n-(2*i+1)):
print(j+1,end="")
print()
'''
OUTPUT:
1
123
12345
1234567
123456789
1234567
12345
123
1
'''
#============================================
n=5
for i in range(n):
for j in range(n-i-1):
print(end=" ")
for j in range(2*i+1):
print(i+1,end="")
print()
for i in range(1,n):
for j in range(i):
print(end=" ")
for j in range(2*n-(2*i+1)):
print(n-i,end="")
print()
'''
OUTPUT:
1
222
33333
4444444
555555555
4444444
33333
222
1
'''
#================================================
n, m = map(int,input().split())
for i in range(n//2):
for j in range(1, (n-1),2):
txt='.|.'*j
print(txt.center(m,"-"))
break
w="WELCOME"
print(w.center(m,"-"))
for i in range(n//2):
for j in range(n-2,0,-2):
txt='.|.'*j
print(txt.center(m,"-"))
break
'''
INPUT:
7 21
OUTPUT:
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
'''
#=============================================
n=5
a=n
if(n==1):
print('a')
else:
for i in range(n):
for j in range(2*n-(2*i)-2):
print(end="-")
for j in range(i+1):
print(chr(96+a-j),end="-")
for j in range(i):
if((96+n+1-i+j==96+n) and (j==n-2)):
print(chr(96+n+1-i+j),end="")
else:
print(chr(96+n+1-i+j),end="-")
for j in range(2*n-(2*i)-2-1):
print(end="-")
print()
for i in range(n-1):
for j in range(2+2*i):
print(end="-")
for j in range(n-i-1):
print(chr(96+n-j),end="-")
for j in range(n-2-i):
print(chr(97+2+j+i),end="-")
for j in range(2*i+1):
print(end="-")
print()
'''
OUTPUT:
--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------
''''
#===========================================
|
df296049dd2cd2d136f15afdf3d8f1ebec49871d | wulianer/LeetCode_Solution | /062_Unique_Paths.py | 902 | 4.25 | 4 | """
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
"""
class Solution(object):
memo = {}
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if (m, n) in self.memo:
return self.memo[(m, n)]
if m == 1 or n == 1:
self.memo[(m, n)] = 1
return 1
res = self.uniquePaths(m-1, n) + self.uniquePaths(m, n-1)
self.memo[(m, n)] = res
return res
s = Solution()
print(s.uniquePaths(100, 100))
|
4e88fc3f4a0a63fbc41f29b2dc27ae7690190719 | wulianer/LeetCode_Solution | /025_Reverse_Nodes_in_k_Group.py | 2,023 | 3.96875 | 4 | """
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
"""
# Definition for singly-linked list.
import time
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
repr_str = ''
node = self
while node:
repr_str += str(node.val) + ' -> '
node = node.next
return repr_str + 'None'
class Solution(object):
def reverseKGroup(self, head, k):
if not self.needReverse(head, k):
return head
head = self.reverseKNodes(head, k)
i, prev, node = 0, None, head
while i < k:
prev = node
node = node.next
i += 1
prev.next = self.reverseKGroup(node, k)
return head
def reverseKNodes(self, head, k):
if head is None or head.next is None:
return head
prev, curr = None, head
while curr and k:
next = curr.next
curr.next = prev
prev = curr
curr = next
k -= 1
node = prev
while node.next:
node = node.next
node.next = curr
return prev
def needReverse(self, head, k):
while k > 0:
if not head:
return False
head = head.next
k -= 1
return True
a, b, c, d, e, f, g = (ListNode(i) for i in 'abcdefg')
s = Solution()
a.next, b.next, c.next = b, c, d
d.next, e.next, f.next = e, f, g
print(s.reverseKGroup(a, 5))
|
43e7ef8659037e36c7e61b0e3c5b3c6766e1bda4 | wulianer/LeetCode_Solution | /128_Longest_Consecutive_Sequence.py | 772 | 3.9375 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
numsSet = set(nums)
maxLength = 0
for num in numsSet:
if num-1 not in numsSet:
currLength = 1
n = num
while n+1 in numsSet:
n = n+1
currLength += 1
maxLength = max(maxLength, currLength)
return maxLength
|
4b367305f53d32a184f9260916827e26a6896c42 | wulianer/LeetCode_Solution | /041_First_Missing_Positive.py | 1,112 | 3.796875 | 4 | """
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3, --> lower: 2, upper: 2
and [3,4,-1,1] return 2. --> lower: 1, upper: 3
nums: 1 5 4 2 3 6 8
lower: 1 1 1 2 3
upper: 1 5 4 4
Your algorithm should run in O(n) time and uses constant space.
"""
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
Idea:
1. For any array whose length is l, the first missing positive value
must in 1, 2, 3, ..., l+1, so we only care about the values in this
range and remove the rest
2. We can use the array index as the hash to restore the frequency
of each number within the range 1, 2, 3, ..., l
"""
nums.append(0)
n = len(nums)
for i in range(n):
if nums[i] <= 0 or nums[i] > n:
nums[i] = 0
for i in range(n):
nums[nums[i]%n] += n
for i in range(1, n):
if int(nums[i]/n) == 0:
return i
return n
|
70f0a5a7ee0fd7b6d75193be8bde2978db720f7d | wulianer/LeetCode_Solution | /076_Minimum_Window_Substring.py | 1,001 | 4.09375 | 4 | """
Given a string S and a string T, find the minimum window in S which will
contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there are multiple such windows, you are guaranteed that there will always
be only one unique minimum window in S.
"""
from collections import Counter
class Solution(object):
def minWindow(self, s, t):
need, missing = Counter(t), len(t)
i = I = J = 0
for j in range(len(s)):
if need[s[j]] > 0:
missing -= 1
need[s[j]] -= 1
if not missing:
while i < j and need[s[i]] < 0:
need[s[i]] += 1
i += 1
if not J or j-i < J-I:
I, J = i, j
return s[I:J+1]
s = Solution()
r = s.minWindow('ADOBECDDDODEBANC', 'ABC')
print(r) |
81437f168b3fa1c08f38fffa627e0567263482be | wulianer/LeetCode_Solution | /050_Pow(x, n).py | 532 | 3.78125 | 4 | """
Implement pow(x, n).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
"""
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
if n < 0:
n = -n
return 1/self.myPow(x, n)
if n % 2 == 0:
return self.myPow(x*x, n/2)
return x * self.myPow(x, n-1)
s = Solution()
r = s.myPow(2, -10)
print(r) |
d7eb6774c273c399562026528da66b35a05d89f7 | wulianer/LeetCode_Solution | /078_Subsets.py | 688 | 3.984375 | 4 | """
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
"""
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
res = [[]]
for i, num in enumerate(nums):
expandRes = [r+[num] for r in res]
res = res + expandRes
res.sort()
return res
s = Solution()
r = s.subsets([1, 2, 3])
print(r)
|
b6783ba65e1f3c7e793e8eb36ad695ba2007015b | vishwanathvishu95/Python-games | /madlibs.generator.py | 613 | 3.953125 | 4 | #prompts for a series of input
programmer = input("Someones Name: ")
company = input("A Company Name: ")
language1 = input("A Programming Language: ")
hr = input("Someone else's Name: ")
language2 = input("Another Programming Language: ")
#printing the story with the given inputs
print("--------------------------------------------------------------------")
print(programmer + " went to attend an interview at " + company + " for the first time.")
print("He knows well to code in " + language1 +".")
print(recruiter + ', the HR says that "we need a ' + language2 + ' developer, so You can go home".') |
3af7d990e3433ff03e3a62368f454d627efe4c35 | Kezuo0605/Python | /Lesson1.py | 4,667 | 4.34375 | 4 | # 1.Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
number = 1205
word = "START"
print(f'Планируем начать обучение {number} {word} course Python')
number = int(input('Напишите, когда хотите начать курс в формате ДДММ '))
print(f'{number} {word} course Python')
# 2. Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и
# выведите в формате чч:мм:сс.
# Используйте форматирование строк.
time = int(input('введите время в секундах '))
time_h = time // 3600
time = time - (time_h * 3600)
time_m = time // 60
time = time % 60
print(f' Время которое вы ввели {time_h:02.0f}:{time_m:02.0f}:{time:02.0f} ')
#3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
number = input("введите число от 1 до 9")
number_1= int(number)
number_2= int(number + number)
number_3= int(number + number + number)
sum= number_1 + number_2 + number_3
print(sum)
#4Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции
number = int(input("Введите целое положительное число"))
schet = -1
while number > 10:
dis = number % 10
number //= 10
if dis > schet:
schet = dis
continue
print(schet)
#5. Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность
# выручки (соотношение прибыли к выручке).
# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
rev = int(input("введите значение выручки фирмы"))
coast = int(input("введите значение издержек фирмы"))
saldo = rev - coast
if saldo > 0:
print("фирма работает в прибыль")
elif saldo < 0:
print("фирма работает в убыток")
if saldo == 0:
print("фирма работает в 0 и это не считая налогов!")
if saldo > 0:
re = (saldo / rev) * 100
print(f' рентабельность составляет {re:0.0f} процентов')
sotr = int(input("сколко сотрудников работает в фирме?"))
rent = (saldo / sotr)
print(f' "рентабельность на одного сотрудника составляет" , {rent}')
# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.
k_start = int(input(" сколько километров спортсмент пробегает за день? введите число "))
k_target = int(input(" сколько километров должен пробегать спортсмен?"))
i=0
while k_start < k_target:
k_start = k_start * 1.1
i= i+1
print(i) |
4e72c806834109e6ac6810e7b6706af02b5a6f22 | tzmhuang/GaussianProcess | /GP_regression.py | 2,140 | 3.609375 | 4 | '''
based on: Machine learning -- Introduction to Gaussian Processes, Nando de Freitas
'''
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(seed = 1010)
n = 5
data_x = np.linspace(3,5,n).reshape(-1,1)
def kernel(a,b): #define kernel
sqr_dist = np.sum(a**2,1).reshape(-1,1)+ np.sum(b**2,1) - 2*np.dot(a,b.T)
return np.exp(-0.5*sqr_dist)
def getL(K):
return np.linalg.cholesky(K)
mu = 0
sigma = 1
d = np.random.normal(mu,sigma,(n,1)) #generate 10 random standard normal datasets
K = kernel(data_x,data_x) #Calculating kernel matrix for GP prior
L = getL(K+1e-6*np.eye(n)) #Calculate Cholesky decomposition
f_prior = np.dot(L,d) #Drawing samples from prior GP
'''Inference Step'''
N = 50
data_x_new = np.linspace(0,10,N).reshape(-1,1)
K_ = kernel(data_x,data_x_new)
_K_ = kernel(data_x_new,data_x_new)
'''raw methode for calculating K inverse'''
InvK = np.linalg.inv(K+1e-6*np.eye(n)) #K is singular, adding 1e-6 to make K invertable
mu_ = K_.T @ InvK @ f_prior #Mean inference
Cov_matrix = _K_- K_.T @ InvK @ K_ #Covariance inference
# '''a better way to computer K inverse?'''
# InvK = np.linalg.inv(L.T) @ np.linalg.inv(L)
# mu_ = K_.T @ InvK @ f_prior #Mean inference
# Cov_matrix = _K_- K_.T @ InvK @ K_ #Covariance inference
L_ = getL(Cov_matrix+1e-6*np.eye(N)) #Calculate Cholesky decomposition of infered Covariance matrix
rand_sample = np.random.normal(0,1,(N,10)) #Drawing 5 sets of random sample each of size 50
f_post = np.dot(L_,rand_sample)+mu_ #Drawing samples from posterior GP
'''Plots'''
plt.plot(data_x,f_prior,'ro',label = 'Observations')
plt.plot(data_x_new,mu_,'k-',label = 'Infered mean')
# plt.plot(data_x_new,mu_+1.65*np.diag(Cov_matrix).reshape(-1,1), 'g--',label='CI')
# plt.plot(data_x_new,mu_-1.65*np.diag(Cov_matrix).reshape(-1,1), 'g--')
plt.fill_between(data_x_new.reshape(-1),(mu_+1.65*np.diag(Cov_matrix).reshape(-1,1)).reshape(-1),(mu_-1.65*np.diag(Cov_matrix).reshape(-1,1)).reshape(-1),facecolor = 'grey',alpha = 0.5, label = 'C.I.')
plt.plot(data_x_new,f_post,'-')
plt.legend()
plt.show() |
d8e7568483e6583d0157bced6a93fd3672d67c34 | shadowstep666/phamminhhoang-fundamental-c4e25 | /section1/intro.py | 174 | 3.703125 | 4 | from turtle import *
shape("turtle")
speed(0)
for i in range(300):
for j in range (4):
forward(200)
left(90)
right(7)
mainloop() |
55cab638287d2ff91e594c7e2111123ed2b4c4ac | shadowstep666/phamminhhoang-fundamental-c4e25 | /section3/homework_day3/turtle2.py | 300 | 3.8125 | 4 | from turtle import *
colors = [ 'red','blue','brown','yellow','gray']
for index , colour in enumerate(colors):
color(colour)
begin_fill()
for i in range(2):
forward(50)
left(90)
forward(100)
left(90)
forward(50)
end_fill()
mainloop() |
33eaa474c2cf5191c44e189987c0de0d1fef4bc1 | shadowstep666/phamminhhoang-fundamental-c4e25 | /section3/menu.py | 679 | 3.78125 | 4 | # item1= " bun dau mam tom"
# item2="pho"
# item3="banh my"
# item4 = "lau"
# items = [] # empty list
# print(type(items))
# items = [ " bun dau"]
# print(items)
items = ["bun dau mam tom ", "pho","banh mi", "lau"]
# print(items)# print la mot loai read nhung chi doc ket qua
# items.append("banh ny") # them banh my vao sau danh sach
# print(items)
# read all => list
# for i in items :
# print(i)
# read one => detail
# print(items[0])
# print(items[-1])
# print(items[1])
# items[1]= " pho xao" # change pho thanh pho xao
# print(items[1])
# print(items)
# items.remove("pho") # xoa ten
# print(items)
# xoa vi tri
items.pop(2)
print(items)
|
c68bf1082ec0684aef2788848101c283c88cb508 | shadowstep666/phamminhhoang-fundamental-c4e25 | /section2/homeworkDay2/n_start.py | 88 | 3.515625 | 4 | xs = "* "
n = int(input("nhap vao n :" ))
for i in range(n):
print(xs, end=" ")
|
4d09e92399cffd253ec767fa52db207f28521079 | ChihaoFeng/Leetcode | /20. Valid Parentheses.py | 541 | 3.796875 | 4 | class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for p in s:
if p == '(':
stack.append(')')
elif p == '[':
stack.append(']')
elif p == '{':
stack.append('}')
elif not stack or stack.pop() != p:
return False
return len(stack) == 0
"""
The idea is to use the stack to record the complement of '(', '[', '{'
Time: O(n)
Space: O(n)
"""
|
273c9140794b49bd00f600c924355d478b4580b3 | ChihaoFeng/Leetcode | /74. Search a 2D Matrix.py | 682 | 3.78125 | 4 | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
x, y = len(matrix), len(matrix[0])
i, j = 0, x * y - 1
while i <= j:
m = (i + j) // 2
m_i = m // y
m_j = m % y
if matrix[m_i][m_j] == target:
return True
elif matrix[m_i][m_j] < target:
i = m + 1
else:
j = m - 1
return False
"""
think about it as binary search
Time: O(log(m*n))
Space: O(1)
""" |
62f5eec73b9300a69398ba171c6daa4444fbf416 | ChihaoFeng/Leetcode | /52. N-Queens II.py | 1,600 | 3.515625 | 4 | def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
def dfs(row):
if row == n:
self.ret += 1
return
for col in range(n):
if cols[col] or d1[col - row + n - 1] or d2[row + col]:
continue
cols[col] = d1[col - row + n - 1] = d2[row + col] = True
dfs(row + 1)
cols[col] = d1[col - row + n - 1] = d2[row + col] = False
self.ret = 0
cols, d1, d2 = [False] * n, [False] * (2 * n - 1), [False] * (2 * n - 1)
dfs(0)
return self.ret
"""
The idea is to have three lookup boolean array for columns and diagonals.
for diagonal k = 1, we use row + col as the index
for diagonal k = -1, we use col - row + n - 1 as the index
-----------------------------------------------------------------------------
eg. n = 4
index i, j for each elements:
(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3)
(3,0) (3,1) (3,2) (3,3)
-----------------------------------------------------------------------------
i + j for each elements:
0 1 2 3 |
-----------
0 1 2 3 |
1 2 3 4 | 4
2 3 4 5 | 5
3 4 5 6 | 6
we can use that elements on the same diagonal line (k = 1) are same
index = i + j
-----------------------------------------------------------------------------
i - j for each elements:
| 4 5 6
--------------------
3 | 0 1 2 3
2 | -1 0 1 2
1 | -2 -1 0 1
0 | -3 -2 -1 0
we can use that elements on the same diagonal line (k = -1) are same
index = i - j + n - 1
Time: O(n*n)
Space: O(n)
"""
|
520410658429bb33202f390ea275b2393e154f5e | ChihaoFeng/Leetcode | /9. Palindrome Number.py | 755 | 3.90625 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 or (x and not x % 10):
return False
y = 0
while x > y:
y = y * 10 + x % 10
x //= 10
return x == y or x == y // 10
"""
we first need to handle some corner case: negative number and positive number with last digit 0
Then we use the same idea as reverse integer. Here we only need to reverse half of the number, which
can be perfectly controlled by condition x > y
Finally, the number is palindrome if x == y if x has even number of digits or x == y//10 if x has odd number
if digits
Time: O(log(n)/2) = O(log(n)) depends on the number of digits of x
Space: O(1)
""" |
a0fc54a4a0ef4f59666707712ed0f16318e9f512 | ChihaoFeng/Leetcode | /37. Sudoku Solver.py | 1,824 | 3.703125 | 4 | class Solution:
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def pre_process():
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
val = 1 << int(board[i][j])
rows[i] |= val
cols[j] |= val
squares[3 * (i // 3) + j // 3] |= val
def is_valid(i, j, c):
val = 1 << int(c)
if rows[i] & val or cols[j] & val or squares[3 * (i // 3) + j // 3] & val:
return False
return True
def set_helper(i, j, c, flag):
val = 1 << int(c)
if flag:
board[i][j] = c
rows[i] |= val
cols[j] |= val
squares[3 * (i // 3) + j // 3] |= val
else:
board[i][j] = '.'
rows[i] &= ~val
cols[j] &= ~val
squares[3 * (i // 3) + j // 3] &= ~val
def solve():
for i in range(9):
for j in range(9):
if board[i][j] == '.':
for c in '123456789':
if is_valid(i, j, c):
set_helper(i, j, c, True)
if solve():
return True
set_helper(i, j, c, False)
return False
return True
rows, cols, squares = [0] * 9, [0] * 9, [0] * 9
pre_process()
solve()
"""
dfs, borrow the same idea from valid sudoku
Time: don't know
Space: don't know
""" |
078fe3fd6e966d82b68b0be61dd2ad73223a0b7f | ChihaoFeng/Leetcode | /103. Binary Tree Zigzag Level Order Traversal.py | 745 | 3.90625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
queue = [root]
ret = []
flag = True
while queue:
if flag:
ret.append([queue[i].val for i in range(len(queue))])
else:
ret.append([queue[i].val for i in range(len(queue) - 1, -1, -1)])
queue = [node0 for node in queue for node0 in [node.left, node.right] if node0]
flag = not flag
return ret |
1fb90380a3e2c19219922cb9d46e2cf8aa520344 | ChihaoFeng/Leetcode | /69. Sqrt(x).py | 403 | 3.609375 | 4 | class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
i, j = 0, x
while i <= j:
m = (i + j) // 2
if m * m == x:
return m
elif m * m < x:
i = m + 1
else:
j = m - 1
return j
"""
binary search problem
Time: O(logn)
Space: O(1)
"""
|
2c231997492be2f5c53c01e6e3469e7d735e0af3 | JuliandroR/Atividades-IFMS | /python/bin4dec.py | 243 | 3.65625 | 4 | entrada = input("A sequência em binário, please")
a = int(entrada[:7], 2)
b = int(entrada[8:15], 2)
c = int(entrada[16:23], 2)
d = int(entrada[24:31], 2)
print("A sequẽncia informada convertida é: {} . {} . {} . {}".format(a, b, c, d)) |
c9364b322396ef9d1c140ba5c8e6c184acf6a41c | chenchals/interview_prep | /amazon/copy_linked_list_with_random_pointer.py | 882 | 3.703125 | 4 | # Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
cur = head
# copy all duplicated node to a hashtable
look_up = dict()
look_up[None] = None
while cur:
new = RandomListNode(cur.label)
look_up[cur] = new
cur = cur.next
cur = head
copied_head = look_up[head]
# another run
while cur:
copied_head.next = look_up[cur.next]
copied_head.random = look_up[cur.random]
copied_head = copied_head.next
cur = cur.next
return look_up[head] |
db082c1d53e70879e26a3d2d1cc9d08f85e38d2c | chenchals/interview_prep | /algorithms/tree_traversal.py | 1,857 | 3.625 | 4 | import math
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def PreOrderTraversal(root, cb):
cb(root.value, end=' ')
if root.left is not None:
PreOrderTraversal(root.left, cb)
if root.right is not None:
PreOrderTraversal(root.right, cb)
return cb
def InOrderTraversal(root, cb):
if root.left is not None:
InOrderTraversal(root.left, cb)
cb(root.value, end=' ')
if root.right is not None:
InOrderTraversal(root.right, cb)
return cb
def PostOrderTraversal(root, cb):
if root.left is not None:
PostOrderTraversal(root.left, cb)
if root.right is not None:
PostOrderTraversal(root.right, cb)
cb(root.value, end=' ')
return cb
def CompleteTree(tree_serialized):
root = Node(tree_serialized.pop(0))
stack = list()
stack.append(root)
while len(stack) > 0:
this = stack.pop(0)
if len(tree_serialized) > 0 :
new_node = Node(tree_serialized.pop(0))
this.left = new_node
stack.append(this.left)
if len(tree_serialized) > 0 :
new_node = Node(tree_serialized.pop(0))
this.right = new_node
stack.append(this.right)
return root
def BuildBST(tree_serialized, start, end, balance='left'):
if start > end:
return None
if balance == 'right':
mid = math.ceil((end+start) / 2)
elif balance == 'left':
mid = math.floor((end+start) / 2)
else:
mid = int((end+start) / 2)
root = Node(tree_serialized[mid])
# print(root.value)
# because the mid is used above
root.left = BuildBST(tree_serialized, start, mid-1)
root.right = BuildBST(tree_serialized, mid+1, end)
return root
if __name__ == "__main__":
t1 = [1,2,3,4,5,6,7]
print(t1)
# test = CompleteTree(t1)
root = BuildBST(t1, 0, len(t1)-1, 'middle')
print('root', root.value)
InOrderTraversal(root, print)
print()
PreOrderTraversal(root, print)
print()
PostOrderTraversal(root, print) |
a2aba7dc8d55e05aa6b7ce31cbc456bed61e946b | chenchals/interview_prep | /amazon/intersection_of_linked_list.py | 1,258 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
track_A = headA
track_B = headB
len_A = self.find_length(track_A)
len_B = self.find_length(track_B)
A_shorter = len_A < len_B
diff = abs(len_A-len_B)
track_A = headA
track_B = headB
if A_shorter:
while diff:
track_B = track_B.next
diff -= 1
else:
while diff:
track_A = track_A.next
diff -= 1
# share the same head
while True:
if track_A == track_B:
return track_A
if not track_A.next:
return None
track_A = track_A.next
track_B = track_B.next
return None
def find_length(self, head):
count = 0
this = head
while this.next != None:
this = this.next
count += 1
return count |
33ce2afb61fca3b33bd2439f9b12d1d09f41436f | chenchals/interview_prep | /linked_list/merge_two_sorted_linked_list.py | 1,303 | 3.96875 | 4 | class Node(object):
def __init__(self):
self.__v = None
self.next = None
def next(self, Node):
self.next = Node
@property
def v(self):
return self.__v
@v.setter
def v(self, v):
self.__v = v
def build_linked_list_from_list(li):
head = Node()
head.v = li[0]
this = head
for each in li[1:]:
new = Node()
new.v = each
this.next = new
this = this.next
return head
def merge_sorted_linked_list(head1, head2):
if head2 is None:
return head1
elif head1 is None:
return head2
elif head1 is None and head2 is None:
return None
# a dummy node to start
head = tail = Node()
# both list1 and list2 exist
while head1 is not None and head2 is not None:
if head1.v < head2.v:
c = head1
head1 = head1.next
else:
c = head2
head2 = head2.next
tail.next = c
tail = c
tail.next = head1 or head2
head = head.next
return head
l1 = [1,3,4]
l2 = [1,4,6]
head1 = build_linked_list_from_list(l1)
head2 = build_linked_list_from_list(l2)
head = merge_sorted_linked_list(head1, head2)
this = head
while this != None:
print(this.v, end=' ')
this = this.next |
6f6010cd508110c20469513733cac735f6313694 | chenchals/interview_prep | /algorithms/dijkstra.py | 462 | 3.8125 | 4 | class Vertex(object):
def __init__(self, x, distance):
# 2-dim tuple (x, y)
self.key = x
# distance[(1,2)] = distance -> coord to cost dict
self.distance = distance
self.parent = None
def Dijkstra(graph, start, end):
# set of visited coord
for i in range(len(graph)):
for j in range(len(graph[0])):
neighbour_list = [(i+1, j), (i-1,j), (i,j-1), (i, j+1)]
for coord in neighbour_list:
x, y = coord
if x < 0 or y < 0:
continue |
f75ae19fcc5b53606004ffe42edd406d0264c7ae | Catherine1000/PythonExercises | /AverageGrades.py | 560 | 4.0625 | 4 | bio_score = float(input("Enter your biology score: "))
chem_score = float(input("Enter your chemistry score: "))
physics_score = float(input("Enter your physics score: "))
if bio_score < 40:
print("Fail")
elif chem_score < 40:
print("Fail")
elif physics_score < 40:
print("Fail")
else:
score = (bio_score + chem_score + physics_score) / 3
if score >= 70:
print("1st")
elif score >= 60:
print("2.1")
elif score >= 50:
print("2.2")
elif score >= 40:
print("Pass")
else:
print("Fail") |
fb10a2f3e98da33e6f5cbbe1f1d08f41dc452855 | vincenttchang90/think-python | /chapter_1/chapter_1_exercises.py | 1,190 | 4.375 | 4 | #chapter 1 exercises
#1-1
# In a print statement, what happens if you leave out one of the parentheses, or both?
## print 'hello') or print('hello' return errors
# If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
## print('hello) or print(hello') return errors while print(hello) says hello is not defined
#You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2?
## 2++2 returns 4, +1+2 returns 3 so it seems you can specify a number is positive with a +
# In math notation, leading zeros are okay, as in 02. What happens if you try this in Python?
## 2+02 returns an invalid token error
# What happens if you have two value with no operator between them?
## returns invalid syntax
#1-2
# How many seconds are there in 42 minutes 42 seconds?
## 42*60+42 = 2562
# How many miles are there in 10 kilometers? Hint: there are 1.61 kilometeres in a mile.
## 10/1.61 = 6.2 miles
# If you run a 10 kilometer race in 42 minutes 52 seconds, what is your average pace? What is your average speed in miles per hour?
## 6:52 minutes per mile. 8.73 miles per hour |
4919605e133d383f8a7c848efa3eaf1405a58a96 | bharatanand/B.Tech-CSE-Y2 | /applied-statistics/python-revisited/intermediate-concepts/list-comprehension/gen-n-even-nos.py | 91 | 3.796875 | 4 | n = int(input("Display even numbers below: "))
ls = [i for i in range(0, n, 2)]
print(ls) |
526886cff12e987b705d2443cd0bc1741a552f36 | bharatanand/B.Tech-CSE-Y2 | /applied-statistics/lab/experiment-3/version1.py | 955 | 4.28125 | 4 | # Code by Desh Iyer
# TODO
# [X] - Generate a random sample with mean = 5, std. dev. = 2.
# [X] - Plot the distribution.
# [X] - Give the summary statistics
import numpy as np
import matplotlib.pyplot as plt
import random
# Input number of samples
numberSamples = int(input("Enter number of samples in the sample list: "))
# Generate sample list
sampleList = [random.normalvariate(5, 2) for x in range(numberSamples)]
# Printing details
print('\nGenerated sample list containing {} elements: '.format(numberSamples))
print(sampleList)
print('\n\nCalculated Mean = {:.3f}\nRounded Calculated Mean = {}\n\nCalculated Std. Deviation = {:.3f}\nRounded Calculated Std. Deviation = {}'.format(
np.mean(sampleList), round(np.mean(sampleList)), np.std(sampleList), round(np.std(sampleList))
)
)
plt.hist(sampleList)
plt.show()
# Reference:
# https://stackoverflow.com/questions/51515423/generate-sample-data-with-an-exact-mean-and-standard-deviation |
5ad337bd7a7d4d10ee0fec4a1e2e1f8806039911 | sjrathod/learning-python | /crackingTheCodingInterview/arrayAndStrings/oneAway.py | 844 | 3.65625 | 4 | #!/usr/bin/python
def oneAway(str1, str2):
i = 0
j = 0
edited = False
diff = len(str1) - len(str2)
if diff < -1 or diff > 1:
return False
s1 = str1 if (len(str1) > len(str2)) else str2
s2 = str2 if (len(str1) > len(str2)) else str1
if diff == 0:
while(i < len(s1) and j < len(s2)):
if s1[i] != s2[j]:
if edited:
return False
edited = True
if diff == 0:
j += 1
else:
j += 1
i += 1
return True
def main():
str1 = raw_input("Enter string1 for one away check:")
str2 = raw_input("Enter string2 for one away check:")
if oneAway(str1, str2):
print "Strings are one edit away."
else:
print "Strings are NOT one edit away."
if __name__ == "__main__":
main() |
1f45cddab2c6b1ac0f4c7b4b24415815c8c24df1 | sjrathod/learning-python | /crackingTheCodingInterview/linkedLists/partition.py | 952 | 3.828125 | 4 | #! /usr/bin/python
from basicLinkedList import *
import pdb
def partition(current, k):
beforeLL = LinkedList()
afterLL = LinkedList()
while current:
if current.data < k :
beforeLL.insertAtTail(current.data)
else:
afterLL.insertAtTail(current.data)
current = current.next
print "Before partition LL"
beforeLL.printList()
print "After partition LL"
afterLL.printList()
temp = beforeLL.head
while temp.next:
temp = temp.next
temp.next = afterLL.head
return beforeLL
def main():
llist = LinkedList()
llist.generateLLofNnodes(n=5)
llist.insertAtNth(11, 5)
llist.insertAtNth(14, 2)
llist.insertAtNth(10, 3)
llist.insertAtNth(1, 6)
llist.insertAtNth(20, 1)
llist.printList()
k = int(raw_input("Enter number for partition, K:"))
resLL = partition(llist.head, k)
print "Final LL"
resLL.printList()
if __name__ == "__main__":
main() |
fa57f7fed7a1b413b04d7f7e331794660b15a2bd | haema5/python_level_1 | /hw01_easy.py | 2,447 | 3.9375 | 4 | __author__ = 'Пашков Игорь Владимирович'
import random
# Задача-1: Дано произвольное целое число (число заранее неизвестно).
# Вывести поочередно цифры исходного числа (порядок вывода цифр неважен).
# Подсказки:
# * постарайтесь решить задачу с применением арифметики и цикла while;
# * при желании решите задачу с применением цикла for.
print('Задача-1:')
print('')
number = random.randint(1000, 9999)
print('Произвольное целое число:', number)
while number > 0:
n = int(number) % 10
number = int(number) // 10
print(n)
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Подсказка:
# * постарайтесь сделать решение через дополнительную переменную
# или через арифметические действия
# Не нужно решать задачу так:
# print("a = ", b, "b = ", a) - это неправильное решение!
print('')
print('Задача-2:')
print('')
a = input('Введите число а: ')
b = input('Введите число b: ')
print('')
print('a: {}, b: {}'.format(a, b))
print('')
print('С помощью дополнительной переменной:')
x = a
a = b
b = x
print('a: {}, b: {}'.format(a, b))
print('')
print('Через арифметические действия: ')
a = int(a)
b = int(b)
a = a + b
b = a - b
a = a - b
print('a: {}, b: {}'.format(a, b))
print('')
# Задача-3: Запросите у пользователя его возраст.
# Если ему есть 18 лет, выведите: "Доступ разрешен",
# иначе "Извините, пользование данным ресурсом только с 18 лет"
print('')
print('Задача-3:')
print('')
answer = int(input('Укажите свой возраст: '))
if answer >= 18:
print('Доступ разрешен')
else:
print('Извините, пользование данным ресурсом только с 18 лет')
|
b8f822a44c8b35e6d1e40a6c04c3afdac0989219 | LBHukan/Clima | /clima.py | 1,176 | 3.671875 | 4 | import requests
import json
name_city = str(input("Digite Sua Cidade: "))
name_state = str(input("Digite Seu Estado Abreviado: "))
def ID(cidade, estado):
city = str(cidade)
state = str(estado)
requisicao = requests.get("https://api.hgbrasil.com/weather?key=40acff95&city_name="+ name_city +","+ name_state +"")
jsn = json.loads(requisicao.text)
return jsn
def Status(json):
json = json
print("################################################################################")
print("Dia " + str(json['results']['date']) + " às " + str(json['results']['time'])) # Horario e Dia
print("Condicao: " + str(json['results']['description'])) # descricao
print("Cidade: " + str(json['results']['city'])) # cidade
print("Nivel de Humidade: " + str(json['results']['humidity'] + "%")) # humidade
print("Temperatura de: " + str(json['results']['temp']) + "°") # temperatura
print("################################################################################")
name = ID(name_city, name_state)
show = Status(name)
|
c5d76587c717609f3a2f3da3a9136f92b3fee367 | bmgarness/school_projects | /lab2_bmg74.py | 755 | 4.125 | 4 | seconds = int(input('Enter number of seconds to convert: '))
output = '{} day(s), {} hour(s), {} minute(s), and {} second(s).'
secs_in_min = 60
secs_in_hour = secs_in_min * 60 # 60 minutes per hour
secs_in_day = secs_in_hour * 24 # 24 hours per day
days = 0
hours = 0
minutes = 0
if seconds >= secs_in_day:
days = seconds // secs_in_day # Interger Division
seconds = seconds % secs_in_day # Remainder Divsion
if seconds >= secs_in_hour:
hours = seconds // secs_in_hour # Interger Divsion
seconds = seconds % secs_in_hour # Remainder Divsion
if seconds >= secs_in_min:
minutes = seconds //secs_in_min # Interger Divsion
seconds = seconds % secs_in_min # Remainder Divsion
print(output. format(days, hours, minutes, seconds))
|
285c7fe0c7af03f251dd0b45dfc1d2cb0d66fced | B7504C/ichw | /pyassign4/wcount.py | 1,823 | 3.75 | 4 | #!/usr/bin/env python3
"""wcount.py: count words from an Internet file.
__author__ = "Bai Yuchen"
__pkuid__ = "1800011798"
__email__ = "[email protected]"
"""
import sys
from urllib.request import urlopen
def wcount(lines, topn):
"""count words from lines of text string, then sort by their counts
in reverse order, output the topn (word count), each in one line.
"""
strlist=[]
for i in lines:
string_dl=i.decode().lower()
string=' '+string_dl+' '
replace_list=['\r\n',',','.',':','"','!','?',"'"]
for j in replace_list:
string=string.replace(j,' ')
strlist=strlist+[string] #每行字符串的list
all_words=[]
for i in strlist:
all_words=all_words+i.split() #所有单词的list
words=list(set(all_words)) #所有出现过的单词
countlist=[]
for word in words:
countlist=countlist+[all_words.count(word)] #每个单词出现次数
ziplist=zip(words,countlist)
sortlist=sorted(ziplist,key=lambda i:i[1],reverse=True) #按次数倒序排序
dic={}
for item in sortlist:
dic[item[0]]=item[1]
if int(topn)<=len(words):
for i in range(int(topn)):
print(sortlist[i][0]+' ',dic[sortlist[i][0]])
else:
for i in range(len(words)):
print(sortlist[i][0]+' ',dic[sortlist[i][0]])
pass
def main():
doc = urlopen(sys.argv[1])
lines = doc.readlines()
topn = sys.argv[2]
wcount(lines,topn)
if __name__ == '__main__':
if len(sys.argv) == 1:
print('Usage: {} url [topn]'.format(sys.argv[0]))
print(' url: URL of the txt file to analyze ')
print(' topn: how many (words count) to output. If not given, will output top 10 words')
sys.exit(1)
main() |
9e905216e5e04d4b1b21d0f30afa26115da84044 | ayeshaghoshal/learn-python-the-hard-way | /ex29.py | 1,607 | 4.03125 | 4 | # -*- coding: utf-8 -*-
print "EXERCISE 29 - What if"
people = 200
cats = 45
dogs = 100
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
# increment operator. Means dogs = dogs + 5 = 100 + 5
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
if cats == 45:
print "Thaaat's right!!"
if people >= cats + dogs:
print "People rulee!!"
# STUDY DRILLS
# if-statement: it's a condition that is to be obeyed by the set parameters
# why indented? the if-statement will only apply to the indented code otherwise, there's an indentationError
# Actual explaination!!
# if-statement - creates what is called a "branch" in the code. The if-statement tells your script,
# "If this boolean expression is True, then run the code under it, otherwise skip it.
# why indented? - A colon at the end of a line is how you tell Python you are going to
# create a new "block" of code, and then indenting four spaces tells Python what lines of
# code are in that block.
# This is exactly the same thing you did when you made functions in the first half of the book.
# If not indented? - will most likely create a Python error.
# Python expects you to indent something after you end a line with a : (colon)
#
|
ec32d18f39290dc135c190a49764ae585be27ccd | ayeshaghoshal/learn-python-the-hard-way | /ex14.py | 1,252 | 4.5 | 4 | # -*- coding: utf-8 -*-
print "EXERCISE 14 - Prompting and Passing"
# Using the 'argv' and 'raw_input' commands together to ask the user something specific
# 'sys' module to import the argument from
from sys import argv
# define the number of arguments that need to be defined on the command line
script, user_name = argv
# instead of using raw_data in the previous formats, this is a new way.
# Defines what character will show up when a raw input is required by the user
prompt = '@ '
#
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
# the following line defines that a prompt is required by the user
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
# Use of triple brackets and % command together to combine string and raw input data
# since this line of code comes after 'likes', 'lives' and 'computer', we know what value to insert
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
|
8c787b221b005f2f997f7d927a008d3ff9fa1514 | ayeshaghoshal/learn-python-the-hard-way | /ex19.py | 2,520 | 4.40625 | 4 | # -*- coding: utf-8 -*-
print "EXERCISE 19 - Functions and Variables"
# defining the function that commands the following strings to be printed out
# there are 2 parameters that have to be defined in brackets
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# use of the parameters is the same method as writing string and designating values to it
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man, that's enough for a party!"
print "Get a blanket.\n"
# a new method of displaying the function directly by designating it values
print "We can just give the function numbers directly:"
# the following function will promth the command to print the stated 4 sentences above
cheese_and_crackers(20,30)
# another method of printing the same function
print "OR, we can use variables from our script:"
# designate a value to new variables
amt_of_cheese = 10
amt_of_crackers = 30
# the new variables will replace the old parameters to state the defined values right above
cheese_and_crackers(amt_of_cheese,amt_of_crackers)
# use just numbers to define the two parameters inside the defined function
print "We can even do math inside too:"
cheese_and_crackers(20 + 25, 48 + 50)
# Showcases the use of both variables and math to display the defined function
# as long as there are only 2 paramenters defined within the brackets!!!
print "And we can combine the two, variables and math:"
cheese_and_crackers(amt_of_cheese + 20, amt_of_crackers + 450)
#STUDY DRILLS - NEW FUNCTION!
def animals_on_farm(cows, chickens, sheep):
print "Can you spot %d cows?" % cows
print "I bet you won't be able to identify %d red chickens!" % chickens
print "Did you sheer all %d sheep this season?" % sheep
print "I hope so! otherwise they will all look like cotton balls! HAHAHA\n"
animals_on_farm(10, 4, 23)
animals_on_farm(3 + 4, 51 + 1, 2 + 7)
a = 20
b = 14
c = 24
# can replace the name of parameters inside the function ()
animals_on_farm(a, b, c)
animals_on_farm(a + 2, b*2, c - 10)
print "We can assign the function to a variable and simply call it by its new variable name"
poo = animals_on_farm
poo(2, 4, 8)
print "We can pass a function as arguments"
print "Now ask the user for the number of cows, chickens and sheep! - brackets within brackets"
animals_on_farm(int(raw_input("How many cows?")), int(raw_input("How many chickens?")), int(raw_input("How many sheep?)")))
|
a4757d33b940e4cfcb580a0d18cb9f7117384929 | giuschil/Python-Essentials | /sorting algorithms/bubblesort.py | 1,214 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 11:36:50 2019
@author: giuse
"""
def swap(a,b):
tmp = b
b = a
a = tmp
return a,b
def random_array():
import random
n= int(input("How many numbers you want to generate? "))
m= int(input("Number Max for choice? "))
my_random=[]
for i in range(n):
my_random.append(random.randrange(1, m, 1))
return my_random
def check_array(array):
for i in range(0,len(array)-1):
if array[i] <= array[i+1]:
continue
else:
return False
return True
def bubblesort(array):
while check_array(array) != True:
for j in range(0,len(array)-1):
if array[j]>array[j+1]:
tmp = array[j]
array[j] = array[j+1]
array[j+1]=tmp
return array
from datetime import datetime
tstart = datetime.now()
bubblesort(array)
tend = datetime.now()
print(tend - tstart)
if __name__ == '__main__':
import sys # importiamo il modulo sys della libreria standard
import random #importiamo il modulo random per numeri casuali
|
77bac9d5c187722aba0582983c074af89176dbfa | giuschil/Python-Essentials | /Hello.py | 251 | 3.9375 | 4 | "Write the numbers from 1 to 10"
lista = []
for i in range(0,11):
lista.append(i)
print("il numero è: ",i)
print("La lista è: ",lista)
print("/n")
for i in lista:
print("il numero nella lista è: ",lista[i])
|
c5ee299d12ea8ad5e50aec5dcc1fcde6a5b789cb | juletats/LabsNMPy | /lab3.2.py | 5,264 | 3.875 | 4 | def NullMatrix(n):
"""Создание нулевой матрицы"""
nullM = [0] * (n);
for i in range(n):
nullM[i] = [0] * (n)
return nullM
def MultiplyMM(matrix1, matrix2):
"""Умножение матрицы на матрицу"""
n = len(matrix1);
result = NullMatrix(n);
for i in range(n):
for j in range(n):
c = 0;
for k in range(n):
c += matrix1[i][k] * matrix2[k][j]
result[i][j] = c
return result
def MultiplyMV(matrix, vector):
"""Умножение матрицы на вектор"""
n = len(vector);
result = [0] * n;
for i in range(n):
for j in range(n):
result[i] += matrix[i][j] * vector[j];
return result;
def Swap(matrix, stroke1, stroke2):
"""Смена строк"""
tmp = 0;
n = len(matrix)
for i in range(n):
tmp = matrix[stroke2][i]
matrix[stroke2][i] = matrix[stroke1][i]
matrix[stroke1][i] = tmp;
def SLAE(matrix1, matrix2, vector):
"""Решение СЛАУ"""
n = len(matrix1)
vector1 = [0] * n;
vector2 = [0] * n;
vector2[0] = vector[0]
for i in range(1, n):
summ = 0
for j in range(0, i):
summ += matrix1[i][j] * vector2[j]
vector2[i] = vector[i] - summ
vector1[n - 1] = vector2[n - 1] / matrix2[n - 1][n - 1]
for k in range(n - 2, -1, -1):
summ = 0
for e in range(k + 1, n):
summ += matrix2[k][e] * vector1[e];
vector1[k] = (1 / matrix2[k][k] * (vector2[k] - summ))
return vector1
def LU(A, b):
n = len(A)
M = NullMatrix(n)
L = NullMatrix(n)
P = NullMatrix(n)
P_k = NullMatrix(n)
for i in range(n):
for j in range(n):
if i == j:
M[i][j] = 1
L[i][j] = 1
P[i][j] = 1
P_k[i][j] = 1
for i in range(n - 1):
maximum = -100000
for l in range(0, n):
if A[l][i] > maximum:
maximum = A[l][i]
index = l;
Swap(P_k, i, index)
P = MultiplyMM(P_k, P)
A = MultiplyMM(P_k, A)
m = i + 1
l = i
for m in range(i + 1, n):
for l in range(i, n):
if m == l:
M[m][l] = 1
else:
if (m != l) and (l == i):
M[m][i] = -A[m][i] / A[i][i]
A = MultiplyMM(M, A)
m = i + 1
for m in range(i + 1, n):
M[m][i] *= -1
L = MultiplyMM(P_k, L)
L = MultiplyMM(L, P_k)
L = MultiplyMM(L, M)
M = NullMatrix(n)
P_k = NullMatrix(n)
m = 0
l = 0
for l in range(0, n):
for m in range(0, n):
if l == m:
M[l][m] = 1
P_k[l][m] = 1
b = MultiplyMV(P, b)
x = SLAE(L, A, b)
return x
####################################################################
xi = [-0.4, -0.1, 0.2, 0.5, 0.8]
fi = [1.9823, 1.6710, 1.3694, 1.0472, 0.64350]
X = 0.1
hi = []
# xi = [0, 1, 2, 3, 4]
# fi = [0, 1.8415, 2.9093, 3.1411, 3.2432]
# X = 1.5
n = len(xi)
for i in range(n - 1):
hi.append(xi[i + 1] - xi[i])
C = NullMatrix(n - 2)
C[0][0] = 2 * (hi[0] + hi[1])
C[0][1] = hi[1] # i=2
C[1][0] = hi[1]
C[1][1] = 2 * (hi[1] + hi[2])
C[1][2] = hi[2]
C[2][1] = hi[2]
C[2][2] = 2 * (hi[2] + hi[3])
rightSide = []
rightSide.append(3 * (((fi[2] - fi[1]) / hi[1]) - ((fi[1] - fi[0]) / hi[0])))
rightSide.append(3 * (((fi[3] - fi[2]) / hi[2]) - ((fi[2] - fi[1]) / hi[1])))
rightSide.append(3 * (((fi[-1] - fi[-2]) / hi[3]) - ((fi[-2] - fi[-3]) / hi[2])))
ai = [];
bi = [];
di = []
ci = LU(C, rightSide);
ci.insert(0, 0)
for i in range(len(ci) - 1):
ai.append(fi[i])
bi.append(((fi[i + 1] - fi[i - 1 + 1]) / hi[i]) - (1 / 3) * hi[i] * (ci[i + 1] + 2 * ci[i]))
di.append((ci[i + 1] - ci[i]) / (3 * hi[i]))
ai.append(fi[-2])
bi.append((fi[-1] - fi[-2]) / (hi[-1]) - (2 / 3) * hi[-1] * ci[-1])
di.append(-ci[-1] / (3 * hi[-1]))
print('\nКубический сплайн\n')
print('| --- a --- | --- b --- | --- c --- | --- d --- |')
print('| --------------------------------------------- |')
for i in range(len(ai)):
print('| {0: 9f} | {1: 9f} | {2: 9f} | {3: 9f} |'.format(round(ai[i], 5), round(bi[i], 5), round(ci[i], 5),
round(di[i], 5)))
print('| --------------------------------------------- |\n')
index = 0
while X > xi[index]:
index += 1
index -= 1
print('f = {0} + {1}*(x-({2})) + {3}*(x-({4}))^2 + {5}*(x-({6}))^3'.format(round(ai[index], 5), round(bi[index], 5),
round(xi[index], 5), round(ci[index], 5),
round(xi[index], 5), round(di[index], 5),
round(xi[index], 5)))
f = ai[index] + bi[index] * (X - xi[index]) + ci[index] * (X - xi[index]) ** 2 + di[index - 1] * (X - xi[index]) ** 3
print('\nf({0}) = {1}\n'.format(X, round(f, 4)))
|
cce19d5079460040e6174142d487e9fac7a22adf | jamesfeng1994/ORIE5270 | /HW2/tree/tree_print.py | 2,454 | 4.15625 | 4 | class Tree(object):
def __init__(self, root):
self.root = root
def get_depth(self, current, n):
"""
This function is to get the depth of the tree using recursion
parameters:
current: current tree node
n: current level of the tree
return: the depth of the tree
"""
if current is not None:
return max(self.get_depth(current.left, n + 1), self.get_depth(current.right, n + 1))
else:
return n
def traverse_tree(self, current, n, tree_list):
"""
This function is to traverse the tree and store keys of tree nodes
parameters:
current: current tree node
n: current tree level
tree_list: a list storing keys of tree nodes (from parents to kids)
return: a list storing all nodes' keys (from root to leaves)
"""
depth = self.get_depth(self.root, 0)
if n == 0:
tree_list = [[] for i in range(depth)]
tree_list[n].append(current.value)
if current.left is not None:
tree_list = self.traverse_tree(current.left, n + 1, tree_list)
elif n < depth - 1:
tree_list[n + 1].append(None)
if current.right is not None:
tree_list = self.traverse_tree(current.right, n + 1, tree_list)
elif n < depth - 1:
tree_list[n + 1].append(None)
return tree_list
def print_tree(self):
"""
This function is to print the tree by returning a matrix
return: a matrix representing the tree
"""
tree_list = self.traverse_tree(self.root, 0, [])
depth = self.get_depth(self.root, 0)
for i in range(depth - 1):
for j in range(len(tree_list[i])):
if tree_list[i][j] is None:
tree_list[i + 1].insert(2 * j, None)
tree_list[i + 1].insert(2 * j + 1, None)
tree_matrix = [['|' for i in range(2 ** depth - 1)] for j in range(depth)]
for i in range(depth):
for j in range(len(tree_list[i])):
if tree_list[i][j] is not None:
tree_matrix[i][2 ** (depth - i - 1) - 1 + j * 2 ** (depth - i)] = tree_list[i][j]
return tree_matrix
class Node(object):
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
|
6ecb1094565598ff59b837c26a0af6ff7d802067 | EnriqueDev01/be_semana_01 | /Reto_01.py | 723 | 3.765625 | 4 | '''
BIENVENIDA
Para este reto tendremos que hacer lo siguiente:
1) Ingresar un nombre y su edad.
2) Si es menor de edad que indique que dependiendo de la hora (si es mas de las 6pm) debe ir a dormir y si no hacer la tarea.
3) Si es mayor de edad que indique que no esta obligado a hacer nada.
'''
import datetime as dt
def bienvenida(nombre, edad):
hora = dt.datetime.now().hour
if edad >= 18:
print(f'{nombre} tienes libertad de hacer lo que gustes')
else:
if hora < 18:
print(f'{nombre} debes hacer la tarea')
else:
print(f'{nombre} debes ir a dormir')
nombre = input("Ingrese su nombre: ")
edad = int(input("Ingrese su edad: "))
bienvenida(nombre, edad)
|
5dd1ad88e8daabdd120c401431088fe8326d86ff | Vandeilsonln/Python_Automate_Boring_Stuff_Exercises | /Chapter-10_Debugging/personalnotes.py | 3,054 | 3.671875 | 4 | #! python3
import logging
logging.basicConfig(filename=r'C:\delicious\logfile.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
# logging.disable(logging.CRITICAL) # Comment this out to disable logging messages to be diplayed
# I'll be writing the author's suggestion and notes in this code.
# ----------------------------------------
# RAISING EXCEPTIONS
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <=2:
raise Exception('Width must be greater than 2.')
if height <= 2:
raise Exception('Height must be greater than 2.')
print(symbol * width)
for i in range(height-2):
print(symbol + (' ' * (width - 2) + symbol))
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('0', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
# ----------------------------------------
print('-' * 50)
# GETTING THE TRACEBACK AS A STRING
import traceback
try:
raise Exception('This is the error message.')
except:
errorFile = open(r'C:\Users\aline\Documents\Coisas do Vandeilson\errorInfo.txt', 'a')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorInfo.txt')
# ----------------------------------------
print('-' * 50)
# ASSERTIONS
podBayDoorStatus = 'open'
# assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I can\'t do that.'
# assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
# ----------------------------------------
print('-' * 50)
# USING AN ASSERTION IN A TRAFFIC LIGHT SIMULATION
market_2nd = {'ns': 'yellow', 'ew': 'green'}
mission_16th = {'ns': 'red', 'ew': 'green'}
def switch_lights(stoplight):
for key in stoplight.keys():
if stoplight[key] == 'green':
stoplight[key] = 'yellow'
if stoplight[key] == 'yellow':
stoplight[key] = 'red'
if stoplight[key] == 'red':
stoplight[key] = 'green'
print(stoplight.values())
# assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight)
switch_lights(market_2nd)
# ----------------------------------------
print('-' * 50)
# LOGGING
logging.debug('Start of program')
def factorial(n):
logging.debug('Start of factorial (%s%%)' % (n))
total = 1
for i in range(1, n + 1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
logging.debug('End of Program')
# ----------------------------------------
print('-' * 50)
# breakpoints
import random
heads = 0
for i in range(1000):
if random.randint(0,1) == 1:
heads += 1
if i == 500:
print('Halway done!')
print('Heads came up ' + str(heads) + ' times.') |
dab565b2e260dadc9fb14543fee9df41c84c904a | Vandeilsonln/Python_Automate_Boring_Stuff_Exercises | /Chapter-9_Organizing-Files/renamepictures.py | 1,491 | 3.8125 | 4 | #! python3
# renamepictures.py - The code will go through a directory tree and will rename all the pictures
# based on it's creation date.
# For now the code will just identify '.jpg' files. Any other formats will remain unchanged, although
# their filenames will be written in the 'rejected.txt' file. By doing this, you are aware of any
# other formats you have to deal with.
import os, shutil
from PIL import Image
def write_to_reject(rejectedFile):
with open('.\\rejected.txt', 'a') as rejected:
rejected.write(rejectedFile)
rejected.write('\n')
# TODO: Create a list of acceptable extension files and make the code working with all of them.
def rename_pictures_to_date(rootPath, ext='.jpg'):
os.chdir(rootPath)
root = os.getcwd()
for folderName, subfolders, filenames in os.walk(root):
for file in filenames:
if not file.endswith(ext):
write_to_reject(file)
continue
else:
oldName = os.path.abspath(folderName) + '\\' + file
with Image.open(oldName) as photo:
try:
info = photo._getexif()
newFileName = root + '\\' + (info[36867].replace(':', '_')) + ext
# shutil.move(oldName, newFileName)
except:
write_to_reject(file)
return 'Done.'
print(rename_pictures_to_date(r'C:\Users\aline\Pictures\Viagens', '.jpg'))
|
180595fd0f78376e8b9d3da6af980876a743fcda | Vandeilsonln/Python_Automate_Boring_Stuff_Exercises | /Chapter-9_Organizing-Files/selective_copy.py | 1,268 | 4.125 | 4 | #! python3
# selective_copy.py - Once given a folder path, the program will walk through the folder tree
# and will copy a specific type of file (e.g. .txt or .pdf). They will be copied to a new folder.
import os, shutil
def copy_files(folderPath, destinyPath, extension):
"""
Copy files from 'folderPath' to 'destinyPath' according to 'extension'.
folderPath (str) - absolute path of the origin folder.
destinyPath (str) - absolute path of the destination folder
extension (str) - extension that will work as a filter. Only files with this extension will be copied.
"""
try:
for currentFolder, subfolders, filenames in os.walk(folderPath):
print(f'Looking for {extension} files in {currentFolder}')
for file in filenames:
if file.endswith(extension):
print(f'\tFound file: {os.path.basename(file)}.')
newFilePath = os.path.join(destinyPath, file) + extension
shutil.copy(os.path.join(currentFolder, file), newFilePath)
except:
print('Something went wrong. Please, verify the function arguments and try again.')
print('Done.')
return None
copy_files('C:\\delicious', 'C:\\Python_Projetos', '.zip')
|
26d42973cb952c3c2af0cddba3d4772c34b2d788 | Liam-Hearty/ICS3U-Unit2-03-Python | /circumference_finder.py | 493 | 4.625 | 5 | #!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: September 2019
# This program will calculate the circumference of a determined circle radius.
import constants
def main():
# this function will calculate the circumference
# input
radius = int(input("Enter the radius of circle (mm): "))
# process
circumference = constants.TAU*radius
# output
print("")
print("circumference is {}mm".format(circumference))
if __name__ == "__main__":
main()
|
8c22a3529adcc775f3178ebe0c2a500e2ba98d74 | Snehitkale/pythonprogramminglab | /lab_function.py | 658 | 4.09375 | 4 | def armn(x): #define a function
sum=0 #then assign variables for values
t=x #using while loop assign a condition
while(t>0): #using a variable d assign a condition of input number to it
d=t%10 #then use the if....else function to get the output
sum+=d**3 #using return function and print the code.
t=t//10
if sum==x:
return "amstrong number"
else:
return "not an amstrong number"
x=int(input("enter number"))
print(armn(x))
|
748da75ce2505e4ea7c3a099ce23016174eced4c | Ziqi-Li/Cracking-the-code-for-interview | /Ch4. Trees and Graphs /4.2.py | 1,148 | 3.921875 | 4 | '''
Ziqi Li
8.2 Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color.
'''
from collections import deque
def BFS(g,start,end):
dq = deque([[start]])
path=[]
while dq:
cur = dq.popleft()
if cur[-1] == end:
path.append(cur)
for i in xrange(0,len(g[start])):
if i!=cur[-1] and g[cur[-1]][i]==1:
newPath = cur+[i]
dq.append(newPath)
return path
def DFS(g,start,end):
def helper(g,start,end,path,res):
if start == end:
res.append(path)
return
for i in xrange(0,len(g[start])):
if i!=start and g[start][i]==1:
helper(g,i,end,path+[i],res)
res = []
helper(g,start,end,[start],res)
return res
def printM(m):
for k in m:
print k
def main():
matrix = [[1,1,1,0,0,0,0],[0,1,0,1,0,0,0],[0,0,0,0,1,0,0],[0,0,0,1,0,1,1],[0,0,0,1,1,0,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,1]]
print "G is:"
printM(matrix)
print "BFS path",BFS(matrix,0,6)
print "DFS path",DFS(matrix,0,6)
if __name__ == "__main__":
main() |
df06470e115da8ebaa8e2e9435c68d4595dec9e4 | Ziqi-Li/Cracking-the-code-for-interview | /Ch2. Linked List/2.3.py | 902 | 4.0625 | 4 | '''
Ziqi Li
2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node 'c' from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e
'''
class node(object):
def __init__(self,data,next):
self.data = data
self.next = next
def printList(list):
if not list:
print None
return
while list!= None:
print str(list.data)
list = list.next
def deleteNode(nodeX):
while nodeX.next:
p = nodeX
nodeX.data = nodeX.next.data
nodeX = nodeX.next
p.next = None
def main():
list = node(0,node(1,node(2,node(3,node(4,node(5,None))))))
index = 2
c = list
for i in range(0,index):
c = c.next
deleteNode(c)
printList(list)
if __name__ == "__main__":
main() |
e579216c6a8e871f956dcfab2c3902e182a75017 | Ziqi-Li/Cracking-the-code-for-interview | /Ch8. Recursion/8.2.py | 1,230 | 4.09375 | 4 | '''
Ziqi Li
8.2 Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color.
'''
def robotWalk(m, n):
if m == 1 or n == 1:
return 1
else:
return robotWalk(m-1,n) + robotWalk(m,n-1)
def robotPaths(matrix):
n = len(matrix)
m = len(matrix[0])
def dfs(n,m,i,j,path,res):
if i==n and j==m and matrix[i-1][j-1]==0:
res.append(path+[(i,j)])
return
if i+1<=n and matrix[i][j-1]==0:
dfs(n,m,i+1,j,path+[(i,j)],res)
if j+1<=m and matrix[i-1][j]==0:
dfs(n,m,i,j+1,path+[(i,j)],res)
res = []
dfs(n,m,1,1,[],res)
return res
def printM(m):
for k in m:
print k
def main():
matrixA = [[0,0,0,1,1,1,1,0],[0,0,1,0,0,0,1,0],[0,0,0,0,0,0,1,0],[0,1,0,0,0,0,1,0],[0,1,0,0,0,0,1,0],[0,1,0,0,0,0,1,0],[0,1,1,1,0,0,0,0],[0,0,0,1,1,0,0,0]]
matrixB = [[0,0,0,1],[1,0,0,0],[0,0,0,0]]
printM(matrixB)
A = robotPaths(matrixB)
print "without traps there are:",robotWalk(len(matrixB),len(matrixB[0])),"paths"
print "with traps paths are:"
for i in A:
print i
if __name__ == "__main__":
main() |
28fb6e72d2529ad57810ed6545e84db41f4a4471 | Ziqi-Li/Cracking-the-code-for-interview | /Ch1. Arrays and Strings/1.6.py | 730 | 3.890625 | 4 | '''
Ziqi Li
1.6 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
'''
def rotate(img,n):
for i in range (0,n):
for j in range (i+1,n):
img[i][j], img[j][i] = img[j][i], img[i][j]
for i in range (0,n/2):
for j in range (0,n):
img[i][j], img[n-i-1][j] = img[n-i-1][j], img[i][j]
return img
def main():
print rotate([1],1)
print rotate([[1,2],[3,4]],2)
print rotate([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],4)
print rotate([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]],5)
if __name__ == '__main__':
main() |
b478e1623d95f0cc868f41ba52824423a8e2fc93 | petef4/payg | /footnote.py | 1,054 | 3.65625 | 4 | from textwrap import fill
def definitions(footnotes):
"""Convert JSON footnotes into a format suitable for Jinja2.
In JSON a footnote is a list.
The first element is the id.
Other elements are either string or list, concatenated to make the text.
A list is a grade (e.g. poor) followed by a string that will be rendered in
a span with class="{{ grade }}".
The definitions returned have numbers, ids and plain and rich text.
The index returned is a map from id to index into definitions.
"""
defs = []
index = {}
for i, footnote in enumerate(footnotes):
id, *text = footnote
defs.append({
'number': i + 1,
'id': id,
'richtext': text,
'tooltip': tooltip(text)})
index[id] = i
return defs, index
def tooltip(richtext, width=40):
"""Strip out rich formattting and fill to fixed width."""
text = [item[1] if isinstance(item, list) else item
for item in richtext]
return fill(' '.join(text), width=width)
|
0d36514e5d069335e7e00b9f1ce6f88635624b65 | eleven2021/xor | /xor.py | 544 | 3.6875 | 4 | def crypto_text_to_hex(src_text, key):
xor_code = key
while len(src_text) > len(xor_code):
xor_code += key
return "".join([chr(ord(data) ^ ord(code))
for (data, code) in zip(src_text, xor_code)]).encode().hex()
def decrypto_hex_to_text(hex_text, key):
crypt_data = bytes.fromhex(hex_text).decode()
xor_code = key
while len(crypt_data) > len(xor_code):
xor_code += key
return "".join([chr(ord(data) ^ ord(code))
for (data, code) in zip(crypt_data, xor_code)])
|
57d65fa197e6ad4672a2f5cc5cfc049c9de3af0b | ronyu21/data-analysis-app | /src/DataAnalysisApp.py | 5,434 | 3.96875 | 4 | from typing import List
import matplotlib.pyplot as plt
from src.FileHandling import load_csv_to_2d_list, save_data_to_csv
if __name__ == "__main__":
# load from csv file and save as a list
data_list = load_csv_to_2d_list('./resource/Emissions.csv')
# transform the list to become dictionary
# with the first item as key, the remaining list as value
data_dict = dict()
for item in data_list:
key = item[0]
value = item[1:]
data_dict.setdefault(key, value)
# output the dictionary as shown in the email day 1
# key - value
# for key, val in data_dict.items():
# print(key, ' - ', val)
# day 2
print("All data from Emissions.csv has been read into a dictionary\n")
# wait for user input
target_year = input("Select a year to find statics (1997 to 2010): ")
# find the index of the user input
header_row_key = "CO2 per capita"
index = None
years = data_dict.get(header_row_key)
temp_idx = 0
for year in years:
if target_year == year:
index = temp_idx
break
temp_idx += 1
if index is None:
print("User entered an invalid year: {}".format(target_year))
exit(-1)
# extract the emissions for the target year
target_year_emissions = []
target_year_emission_countries = []
for k, v in data_dict.items():
if k == header_row_key:
continue
else:
target_year_emissions.append(float(v[index]))
target_year_emission_countries.append(k)
# calculate the min, max, average
min_val = min(target_year_emissions)
min_val_country = target_year_emission_countries[target_year_emissions.index(min_val)]
max_val = max(target_year_emissions)
max_val_country = target_year_emission_countries[target_year_emissions.index(max_val)]
avg_val = sum(target_year_emissions) / len(target_year_emissions)
# output the result as shown in email
print('In {}, countries with minimum and maximum CO2 emission levels were [{}] and [{}] respectively.'.format(
target_year, min_val_country, max_val_country))
print('Average CO2 emissions in {} were {:0.6f}'.format(target_year, avg_val))
# day 3 visualize the data for specific country
# get target country from user input
target_country = input("Select the country to visualize: ").capitalize()
# get the year data and convert to int
year_header = list(map(lambda x: int(x), data_dict.get(header_row_key)))
# get the data for the targeted country
target_country_data = data_dict.get(target_country)
if target_country_data is None:
print("No emission data for {} available".format(target_country_data))
exit(-1)
# convert string values to float
target_country_data = list(map(lambda x: float(x), target_country_data))
fig, ax = plt.subplots()
ax.plot(year_header, target_country_data)
ax.set(xlabel='Year', ylabel='Emissions in {}'.format(target_country), title='Year vs Emission in Capita')
plt.show()
print("\n")
# day 4 plotting a comparison graph
# get user inputs
target_countries = input("Write two comma-separated countries for which you want to visualize data: ").split(",")
# create temporary plotting data dictionary
plotting_data = dict()
# iterate through the target countries to obtain data and store in the temporary variable
for target in target_countries:
# strip the whitespace and capitalize the string
striped_capitalized_country_name = target.strip().capitalize()
plotting_data.setdefault(striped_capitalized_country_name,
list(map(lambda x: float(x), data_dict.get(striped_capitalized_country_name))))
# create a new plot
fig, ax = plt.subplots()
# plotting data
for data in plotting_data.keys():
ax.plot(year_header, plotting_data.get(data), label=data)
# add legend to plot
ax.legend()
ax.set(xlabel='Year', ylabel='Emissions in', title='Year vs Emission in Capita')
# display the plot
plt.show()
# day 5 exporting subset of data
# get user input
target_countries = input("Write up to three comma-separated countries for which you want to extract data: ").split(
",")
# ensure user only enter maximum of 3 countries
if len(target_countries) > 3:
print("ERR: Sorry, at most 3 countries can be entered.")
exit(-1)
# temporary data storage variable
extracted_data = []
# get and prepare headers
header = data_dict.get(header_row_key)
header.insert(0, header_row_key)
extracted_data.append(','.join(header) + '\n')
countries = None
# get the country data
for target in target_countries:
striped_capitalized_country_name = target.strip().capitalize()
data: List = data_dict.get(striped_capitalized_country_name)
data.insert(0, striped_capitalized_country_name)
if countries is None:
countries = striped_capitalized_country_name
else:
countries += ', ' + striped_capitalized_country_name
extracted_data.append(','.join(data) + '\n')
# call data save function
save_data_to_csv('./resource/Emissions_subset.csv', extracted_data)
print("Data successfully extracted for countries {} saved into file Emissions_subset.csv".format(countries))
|
eac543f52b8e273aaa54942592edc2e1d0680759 | dudu9999/Tkinter_Projects_dudu9999 | /03 - muda label Funcionou/main.py | 366 | 3.671875 | 4 | from tkinter import *
def bt_click():
print("Botao clicado")
lb['text'] = 'Funcionou'
janela = Tk()
janela.title("Janela Principal")
janela["bg"] = "purple"
lb = Label(janela, text="Texto Label")
lb.place(x=120, y=100)
bt = Button(janela, width=20, text='OK', command=bt_click )
bt.place(x=80, y=150)
janela.geometry("300x300+200+200")
janela.mainloop
|
2b37622cd4de1d5beb32d3e3734ebd704f5582e2 | bipins867/Python-Server-Clinet-Remote-Controlling | /Encode.py | 1,412 | 3.53125 | 4 | #Encoder
from collections import OrderedDict
from re import sub
def encode(text):
'''
Doctest:
>>> encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')
'12W1B12W3B24W1B14W'
'''
return sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1),
text)
def decode(text):
'''
Doctest:
>>> decode('12W1B12W3B24W1B14W')
'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
'''
return sub(r'(\d+)(\D)', lambda m: m.group(2) * int(m.group(1)),
text)
def runLengthEncoding(input):
# Generate ordered dictionary of all lower
# case alphabets, its output will be
# dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0}
dict=OrderedDict.fromkeys(input, 0)
print(dict)
# Now iterate through input string to calculate
# frequency of each character, its output will be
# dict = {'w':4,'a':3,'d':1,'e':1,'x':6}
for ch in input:
dict[ch] += 1
print(dict)
# now iterate through dictionary to make
# output string from (key,value) pairs
output = ''
for key,value in dict.items():
output = output + key + str(value)
return output
# Driver function
if __name__ == "__main__":
input="wwwwaaadexxxxxx"
print (runLengthEncoding(input))
|
32f56e3193bb85c6b23213a1e09332aef8f5ac17 | bjrubinstein/PyHSPF | /examples/evapotranspiration/etexample01.py | 9,200 | 3.65625 | 4 | # etexample01.py
#
# David J. Lampert ([email protected])
#
# last updated: 03/15/2015
#
# this example shows how to use the ETCalculator class to compute daily
# reference evapotranspiration from the other time series after using the
# ClimateProcessor class to extract and aggregate the climate data from the
# World Wide Web. the script consists of five parts:
#
# 1. download and aggregate climate data
# 2. get pan evaporation data
# 3. get areal-weighted average latitude, longitude, and elevation
# 4. calculate reference evapotranspiration
# 5. plot (4) vs (2) for comparison
#
import os, datetime, pickle
from pyhspf.preprocessing import ClimateProcessor, ETCalculator
from shapefile import Reader
# output directory for data files
output = 'HSPF_data'
if not os.path.isdir(output): os.mkdir(output)
# start and end dates
start = datetime.datetime(1980, 1, 1)
end = datetime.datetime(2010, 1, 1)
# use the "subbasin_catchments" shapefile to define the data processing area
filename = 'subbasin_catchments'
if not os.path.isfile(filename + '.shp'):
print('error: file {} does not exist!'.format(filename))
raise
# make an instance of the ClimateProcessor to fetch the climate data
processor = ClimateProcessor()
# the Penman-Monteith Equation requires temperature, humidity of dewpoint,
# wind speed, and solar radiation, which can be obtained from the processor
processor.download_shapefile(filename, start, end, output, space = 0.)
# let's get the daily tmin, tmax, dewpoint, and wind speed from GSOD
tmax = processor.aggregate('GSOD', 'tmax', start, end)
tmin = processor.aggregate('GSOD', 'tmin', start, end)
dewt = processor.aggregate('GSOD', 'dewpoint', start, end)
wind = processor.aggregate('GSOD', 'wind', start, end)
# let's use the hourly METSTAT data from the NSRDB for solar radiation
solar = processor.aggregate('NSRDB', 'metstat', start, end)
# since the solar data are hourly and this example uses daily ET, the time
# series has to be aggregated to an average daily value
solar = [sum(solar[i:i+24]) / 24 for i in range(0, 24 * (end-start).days, 24)]
# let's parse the GHCND data and see if there are any pan evaporation
# observations (only available from GHCND) to compare with estimated PET
# (there are two stations with data); let's store the data in a dictionary
# structure with keys as names and values as the timeseries data
evaporation = {}
for k, v in processor.metadata.ghcndstations.items():
if v['evap'] > 0:
its = v['name'], v['evap']
print('station {} has {} evaporation observations'.format(*its))
# open up the file and use the GHCNDStation instance to get the data
with open(k, 'rb') as f: s = pickle.load(f)
data = s.make_timeseries('evaporation', start, end)
# ignore datasets with no observations during the requested period
observations = [v for v in data if v is not None]
if len(observations) > 0:
# the pan evaporation data are "backward-looking;" i.e., the value
# for June 2 represents evaporation between midnight June 1 and
# midnight June 2; whereas the ETCalculator uses data that are
# "forward-looking;" i.e., tmin, tmax, dewpoint, wind speed for
# June 2 represent values between midnight June 2 and midnight
# June 3; so the pan evaporation data must be shifted forward by
# a day for comparison.
evaporation[v['name']] = data[1:] + [None]
print('')
# the ETCalculator class uses the Penman-Monteith Equation to estimate
# evapotranspiration time series; let's make an instance to use
calculator = ETCalculator()
# the ETCalculator makes use of hourly and daily time series that must be
# supplied externally as:
#
# 1. time series type (temperature, dewpoint, humidity, wind, solar, etc)
# 2. time step step ("daily", "hourly", or size in minutes, e.g., 60, 1440)
# 3. start time
# 4. list of data values
#
# note these are the same formats used by the PyHSPF HSPFModel class
# so now we can add the daily timeseries from above
calculator.add_timeseries('tmin', 'daily', start, tmin)
calculator.add_timeseries('tmax', 'daily', start, tmax)
calculator.add_timeseries('dewpoint', 'daily', start, dewt)
calculator.add_timeseries('wind', 'daily', start, wind)
calculator.add_timeseries('solar', 'daily', start, solar)
# the temperature and dewpoint are assumed to be in C, wind speed in m/s, and
# solar radiation in W/m2; these are the units supplied by the other classes
# in PyHSPF already so no manipulation is needed
# some of the parameters in the Penman-Monteith Equation depend on the
# geographic location so let's use the information in the shapefile to
# provide the average longitude, latitude, and elevation
sf = Reader(filename)
# make a list of the fields for each shape
fields = [f[0] for f in sf.fields]
# get the area, centroid and elevation of each shape
areas = [r[fields.index('AreaSqKm') - 1] for r in sf.records()]
xs = [r[fields.index('CenX') - 1] for r in sf.records()]
ys = [r[fields.index('CenY') - 1] for r in sf.records()]
zs = [r[fields.index('AvgElevM') - 1] for r in sf.records()]
# get the areal-weighted averages
lon = sum([a * x for a, x in zip(areas, xs)]) / sum(areas)
lat = sum([a * y for a, y in zip(areas, ys)]) / sum(areas)
elev = sum([a * z for a, z in zip(areas, zs)]) / sum(areas)
# add the information to the calculator
calculator.add_location(lon, lat, elev)
# it is pretty trivial to get the corresponding reference evapotranspiration
# (RET) time series from the Daily Penman-Monteith Equation if the necessary
# data are available by calling the public "penman_daily" method
calculator.penman_daily(start, end)
# the RET estimates are stored in the calculator's daily timeseries dictionary
# with the start date and data (the timestep is 1440 minutes = 1 day)
start, RET = calculator.daily['RET']
# calculate the linear regression between the Penman-Monteith model and the
# observed pan evaporation using scipy
from scipy import stats
# plot up the results (note that there are no observations over the winter)
from matplotlib import pyplot, dates, ticker
fig = pyplot.figure(figsize = (8,10))
# make plots for 1. evaporation (3x) 2. temperature (2x) 3. solar 4. wind
subs = []
subs.append(pyplot.subplot2grid((7,1), (0,0), rowspan = 3))
subs.append(pyplot.subplot2grid((7,1), (3,0), rowspan = 2, sharex = subs[-1]))
subs.append(pyplot.subplot2grid((7,1), (5,0)))
subs.append(pyplot.subplot2grid((7,1), (6,0)))
# make a list of times
times = [start + i * datetime.timedelta(days = 1)
for i in range((end-start).days)]
subs[0].plot_date(times, RET, fmt = '-', lw = 2, color = 'green',
label = 'Penman-Monteith Equation')
# make a label for the series
l = ''
# plot the pan evaporation for comparison
colors = ('green', 'brown', 'blue', 'red')
for k,c in zip(evaporation, colors):
v = evaporation[k]
# remove the Nones (first have to remove the predictions that have no
# corresponding observation)
model = [m for o,m in zip(v, RET) if o is not None]
data = [o for o,m in zip(v, RET) if o is not None]
m, b, r, p, stderr = stats.linregress(model, data)
subs[0].plot_date(times, v, fmt = 's', markerfacecolor = 'None',
markeredgecolor = c, markersize = 4, label = k)
# add a label with the correlation and pan coefficient
its = k[:20] + ':', m, b, r**2
l += '{:<20s}\ny = {:.2f}x + {:.2f}; r\u00B2 = {:.2f}\n'.format(*its)
# add the regression info
t = subs[0].text(0.01,0.98, l, ha = 'left', va = 'top', fontsize = 9,
transform = subs[0].transAxes)
subs[-1].xaxis.set_major_locator(dates.YearLocator(3))
subs[-1].xaxis.set_major_formatter(dates.DateFormatter('%Y'))
subs[0].set_ylim((0, 12))
subs[0].set_ylabel('Evaporation (mm)', fontsize = 11)
subs[0].legend(fontsize = 8)
subs[1].plot_date(times, tmin, fmt = '-', color = 'blue', label = 'tmin')
subs[1].plot_date(times, tmax, fmt = '-', color = 'red', label = 'tmax')
subs[1].plot_date(times, dewt, fmt = '-', color = 'green',
label = 'dewpoint')
subs[1].set_ylabel('Temperature\n(\u00B0C)', fontsize = 11)
subs[1].legend(fontsize = 8)
subs[2].plot_date(times, solar, fmt = '-', color = 'orange')
subs[2].set_ylabel('Solar Radiation\n(W/m\u00B2)', fontsize = 11)
subs[3].plot_date(times, wind, fmt = '-', color = 'purple')
subs[3].set_ylabel('Wind\n(m/s)', fontsize = 11)
for t in (subs[0].xaxis.get_ticklabels() +
subs[1].xaxis.get_ticklabels() +
subs[2].xaxis.get_ticklabels()):
t.set_visible(False)
for t in (subs[0].yaxis.get_ticklabels() +
subs[1].yaxis.get_ticklabels() +
subs[2].yaxis.get_ticklabels() +
subs[3].yaxis.get_ticklabels()):
t.set_fontsize(10)
for sub in subs[-2:]: sub.yaxis.set_major_locator(ticker.MaxNLocator(6))
filename = '{}/daily_penman_monteith'.format(output)
pyplot.suptitle('Penman-Monteith Calculation')
pyplot.subplots_adjust(hspace = 0.3, top = 0.95)
pyplot.savefig(filename)
pyplot.show()
|
c9497ad2a313d2664ee99f371138776ab980f1f4 | hugovk/wotdbot | /wotdbot.py | 3,644 | 3.609375 | 4 | #!/usr/bin/env python
"""
Pick a random [Finnish] word from a word list,
open its Wiktionary page and tweet it
"""
import argparse
import random
import sys
import webbrowser
from urllib.parse import quote
import yaml # pip install pyyaml
from twitter import OAuth, Twitter # pip install twitter
def load_yaml(filename):
with open(filename) as f:
data = yaml.safe_load(f)
if not data.keys() >= {
"oauth_token",
"oauth_token_secret",
"consumer_key",
"consumer_secret",
}:
sys.exit("Twitter credentials missing from YAML: " + filename)
return data
def random_word(filename):
words = []
with open(filename, encoding="utf-8") as infile:
for line in infile:
words.append(line.rstrip())
print("Loaded", len(words), "words")
randnum = random.randrange(len(words))
print("Random number:", randnum)
word = words[randnum]
print(word)
return word
def open_url(url):
print(url)
if not args.no_web:
webbrowser.open(url, new=2) # 2 = open in a new tab, if possible
def tweet_it(string, credentials):
if len(string) <= 0:
return
# Create and authorise an app with (read and) write access at:
# https://dev.twitter.com/apps/new
# Store credentials in YAML file. See data/onthisday_example.yaml
t = Twitter(
auth=OAuth(
credentials["oauth_token"],
credentials["oauth_token_secret"],
credentials["consumer_key"],
credentials["consumer_secret"],
)
)
print("TWEETING THIS:\n", string)
if args.test:
print("(Test mode, not actually tweeting)")
else:
result = t.statuses.update(status=string)
url = (
"http://twitter.com/"
+ result["user"]["screen_name"]
+ "/status/"
+ result["id_str"]
)
print("Tweeted:\n" + url)
if not args.no_web:
webbrowser.open(url, new=2) # 2 = open in a new tab, if possible
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Pick a random word from a word list, open its "
"Wiktionary page and tweet it",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-y",
"--yaml",
default="/Users/hugo/Dropbox/bin/data/wotdbot.yaml",
help="YAML file location containing Twitter keys and secrets",
)
parser.add_argument(
"-w",
"--wordlist",
default="data/finnish.txt",
help="Filename of word list with a single word per line",
)
parser.add_argument(
"-x", "--test", action="store_true", help="Test mode: don't tweet"
)
parser.add_argument(
"-nw",
"--no-web",
action="store_true",
help="Don't open a web browser to show the tweeted tweet",
)
args = parser.parse_args()
twitter_credentials = load_yaml(args.yaml)
# Can generate word lists with wotdbot_extract_words.py
word = random_word(args.wordlist)
url_word = quote(word.encode("utf8"))
foreign_url = "https://fi.wiktionary.org/wiki/" + url_word + "#Suomi"
open_url(foreign_url)
native_url = "https://en.wiktionary.org/wiki/" + url_word + "#Finnish"
open_url(native_url)
tweet = (
"Finnish word of the day: "
+ word
+ " "
+ native_url
+ " "
+ foreign_url
+ " #Finnish #WOTD #Suomi #"
+ word.replace(" ", "")
)
print("Tweet this:\n", tweet)
tweet_it(tweet, twitter_credentials)
# End of file
|
cfbb448e37e667067f98ffcfbf1c7972b807f85e | xiawq1/leetcode-c- | /leetcode/stack.py | 4,902 | 3.5625 | 4 | #coding:gbk
#ջźƥ䣬ųջжջǷΪգΪΪTrueΪFalse.
class Solution:
def isValid(self, s):
stack = [] #ڴſ
mapping = {')':'(', '}':'{', ']':'['} #ɢбƥ
for char in s:
if char in mapping:
if len(stack) != 0:
tmp = stack.pop()
if mapping[char] != tmp:
return False
else:
return False
else:
stack.append(char)
return not stack
Solution().isValid("([)]")
#42
class Solution:
def trap(self, height):
if len(height) < 3:
return 0
hei_len = len(height)
left = 0
right = hei_len - 1
max_left = height[0]
max_right = height[-1]
res = 0
while left < right:
if height[left] < height[right]: #עߵұʱ߿ʼߴұʱұ߿ʼԶϵһ࣡
if max_left < height[left]:
max_left = height[left]
else:
res += max_left - height[left]
left += 1 #
else:
if max_right < height[right]:
max_right = height[right]
else:
res += max_right - height[right]
right -= 1
return res
Solution().trap([0,1,0,2,1,0,1,3,2,1,2,1])
#ջӦhttps://leetcode-cn.com/problems/trapping-rain-water/solution/dan-diao-zhan-jie-fa-fu-xiang-xi-jie-ti-kmyyl/
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if len(height) < 3:
return 0
stack = [] ######¼
sum = 0
for i in range(0, len(height)):
while stack and height[i] > height[stack[-1]]:
temp = height[stack.pop()]
if stack:
w = i - stack[-1] - 1 #
h = min(height[i], height[stack[-1]])-temp
sum += w*h
stack.append(i)
return sum
#496
class Solution:
def nextGreaterElement(self, nums1, nums2):
stack = []
dic = {}
for i in nums2:
while stack and stack[-1] < i:
dic[stack.pop()] = i
stack.append(i)
return [dic.get(i, -1) for i in nums1]
Solution().nextGreaterElement([4,1,2], [1,3,4,2])
#503
class Solution:
def nextGreaterElements(self, nums):
nums1 = nums + nums
res = [-1] * len(nums1) #ſԽres[stack.pop()] = nums1[i]
# tar = nums[0]
stack = []
for i in range(len(nums1)):
while stack and nums1[stack[-1]] < nums1[i]:
res[stack.pop()] = nums1[i]
stack.append(i)
return res[:len(nums)]
#739
class Solution:
def dailyTemperatures(self, T):
stack = []
res = [0] * len(T)
for i in range(len(T)):
while stack and T[stack[-1]] < T[i]:
j = stack.pop()
res[j] = i - j
stack.append(i)
return res
#901
class StockSpanner(object):
def __init__(self):
self.stack = []
def next(self, price):
weight = 1
while self.stack and self.stack[-1][0] <= price:
weight += self.stack.pop()[1]
self.stack.append((price, weight))
return weight
#84
class Solution:
def largestRectangleArea(self, heights):
n = len(heights)
left, right = [0] * n, [0] * n
## ұ
mono_stack = list()
for i in range(n):
while mono_stack and heights[mono_stack[-1]] >= heights[i]:
mono_stack.pop()
left[i] = mono_stack[-1] if mono_stack else -1
mono_stack.append(i)
mono_stack = list()
for i in range(n - 1, -1, -1):
while mono_stack and heights[mono_stack[-1]] >= heights[i]:
mono_stack.pop()
right[i] = mono_stack[-1] if mono_stack else n
mono_stack.append(i)
ans = max((right[i] - left[i] - 1) * heights[i] for i in range(n)) if n > 0 else 0
return ans
Solution().largestRectangleArea([2,1,5,6,2,3])
#71
class Solution:
def simplifyPath(self, path):
stack = []
path = path.split("/")
for item in path:
if item == "..":
if stack : stack.pop()
elif item and item != ".":
stack.append(item)
return "/" + "/".join(stack)
Solution().simplifyPath("/a/./b/../../c/")
|
8f8b1f239de525c01abfce4e556caed1f12a9300 | JensMellberg/Neural-Networks-Exercise-2 | /Exercise2.py | 6,083 | 3.65625 | 4 |
# coding: utf-8
# # Tensorflow Tutorial (MNIST with one hidden layer)
# ## Neural Networks (TU Graz 2018)
# (Adapted from the documentation of tensorflow, find more at: www.tensorflow.org)
#
#
# Improving the MNIST tutorial by adding one hidden layer
#
# <img src="hidden_layer.png" style="width: 200px;" />
# In[1]:
#get_ipython().run_line_magic('matplotlib', 'inline')
# Import dataset and libraries.
# Please ignore the deprecation warning while importing the MNIST dataset.
# In[11]:
from nn18_ex2_load import load_isolet
import tensorflow as tf
import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt
import sys
from tensorflow.examples.tutorials.mnist import input_data
#mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
(X, C, X_tst, C_tst) = load_isolet()
#print(X.shape[0])
#print( X[1,:])
#print(np.mean(X[1,:]))
#print(np.std(X[1,:]))
#
for i in range(X.shape[0]):
mean = np.mean(X[i,:])
std = np.std(X[i,:])
for f in range(X.shape[1]):
X[i,f] = (X[i,f] - mean)/std
#print(np.std(X[1,:]))
#print(np.std(X[5,:]))
#print(X[1,:])
C_matrix = np.zeros((6238,26))
for x in range(6238):
C_matrix[x,C[x]-1] = 1
C_matrix_test = np.zeros((1559,26))
for x in range(1559):
C_matrix_test[x,C_tst[x]-1] = 1
print(X.shape)
C = C_matrix
C_tst = C_matrix_test
# Define your variables and the operations that define the tensorflow model.
# - x,y,z do have have numerical values, those are symbolic **"Tensors"**
# - x is a matrix and not a vector, is has shape [None,784]. The first dimension correspond to a **batch size**. Multiplying larger matrices is usually faster that multiplying small ones many times, using minibatches allows to process many images in a single matrix multiplication.
# In[3]:
final = False
if len(sys.argv) > 1 and sys.argv[1] == "final":
final = True
if not final:
Val_set = X[0:1247,:]
Val_set_tar = C[0:1247,:]
X = X[1247:,:]
C = C[1247:,:]
# Give the dimension of the data and chose the number of hidden layer
n_in = 300
n_out = 26
n_hidden = 220
learning_rate = 0.3
# Set the variables
W_hid = tf.Variable(rd.randn(n_in,n_hidden) / np.sqrt(n_in),trainable=True)
b_hid = tf.Variable(np.zeros(n_hidden),trainable=True)
w_out = tf.Variable(rd.randn(n_hidden,n_out) / np.sqrt(n_in),trainable=True)
b_out = tf.Variable(np.zeros(n_out))
# Define the neuron operations
x = tf.placeholder(shape=(None,300),dtype=tf.float64)
y = tf.nn.tanh(tf.matmul(x,W_hid) + b_hid)
z = tf.nn.softmax(tf.matmul(y,w_out) + b_out)
# Define the loss as the cross entropy: $ - \sum y \log y'$
# In[4]:
z_ = tf.placeholder(shape=(None,26),dtype=tf.float64)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(z_ * tf.log(z), reduction_indices=[1]))
# The operation to perform gradient descent.
# Note that train_step is still a **symbolic operation**, it needs to be executed to update the variables.
#
# In[23]:
#argument is learning rate
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
# To evaluate the performance in a readable way, we also compute the classification accuracy.
# In[8]:
correct_prediction = tf.equal(tf.argmax(z,1), tf.argmax(z_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
# Open a session and initialize the variables.
# In[7]:
init = tf.global_variables_initializer() # Create an op that will
sess = tf.Session()
sess.run(init) # Set the value of the variables to their initialization value
# In[24]:
# Re init variables to start from scratch
sess.run(init)
# Create some list to monitor how error decreases
test_loss_list = []
train_loss_list = []
test_acc_list = []
train_acc_list = []
# Create minibatches to train faster
k_batch = 40
X_batch_list = np.array_split(X,k_batch)
labels_batch_list = np.array_split(C,k_batch)
train_acc_final=0
test_acc_final=0
final_test_eval = 0
epochs=0
iterations = 50
if final:
iterations = int(sys.argv[2])
for k in range(iterations):
# Run gradient steps over each minibatch
for x_minibatch,labels_minibatch in zip(X_batch_list,labels_batch_list):
sess.run(train_step, feed_dict={x: x_minibatch, z_:labels_minibatch})
train_loss = sess.run(cross_entropy, feed_dict={x:X, z_:C})
train_acc = sess.run(accuracy, feed_dict={x:X, z_:C})
test_loss = 0
test_acc = 0
if final:
test_loss = sess.run(cross_entropy, feed_dict={x:X_tst, z_:C_tst})
test_acc = sess.run(accuracy, feed_dict={x:X_tst, z_:C_tst})
else:
test_loss = sess.run(cross_entropy, feed_dict={x:Val_set, z_:Val_set_tar})
test_acc = sess.run(accuracy, feed_dict={x:Val_set, z_:Val_set_tar})
#test_acc = sess.run(accuracy, feed_dict={x:X_tst, z_:C_tst})
if test_acc > test_acc_final and not final:
train_acc_final=train_acc
test_acc_final=test_acc
epochs=k
final_test_eval = sess.run(accuracy, feed_dict={x:X_tst, z_:C_tst})
# Put it into the lists
test_loss_list.append(test_loss)
train_loss_list.append(train_loss)
test_acc_list.append(test_acc)
train_acc_list.append(train_acc)
if np.mod(k,10) == 0:
print('iteration {} test accuracy: {:.3f}'.format(k+1,test_acc))
# In[25]:
if not final:
print("Training error")
print(train_acc_final)
print("Validation error")
print(test_acc_final)
print("Epochs")
print(epochs)
print("Test set accuracy")
print(final_test_eval)
else:
print("Training error")
print(train_acc_list[-1])
print("Test error")
print(test_acc_list[-1])
fig,ax_list = plt.subplots(1,2)
ax_list[0].plot(train_loss_list, color='blue', label='training', lw=2)
ax_list[0].plot(test_loss_list, color='green', label='testing', lw=2)
ax_list[1].plot(train_acc_list, color='blue', label='training', lw=2)
ax_list[1].plot(test_acc_list, color='green', label='testing', lw=2)
ax_list[0].set_xlabel('training iterations')
ax_list[1].set_xlabel('training iterations')
ax_list[0].set_ylabel('Cross-entropy')
ax_list[1].set_ylabel('Accuracy')
plt.legend(loc=2)
plt.show()
|
71fecce0bba7ea6072ac11c0c7e82466480c5015 | EdgeLord836/229 | /Labs_Mat_Vec_etc/Lab3_229.py | 490 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 15:48:46 2017
@author: Sam
"""
print('P1')
s = [1,2,3,4]
def cubes(arg): return [x**3 for x in s if x % 2 == 0]
print(cubes(s))
print('\nP2')
dct = {0:'A', 1:'B', 2:'C'}
keylist = [1,2,0]
def dict2list(dct, keylist): return [dct[i] for i in keylist]
print(dict2list(dct,keylist))
print('\nP3')
L = ['A','B','C']
keylist = [0,1,2]
def list2dict(L,keylist): return {x:y for (x,y) in zip(keylist,L)}
print(list2dict(L,keylist)) |
d97f49825c56c71f1f6864c46840bbe7f71237f8 | OldSchoolWeaver/WeatherGeneratorApp | /Run.py | 2,725 | 3.609375 | 4 | #!/usr/bin/env python3
# coding: utf-8
import pandas as pd
import numpy as np
import datetime
import random
import sys
from Aux import *
from WeatherSimulator import *
from WeatherDataGenerator import *
def RunSimulation():
"""
This function will create an instance of a simulation and will save the output as
as csv file
"""
#Initialise variables
start_date = datetime.datetime.strptime('1900-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
end_date = datetime.datetime.strptime('2019-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
random_date = get_randomDate(start_date,end_date)
weather_simulation = WeatherSimulation()
#Run and save the simulation
try:
df = weather_simulation.generate(random_date)
print(df.columns)
print(df)
save_csvFile(df=df,
file_location='Simulations/',
file_name='weatherforecast_simulation.csv',
sep='|',
encoding='utf-8'
)
print('Simulation run successfully at: ', datetime.datetime.now().replace(microsecond=0).isoformat())
except:
print('Error running the weather simulator')
def LoadHistoricalData(google_api_key,dark_sky_api_key):
"""
This function will create an instance of a weather data and retrive the historical data
for the specific location save the output as csv file
as csv file
"""
#Load historical data
try:
#Creates a weather_historical_data object
weather_historical_data=WeatherData(google_api_key,dark_sky_api_key)
#Returns a pandas data frame with locations
df_locations=weather_historical_data.loadLocations()
#Returns a pandas data frame with the coordinates of the locations
df_geographic_coordinates=weather_historical_data.generateGeographicCoordinates(df_locations)
#Returns a pandas data frame with the elevation of the locations
df_geographic_elevation=weather_historical_data.generateGeographicElevation(df_geographic_coordinates)
#Returns a pandas data frame with historical weather data of the locations
df_historical_data=weather_historical_data.generateHistoricalData(df_geographic_elevation)
#Saves the data frame into a csv
save_csvFile(df=df_historical_data,
file_location='Data/',
file_name='Locations_HistoricalData.csv',
sep='|',
encoding='utf-8'
)
except:
print('Error running the weather data generator')
if __name__ == '__main__':
#Run Simulation
RunSimulation()
|
Subsets and Splits