blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
c26c83862e011a002aa0f02afcbe2ba5827c3a21 | reading-stiener/For-the-love-of-algos | /Trees/even_odd.py | 1,057 | 3.984375 | 4 | class Solution:
def isEvenOddTree(self, root):
level_list = {}
def even_odd(root, level):
if root:
left_ans = even_odd(root.left, level+1)
# append to list and check
if level_list.get(level, -1) != -1:
if level_list[level] % 2 == 0 and root.val % 2 == 1 and root.val > level_list[level]:
level_list[level].append(root.val)
curr_ans = True
elif level_list[level] % 2 == 1 and root.val % 2 == 0 and root.val < level_list[level]:
level_list[level].append(root.val)
curr_ans = True
else:
curr_ans = False
else:
level[level] = [root.val]
curr_ans = True
right_ans = even_odd(root.right, level+1)
return left_ans and curr_ans and right_ans
return True
return even_odd(root, 0) |
4042daf312212d5c47ed105d8996e9840cb3f2ed | rajib80/python-playground | /list-exercise/list-exercise-02.py | 812 | 4.15625 | 4 | # Open the file mbox-short.txt and read it line by line.
# When you find a line that starts with 'From ' like the following line:
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# You will parse the From line using split()
# and print out the second word in the line
# (i.e. the entire address of the person who sent the message).
# Then print out a count at the end.
# Hint: make sure not to include the lines that start with 'From:'.
# You can download the sample data at
# http://www.py4e.com/code3/mbox-short.txt
file_handle = open("mbox-short.txt")
line_count = 0
for line in file_handle:
if not line.startswith("From:") and line.startswith("From"):
words = line.split()
print(words[1])
line_count += 1
print(f"There were {line_count} lines in the file with From as the first word")
|
2ab1838e48bd993e0da26526925017a1ba8812c7 | kstolzenberg/LPTHW | /ex31.1.py | 360 | 3.703125 | 4 | # new game from scratch
print "this is a new gyme. what do you want to play?"
play = raw_input("..?")
if play != "kittens" or play >= 15:
print "ok now we are cooking with gas"
what = raw_input("what are we cooking? ")
if what == "meat" or what == "bean":
print "yah i can smell it"
else:
print "time for groceries"
else:
print "pet that cat!"
|
fbe767958f6e5d4373a46b7d00117f84bdeae822 | Aeee90/python | /algorism/EulerProject/9.py | 219 | 3.671875 | 4 | def solution(num):
for a in range(num//3):
for b in range(a+1, (num - a)//2):
c = num - a - b
if a**2 + b**2 == c**2:
return (a*b*c)
print(solution(1000))
|
bcc8de19dff3aad5224e90690ac0f2688e0e6dea | jenleap/adventofcode2018 | /dayone/partone.py | 745 | 4.03125 | 4 | #Day 1: Chronal Calibration
#Given a file containing frequency inputs, calculate the resulting frequency after all the changes in frequency have been applied.
#Open the file. This file comes from https://adventofcode.com/2018/day/1/input. Inputs differ per user.
frequency_inputs = open('input.txt')
#Read each line of the file and save to a variable.
frequencies_raw = frequency_inputs.readlines()
#Initialize the total variable to zero.
frequency_total = 0
#Loop through the list of frequencies. For each frequency, remove the new line char and convert to an integer. Add the resulting integer to the total.
for f in frequencies_raw:
cleaned = int(f.strip('\n'))
frequency_total += cleaned
#Return the total
print(frequency_total) |
aaa80f255e06778ab27c8a44ca9b2b05d6c74a2e | coleenangelrose/python-exercises | /conditional-statements-exercise-2.py | 303 | 4.125 | 4 | hours = input('Enter Hours: ')
try:
hours = float(hours)
rate = input('Enter Rate: ')
try:
rate = float(rate)
pay = hours * rate
print('Pay: ', pay)
except:
print('Error, please enter numeric input')
except:
print('Error, please enter numeric input')
|
1af3c816057364764100d63120322a8aecaa6e1d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2606/60672/277397.py | 144 | 3.59375 | 4 | ar=input()
target=input()
for i in range(len(ar)):
if ar[i]==target:
print(i)
break
elif i==len(ar)-1:
print(-1) |
4c64c991a2e57cb9a809714f97a0dcef94e90f4c | ChristophWuersch/dsutils | /src/dsutils/cleaning.py | 6,856 | 3.640625 | 4 | """Data cleaning
* :func:`.remove_noninformative_cols`
* :func:`.categorical_to_int`
"""
from hashlib import sha256
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
def remove_duplicate_cols(df):
"""Remove duplicate columns from a DataFrame.
Uses hashing to quickly determine where there are duplicate columns,
and removes the duplicates.
Parameters
----------
df : pandas DataFrame or a list of them
Dataframe from which to remove the non-informative columns
Returns
-------
Nothing, deletes the columns in-place.
"""
# Perform on each element if passed list
if isinstance(df, list):
for i in range(len(df)):
print('DataFrame '+str(i))
remove_duplicate_cols(df[i])
return
# Hash columns
hashes = dict()
for col in df:
hashes[col] = sha256(df[col].values).hexdigest()
# Get list of duplicate column lists
Ncol = df.shape[1] #number of columns
dup_list = []
dup_labels = -np.ones(Ncol)
for i1 in range(Ncol):
if dup_labels[i1]<0: #if not already merged,
col1 = df.columns[i1]
t_dup = [] #list of duplicates matching col1
for i2 in range(i1+1, Ncol):
col2 = df.columns[i2]
if ( dup_labels[i2]<0 #not already merged
and hashes[col1]==hashes[col2] #hashes match
and df[col1].equals(df[col2])): #cols are equal
#then this is actually a duplicate
t_dup.append(col2)
dup_labels[i2] = i1
if len(t_dup)>0: #duplicates of col1 were found!
t_dup.append(col1)
dup_list.append(t_dup)
# Remove duplicate columns
for iM in range(len(dup_list)):
o_col = dup_list[iM][-1] #original column
for iD in range(len(dup_list[iM])-1):
t_dup = dup_list[iM][iD]
print('Removing \''+t_dup+'\' (duplicate of \''+o_col+'\')')
df.drop(columns=t_dup, inplace=True)
def remove_noninformative_cols(df):
"""Remove non-informative columns (all nan, all same value, or duplicate).
Parameters
----------
df : pandas DataFrame or a list of them
Dataframe from which to remove the non-informative columns
Returns
-------
Nothing, deletes the columns in-place.
"""
# Check inputs
if not isinstance(df, (list, pd.DataFrame)):
raise TypeError('df must be a pandas DataFrame or list of them')
# Perform on each element if passed list
if isinstance(df, list):
for i in range(len(df)):
print('DataFrame '+str(i))
remove_noninformative_cols(df[i])
return
# Remove non-informative columns
for col in df:
if df[col].isnull().all():
print('Removing \''+col+'\' (all NaN)')
del df[col]
elif df[col].nunique()<2:
print('Removing \''+col+'\' (<2 unique values)')
del df[col]
# Remove duplicate columns
remove_duplicate_cols(df)
def categorical_to_int(df, cols=None):
"""Convert categorical columns of a DataFrame to unique integers, inplace.
Parameters
----------
df : pandas DataFrame
DataFrame in which to convert columns
cols : list
"""
# Do for all "object" columns if not specified
if cols is None:
cols = [col for col in df if str(df[col].dtype)=='object']
# Make list if not
if isinstance(cols, str):
cols = [cols]
# Map each column
maps = dict()
for col in cols:
# Create the map from objects to integers
maps[col] = dict(zip(
df[col].values,
df[col].astype('category').cat.codes.values
))
# Determine appropriate datatype
max_val = max(maps[col].values())
if df[col].isnull().any(): #nulls, so have to use float!
if max_val < 8388608:
dtype = 'float32'
else:
dtype = 'float64'
else:
if max_val < 256:
dtype = 'uint8'
elif max_val < 65536:
dtype = 'uint16'
elif max_val < 4294967296:
dtype = 'uint32'
else:
dtype = 'uint64'
# Map the column
df[col] = df[col].map(maps[col]).astype(dtype)
# Return the maps used
return maps
class DeleteCols(BaseEstimator, TransformerMixin):
"""Delete columns from a dataframe.
This is an sklearn-compatible transformer which deletes columns from a
dataframe.
Parameters
----------
cols : int or str or list of either
Columns to delete
"""
def __init__(self, cols):
# Check types
if not isinstance(cols, list):
cols = [cols]
for col in cols:
if not isinstance(col, (str, int)):
raise TypeError('cols must be list of str or int')
# Store columns
self.cols = cols
def fit(self, X, y):
return self
def transform(self, X, y=None):
Xo = X.copy()
for col in self.cols:
if isinstance(X, pd.DataFrame):
if isinstance(col, str):
Xo.drop(col, axis=1, inplace=True)
else:
Xo.drop(Xo.columns[i], axis=1, inplace=True)
else: #numpy array, hopefully
if isinstance(col, str):
raise TypeError('X is an array, cannot index with str')
else:
Xo = np.delete(Xo, col, 1)
return Xo
def fit_transform(self, X, y=None):
return self.fit(X, y).transform(X, y)
class KeepOnlyCols(BaseEstimator, TransformerMixin):
"""Delete all columns except specified ones from a dataframe.
This is an sklearn-compatible transformer which deletes all columns
except specified ones from a dataframe.
Parameters
----------
cols : str or list of str
Columns to delete
"""
def __init__(self, cols):
# Check types
if not isinstance(cols, list):
cols = [cols]
for col in cols:
if not isinstance(col, str):
raise TypeError('cols must be list of str')
# Store columns
self.cols = cols
def fit(self, X, y):
return self
def transform(self, X, y=None):
Xo = X.copy()
for col in X:
if col not in self.cols:
Xo.drop(col, axis=1, inplace=True)
return Xo
def fit_transform(self, X, y=None):
return self.fit(X, y).transform(X, y) |
e671ddb57c075773ad5c7c868e20bd738377c6f9 | jdcarvalho/aulas-gabriel | /8-operadores.py | 1,563 | 4.25 | 4 | #!/usr/bin/python3
# Operadores Unários
valor = 1
# valor +=1 == valor = valor + 1
valor += 1
valor -= 1
print('\n----------------------Operadores Unários----------------------')
print(valor)
print('\n----------------------Operadores Binários----------------------')
# Operadores Binários
numero1 = 1
numero2 = 2
print(numero2 + numero1)
print(numero1 - numero2)
# Operadores Ternários
print('\n----------------------Operadores Ternários----------------------')
idade = 18
maioridade = True if idade >= 18 else False
print(maioridade)
print('\n----------------------Operadores Relacionais----------------------')
idade = 13
maioridade = 18
print('idade > maioridade: {0}'.format(idade -> maioridade))
print('idade < maioridade: {0}'.format(idade < maioridade))
print('idade >= maioridade: {0}'.format(idade >= maioridade))
print('idade <= maioridade: {0}'.format(idade < maioridade))
print('idade == maioridade: {0}'.format(idade == maioridade))
nome = 'Miguel'
sobrenome = 'Carvalho'
print(nome +' '+sobrenome)
print('\n----------------------Índices de Lista----------------------')
lista = [1,2,3,4,5,6,7,8,9,10]
print('Tamanho da Lista: ', len(lista))
print('Primeiro elemento da lista: ', lista[0])
print('Último elemento da lista: ', lista[len(lista)-1])
print('Último elemento da lista: ', lista[-1])
print('\n----------------------Dicionários----------------------')
valor = {
'nome': 'Gabriel',
'telefone': 'Quebrado',
}
valor.update({
'idade': 13,
'nome_do_pai': 'Silvio',
})
valor['nascimento'] = '06/12/2007'
print(valor)
|
e34fbd0bfdc8d888e19329150aeceee968722c29 | manojkumar1053/GMAONS | /slidingWindow/avgSybarrayK.py | 493 | 3.8125 | 4 | def find_averages_of_subarrays(K, arr):
result = []
windowStart = 0
windowSum = 0.0
for windowEnd in range(len(arr)):
windowSum += arr[windowEnd]
if windowEnd >= K - 1:
result.append(windowSum / K)
windowSum -= arr[windowStart]
windowStart += 1
return result
def main():
result = find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2])
print("Averages of subarrays of size K: " + str(result))
main()
|
c97c180471aecf1b4fceb6e2aa94e09f09194735 | ErMax-Inc/Mores-Module-for-Python | /main.py | 2,012 | 4.46875 | 4 | def isInt(num):
"""
Finds if a number is an int or a float.
This is a better version of the "isinstance"
function in python. This function returns a
bool value (like the "isinstance" function)
:param num: The number to check if is a float
"""
num = str(num)
if num.find('.'):
if len(num) >= 3:
if num[2].find('0') != int(-1):
return False
else:
return True
else:
return True
else:
return True
def truncate_utf8_chars(filename, count, ignore_newlines=True):
"""
Truncates last `count` characters of a text file encoded in UTF-8.
:param filename: The path to the text file to read
:param count: Number of UTF-8 characters to remove from the end of the file
:param ignore_newlines: Set to true, if the newline character at the end of the file should be ignored
"""
with open(filename, 'rb+') as f:
last_char = None
size = os.fstat(f.fileno()).st_size
offset = 1
chars = 0
while offset <= size:
f.seek(-offset, os.SEEK_END)
b = ord(f.read(1))
if ignore_newlines:
if b == 0x0D or b == 0x0A:
offset += 1
continue
if b & 0b10000000 == 0 or b & 0b11000000 == 0b11000000:
# This is the first byte of a UTF8 character
chars += 1
if chars == count:
# When `count` number of characters have been found, move current position back
# with one byte (to include the byte just checked) and truncate the file
f.seek(-1, os.SEEK_CUR)
f.truncate()
return
offset += 1
|
cf367fcb4a8206201da830e7d0c4939a26a00caf | santosh-srm/srm-pylearn | /11_strings_n_numbers.py | 143 | 3.9375 | 4 | a = 25
b = 55
print(f'sum of numbers {a} and {b} are {a+b}')
a="25"
b="55"
print(f'string addition of {a} and {b} are representd by {a+b}')
|
bb1f75b55f4d0d236f255b6bf7b88823fcbcbeef | Glib79/kik | /hand.py | 3,575 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 15:58:40 2018
@author: Grzegorz Libera
"""
class Hand(object):
""" Hand object """
chnd = 0
def __init__(self, start_pos, player):
""" Hand initiation """
Hand.chnd += 1
self.tiles = []
self.size = 80
self.chosen = 0
self.start_position = start_pos
self.name = player[0] if player[0] != '' else 'Player ' + str(Hand.chnd)
self.type = player[1]
self.color = player[2]
self.space = 20
self.points = 0
self.end = False
def __len__(self):
""" Return number of tiles on hand """
return len(self.tiles)
def add_tile(self, tile):
""" Add tile, and set it's position"""
tile.set_size(self.size)
pos = self.get_pos_on_hand(len(self.tiles))
tile.set_position(pos[0], pos[1])
self.tiles.append(tile)
def add_points(self, points):
""" Add points"""
self.points += points
def rem_chosen_tile(self):
""" Remove chosen tile from hand """
if self.tiles:
del self.tiles[self.chosen]
if self.tiles:
self.chosen = 0
pos = self.get_pos_on_hand(0)
self.get_chosen().set_position(pos[0], pos[1])
else:
self.end = True
def set_chosen(self, chosen):
""" Set chosen tile """
self.chosen = chosen
def get_pos_on_hand(self, nr):
""" Return tile position on hand """
return (self.start_position[0], self.start_position[1] + (self.size + self.space) * nr)
def get_chosen(self):
""" Return chosen tile """
return self.tiles[self.chosen]
def get_hand(self):
""" Return all tiles on hand """
return self.tiles
def is_end(self):
return self.end
def find_best_move(self, table):
""" Finding the best move """
best_pos = [] #tile nr, tile site, tile rotation, () - position on table
best_points = 0
best_pfc = {}
for t in range(len(self.tiles)):
for s in range(2):
for r in range(4):
for p in table.posible_moves:
points, pfc = table.is_on_correct_move(p, self.tiles[t])
# if points:
# print([t,s,r,p], end=" ")
# print(points, end=" ")
# print(pfc, end=" ")
# print(self.tiles[t].get_tile())
if points and points > best_points:
best_pos = [t, s, r, p]
best_points = points
best_pfc = pfc
self.tiles[t].rotate_tile('l')
self.tiles[t].flip_tile()
return best_pos, best_points, best_pfc
def draw(self, screen, pygame):
""" Draw hand """
for t in range(len(self.tiles)):
self.tiles[t].draw(screen, pygame)
if t == self.chosen:
pygame.draw.rect(screen, (255,0,255), pygame.Rect(self.tiles[t].position[0], self.tiles[t].position[1], self.tiles[t].size, self.tiles[t].size), 2)
if __name__ == "__main__":
print("This is a module with Hand for kik game.")
input("\nPress the enter key to exit.") |
a45c61b02857ebd57460a9db35bd3a7711753b8a | StarLight-Academy/python-codes | /palindrome.py | 264 | 3.96875 | 4 | def is_palindrome(n):
rev = 0
temp = n
while temp != 0:
digit = temp % 10
rev = rev * 10 + digit
temp = temp // 10
return rev == n
if __name__ == '__main__':
a = int(input('Enter number: '))
print(is_palindrome(a)) |
766a8caa3b0d15ba9fb327f3bf94d64a8b302171 | kuchunbk/PythonBasic | /5_tuple/Sample/tuple_ex7.py | 692 | 4 | 4 | '''Question:
Write a Python program to get the 4th element and 4th element from last of a tuple.
'''
# Python code:
>>> #Get an item of the tuple
>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
>>> print(tuplex)
>>> #Get item (4th element)of the tuple by index
>>> item = tuplex[3]
>>> print(item)
>>> #Get item (4th element from last)by index negative
>>> item1 = tuplex[-4]
>>> print(item1)
'''Output sample:
('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
e
u
''' |
fc1c03b4493c52add0962e29c965ab5207f0eaed | ofir123/MP3-Organizer | /mp3organizer/datatypes/album.py | 1,629 | 4.1875 | 4 | class Album(object):
"""
A POPO class to hold all the album data.
Contains the following information:
Name, Artist, Genre, Year and Artwork (as path).
"""
def __init__(self, name, artist, genre=None, year=None,
artwork_path=None, tracks_list=None):
"""
Initializes the album data object.
:param name: The album's name.
:param artist: The artist's name.
:param genre: The album's genre.
:param year: The album's release year.
:param artwork_path: The artwork's file path.
:param tracks_list: The tracks_list.
"""
self.name = ' '.join(x.capitalize() for x in name.strip().split(' '))
self.artist = ' '.join(x.capitalize() for x in artist.strip().split(' '))
self.genre = genre
self.year = year
self.artwork_path = artwork_path
self.tracks_list = tracks_list
def __eq__(self, other):
"""
Compare albums to one another using the information.
:param other: The other track to compare to.
:return: True if the objects are equal, and False otherwise.
"""
return other.name == self.name and other.artist == self.artist and \
other.genre == self.genre and other.year == self.year and \
other.artwork_path == self.artwork_path and other.tracks_list == self.tracks_list
def __repr__(self):
"""
Prints the album data in the format <Artist> - <Album>.
:return: The string representing the album's data.
"""
return '{} - {}'.format(self.artist, self.name)
|
88fe2f9851f1a8728b26dfc1b351f027bf231b43 | ypliu/leetcode-python | /src/056_merge_intervals/056_merge_intervals_TLE_ConnectedComponents.py | 2,865 | 3.640625 | 4 | # Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
import collections
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if not intervals or 0 == len(intervals):
return []
elif 1 == len(intervals):
return intervals
graph = self.buildGraph(intervals)
nodes_in_comp, num_comps = self.getComponents(graph, intervals)
res = [self.mergeNodes(nodes_in_comp[i]) for i in range(num_comps)]
return res
def buildGraph(self, intervals):
graph = collections.defaultdict(list)
for i in xrange(len(intervals)-1):
interval_i = intervals[i]
for j in xrange(i+1, len(intervals)):
interval_j = intervals[j]
if self.overlap(interval_i, interval_j):
graph[interval_i].append(interval_j)
graph[interval_j].append(interval_i)
return graph
def overlap(self, interval_i, interval_j):
return interval_i.end >= interval_j.start and interval_j.end >= interval_i.start
def getComponents(self, graph, intervals):
nodes_visited = set()
num_comps = 0
nodes_in_comp = collections.defaultdict(list)
def markComponentDfs(start):
stack = [start]
while stack:
node = stack.pop()
nodes_visited.add(node)
nodes_in_comp[num_comps].append(node)
for interval in graph[node]:
if interval not in nodes_visited:
stack.append(interval)
for interval in intervals:
if interval not in nodes_visited:
markComponentDfs(interval)
num_comps += 1
return nodes_in_comp, num_comps
def mergeNodes(self, nodes):
min_start, max_end = nodes[0].start, nodes[0].end
for i in xrange(1, len(nodes)):
if min_start > nodes[i].start:
min_start = nodes[i].start
if max_end < nodes[i].end:
max_end = nodes[i].end
return Interval(min_start, max_end)
# debug
def print_intervals(self, intervals):
print '[ ',
for it in intervals:
print '[', it.start, ',', it.end, ']',
print ' ]'
s = Solution()
intervals = []
intervals.append(Interval(1,3))
intervals.append(Interval(2,6))
intervals.append(Interval(8,10))
intervals.append(Interval(15,18))
s.print_intervals(s.merge(intervals))
intervals = []
intervals.append(Interval(1,4))
intervals.append(Interval(4,5))
s.print_intervals(s.merge(intervals))
intervals = []
# intervals.append(Interval(1,4))
s.print_intervals(s.merge(intervals))
|
e8f9fae0a9240e008c62708f6ff9ea28a3b087dd | Blankpanda/Scripts-and-Dotfiles | /scripts/python/line.py | 2,632 | 3.8125 | 4 | # arbitrarily counts the line numbers of files in a directory
# not entirely accurate but I use this to get a general idea
# of the number of lines a program that I have written is
# composed of.
import sys
import os
def main():
args = sys.argv
if len(args) != 2:
print("Invalid number of arguments")
else:
path = args[1]
if sys.platform == "win32":
fix_windows_directory(path)
# get a list of all the files in the project
file_list = []
file_list = get_directory_files(path, file_list)
# accumulate the values
count = 0
countws = 0
for f in file_list:
try:
count = count + get_lines(f)
countws = countws + get_lines_ws(f)
except Exception as e:
print("Couldn't read file: " + f)
print("Lines: " + str(count))
print("Lines (with whitespace): " + str(countws))
# returns the paths in a list of all of the files in a directory
# and each of its subsequent sub directory
def get_directory_files(project_path, file_list):
ignore_list = ['.git' , '.gitattributes', '.gitignore']
main_dir = os.listdir(project_path)
for node in main_dir:
if node not in ignore_list:
if is_file(node):
file_list.append(project_path + "/" +node)
else:
try:
file_list = get_directory_files(project_path + "/" + node, file_list)
except Exception as e:
print("Couldnt read " + project_path + "/" + node)
return file_list
# hack
def is_file(name):
if '.' in name:
return True
else:
return False
# L . M . A . O
def fix_windows_directory(project_path):
if '\\' in project_path:
project_path = project_path.replace('\\', '/')
return project_path
# return the number of lines.
def get_lines(fname):
try:
infile = open(fname, 'r')
lines = infile.readlines()
ln = len(lines)
for line in lines: # we dont want to count whitespace
if line == '\n':
ln -= 1
return int(ln)
except Exception as e:
print("Couldnt read file:" + fname + "|" + str(e))
# returns the number of lines. whitespace inclusive.
def get_lines_ws(fname):
try:
infile = open(fname, 'r')
lines = infile.readlines()
return len(lines)
except Exception as e:
print("Couldnt read file:" + fname + "|" + str(e))
if __name__ == '__main__':
main()
|
66ed2c63e1adc57484fc1bd2034a4e2feae68026 | dylanlee101/leetcode | /code_week23_928_104/insert_into_a_binary_search_tree.py | 1,583 | 4.09375 | 4 | '''
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据保证,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
例如,
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和 插入的值: 5
你可以返回这个二叉搜索树:
4
/ \
2 7
/ \ /
1 3 5
或者这个树也是有效的:
5
/ \
2 7
/ \
1 3
\
4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
pos = root
while pos:
if val < pos.val:
if not pos.left :
pos.left = TreeNode(val)
break
else:
pos = pos.left
else:
if not pos.right:
pos.right = TreeNode(val)
break
else:
pos = pos.right
return root |
e4de625b3cdc906f59a88b58a90910c2629a3234 | dnootana/Python | /concepts/stackQueueDeque/stack.py | 570 | 4.15625 | 4 | #!/usr/bin/env python3.8
class Stack(object):
def __init__(self):
self.items = []
self.size = 0
def size(self):
return self.size
def isEmpty(self):
return self.size == 0
def push(self,item):
self.items.append(item)
self.size += 1
def pop(self):
if self.isEmpty():
raise Exception("Popping from an empty stack")
self.size -= 1
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def main():
s = Stack()
for i in range(5):
s.push(i)
for i in range(5):
print(s.pop())
if __name__ == "__main__":
main()
|
aa03a0e614c8baebae7f8431a814e72d12e73183 | Elton86/ExerciciosPython | /EstrtuturaSequencial/Exe15.py | 1,100 | 4.03125 | 4 | """Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês.
Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda,
8% para o INSS e 5% para o sindicato, faça um programa que nos dê: 1. salário bruto. 2.quanto pagou ao INSS. 4. quanto
pagou ao sindicato. 5. o salário líquido. calcule os descontos e o salário líquido, conforme a tabela abaixo:
Obs.: Salário Bruto - Descontos = Salário Líquido."""
valorHora = float(input("Digite o valor da hora: "))
horasTrabalhadas = float(input("Digite o total de horas trabalhadas: "))
salarioBruto = valorHora * horasTrabalhadas
impostoRenda = salarioBruto * .11
inss = salarioBruto * .08
sindicato = salarioBruto * .05
desconto = impostoRenda + inss + sindicato
salarioLiquido = salarioBruto - desconto
print("Salario bruto -> {}".format(salarioBruto))
print("IR (11%) -> {}".format(impostoRenda))
print("INSS (8%) -> {}".format(inss))
print("Sindicato (5%) -> {}".format(sindicato))
print("Salario Liquido -> {}".format(salarioLiquido))
|
75d8347ee78f340b7396c801aa31b8779b47c87c | qujay/leetcode | /056-merge-intervals/merge-intervals.py | 948 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# Given a collection of intervals, merge all overlapping intervals.
#
#
# For example,
# Given [1,3],[2,6],[8,10],[15,18],
# return [1,6],[8,10],[15,18].
#
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if not intervals:
return []
intervals.sort(key = lambda x: x.start, reverse=True)
stack = []
tmp = intervals.pop()
while intervals:
x = intervals.pop()
if tmp.end >= x.start:
tmp.end = max(tmp.end, x.end)
else:
stack.append(tmp)
tmp = x
stack.append(tmp)
return stack
|
52ae7ab77c1b2d3d0cadde09b9060ff6d25b0cba | daniel-reich/ubiquitous-fiesta | /AnjPhyJ7qyKCHgfrn_4.py | 148 | 4 | 4 |
# Fix this incorrect code, so that all tests pass!
def remove_vowels(string):
return "".join(vowel for vowel in string if vowel not in "aeiou")
|
00787f2f9919b312a6a36fa37de9e3d695917dbf | JonnatasCabral/algorithms | /caesar_cipher.py | 345 | 3.84375 | 4 | # Caesar Cipher
def shift_position(shift, letter):
if shift > 90 and letter.isupper():
shift -= 26
elif shift > 122 and letter.islower():
shift -= 26
return shift
def encrypt(v, k):
v = map(
lambda x: chr(
shift_position(ord(x) + k % 26, x)) if x.isalpha() else x, v)
return ''.join(v)
|
b7d46778c3727e088d291dc76f644ddfd1df9930 | flyingfruit/Algorithm | /test1/main.py | 1,674 | 3.875 | 4 | from collections import deque
class Node(object):
def __init__(self, value, p=None):
self.value = value
self.p = p
class LinkList(object):
def __init__(self, head=None):
self.head = head
def insert(self, date):
node = Node(date, self.head)
self.head = node
def delete_node(self):
temp_node = self.head
last_node = self.head
while temp_node.p is not None:
last_node = temp_node
temp_node = temp_node.p
last_node.p = None
def print_value(self):
temp_node = self.head
while temp_node.p is not None:
print(temp_node.value, end=" ")
temp_node = temp_node.p
print(temp_node.value)
def change_node(self, value="a"):
temp_node = self.head
if temp_node.value == value:
return True
while temp_node.p is not None:
temp_node2 = temp_node
temp_node = temp_node.p
if temp_node.value == value:
temp_node2.p == temp_node.p
self.insert(temp_node.value)
self.delete_node()
return True
self.insert(value)
self.delete_node()
return False
if __name__ == '__main__':
node_head = Node('b', None)
cache = LinkList(node_head)
cache.insert('a')
cache.print_value()
q = ['a', 'b', 'c', 'b', 'c', 'a', 'b']
for q_item in q:
result = cache.change_node(q_item)
if not result:
print("cache miss!", end=" ")
cache.print_value()
|
346e790744b3f800074d1207f1fe92dc4cc9eeac | danielkpodo/python-zero-to-mastery | /python_basics/datatypes/sets/setintro.py | 214 | 3.734375 | 4 | # last data structure
# Sets are unorded collection of unique objects
my_set = {1, 2, 4, 4, 5, 5, 5, 4, 3, 3}
print(my_set)
# useful methods
new_set = my_set.copy()
print(new_set)
my_set.add(100)
print(my_set)
|
bb4510f1b50b03478420727db1a9bbe576d01baa | wwest4/tdd-by-example | /part-3/triangle.py | 507 | 3.984375 | 4 | class Triangle:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
negative = a <= 0 or b <= 0 or c <= 0
illegal = a + b <= c or b + c <= a or c + a <= b
if negative or illegal:
raise ValueError('invalid Triangle dimensions')
def type(self):
ab = self.a == self.b
bc = self.b == self.c
if ab and bc:
return 1
elif ab or bc:
return 2
else:
return 3
|
e803b2fe6a65c464b306219b7ecd5f41580485ef | ashishgupta2014/problem_solving_practices | /implimentation/X_O_Replace.py | 3,706 | 3.671875 | 4 | """
https://app.glider.ai/practice/problem/algorithms/replace-os-with-xs/problem
Given a matrix of size N x M where every element is either ‘O’ or ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’. A ‘O’
(or a set of ‘O’) is considered to be by surrounded by ‘X’ if there are ‘X’ at locations just below, just above, just
left and just right of it.
Examples:
Input: mat[N][M] = {{'X', 'O', 'X', 'X', 'X', 'X'},
{'X', 'O', 'X', 'X', 'O', 'X'},
{'X', 'X', 'X', 'O', 'O', 'X'},
{'O', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'O'},
{'O', 'O', 'X', 'O', 'O', 'O'},
};
Output: mat[N][M] = {{'X', 'O', 'X', 'X', 'X', 'X'},
{'X', 'O', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
{'O', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'O'},
{'O', 'O', 'X', 'O', 'O', 'O'},
};
Input: mat[N][M] = {{'X', 'X', 'X', 'X'}
{'X', 'O', 'X', 'X'}
{'X', 'O', 'O', 'X'}
{'X', 'O', 'X', 'X'}
{'X', 'X', 'O', 'O'}
};
Input: mat[N][M] = {{'X', 'X', 'X', 'X'}
{'X', 'X', 'X', 'X'}
{'X', 'X', 'X', 'X'}
{'X', 'X', 'X', 'X'}
{'X', 'X', 'O', 'O'}
};
"""
# Python3 program to replace all 'O's with
# 'X's if surrounded by 'X'
# Size of given matrix is M x N
# A recursive function to replace previous
# value 'prevV' at '(x, y)' and all surrounding
# values of (x, y) with new value 'newV'.
def floodFillUtil(mat, x, y, prevV, newV):
# Base Cases
if (x < 0 or x >= M or y < 0 or y >= N):
return
if (mat[x][y] != prevV):
return
# Replace the color at (x, y)
mat[x][y] = newV
# Recur for north, east, south and west
floodFillUtil(mat, x + 1, y, prevV, newV)
floodFillUtil(mat, x - 1, y, prevV, newV)
floodFillUtil(mat, x, y + 1, prevV, newV)
floodFillUtil(mat, x, y - 1, prevV, newV)
# Returns size of maximum size subsquare
# matrix surrounded by 'X'
def replaceSurrounded(mat):
# Step 1: Replace all 'O's with '-'
global M, N
M = len(mat)
N = len(mat[0])
for i in range(M):
for j in range(N):
if (mat[i][j] == 'O'):
mat[i][j] = '-'
# Call floodFill for all '-'
# lying on edges
# Left Side
for i in range(M):
if (mat[i][0] == '-'):
floodFillUtil(mat, i, 0, '-', 'O')
# Right side
for i in range(M):
if (mat[i][N - 1] == '-'):
floodFillUtil(mat, i, N - 1, '-', 'O')
# Top side
for i in range(N):
if (mat[0][i] == '-'):
floodFillUtil(mat, 0, i, '-', 'O')
# Bottom side
for i in range(N):
if (mat[M - 1][i] == '-'):
floodFillUtil(mat, M - 1, i, '-', 'O')
# Step 3: Replace all '-' with 'X'
for i in range(M):
for j in range(N):
if (mat[i][j] == '-'):
mat[i][j] = 'X'
return mat
# Driver code
if __name__ == '__main__':
mat = [['X', 'O', 'X', 'O', 'X', 'X'],
['X', 'O', 'X', 'X', 'O', 'X'],
['X', 'X', 'X', 'O', 'X', 'X'],
['O', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'O', 'X', 'O'],
['O', 'O', 'X', 'O', 'O', 'O']];
replaceSurrounded(mat)
for i in range(M):
print(*mat[i])
# This code is contributed by himanshu77
|
1904bdc89188cfe9834d5a50ca780780a9c44680 | Lwq1997/leetcode-python | /primary_algorithm/array/moveZeroes.py | 972 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/4/12 21:37
# @Author : Lwq
# @File : plusOne.py
# @Software: PyCharm
"""
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
"""
class Solution:
@staticmethod
def moveZeroes(arr):
"""
移动0
:type arr: object
"""
length = len(arr)
j = 0
for i in range(length):
if arr[i] != 0:
arr[j] = arr[i]
j += 1
arr[j:] = (length - j) * [0]
return arr
if __name__ == '__main__':
nums1 = [1, 2, 2, 1, 0, 1, 0, 0, 2, 5, 3, 6]
nums2 = [9, 90, 1, 4, 0, 2, 5, 0, 0, 5, 9]
res1 = Solution.moveZeroes(nums1)
res2 = Solution.moveZeroes(nums2)
print(res1)
print(res2)
|
78bd77149314cba6cc1b4c64c6bd8c00a1bee6ad | yusseef/python-simple-codes | /simple factorial.py | 125 | 4.125 | 4 | print("enter the num")
num=int(input())
factorial=1
for i in range(num):
factorial=factorial*(i+1)
print (factorial) |
a087bd196a613a888c139fbd43f888ed8c952aa6 | galacticsquad15/Python | /test_assign_average.py | 873 | 3.609375 | 4 | import unittest
import assign_average
class MyTestCase(unittest.TestCase):
def test_a(self):
my_value = 'A'
self.assertEqual(assign_average.switch_average(my_value), 1)
def test_b(self):
my_value = 'B'
self.assertEqual(assign_average.switch_average(my_value), 2)
def test_c(self):
my_value = 'C'
self.assertEqual(assign_average.switch_average(my_value), 3)
def test_d(self):
my_value = 'D'
self.assertEqual(assign_average.switch_average(my_value), 4)
def test_e(self):
my_value = 'E'
self.assertEqual(assign_average.switch_average(my_value), 5)
def test_incorrect_key(self):
my_value = 'F'
self.assertEqual(assign_average.switch_average(my_value), "Invalid entry")
if __name__ == '__main__':
unittest.main()
|
0bdce7a44bb3ab4fa7c48a67d99a93cb38bbaa03 | Erkinumur/hm_17.04.2020 | /17.04.2020_task2.py | 971 | 3.75 | 4 | name = input('Как Вас зовут? ').title()
hello = ('Hello', 'Привет')
start = input('Напишите Привет или Hello: ')
while start.title() not in hello:
start = input('Напишите Привет или Hello: ')
print(f'Hello, {name}!\n')
offices = {'KZ': 'google_kazakstan.txt', 'PS': 'google_paris.txt,', 'UAR': 'google_uar.txt',
'KG': 'google_kyrgystan.txt', 'SF': 'google_san_francisco.txt', 'DE': 'google_germany.txt',
'MC': 'google_moscow.txt', 'SE': 'google_sweden.txt'}
select_text = '''
KZ - Казахстан
PS - Париж
UAR - ЮАР
KG - Кыргызстан
SF - Сан-Франциско
DE - Германия
MC - Москва
SE - Швеция
'''
select = input(f'Выберите, в какой офис Гугл Вы хотите обратиться:{select_text}').upper()
complain = input('Напишите Ваш отзыв:\n')
with open(offices[select], 'a') as f:
f.write(f'{name}: {complain}\n') |
399d36e328d8996b7c5359faae4ccc89c8ef0bde | vk27inferno/Guess-the-Number | /GuesstheNumber.py | 5,255 | 3.578125 | 4 | class GuessNumber:
font = ("Comic Sans MS", 15, "bold")
title = "Guess the Number!"
ask = "Guess a number between {} and {}: "
def __init__(self, minNum = 0, maxNum = 1000, tries = 10):
self.min = minNum
self.max = maxNum
self.retries = tries
self.reset()
def reset(self):
self.tries = self.retries
from random import randint
self.num = randint(self.min, self.max)
def play(self):
def askReplay():
self.bind = window.bind('<Return>', lambda event: replay())
window.bind('<Key>', lambda event: window.destroy())
def replay():
self.reset()
logLabel['text'] = ''
triesLabel['text'] = "{} Oops left.".format(self.tries)
window.unbind('<Key>')
window.bind('<Return>', process)
def isValid(string):
try:
string = eval(string)
return True
except:
return False
def inRange(num):
if num >= self.min and num <= self.max:
return True
def updateTries():
self.tries -= 1
triesLabel['text'] = "{} Oops left.".format(self.tries)
def log(state):
if state == 'no tries':
logLabel['text'] = "You ran out of tries.\nEnter to Replay; Any Key to exit."
elif state == 'invalid':
logLabel['text'] = "Enter only a number."
elif state == 'outOfDomain':
logLabel['text'] = "It's out of range."
elif state == 'match':
logLabel['text'] = "You guessed it.\nEnter to Replay; Any Key to exit."
elif state == 'too low':
logLabel['text'] = "Too low..."
elif state == 'low':
logLabel['text'] = "Low."
elif state == 'low close':
logLabel['text'] = "A bit lower."
elif state == 'too high':
logLabel['text'] = "Too high..."
elif state == 'high':
logLabel['text'] = "High."
elif state == 'high close':
logLabel['text'] = "A bit higher."
def process(event):
user = enter.get().strip()
if isValid(user):
user = float(eval(user))
if inRange(user):
if user == self.num:
log('match')
askReplay()
elif user < self.num:
if user < self.num - (self.max - self.min) * 0.22:
log('too low')
elif user < self.num - (self.max - self.min) * 0.05:
log('low')
else:
log('low close')
updateTries()
else:
if user > self.num + (self.max - self.min) * 0.3:
log('too high')
elif user > self.num + (self.max - self.min) * 0.05:
log('high')
else:
log('high close')
updateTries()
else:
log('outOfDomain')
else:
log('invalid')
enter.delete(0, 'end')
if self.tries == 0:
log('no tries')
askReplay()
def changeTheme():
if themeButton['text'] == 'Dark':
themeButton['text'] = 'Light'
bg = 'white'
fg = 'black'
else:
themeButton['text'] = 'Dark'
bg = 'black'
fg = 'white'
window.config(bg = bg)
enter['insertbackground'] = fg
for i in [frame1, frame2]:
i['bg'] = bg
for i in [askLabel, themeButton, enter, triesLabel, logLabel]:
i['bg'] = bg
i['fg'] = fg
## GUI Design
from tkinter import Tk, Label, Entry, Frame, Button
# Main Window
window = Tk()
window.title(self.title)
window.geometry("600x150")
frame1 = Frame(master = window)
frame1.pack(fill = 'x')
askLabel = Label(master = frame1, font = self.font, text = self.ask.format(self.min, self.max))
askLabel.pack()
themeButton = Button(master = frame1, font = ("Comic Sans MS", 10), text = 'Light' , command = changeTheme)
themeButton.pack(side = 'right')
frame2 = Frame(master = window)
frame2.pack()
enter = Entry(master = frame2, font = self.font, width = 5)
enter.focus_set()
enter.pack(side = 'left')
triesLabel = Label(master = frame2, font = self.font, text = " {} Oops left.".format(self.tries))
triesLabel.pack(side = 'left')
logLabel = Label(master = window, font = self.font)
logLabel.pack()
# MainLoop, Theme & Event Handlers
changeTheme()
window.bind('<Return>', process)
window.mainloop()
game = GuessNumber()
game.play()
|
e70d39bdd1533a31376c7b6609920535e9a06d65 | TimeCracker/python | /range_function/range_test.py | 781 | 3.8125 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
###############################################################
# © kenwaldek MIT-license
#
# Title: range function Version: 1.0
# Date: 28-12-16 Language: python3
# Description: de range funktie uitgelegd
#
###############################################################
#range word een generator genoemd
for i in range (10): #print 10x do something
#do something
print('hello world') #het geen uitgevoerd zal worden
print('#########')
xyz = [i for i in range (10)] #vierkante haakjes wordt in memory geladen
print('done')
xyz = (i for i in range (10)) #dit is een "generator object"
print(xyz)
# todo zoek meer info over "generator objects"
|
368792d6415d63f803656ecdf94531b269432625 | Yomiguel/freecodecamp-python-course | /readingwritingfiles.py | 1,075 | 3.984375 | 4 | #-------------------------reading files--------------------------
# 'r' for reading only, 'w' for writing only, 'r+' for writing and reading, 'a' for append.
file_names = open("names.txt","a")
""" #this line print the state of the file (r(readable), w(wirtable), r+ or a).
print(file_names.writable())
#this line print the first line of the file.
print(file_names.readline())
#this line print the lines of the file as a list.
print(file_names.readlines())
#this part of the code print line by line the file.
for i in file_names.readlines():
print(i)
#this line print the third line in file.
print(file_names.readlines()[2]) """
#-------------------------writing files--------------------------
#this line adds the element 'peru' to the final line of the file.
file_names.write('\nPeru')
# 'r' for reading only, 'w' for writing only, 'r+' for writing and reading, 'a' for append.
file_names = open("names.txt","r")
#this part of the code print line by line the file.
for i in file_names.readlines():
print(i)
#this line close the file.
file_names.close |
beed913c8cd5dafcb4deda90e60be5fabb290141 | sonushahuji4/Data-Structure-and-Algorithm | /Linklist/linked.py | 12,016 | 4.03125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Linklist:
def __init__(self):
self.start = None
self.temp = None
self.mov = None
self.cur = None
self.head = None
self.size = 0
def insertData(self,data):
if self.start is None: # if start is None
self.start = Node(data) # create a node
self.temp = self.start # point temp to newly created node (so that u can iterate temp whenever u want)
else: # if start is not None
self.temp.next = Node(data) # create a node, since temp is already on start node so point temp ka next to node
self.temp = self.temp.next # Now move temp to newly created node
self.size += 1 # just to get the size of the data
def insertBeg(self,data):
if self.start == None: # if start is None
self.temp=Node(data) # create a node with a data
self.start=self.temp # point start to temp (newly created node)
else: # if start is not None
self.temp = Node(data) # create a node
self.temp.next=self.start # point temp ka next pointer to 1st node i.e. start node
self.start=self.temp # move start to newly create node i.e temp node
def insertEnd(self,data):
if self.start is None: # if start is None i.e there is not data then
self.start=Node(data) # create a node
self.temp=self.start # point temp to start
else: # if start is not None
self.temp=self.start # point temp to start so that u can iterate from the beginning
while self.temp.next is not None: # while temp ka next is not None i.e. loop will iterate until it encounters None
self.temp=self.temp.next # move temp to next node
self.temp.next=Node(data) # when it encounters temp ka pointer None, then temp ka next pointer will connect the new node
self.temp = self.temp.next # move temp to next node
def insretSpecificLocation(self,data,location):
if self.start is None: # if start is None i.e. means database is empty & data cannot be inserted at a perticular location
print("Database is Null") #prints a message
else: # if database is not empty then
self.temp=self.start # temp points to start node
prev=None # variable "prev" is used here just to keep a track of previous node
mov=location-1
while mov>0:
prev=self.temp # prev pints to temp
self.temp=self.temp.next # move temp to next node
mov-=1
prev.next=Node(data) # point prev ka next pointer to new node so that it can connect to newly create node
prev=prev.next # move prev to next node
prev.next=self.temp # point prev ka pointer next to temp
def searchData(self,key):
if self.start is None:
print("Data base is Null")
else:
self.temp=self.start # temp points to start node
flag=1 # used here just to keep track of location
while self.temp is not None: # loop runs until temp encounters None
if self.temp.data==key: # if key matches the data in the database then
print(self.temp.data,"was found at location",flag) # print flag
break # break the loop
self.temp=self.temp.next # move temp to next node
flag+=1 # increment the flag by 1
else: # in case if data dese not exits in database, then
print("No match found") # print message
def deleteBeg(self):
if self.start is None: # if database is empty then
print("Database is Null, data cannot be deleted") # prints message
else: # if database is not empty, then
self.cur=self.start # point cur to start node
self.temp=self.start.next # move temp to start ka next node
self.start=self.temp # move start to point temp node
del self.cur # delete the cur node i.e. the 1st node
def deleteEnd(self):
if self.start is None: # if database is empty,then
print("Database is Null") # prints the message
else: # if database is not empty,then
self.temp=self.start # point temp to start node
prev=None # variable "prev" is used here just to keep a track of previous node
while self.temp.next is not None: # loop runs until it encounters None
prev=self.temp # prev moves to temp node
self.temp=self.temp.next # temp moves to next node
self.temp=self.temp.next # After loop encounters None,then temp moves to the last node
prev.next=None # prev ka pointer i.e. next points to None i.e. it no longer connects the last node
def deleteData(self,data):
if self.start is None: # if database is empty,then
print("Database is empty") # prints message
else: # if database is not empty
self.temp=self.start # temp points to start node
if self.temp and self.temp.data==data: # suppose if the data that is to be deleted is 1st data, then
self.start=self.temp.next # move start to next node
self.temp=None # delete temp node
prev=None
while self.temp and self.temp.data != data: # suppose if the data that is to be deleted is not the 1st data, then
prev = self.temp # point prev to temp node (just to keep the track of the previous node)
self.temp = self.temp.next # move temp to next node
if self.temp is None: # suppose if the data that is to be deleted dose not exits in the database, then
print("Dtat does not exits in the list") # prints message
prev.next=self.temp.next # points prev ka next to temp ka next
self.temp=None # delete the temp node
def countData(self):
if self.start is None: # if database is empty,then
print("Database is Null") # prints message
else: # if database is not empty,then
self.temp = self.start # temp points to start node
flag=0 # flag is used to keep a track of the data length
while self.temp is not None: # loop runs until the temp encounters None
flag += 1 # increment the flag by 1
self.temp = self.temp.next # move temp to next node
print("Data Length:",flag) # print the data length
def reversseNode(self): # here nodes are reversed instead of reversing the data
if self.start is None:
print("Database is Null")
else:
self.temp=self.start # temp points to start node
prev=None # variable "prev is used just to keep track of previous node"
while self.temp: # loop runs until temp encounters None
self.cur=self.temp.next # cur moves to temp ka next node
self.temp.next=prev # temp ka next pointer points to prev node
prev=self.temp # prev points at temp node
self.temp=self.cur # temp points to cur node
self.start=prev # brings prev back to starting node
def copyData(self):
if self.start is None:
print("Database is Null")
else:
self.temp=self.start
while self.temp is not None:
if self.temp == self.start:
self.cur = Node(self.temp.data)
self.mov=self.cur
else:
self.cur.next=Node(self.temp.data)
self.cur=self.cur.next
self.temp = self.temp.next
self.cur = self.mov
while self.cur is not None:
print(self.cur.data,end=" ")
self.cur = self.cur.next
def sortData(self):
self.temp=self.start
s=self.size
for j in range(s):
self.temp = self.start
while self.temp.next is not None:
if self.temp.data > self.temp.next.data:
val = self.temp.data
self.temp.data = self.temp.next.data
self.temp.next.data = val
else:
pass
self.temp = self.temp.next
def splitData(self,data):
self.temp=self.start
while self.temp and self.temp.data != data:
self.temp=self.temp.next
if self.temp and self.temp.data == data:
self.head=self.temp.next
self.temp.next=None
self.temp=self.start
print("List 1")
l.displayData()
print("List 2")
self.cur=self.head
while self.cur is not None:
print(self.cur.data,end=" ")
self.cur=self.cur.next
print()
def displayData(self):
self.temp=self.start
while self.temp is not None:
print(self.temp.data,end=" ")
self.temp=self.temp.next
print()
l=Linklist()
f=True
while f==True:
print("---------- Single Link List ----------\n")
print("1)Insert Data",end=" ")
print("2)Insert Data Beg")
print("3)Insert Data End",end=" ")
print("4)Insert Data at specific location")
print("5)Delete Data",end=" ")
print("6)Delete Data Beg")
print("7)Delete Data End", end=" ")
print("8)Search by Data")
print("9)Count Data Length", end=" ")
print("10)Copy Data")
print("11)Reverse Data by Node", end=" ")
print("12)Sort Data")
print("13)Merge Data", end=" ")
print("14)Split Data")
print("15)Display Data", end=" ")
print("16)Exit Data")
choice=int(input("\nEnter your choice:"))
if choice==1:
n=int(input("Enter Data Length:"))
print("Enter data here:")
while n>0:
data=int(input())
l.insertData(data)
n-=1
elif choice==2:
data=int(input("Enter data:"))
l.insertBeg(data)
elif choice==3:
data=int(input("Enter data:"))
l.insertEnd(data)
elif choice==4:
data=int(input("data"))
location = int(input("Enter locaiton:"))
l.insretSpecificLocation(data,location)
elif choice==5:
data=int(input("Enter data:"))
l.deleteData(data)
elif choice==6:
l.deleteBeg()
elif choice==7:
l.deleteEnd()
elif choice==8:
data=int(input("Enter data:"))
l.searchData(data)
elif choice==9:
l.countData()
elif choice==10:
l.copyData()
elif choice==11:
l.reversseNode()
elif choice==12:
l.sortData()
elif choice==13:
# l.mergedata()
n = int(input("Enter Data Length:"))
print("Enter data here:")
while n > 0:
data = int(input())
l.insertData(data)
n -= 1
elif choice==14:
data = int(input("Enter data from where u want to split"))
l.splitData(data)
elif choice==15:
l.displayData()
elif choice==16:
exit()
else:
print("Invalide Choice:") |
7efba58b1e7271d95dd5d51db388064eeb6f79cb | ablancoze/ComputacionBioInspirada | /TrabajoGenetico/mapa.py | 1,070 | 3.5625 | 4 | import numpy as np
import random
import sys
from random import sample
class mapa():
ciudad=np.zeros((3, 3))
nCiudades=3
def __init__(self,_nCiudades):
self.ciudad=np.zeros((_nCiudades, _nCiudades),int)
self.nCiudades = _nCiudades
self.generarMapa()
#Permite generar un mapa de ciudades con costes simetricos
def generarMapa(self):
j=1
for i in range(self.nCiudades):
L=sample(range(1,100),self.nCiudades-i)
if (i==0):
self.ciudad[i]=L
continue
for x in range(i):
if (x<i):
L.insert(x,self.ciudad[x][j])
if (j<self.nCiudades):
self.ciudad[j]=L
j=j+1
np.fill_diagonal(self.ciudad, 0)
#Muestra el mapa generado.
def mostrarMapa(self):
for i in range(self.nCiudades):
if (i<=9):
print("ciudad ",i, "" ,self.ciudad[i])
else:
print("ciudad ",i ,self.ciudad[i])
print("")
|
cd20d5431271a0a0a86e63ec490685b62534ec84 | linlilin/GA | /editga.py | 2,179 | 3.609375 | 4 | """
Finding x,y for function minimization F(x,y) = 3x^2 + 2y^2 - 4x + y/2 using Genetic Algorithm
wrismawan, E101
"""
from random import randint
import collections
Individu = collections.namedtuple('Individu', 'ind fitness')
class GA(object):
def __init__(self, jum_pop=10, mut_rate=.3):
self.jum_pop = jum_pop
self.mut_rate = mut_rate
def solve(self, fitness, initial_population, generation=10):
"""
Main function of GA
"""
current_generation = [Individu(ind, fitness(ind)) for ind in initial_population]
print current_generation
def _crossover(self,u,v):
"""
LILIN
"""
TP = randint(1,7)
Anak1= "".join([u[:TP],v[TP:]])
Anak2 = "".join([v[:TP],u[TP:]])
print Anak1
print Anak2
print TP
def _mutation(self, ind):
"""
Haris
"""
for x in range(len(ind)) :
rnd = random.random()
if rnd >= self.mut_rate :
if ind[x] == 0 :
ind[x] = 1
else :
ind[x] = 0
def _selection(self, pop):
"""
Selection function ..... coming soon
"""
if __name__ == "__main__":
def decode(ind):
"""
Decode string individual into integer x,y (as function parameter)
"""
mid = len(ind)/2
x = int(ind[:mid],2)
y = int(ind[mid:],2)
return [x , y]
def encode(x,y):
"""
Encode two integers x,y into string as individual
"""
bin_x = '{0:04b}'.format(x)
bin_y = '{0:04b}'.format(y)
return bin_x+bin_y
def calculate_fitness(ind):
"""
Calculate fitness of individual
F(x,y) = 3x^2 + 2y^2 - 4x + y/2
"""
val = decode(ind)
x = val[0]
y = val[1]
f = 3*(x**2) + 2*(y**2) - (4*x) + (y*1.0/2)
return 1 * 1.0 / f + .1
ga = GA()
#init population
pop = ["".join([str(randint(0,1)) for _ in range(8)]) for _ in range(ga.jum_pop)]
ga.solve(calculate_fitness, pop, generation=10)
"""
LILIN
"""
Ortu1= '11101010'
Ortu2= '11010011'
ga._crossover(Ortu1,Ortu2)
|
6cb9616fa49f4b5a2c19c222672eb342d34c881b | NicholasBreazeale/NB-springboard-projects | /python-ds-practice/34_same_frequency/same_frequency.py | 569 | 3.8125 | 4 | def same_frequency(num1, num2):
"""Do these nums have same frequencies of digits?
>>> same_frequency(551122, 221515)
True
>>> same_frequency(321142, 3212215)
False
>>> same_frequency(1212, 2211)
True
"""
def frequency(string):
letters = {}
for char in string:
if char not in letters:
letters[char] = 1
else:
letters[char] += 1
return sorted(letters)
return frequency(str(num1)) == frequency(str(num2)) |
bc05e6f34a1eb1074ee29e2e3f379ff46fcd20ef | MadhanArts/PythonInternshipBestEnlist | /day13_task1/main.py | 878 | 3.90625 | 4 | from day13_task1.CoffeeMachine import CoffeeMachine
from day13_task1.Drink import Drink
my_machine = CoffeeMachine(3000, 2000, 1000, 0)
latte = Drink("Latte", 200, 150, 24, 2.5)
espresso = Drink("Espresso", 150, 100, 30, 3)
cappuccino = Drink("Cappuccino", 150, 175, 20, 4)
while True:
print("****** Welcome sir ******")
print("What would you like? ([1] espresso/[2] latte/[3] cappuccino)")
choice = input("Enter your choice or option : ").lower().strip()
if choice in ("espresso", "1"):
my_machine.make(espresso)
elif choice in ("latte", "2"):
my_machine.make(latte)
elif choice in ("cappuccino", "3"):
my_machine.make(cappuccino)
elif choice == "report":
my_machine.generate_report()
elif choice == "off":
exit(1)
else:
print("No option like that sir! Try again")
|
565fc38a24e86c52a53eb61cb37708f6be2e5a15 | chuanfanyoudong/algorithm | /leetcode/String/WordBreak.py | 660 | 3.796875 | 4 | """
不要用递归,用动态规划
@author: zkjiang
@time: 2019/4/30 20:38
"""
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
n = len(s)
result_lis = [0]*(n+1)
for i in range(n+1):
for k in range(i):
if (result_lis[k] and s[k:i] in wordDict) or s[:i] in wordDict:
result_lis[i] = 1
# break
return result_lis[-1]
if __name__ == '__main__':
s = "leetcode"
wordDict = ["leet", "code"]
print(Solution().wordBreak(s, wordDict))
|
e93cb8a3cc187dcaa0a0b9e8e83268a00e0b27cb | skhan75/CoderAid | /Techniques/Sliding Window/container_with_most_water.py | 1,321 | 4.1875 | 4 | """
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
"""
def max_area(height):
max_area = 0
left, right = 0, len(height)-1
while left < right:
# Area = height * breadth
# Always pick the smallest line to maximize the area
height = min(height[left], height[right])
# breadth is the distance between the line i.e. difference of the indexes
breadth = right - left
current_area = height * breadth
max_area = max(max_area, current_area)
# If left line is smaller than right line, then move left forward
if height[left] < height[right]:
left+=1
# Else move right backward
else:
right-=1
return max_area
if __name__ == "__main__":
print max_area([1,8,6,2,5,4,8,3,7])
|
8cfaa3998bfcf56489392a6708b5f7c72cb7ad4c | mohdsameer7408/python_codes | /utils.py | 156 | 3.875 | 4 | # A program to find the greatest number!!!
def find_max(numbers):
g = numbers[0]
for i in numbers:
if g < i:
g = i
return g
|
b1f88ee984178fb719db7a4272dd84971162428a | Allan-Perez/CStudies- | /LinearAlgebra/linTransf.py | 8,254 | 3.90625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# A transformation is linear if it follows the following properties:
# Additivity: L(u+w) = L(u)+L(w)
# Scaling: L(cv) = cL(v)
# Example of linear transformations to functions: derivative: chain rule.
# Stuff worthy to note: Linear algebra concepts have direct connection to other fancy terminology
# of utilities on other math fields that do the same at an underlying level: they are analog.
# Linear transformations -> Linear operators
# Dot products -> Inner products
# Eigenvectors -> eigenfunctions
#Other worhty notes -- 8 axioms that defines a vector space:
# 1. u + (v + w) = (u + v) + w
# 2. u + w = w + u
# 3. 0 + v = v ; for every v
# 4. v + (-v) = 0; for every v
# 5. a(bv) = (ab)v
# 6. 1*v = v
# 7. a*(u + v) = au + av
# 8. (a + b)v = av + bv
def transform(vectors, transformation):
assert transformation.shape[-1] == vectors.T.shape[0]
V2 = np.dot(transformation, vectors.T).T
return V2
def main():
#demo2D()
#demo3D()
#demoBetweenDim()
#basisChange()
eigenstuff()
def demo2D():
# V vector : V[0] = i_hat, V[1] = j_hat, V[2] = given vector
origin = [0], [0]
V1 = np.array([[1,0], [0,1], [1,2]])
transf1 = np.array([[0,-1], [1,0]]) # π/2 rotation
V2 = transform(V1, transf1)
transf2 = np.array([[1,1],[0,1]]) # Shear
V3 = transform(V2, transf2)
transf3 = np.array([[1,-1], [1,0]]) # π/2 + shear hardcoded
V4 = transform(V1, transf3)
compositionTransf = np.dot(transf2, transf1) # π/2 + shear composite
inverseComposite = np.dot(transf1, transf2) # shear + π/2 composite
V5 = transform(V1, compositionTransf)
V6 = transform(V1, inverseComposite)
plt.quiver(*origin, V5[:,0], V5[:,1], angles='xy', scale_units='xy', scale=1)
plt.quiver(*origin, V6[:,0], V6[:,1], color=['r','g','b'], angles='xy', scale_units='xy', scale=1)
plt.grid(True)
plt.xlim(-5,5)
plt.ylim(-5,5)
plt.show()
def demo3D():
origin = [0],[0],[0]
V1 = np.array([ [1, 0, 0], #i
[0, 1, 0], #j
[0, 0, 1], #k
[1, 1, 1]])#v
n_vectors = V1.shape[0]
transform1 = np.array([[0,0,1],[0,1,0],[-1,0,0]]) # π/2 rotation on i_hat
transform2 = np.array([[0,1,2],[3,4,5],[6,7,8]]) # shearing i
transform3 = np.array([[0,-2,2],[5,1,5],[1,4,-1]]) # shearing k
compostieTransf = np.dot(transform3, transform2)
print(f'{compostieTransf}')
U, V, W = zip(*V1)
Ut, Vt, Wt = zip(*transform(V1, compostieTransf))
oi, oj, ok = origin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(oi*n_vectors, oj*n_vectors, ok*n_vectors, U, V, W)
ax.quiver(oi*n_vectors, oj*n_vectors, ok*n_vectors, Ut, Vt, Wt, color=['g','r','b'])
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
ax.set_zlim([-2, 2])
plt.show()
def demoBetweenDim():
#_2dTo3d()
_3dTo2d()
def _2dTo3d():
# Basically with non-square matrices.
origin = [0],[0],[0]
V1 = np.array([ [1, 0], #i
[0, 1], #j
[1, 1]])#v
n_vectors = V1.shape[0]
transf2Dto3D = np.array([[2,0],[-1,1],[-2,1]])
U, V= zip(*V1)
Ut, Vt, Wt = zip(*transform(V1, transf2Dto3D))
oi, oj, ok = origin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#ax.quiver(oi*n_vectors, oj*n_vectors, ok*n_vectors, U, V)
ax.quiver(oi*n_vectors, oj*n_vectors, ok*n_vectors, Ut, Vt, Wt, color=['g','r','b'])
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
ax.set_zlim([-2, 2])
plt.show()
def _3dTo2d():
# Basically with non-square matrices.
origin = [0],[0]
V1 = np.array([ [1,0,0], #i
[0,1,0], #j
[0,0,1], #k
[1,1,1]])#v
n_vectors = V1.shape[0]
transf3Dto2D = np.array([[3,1,4],[1,5,9]])
Ut, Vt = zip(*transform(V1, transf3Dto2D))
oi, oj = origin
#ax.quiver(oi*n_vectors, oj*n_vectors, ok*n_vectors, U, V)
plt.quiver(oi*n_vectors, oj*n_vectors, Ut, Vt, color=['g','r','b', 'black'], angles='xy', scale_units='xy', scale=1)
plt.grid(True)
plt.xlim(-5,5)
plt.ylim(-5,5)
plt.show()
def basisChange():
#Goal: to translate v from our basis to V1's basis (2,3)+(1,2)
origin = [0],[0]
V0 = np.array([ [1,0], #i
[0,1], #j
[1,1]])#v
V1 = np.array([ [2,3],
[1,2]])
n_vectors = V0.shape[0]
translation = np.array([[2,3],[1,2]])
noitalsnart = np.linalg.inv(translation)
tV0 = transform(V0, noitalsnart)
V1 = np.vstack((V1,tV0[-1]))
oi, oj = origin
plt.quiver(oi*n_vectors, oj*n_vectors, V0[:,0], V0[:,1], angles='xy', scale_units='xy', scale=1)
plt.quiver(oi*n_vectors, oj*n_vectors, V1[:,0], V1[:,1], color=['g','r','b'], angles='xy', scale_units='xy', scale=1)
plt.grid(True)
plt.xlim(-5,5)
plt.ylim(-5,5)
plt.show()
def eigenstuff():
#Eigenvectors --> vectors that after a linear transformation, they're just stretched -- keeping their span unchanged,
#i.e. that a linear transformation or vector-matrix multiplication has the same effects as multiplying by a scalar.
#Eigenvalue --> the factor by which the eigenvectors is stretched or squished during the transformation.
# This can also be helpful to describe a 3D rotation in terms of an angle and an "axis" than a 3x3 matrix.
# Av = lv -> v is the eigenvector / l is the eigenvalue / A is the transformation matrix.
# A = [[l,0,0],[0,l,0],[0,0,l]] -> Av = (lI)v | I is the identity matrix
# Goal: to solve for l and v.
# Av - (lI)v = 0 -> (A-lI)v=0 --> This is going to be true always for v = zero vector, but also for other vectors.
# Now, if v is nonzero, then the resulting matrix (A-lI) has to be a transformation that squishes space into lower dims,
# i.e. det(A-lI) = 0.
# For example, for a given linear transformation A = [[2,2],[1,3]], the only way det(A-lI)=0 is if l=1, meaning that when l=1
# the transformation squishes space into lower dimension (in this case 1D), and that there exists a vector that when transformed,
# it equals the zero vector. This means that the vector v is an eigenvector of A (staying in its own span during the transformation A):
# [[2,2],[1,3]]*v = 1*v
# To find the corresponding eigenvectors, just go to the equation and solve:
# [[2-1, 2], [1,3-1]]*v = 0 -> [[1,2],[1,2]]*v = 0 -> so v is any vector on the span of (2,1) [i.e. (4,2),(6,3),...]
# Even though,... a 2D matrix doesn't have to have eigenvectors (e.g. π/2 rotaiton). Some solutions on eigenvectors of π/2 rotations
# can end up with l=i and l=-i, the imaginary plane.
# Another example: "SHEAR", A=[[1,1],[0,1]] -> l=1, meaning that the transformation's eigenvalue doesn't stretch the eigenvector.
# Eigenbases-> after the transformation, the original basis (may be i and j) is just stretched or scaled by an eigenvalues.
# These kind of transformation matrices have a particular shape: diagonal matrices, which have the particularity that all the
# base vectors are eigenvectors (i.e. after the transformation they are only scaled by a scalar) so that each entry of the diagonal matrix
# is their corresponding eigenvalues.
# Note that if we have many eigenvectors for a given transformation (enough to keep the same rank), we may want to change our basis vectors
# (throw i and j, and get i' and j') so that our basis vectors become eigenbasis so that the transformation matrix A is just a diagonal matrix
# with which may be far easier to work with.
# So if we want to do a transformation A=[[3,1],[0,2]] with eigenvectors v1= [1,0] and v2=[-1,1] (change basis transformation
# V=[[1,-1],[0,1]]), then we can change the basis with the "emphaty formula" V^-1 * A * V = A', where A' is a diagonal matrix which
# represents the original transformation in terms of stretching the eigenvectors.
# But note that not all transformations have eigenbasis, for example "shear", which only has 1 eigenvector (not enough for a basis).
A = np.array([[0,1],[1,1]])
B = A
for n in range(1,10):
B = np.dot(A,B)
print(f"A^10:{B}")
eigenvector1 = np.array([2,1+np.sqrt(5)])
eigenvector2 = np.array([2,1-np.sqrt(5)])
eigenbasis = np.vstack((eigenvector1, eigenvector2)).T
diagmat = np.dot(np.linalg.inv(eigenbasis), np.dot(A, eigenbasis)).round(5)**10
invertedDiag = np.dot(eigenbasis, np.dot(diagmat,np.linalg.inv(eigenbasis))).round(5)
print(f'{A}')
print(f'{diagmat}')
print(f'{invertedDiag}')
if __name__ == '__main__':
main() |
0e38062ad61e086ffa923a5bfeb603441769eed9 | yuandaqiancheng/Python_learning | /shili.py | 3,684 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
#输出N以内的素数
import math
l = []
n = int(input('please input a number more than 2:'))
if n == 2:
print('there is no prime less than 2!')
else:
for a in range(2, n):
for b in range(2, int(math.sqrt(a)) + 1):#素数只需要不能整除2-根号自己就可以了。
l.append(a % b)#将所有b遍历的结果加到列表中
if 0 not in l:
print(a)
l = []
'''
'''
#计算两个数之和
#写法一:
num1=input('输入第一个数字:')
num2=input('输入第二个数字:')
sum=float(num1)+float(num2) #input返回一个字符串,用float()方法将字符串转换为数字
print('数字{0}和{1}相加结果为:{2}'.format(num1,num2,(sum)))
#写法二:一行代码输出
print('两个数之和为%0.1f' % (float(input('输入第一个数:'))+float(input('输入第二个数:'))))
'''
'''
#计算平方根
#计算一个正数的平方根:写出该数的0.5次方即可
num=float(input('输入一个正数:'))
num_sqrt=num**0.5
print(('%0.3f的平方根为%0.3f')%(num,num_sqrt))
#计算负数和复数平方根:
import cmath #导入复数数学模块
num=int(input('输入一个数字:'))
num_sqrt=cmath.sqrt(num)
print('{0}的平方根为{1:0.3f}+{2:0.3f}j'.format(num,num_sqrt.real,num_sqrt.imag)) #注意format中分隔只能用逗号
#两者综合,判断所有数
#注意0既不是正数也不是负数
import cmath
num=float(input('输入一个数:'))
if(num==0):
print(0)
elif(num>0):
num_sqrt=num**0.5
print('%0.1f的平方根为%0.1f'%(num,num_sqrt))
else:
num_sqrt=cmath.sqrt(num)
print('{0}的平方根为{1:0.3f}+{2:0.3f}j'.format(num,num_sqrt.real,num_sqrt.imag))
'''
'''
#计算二次方程ax**2+bx+c=0的根,其中a,b,c由用户提供
#可能会有复数,导入cmath模块
import cmath
a=float(input('输入a:'))
b=float(input('输入b:'))
c=float(input('输入c:'))
d=b**2-4*a*c
sol1=(-b-cmath.sqrt(d))/(2*a)
sol2=(-b+cmath.sqrt(d))/(2*a)
print('结果为{0},{0}'.format(sol1,sol2))
#优化一下,考虑到无穷解和的情况
import cmath
#a,b,c=input('依次输入三个数(空格分隔):').split() #这句不知道为啥有错误
a=float(input('输入a:'))
b=float(input('输入b:'))
c=float(input('输入c:'))
d=b**2-4*a*c
if(a==0 and b==0 and c==0):
print('有无穷多个解')
else:
x1=(-b-cmath.sqrt(d))/(2**a)
x2=(-b+cmath.sqrt(d))/(2**a)
print('方程的解为{0},{1}'.format(x1,x2))
#此处不用考虑判断d,因为都可以算出来,具体原因不详
#else:
# d=4*a*c-b**2
# x1=(-b-cmath.sqrt(d))/(2**a)
# x2=(-b+cmath.sqrt(d))/(2**a)
# print('方程的解为{0},{1}'.format(x1,x2))
'''
'''
#计算三角形的面积,用户输入三边长度
#公式:应用海伦公式 S=(p(p-a)(p-b)(p-c))**0.5 ,其中p为半周长
a=float(input('输入第一个边长:'))
b=float(input('输入第二个边长:'))
c=float(input('输入第三个边长:'))
p=(a+b+c)/2 #计算半周长
s=(p*(p-a)*(p-b)*(p-c))**0.5
print('三角形的面积为%0.3f'%s) #记住要格式化输出,不然中文输出可能乱码
#优化:增加一个判断三边是否构成三角形
a=float(input('输入第一个边长:'))
b=float(input('输入第二个边长:'))
c=float(input('输入第三个边长:'))
while(a+b<c or a+c<b or b+c<a):
print('不能构成三角形,请重新输入:')
a = float(input('输入第一个边长:'))
b = float(input('输入第二个边长:'))
c = float(input('输入第三个边长:'))
p=(a+b+c)/2
s=(p*(p-a)*(p-b)*(p-c))**0.5
print('三角形的面积为%0.3f'%s)
'''
a=set([1,2,3])
print(a)
|
0c67eb2bc3c1ffbdd1e05d77b1a54a4e4c970876 | jessicazhuofanzh/Jessica-Zhuofan--Zhang | /mygame.py | 12,226 | 4.25 | 4 |
# Isolated Island
# Now updated to Python 3
# At the top of the file are declarations and variables we need.
#
# Scroll to the bottom and look for the main() function, that is
# where the program logic starts.
import random # random numbers (https://docs.python.org/3.3/library/random.html)
import sys # system stuff for exiting (https://docs.python.org/3/library/sys.html)
# an object describing our player
player = {
"name": "p1",
"score": 0,
"items" : ["milk"],
"friends" : [],
"location" : "start"
}
rooms = {
"room1" : "an isolated island",
"room2" : "a long path",
"room3" : "a scary path"
}
def rollDice(minNum, maxNum, difficulty):
# any time a chance of something might happen, let's roll a die
result = random.randint(minNum,maxNum)
print ("You roll a: " + str(result) + " out of " + str(maxNum))
if (result <= difficulty):
print ("trying again....")
raw_input("press enter >")
rollDice(minNum, maxNum, difficulty) # this is a recursive call
return result
def printGraphic(name):
if (name == "house"):
print (' __- - ')
print (' ( ')
print (' _))_ ')
print (' | |________ ')
print (' .-------""""" | """""------. ')
print (' /.".\ | /.".\ ')
print (' /. .\ | /. .\ ')
print (' /. .\ | /. .\ ')
print (' /. ___ ' "T" ' ___ .\ ')
print (' | |_|_| | _.. | --. | |_|_| | ')
print (' | |_|_| | | | | |_| | |_|_| | ')
print (' |__________|__|..+--"""--....__|_________| ')
print (' the house ')
if (name == "man"):
print (' ))),, ')
print (' / /// ')
print (' . . . / ')
print (' \\ < ) ')
print (' -C\ \_- | ')
print (' \_/ __|__/L__ ')
print (' / \ ')
print (' ___ \ ')
print (' \ / ')
print (' V __ ')
print (' |--\ ')
print (' \__/-- ')
print (' the man ')
if (name == "key"):
print (' ,o. 8 8 ')
print (' d bzzzzzzzza8o8b ')
print (' `o ')
print (' the key ')
if (name == "ghost"):
print (' .````. ... ')
print (' :o o `....`` ; ')
print (' `. O :` ')
print (' ``: `. ')
print (' `:. `. ')
print (' : `. `. ')
print (' `..``... `. ')
print (' `... `. ')
print (' ``... `. ')
print (' `````.')
print (' ')
print (' not-so-scary ghost ')
if (name == "title"):
print ('.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.')
print ('. _.,.__ . .')
print ('. ((o\o\)) . . ')
print ('. .-. ` `` . A tropical island .')
print ('. __( )___.o"^^".,___ . .')
print ('. === ~~~~~~~~ . .')
print ('. == ldb . .')
print ('. = . .')
print ('.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.')
def gameOver():
printGraphic("title")
print("-------------------------------")
print("to be continued!")
print("name: " + player["name"] ) # customized with a name
print( "score: " + str(player["score"]) ) # customized with a score
return
def scaryPath():
print("The path led you to a cave.")
print("It's dark and you feel really scared...")
print("Then you see there's something moving! It's a man!")
printGraphic("man")
raw_input("press enter >")
print("You consider your options.")
print("options: [ talk to the man , walk around , back to island]")
pcmd = raw_input(">")
if (pcmd == "talk to the man"):
print ("You walk to the man.")
print ("Let's roll a dice to see what happens next!")
# roll a dice from 0 to 20 to see what happens
# if your number is higher than the difficulty, you win!
difficulty = 10
roll = rollDice(0, 20, difficulty)
# you have to get lucky! this only happens to the player
# if you roll the dice high enough
if (roll >= difficulty):
print ("The man say he has a boat which can help you escape from the island!")
print ("Do you want to ask for the key?")
printGraphic("key")
# we dive further into the logic
pcmd = raw_input("yes or no >")
if (pcmd == "no"):
print ("You leave it there.")
scaryPath()
elif (pcmd == "yes"):
print ("You take the key and find the boat.")
player["items"].append("gem") # add an item to the array with append
player["score"] += 100 # add to the score
isolatedIsland()
else:
print ("You leave it there.")
isolatedIsland()
else:
print ("Turns out it's nothing... oh well.")
scaryPath()
elif (pcmd == "walk around"):
print ("You walk around... you have a strange feeling")
print ("that you never leave the cave...") # the lost woods reference
scaryPath()
elif (pcmd == "back to island"):
print ("You decide to go back.")
pcmd = raw_input(">")
isolatedIsland()
else:
print ("You can't do that!")
scaryPath()
def longPath():
print ("The long path leads you down a narrow road.")
print ("You see there is a big house at the end of the road.")
raw_input("press enter >")
printGraphic("house")
print ("It looks like an abandoned house.")
print ("You stand in front of the house.")
print ("The door open...")
raw_input("press enter >")
print ("You consider your options.")
# check the list for items
# the 'in' keyword helps us do this easily
if ("key" in player["items"]):
print ("options: [ go back, enter the house, give up key, screaming ]")
else:
print ("options: [ go back, enter the house, run ]")
pcmd = raw_input(">")
# option 1: look at the fox
if (pcmd == "go back"):
print ("You go back...")
isolatedIsland() # try again
# option 2: enter the house
elif (pcmd == "enter the house"):
print ("You walk into the house")
print ("Let's roll a dice to see what happens next!")
raw_input("press enter to roll >")
difficulty = 5
chanceRoll = rollDice(0,20,difficulty) # roll a dice between 0 and 20
# if the roll is higher than 5... 75% chance
if (chanceRoll >= difficulty):
print ("It's some food! You're lucky.")
player["score"] += 50
else:
print ("You walk around, but... you got lose.")
longPath() # try again
# nested actions and ifs
pcmd = raw_input("You like the house, do you want to stay? yes or no >")
# yes
if (pcmd == "yes"):
print ("You really like live in this house!")
player["friends"].append("white fox")
# string and int converstion!
# we need to convert the score to a number to add to it
# then convert it back to a string to display it to the player
player["score"] = int(player["score"]) + 100 # conversion
# we generate a custom string and add the score
print ( "Your score increased to: " + str(player["score"]) )
gameOver()
# no
elif (pcmd == "no"):
print ("You walk back...")
longPath()
# try again
else:
longPath()
elif (pcmd == "give up key"):
print ("You throw away the key.")
raw_input("press enter>")
printGraphic("key")
gameOver()
# option 3: run
elif (pcmd == "screaming"):
print ("It's so scary!")
isolatedIsland() # back to start
# try again
else:
print ("I don't want to go in there.")
longPath() # long path
def isolatedIsland():
print ("You are in an isolated island.")
print ("There is a path ahead of you and another path to the right.")
# this piece of game logic checks to see if the requirements are met to continue.
# we can have some fun and change the options for the player
# based on variables we stored
# 1. check the list of items, to see if it is there
# 2. check the list of friends, to see if you are in friends list
if (("key" in player["items"]) and not ("fox" in player["friends"])):
print ("Your options: [ look around, path, trade key with the island ghost]")
elif ("key" in player["items"]):
print ("Your options: [ look around, path, exit ]")
else:
print ("Your options: [ look around, path , other path , exit ]")
pcmd = raw_input(">") # user input
# player options
if (pcmd == "look around"):
# its a trick!
print ("You look around... you hear some scary moan")
raw_input("press enter >")
isolatedIsland()
# path option
elif (pcmd == "path"):
print ("You take the path.")
raw_input("press enter >")
longPath() # path 1
# path2 option
elif (pcmd == "other path"):
print ("You take the other path.")
raw_input("press enter >")
strangePath() # path 2
# exiting / catching errors and crazy inputs
elif (pcmd == "exit"):
print ("you exit.")
return # exit the application
elif (pcmd == "trade key with the island ghost"):
print ("you give the key to the ghost... hugh?")
printGraphic("ghost")
print ("'tooooodaaloooooo'\", he says.") # escaped
return # exit the application, secret ending
else:
print ("I don't understand that")
isolatedIsland() # the beginning
def introStory():
# let's introduce them to our world
print ("Nice to meet you! What should I call you?")
player["name"] = raw_input("Please enter your name >")
# intro story, quick and dirty (think star wars style)
print ("Welcome to the isolated island " + player["name"] + "...")
print ("The story so far...")
print ("You wake up in the morning.")
print ("You found that you are in a strange place...")
print ("There's no body around you...")
print ("Do you want to go check what's happening?")
pcmd = raw_input("please choose yes or no >")
# the player can choose yes or no
if (pcmd == "yes"):
print ("You walk out the room, you found out that you are in a isolated island...")
raw_input("press enter >")
isolatedIsland()
else:
print ("No? ... That doesn't work here.")
pcmd = raw_input("press enter >")
introStory() # repeat over and over until the player chooses yes!
# main! most programs start with this.
def main():
printGraphic("title") # call the function to print an image
introStory() # start the intro
main() # this is the first thing that happens
|
517da59aa659529177df66df1956b0ba5ce74420 | JeremiahZhang/gopython | /data-analysis-with-python/demographic_data_analyzer.py | 4,915 | 4.15625 | 4 | import pandas as pd
def calculate_demographic_data(print_data=True):
# Read data from file
df = pd.read_csv('adult.data.csv', delimiter=',')
# How many of each race are represented in this dataset? This should be a Pandas series with race names as the index labels.
df_race = df.groupby('race')['age'].count().reset_index()
df_race = df_race.set_index('race')
race_count = df_race['age'].squeeze().sort_values(ascending=False)
# What is the average age of men?
df_male= df[df['sex'] == 'Male']
average_age_men = round(df_male.age.mean(), 1)
# What is the percentage of people who have a Bachelor's degree?
caseload = df.shape[0] # total
percentage_bachelors = round(df.education.value_counts().Bachelors / caseload * 100.0, 1)
# What percentage of people with advanced education (`Bachelors`, `Masters`, or `Doctorate`) make more than 50K?
# What percentage of people without advanced education make more than 50K?
# with and without `Bachelors`, `Masters`, or `Doctorate`
# people with adv education & make more than 50k
mask = ((df['education'] == 'Bachelors') |
(df['education'] == 'Masters') |
(df['education'] == 'Doctorate')) & (df['salary'] == '>50K')
higher_education = df[mask].shape[0]
# people with adv education
mask = (df['education'] == 'Bachelors') | (df['education'] == 'Masters') | (df['education'] == 'Doctorate')
num_higher = df[mask].shape[0]
# people without adv edu & make more than 50k
mask = df['salary'] == '>50K'
lower_education = df[mask].shape[0] - higher_education
# people without adv edu
num_lower = caseload - num_higher
# percentage with salary >50K
higher_education_rich = round(higher_education / num_higher * 100.0, 1)
lower_education_rich = round(lower_education / num_lower * 100.0, 1)
# What is the minimum number of hours a person works per week (hours-per-week feature)?
min_work_hours = df['hours-per-week'].min()
# What percentage of the people who work the minimum number of hours per week have a salary of >50K?
mask = (df['salary'] == '>50K') & (df['hours-per-week'] == min_work_hours)
num_min_worker_50K = int(df[mask].shape[0])
mask = df['hours-per-week'] == min_work_hours
total_min_worker = df[mask].shape[0]
rich_percentage = round(num_min_worker_50K / total_min_worker * 100.0, 1)
# What country has the highest percentage of people that earn >50K?
# how many people of each country
df_country_total = df.groupby(['native-country'])['age'].count().reset_index()
df_salary = df.groupby(['native-country', 'salary'])['age'].count().reset_index()
df_50k = df_salary[df_salary['salary'] != '>50K'].reset_index()
df_country_total['<=50K'] = df_50k['age']
df_country_total['per'] = (df_country_total['age'] - df_country_total['<=50K']) / df_country_total['age'] * 100.0
mask = df_country_total['per'] == df_country_total['per'].max()
highest_earning_country = df_country_total[mask]['native-country'].iloc[0]
highest_earning_country_percentage = round(df_country_total['per'].max(), 1)
# Identify the most popular occupation for those who earn >50K in India.
mask = df['salary'] == '>50K'
df2 = df[mask].groupby(['native-country', 'occupation'])['salary'].count().reset_index()
df3 = df2[df2['native-country'] == 'India']
india_occ_max = df3['salary'].max()
top_IN_occupation = df3[df3['salary'] == india_occ_max].iloc[0]['occupation']
# DO NOT MODIFY BELOW THIS LINE
if print_data:
print("Number of each race:\n", race_count)
print("Average age of men:", average_age_men)
print(f"Percentage with Bachelors degrees: {percentage_bachelors}%")
print(f"Percentage with higher education that earn >50K: {higher_education_rich}%")
print(f"Percentage without higher education that earn >50K: {lower_education_rich}%")
print(f"Min work time: {min_work_hours} hours/week")
print(f"Percentage of rich among those who work fewest hours: {rich_percentage}%")
print("Country with highest percentage of rich:", highest_earning_country)
print(f"Highest percentage of rich people in country: {highest_earning_country_percentage}%")
print("Top occupations in India:", top_IN_occupation)
return {
'race_count': race_count,
'average_age_men': average_age_men,
'percentage_bachelors': percentage_bachelors,
'higher_education_rich': higher_education_rich,
'lower_education_rich': lower_education_rich,
'min_work_hours': min_work_hours,
'rich_percentage': rich_percentage,
'highest_earning_country': highest_earning_country,
'highest_earning_country_percentage':
highest_earning_country_percentage,
'top_IN_occupation': top_IN_occupation
}
|
fb515b67143eef6346b524e334ea8101573fd560 | LacieNat/Algorithm-Practices | /coding interview book/Parenthesis.py | 939 | 3.625 | 4 | '''
Created on Oct 9, 2015
@author: lacie
'''
from collections import deque
queue = deque([])
list = []
def generateParenthesis(numOfPairs, numOfOpen, numOfClose, queue):
if numOfOpen == numOfClose and numOfOpen == numOfPairs:
st = ""
while len(queue) is not 0:
st += queue.popleft()
list.append(st)
return
if numOfOpen == numOfClose:
queue.append("(")
numOfOpen +=1
if numOfOpen is not numOfPairs:
queue2 = deque(queue)
queue3 = deque(queue)
queue3.append(")")
queue2.append("(")
generateParenthesis(numOfPairs, numOfOpen+1, numOfClose, queue2)
generateParenthesis(numOfPairs, numOfOpen, numOfClose+1, queue3)
else:
queue2 = queue
queue2.append(")")
generateParenthesis(numOfPairs, numOfOpen, numOfClose+1, queue2)
generateParenthesis(0, 0, 0, queue)
print(list) |
800eb1c5ea1b4d4353653d19a30d52d30724aec5 | won-cp/school-interface-four | /classes/interface.py | 2,323 | 3.65625 | 4 | from classes.school import School
class SchoolInterface:
def __init__(self, school_name):
self.school = School(school_name)
def run(self):
authenticated = self.authenticate_user()
if not authenticated:
print("Please enter the valid credentials.")
print()
authenticated_2 = self.authenticate_user()
if not authenticated:
print("Second attempt failed.")
return
while True:
mode = input(self.menu())
if mode == '1':
self.school.list_students()
elif mode == '2':
student_id = input('Enter student id:')
student_string = str(
self.school.find_student_by_id(student_id))
print(student_string)
elif mode == '3':
self.mode_3()
elif mode == '4':
student_id = input("Please enter the student's id:\n")
self.school.delete_student(student_id)
elif mode == '5':
break
def menu(self):
return "\nWhat would you like to do?\nOptions:\n1 list_students\n2 individul Student <student_id>\n3 add_student\n4 remove_student <student_id>\n5 quit\n"
def mode_3(self):
student_data = {'role': 'student'}
student_data['name'] = input('Enter student name:\n')
student_data['age'] = input('Enter student age: \n')
student_data['school_id'] = input(
'Enter student school id: \n')
student_data['password'] = input('Enter student password: \n')
self.school.add_student(student_data)
def authenticate_user(self):
employee_ids = []
for staff in self.school.staff:
employee_ids.append(staff.employee_id)
print("Welcome to Ridgemont High")
print("_________________________")
print("Please enter a valid employee id:")
id = input("")
print()
if (id not in employee_ids):
return False
print()
print("Please enter a valid password:")
pswrd = input("")
for staff in self.school.staff:
if (id == staff.employee_id and pswrd == staff.password):
return True
return False
|
f1103642d2a3d39a720223d5fbee1c718ede74b7 | EEEGUI/LeetCode | /606. Construct String from Binary Tree.py | 1,154 | 3.71875 | 4 | class Solution:
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
ans = ''
if not t:
return ''
stack = [t]
while stack:
node = stack.pop()
while node:
ans += str(node.val)
if node.right:
stack.append(node.right)
node = node.left
return ans
class Solution:
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if not t:
return ''
if not t.left and t.right:
return str(t.val) + '()' + '(' + str(self.tree2str(t.right)) + ')'
elif t.left and not t.right:
return str(t.val) + '(' + str(self.tree2str(t.left)) + ')'
elif not t.left and not t.right:
return str(t.val)
else:
return str(t.val) + '(' + str(self.tree2str(t.left)) + ')' + '(' + str(self.tree2str(t.right)) + ')'
class TreeNode:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right |
3fada598567b0e6df81d5d292b84edd4de9aa8ae | pangyouzhen/data-structure | /math_/7 reverse.py | 361 | 3.734375 | 4 | class Solution:
def reverse(self, x):
str_x = str(abs(x))
val = int("".join(str_x[::-1]))
if x < 0:
val = -val
if (-2 ** 31) <= val <= (2 ** 31):
return val
else:
return 0
if __name__ == '__main__':
sol = Solution()
res = sol.reverse(-120)
print(res)
|
d0359dfcec94eecba64a381c58b3f18faede2401 | dougfunny1983/Hello_Word_Python3 | /ex055.py | 342 | 3.9375 | 4 | print('''##############################
##Maior e menor da sequência##
##############################''')
print('→←'*30)
peso = []
for c in range(1,6):
peso.append(float(input(f'Digite o {c}º peso → Kg ')))
peso.sort()
print(f'O maior peso lido foi: {peso[4]} Kg')
print(f'o menor peso lido foi: {peso[0]} Kg')
print('→←'*30)
|
6fe89481e0f979e11c12395c96ba2ba83cc6364c | NakibHasan/Code-Examples | /Lab8P1.py | 604 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 22 13:23:23 2018
@author: hasna
"""
principal = (int(input("what is the principal amount:")))
annualcontrib = (int(input("what amount do you add per year:")))
growthrate = 1.05
years = (int(input("how many years do you want to invest:")))
def constantinvestment(principal, annualcontrib,growthrate, years):
invest = (principal + annualcontrib)*growthrate
for i in range(1,years):
invest = (invest + annualcontrib)*growthrate
return invest
print(constantinvestment(principal, annualcontrib,growthrate, years))
|
9b1fac7415526ae0bf56c9bfdc65a1800e6e98a6 | rrodenburg/prfl | /archive/transposetest.py | 289 | 3.53125 | 4 | import numpy as np
input = np.array(
[
[[1,2,3,4],[5,6,7,8],[9,10,11,12]],
[[13,14,15,16],[17,18,19,20],[21,22,23,24]]
]
)
#print(input.shape)
output = np.transpose(input,(1,2,0))
print(input.shape)
print(output.shape)
print(input)
print(output)
|
0c9e429c5a926bab7622108c4d8759f15fe2f857 | jianhui-ben/leetcode_python | /uber_oa_处理字符串.py | 1,072 | 3.71875 | 4 | #地里有过的面经, 就是给一个字符串string,里面只有 "W" "D" "L" 需要按照以下顺序排列
#1) 如果string 有“W”, 加到result 里, 输入的string remove这个“W” (每次只能remove一个)
#2) 如果string 有“D”, 加到result 里, 输入的string remove这个“D” (每次只能remove一个)
#3) 如果string 有“L”, 加到result 里, 输入的string remove这个“L” (每次只能remove一个)
#4) 如果输入字符串没有 "W" "D" "L" , return result 不然从step 1重复
# example: "LDWDL" -> 输出 "WDLDL"
s = 'LDWDL'
def process(s):
## ordered dictionary
import collections
temp = {'W':0, 'D':0, 'L':0}
for i in s:
temp[i]+=1
## use a deque
stored = collections.deque()
for i, v in temp.items():
if v>0:
stored.append((i, v))
res=''
while stored:
cur_let, v = stored.popleft()
if v==0:
continue
res+=cur_let
stored.append((cur_let, v-1))
return res
print(process(s))
|
f07c389047d92c5e2c853751376bebbfe5e4ce37 | okhster/Python | /Lecture Notes/Lect3-1stFunction4.py | 70 | 3.5 | 4 |
x=1
y=2
z=3
def f(x,y):
sum = x+y
sum=sum*sum
print sum
|
3ca7e36467f4f7336bf34c8789688eb12c5d3e4b | vipinvkmenon/canddatastructures_python | /chapter10/example3.py | 277 | 3.703125 | 4 | # Chapter 10.3
#Parameter Passing
def main(): # Main Function
i = 0
print("The value of i before call " + str(i))
f1(i)
print("The value of i after call " + str(i))
def f1(k): # Function f1
k = k +1
main() # Main Function entry
|
eed260d82f60d919847c61cadd5ac7c729039a52 | jugomo/python_review | /basics/numtypes.py | 337 | 3.53125 | 4 | """
Data types - Python
Author: Julio Gonzalez
"""
a = 13
b = -66
c = 33.6 #float
d = 3+6j #complex
e = 0B101 #binary
f = 0XFF1 #hex
g = False #boolean
print(a ,b)
print(type(b))
print(type(c))
cc = int(c)
print(type(cc))
print(d)
print(type(d))
print(e)
print(type(e))
print(f)
print(type(f))
print(g)
print(type(g)) |
93145fa4c8f52873435e18a872398b1d8b1b34c3 | AdityaWadkar/Python-Calculator | /calculator.py | 1,570 | 3.546875 | 4 | from tkinter import *
import tkinter.messagebox as t
a,y,yz,aw=0,70,"red","pink"
def click(event):
global s
text = event.widget.cget("text")
if text == "=":
a=s.get()
if "^" in s.get():
a=a.replace("^","**")
try:
value=eval(a)
s.set(value)
screen.update()
except Exception as e:
t.showerror("Error!!","Please select 2 numbers")
elif text =="C":
s.set("")
screen.update()
else:
s.set(s.get()+text)
screen.update()
root=Tk()
root.geometry("335x420")
root.title("Calculator")
root.config(bg="#FFDEAD")
s=StringVar()
s.set("")
screen =Entry(root,textvar=s, font="verdena 20 bold",justify=RIGHT)
screen.pack(pady=10)
text = ("7", "8", "9", "C", "4", "5", "6", "+", "1", "2", "3", "-", "^", "0", ".", "x")
def button (text,l,m):
if text =="-" or text == "." or text=="/":
f=9
else:
f=6
b = Button(root,text=text, font="lucida 20 bold", padx=f, pady=0,activeforeground=yz,bg=aw)
b.place(x=l,y=m)
b.bind("<Button-1>", click)
for m in range(4):
x=27
for l in range (4):
button(text[a],x,y)
a=a+1
x=x+80
y=y+70
b = Button(root,text="/", font="lucida 20 bold", width=3, height=1,activeforeground=yz,bg=aw)
b.place(x=267,y=350)
b.bind("<Button-1>", click)
b = Button(root,text="=", font="lucida 20 bold", width=13, height=1,activeforeground=yz,bg=aw)
b.place(x=23,y=350)
b.bind("<Button-1>", click)
root.mainloop() |
a3fd72ccd2e1f5716b2a3d7dd42a39a8cdf086e9 | hizircanbayram/Graduation-Project | /UNet/DataProcessing/quick_processing.py | 6,618 | 3.875 | 4 | import os
def delete_unnecessary_files(dir_path):
'''
Given a directory path, this function deletes the images created by pixel annotation tool that we dont wan't to.
'''
file_names = os.listdir(dir_path)
for file_name in file_names:
if ('_mask' not in file_name) or ('_color_mask' in file_name):
continue
else:
os.remove(dir_path + '/' + file_name)
print('unnecessary files are deleted')
def is_dir_name_okay(dir_path):
'''
Given a directory path, this function checks if the directory name is valid or not. It determines this by following the convention: name_(hand no)
'''
def is_possible_movement(possible_num_str):
if (possible_num_str == '0') or (possible_num_str == '1') or (possible_num_str == '2') or (possible_num_str == '3') or (possible_num_str == '4') or \
(possible_num_str == '5') or (possible_num_str == '6') or (possible_num_str == '7') or (possible_num_str == '8') or (possible_num_str == '9') or (possible_num_str == '10'):
return True
else:
return False
parsed_dir_path = dir_path.split('/')
dir_name = parsed_dir_path[len(parsed_dir_path) - 1]
parsed_dir_names = dir_name.split('_')
if not is_possible_movement(parsed_dir_names[0]):
print(dir_name, ' is not a valid name, correct it.')
else:
print(dir_name, ' is a valid name.')
def change_file_names(dir_path):
'''
Given a directory path, this function changes the name of the images that we need generated by pixel annotation tool.
Naming convention follows the convention: (dir name that holds the video this frame taken from)-(frame no of the video)-(hand movement no)-(colormask.png)
'''
def move_color_mask_first(file_name):
color_mask_indice = file_name.find("_color_mask")
vid_name = file_name[:color_mask_indice]
file_name = 'colormask-' + vid_name + '.png'
return file_name
def change_underscore_to_hyphen(file_name):
k = len(file_name) - 1
file_name = list(file_name)
while k >= 0:
if file_name[k] == '_':
file_name[k] = '-'
break
k -= 1
file_name = ''.join(file_name)
return file_name
def move_color_mask_last(file_name):
name_without_colormask = file_name[len('-colormask'):]
name_withour_extension = name_without_colormask[:len(name_without_colormask) - 4]
file_name = name_withour_extension + '-colormask' + '.png'
return file_name
file_names = os.listdir(dir_path)
for file_name in file_names:
new_file_name = file_name
if '_color_mask' in file_name:
new_file_name = move_color_mask_first(file_name)
new_file_name = change_underscore_to_hyphen(new_file_name)
parsed_dir_path = dir_path.split('/')
dir_name = parsed_dir_path[len(parsed_dir_path) - 1]
parsed_dir_names = dir_name.split('_')
new_file_name = new_file_name[:len(new_file_name) - 4] + '-' + parsed_dir_names[0] + new_file_name[len(new_file_name) - 4:]
if 'colormask-' in new_file_name:
new_file_name = move_color_mask_last(new_file_name)
os.rename(dir_path + '/' + file_name, dir_path + '/' + new_file_name)
def detect_missing_files(normal_dir_path, segmented_dir_path):
'''
Given both directories that contain normal and segmented images, this function checks if an image in either directory has its corresponding image in the other directory.
If it does not, the image is moved to UnetDatasetProcedure/again/name_(hand no) and log file is updated.
'''
def check_equal_dirs(normal_dir_path, segmented_dir_path):
normal_files = os.listdir(normal_dir_path)
segmented_files = os.listdir(segmented_dir_path)
for normal_file in normal_files:
found = False
normal_file = normal_file[:-4]
for segmented_file in segmented_files:
segmented_file = segmented_file[:-14]
if normal_file == segmented_file:
found = True
break
if not found:
print(normal_file)
normal_files = os.listdir(normal_dir_path)
segmented_files = os.listdir(segmented_dir_path)
copy_normal = normal_files.copy()
copy_segmented = segmented_files.copy()
segmented_bigger = False
equal_file = False
i = 0
while i < len(normal_files):
normal_files[i] = normal_files[i][:-4]
i += 1
k = 0
while k < len(segmented_files):
segmented_files[k] = segmented_files[k][:-14]
k += 1
if len(normal_files) >= len(segmented_files):
bigger_files = normal_files
smaller_files = segmented_files
bigger_path = normal_dir_path
segmented_bigger = False
elif len(normal_files) < len(segmented_files):
bigger_files = segmented_files
smaller_files = normal_files
bigger_path = segmented_dir_path
segmented_bigger = True
for i, bigger_file in enumerate(bigger_files):
found = False
for smaller_file in smaller_files:
if smaller_file == bigger_file:
found = True
break
if not found:
parsed_bigger_path = bigger_path.split('/')
with open("errors.log", "a") as logfile:
if segmented_bigger:
logfile.write('DETECT MISSING FILES: ' + copy_segmented[i] + ' can not be found in the directory ' + bigger_path + '\n')
os.rename(bigger_path + '/' + copy_segmented[i], 'UnetDatasetProcedure/again' + '/' + parsed_bigger_path[len(parsed_bigger_path) - 1] + '/' + copy_segmented[i])
else:
logfile.write('DETECT MISSING FILES: ' + copy_normal[i] + ' can not be found in the directory ' + bigger_path + '\n')
os.rename(bigger_path + '/' + copy_normal[i], 'UnetDatasetProcedure/again' + '/' + parsed_bigger_path[len(parsed_bigger_path) - 1] + '/' + copy_normal[i])
if (i != 0) and (i % 100 == 0):
print('100 files are processed')
parent_dir = 'UnetDatasetProcedure'
dir_name = '1_mustafa'
dir_path = parent_dir + '/' + dir_name
# errors.log ' u her isleme oncesi yeniden yarat ki temizlensin
delete_unnecessary_files(dir_path)
is_dir_name_okay(dir_path)
change_file_names(dir_path)
detect_missing_files('UnetDataset/normal/' + dir_name, 'UnetDataset/segmented/' + dir_name)
|
9d9743052e65922ac142508ecc66d6d5433adcb1 | AK5123/coding-prep | /solved_problems/candies.py | 570 | 3.828125 | 4 | # https://www.hackerearth.com/challenges/competitive/hackerearth-test-draft-3-115/problems/c288d26a1c724b01be096c3ac6e919da/
def extra_candy (n, candies, extra_candies):
# Write your code here
big = max(candies)
res = []
for i in candies:
if i+extra_candies >= big:
res.append(1)
else:
res.append(0)
return res
pass
n = int(input())
candies = list(map(int, input().split()))
extra_candies = int(input())
out_ = extra_candy(n, candies, extra_candies)
print (' '.join(map(str, out_))) |
668d6cc68666593b70fd6c31435f79ca02509bfd | sbbasak/CIT_ES_PP_2001_Assignment-1 | /name+age.py | 220 | 4.40625 | 4 |
# 2.Enter your Name And age and show it in your screen.
print('Enter your name:')
your_name = input()
print('Enter your age:')
your_age = input()
print('Hi!' + your_name + ' you are ' + your_age + ' years old.') |
f91784e33a7cc06f457c03f18c4a729fd623b55f | mwaskom/seaborn | /seaborn/objects.py | 2,208 | 3.515625 | 4 | """
A declarative, object-oriented interface for creating statistical graphics.
The seaborn.objects namespace contains a number of classes that can be composed
together to build a customized visualization.
The main object is :class:`Plot`, which is the starting point for all figures.
Pass :class:`Plot` a dataset and specify assignments from its variables to
roles in the plot. Build up the visualization by calling its methods.
There are four other general types of objects in this interface:
- :class:`Mark` subclasses, which create matplotlib artists for visualization
- :class:`Stat` subclasses, which apply statistical transforms before plotting
- :class:`Move` subclasses, which make further adjustments to reduce overplotting
These classes are passed to :meth:`Plot.add` to define a layer in the plot.
Each layer has a :class:`Mark` and optional :class:`Stat` and/or :class:`Move`.
Plots can have multiple layers.
The other general type of object is a :class:`Scale` subclass, which provide an
interface for controlling the mappings between data values and visual properties.
Pass :class:`Scale` objects to :meth:`Plot.scale`.
See the documentation for other :class:`Plot` methods to learn about the many
ways that a plot can be enhanced and customized.
"""
from seaborn._core.plot import Plot # noqa: F401
from seaborn._marks.base import Mark # noqa: F401
from seaborn._marks.area import Area, Band # noqa: F401
from seaborn._marks.bar import Bar, Bars # noqa: F401
from seaborn._marks.dot import Dot, Dots # noqa: F401
from seaborn._marks.line import Dash, Line, Lines, Path, Paths, Range # noqa: F401
from seaborn._marks.text import Text # noqa: F401
from seaborn._stats.base import Stat # noqa: F401
from seaborn._stats.aggregation import Agg, Est # noqa: F401
from seaborn._stats.counting import Count, Hist # noqa: F401
from seaborn._stats.density import KDE # noqa: F401
from seaborn._stats.order import Perc # noqa: F401
from seaborn._stats.regression import PolyFit # noqa: F401
from seaborn._core.moves import Dodge, Jitter, Norm, Shift, Stack, Move # noqa: F401
from seaborn._core.scales import ( # noqa: F401
Boolean, Continuous, Nominal, Temporal, Scale
)
|
e538eaf3f4be947c62b46a202e0ec37ad26de491 | chesterking123/Leet-Code | /.ValidSudoku.py | 774 | 3.578125 | 4 | class Solution(object):
def isValidSudoku(self, board):
for row in board:
row = [x for x in row if x!= '.']
if(len(row)!=len(set(row))):
return False
col_board = [i for i in zip(*board)]
for row in col_board:
row = [x for x in row if x!= '.']
if(len(row)!=len(set(row))):
return False
blocks=[]
for i in range(0,9,3):
for j in range(0,9,3):
blocks.append(board[i][j:j+3] + board[i+1][j:j+3] + board[i+2][j:j+3])
for row in blocks:
row = [x for x in row if x!= '.']
if(len(row)!=len(set(row))):
return False
return(True)
|
44291f5f7667aeeaa79fb60ecd98016eec05d8db | Krishna3-cloud/salarypredicter-ml-model | /salarypredict.py | 256 | 3.5625 | 4 | import joblib
pred_model=joblib.load("Salarypredicter-model.pk1")
#Now to predict salary
p=int(input("Enter years of experience-: "))
sal=pred_model.predict([[p]])
#Now print the predicted salary
print("Estimated Salary is: ", round(sal[0],2), "INR.")
|
2f70882e135fc5417eefc13a0365ec46a7b1630c | prodevans-technologies/vipin-prodevans | /Python/prime.py | 312 | 4.15625 | 4 | '''
Python Script to check whether entered number is prime or not
'''
n=int(raw_input('Enter number : '))
print(n)
flag=False
for i in range(2,n):
if n%i==0:
flag=True
break
else:
flag=False
if flag:
print("Not Prime")
else:
print("prime number")
|
91ea9b0f3390fd3b738080eb827779f3a051ee6a | Aasthaengg/IBMdataset | /Python_codes/p03424/s935030063.py | 70 | 3.53125 | 4 | n=int(input())
s=input()
if 'Y' in s:print("Four")
else:print("Three") |
13308edb6d00d20dce3348c942d8ab6a234f46a1 | yashgitwork/Python | /User_input.py | 159 | 3.90625 | 4 | name = input("What is your name?")
print (name)
age= input("What is your age?")
age=int(age)
print(age)
pi = input("value of pi?")
pi = float(pi)
print(pi)
|
fc9697943050e12c3674ddbfa65e6815449da035 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/algorithms-master/algorithms/dp/planting_trees.py | 1,921 | 4.34375 | 4 | """
An even number of trees are left along one side of a country road. You've been assigned the job to
plant these trees at an even interval on both sides of the road. The length L and width W of the road
are variable, and a pair of trees must be planted at the beginning (at 0) and at the end (at L) of
the road. Only one tree can be moved at a time. The goal is to calculate the lowest amount of
distance that the trees have to be moved before they are all in a valid position.
"""
from math import sqrt
import sys
def planting_trees(trees, L, W):
"""
Returns the minimum distance that trees have to be moved before they are all in a valid state.
Parameters:
tree (list<int>): A sorted list of integers with all trees' position along the road.
L (int): An integer with the length of the road.
W (int): An integer with the width of the road.
Returns:
A float number with the total distance trees have been moved.
"""
trees = [0] + trees
n_pairs = int(len(trees) / 2)
space_between_pairs = L / (n_pairs - 1)
target_locations = [location * space_between_pairs for location in range(n_pairs)]
cmatrix = [[0 for _ in range(n_pairs + 1)] for _ in range(n_pairs + 1)]
for ri in range(1, n_pairs + 1):
cmatrix[ri][0] = cmatrix[ri - 1][0] + sqrt(
W + abs(trees[ri] - target_locations[ri - 1]) ** 2
)
for li in range(1, n_pairs + 1):
cmatrix[0][li] = cmatrix[0][li - 1] + abs(trees[li] - target_locations[li - 1])
for ri in range(1, n_pairs + 1):
for li in range(1, n_pairs + 1):
cmatrix[ri][li] = min(
cmatrix[ri - 1][li]
+ sqrt(W + (trees[li + ri] - target_locations[ri - 1]) ** 2),
cmatrix[ri][li - 1] + abs(trees[li + ri] - target_locations[li - 1]),
)
return cmatrix[n_pairs][n_pairs]
|
91acb3b85fba71beb1a56798166474ca1274efa2 | LeeTeng2001/SJTU-ITE-Project-Platform | /app/testing/local_function.py | 310 | 3.515625 | 4 | import datetime
import random
# sd = datetime.date(2020, 1, 2)
# ed = datetime.date(2020, 12, 1)
def random_date_between(d1, d2=datetime.date.today()):
time_difference = d2 - d1
new_time = d1 + datetime.timedelta(seconds=int(time_difference.total_seconds() * random.random()))
return new_time
|
437d354adc62a7d38f1bfc6b03ee1fbdcd87dc3c | delmondesfe/python_jogos | /forca.py | 848 | 3.984375 | 4 | def jogar():
print("*********************************")
print("***Bem vindo ao jogo da Forca!***")
print("*********************************")
palavra_secreta = "python"
letras_acertadas = ["_","_","_","_","_","_"]
enforcou = False
acertou = False
print("A palavra secreta contem {} letras".format(len(letras_acertadas)))
print(letras_acertadas)
while (not enforcou and not acertou ):
chute = input ("Qual a letra?: ")
chute = chute.strip()
index = 0
for letra in palavra_secreta:
if (chute.upper() == letra.upper()):
letras_acertadas[index] = letra
index = index + 1
print(letras_acertadas)
print("Fim do jogo")
if(__name__ == "__main__"):
jogar() |
a0fd4052e638f0a4028ae18a329f6236babb05ab | MasiaMatteo03/SistemiEReti | /pytohn_natale/es4_rot15.py | 767 | 4.0625 | 4 | def encode(string):
strEnc = ""
for elemento in string:
elemento = ord(elemento) + 15
elemento = chr(elemento)
strEnc = strEnc + elemento
print(strEnc)
def decode(string):
strDec = ""
for elemento in string:
elemento = ord(elemento) - 15
elemento = chr(elemento)
strDec = strDec + elemento
print(strDec)
def main():
choice = int(input("Inserisci 1 se devi decriptare la stringa o 2 per criptarla: "))
if choice == 1:
string = str(input("inserisci la stringa da decriptare: "))
decode(string)
elif choice == 2:
string = str(input("inserisci la stringa da criptare: "))
encode(string)
if __name__ == "__main__":
main() |
3f01526070a2362c5622c147f399d46839ea3342 | mlee177/sc_1 | /badgenerator.py | 684 | 3.84375 | 4 | #!/bin/env python
import random
def changeCase(char):
return char.lower if char.isupper() else char.upper()
def repeat(char):
return char * random.randint(1,4)
def changevowel(char):
return random.choice([vowel for vowel in 'aeiou' if vowel is not char])
for i in range(50):
word = random.choice(list(open('wordsEn.txt'))).strip()
output = ""
for char in word:
if char in 'aeiouAEIOU':
output += changevowel(char)
else:
output += char
output2 = ""
for char in output:
output2 += repeat(char)
output = ""
for char in output2:
if random.randint(0,1):
output += changeCase(char)
else:
output += char
print(word)
print(output)
print("")
|
4759121df92cbcb435acc15380147b6e49338089 | kanwal07/Playing-with-Python | /Some more exercises/Question5.py | 600 | 4.09375 | 4 | #question5
#pseudo- input two strings and the index,
#traverse through the first string till i reach the index and match the other string,
#if match then true else false
def substring(s1,s2,k):
if((s1.index(s2,k)) == k):
print ("True")
else:
print("False")
s1 = input("Enter a string: ")
s2 = input("Enter the substring: ")
index = int(input("Enter the index of the substring: "))
substring(s1,s2,index)
# index()- takes up 3 arguments
# index(substring,start position, optional end position)
# match the substring with index as the start position and return true/false |
430e77f9955546fd63613d4e75ddcf9c72e0fc7e | Pabloold/python | /task2-2.py | 582 | 3.53125 | 4 | my_list = []
user_count = input('Введите количество элементов в списке ')
if not user_count.isdigit():
print('Введён неверный формат числа')
exit()
count = int(user_count)
my_list.append(int(input('Введите первое число списка: ')))
i = 1
while i < count:
my_list.append(int(input('Введите следующее число списка: ')))
i += 1
print(my_list)
for a in range(1, len(my_list), 2):
my_list[a - 1], my_list[a] = my_list[a], my_list[a - 1]
print(my_list) |
d80bef70ea3b9612f68b9bd1ea1c7afbd9986a00 | sirbowen78/lab | /filter_function_examples/using_filter.py | 1,418 | 4.3125 | 4 | # Populate the numbers.
numbers = [x for x in range(1, 51)]
# so far the best and shortest way to check prime number:
# https://www.tutorialgateway.org/python-program-to-find-prime-number/
def is_prime(num):
count = 0
for i in range(2, (num // 2 + 1)):
if num % i == 0:
count += 1
break
if count == 0 and num !=1:
return True
else:
return False
if __name__ == '__main__':
print("Original list of numbers:")
print(numbers)
# filter takes in the function and iterables: tuple, set, list as arguments.
# the first argument only requires to pass in the function name without the ().
# the first argument is a function that does the evaluation of True or False.
# filter(is_prime, numbers) is the same as below:
# for num in numbers:
# if is_prime(num):
# prime_only_numbers.append(num)
prime_only_numbers = filter(is_prime, numbers)
print("Prime numbers found within the original list:")
print([prime_number for prime_number in prime_only_numbers])
'''
The results:
Original list of numbers:
[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, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
Prime numbers found within the original list:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
''' |
4e6d5c47dc808301f3a77c6238d610abc1c2ecb2 | Eleveil/leetcode | /Python/count-and-say.py | 2,706 | 4.0625 | 4 |
'''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
'''
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
# Approach #1 复杂的逻辑……
# ans = '1'
# num = 1
# while n != num:
# loc = []
# length = len(ans) - 1
# ori_ans = ans
# for i in range(length):
# if ori_ans[i] != ori_ans[i+1]:
# if loc != []:
# ans += str(len(ori_ans[loc[-1]:i+1])) + str(ori_ans[i])
# else:
# ans = str( len(ori_ans[:i+1])) + str(ori_ans[0])
# loc.append(i+1)
# if length == i+1:
# ans += str( len(ori_ans[loc[-1]:i+2])) + str(ori_ans[i+1])
# elif loc != [] and length == i+1:
# ans += str( len(ori_ans[loc[-1]:i+2])) + str(ori_ans[i+1])
# elif i+1 == length:
# ans = str(length + 1) + ans[0]
# if length == 0: ans = '1' + ans
# num += 1
# return ans
#Approach #2
# import itertools
# ans='1'
# for i in range(1,n):
# v=''
# for digit,group in itertools.groupby(ans): #itertools.groupby(ans) 函数默认将一个字符串按照连续相同的部分分割。返回的迭代器有两个成分,一个是分割的元素,另一部分是分割的字符串
# v+=str(len(list(group)))+digit
# ans=v
# return ans
# Approach #3 相比于Approach 1 新建一个变量let表示字符,就可以避免复杂易错的数组操作; ans只有在每次循环结束时才变化,需要复制一份。
ans = '1'
for _ in range(n-1):
let, temp, count = ans[0], '', 0
for l in ans:
if let == l:
count += 1
else:
temp += str(count)+let
let = l
count = 1
temp += str(count)+let # 处理最后一个字符串片段
ans = temp
return ans
|
bd5d3247ad6d85df9424ec92519ad32d3858610a | nayansethia/Nayan_Sethia_Assignments | /Nayan_Sethia_AWS_Assignment_1/Question 2/ns-aws-q2-script.py | 1,165 | 3.671875 | 4 | import boto3
s3 = boto3.resource('s3')
print("Enter the name of bucket")
my_bucket = s3.Bucket(input()) #to get bucket name as input from user
print("Enter the name of object")
obj=input() #to get object name as input from user
l= s3.list_object_versions(Bucket=my_bucket, Prefix=obj) #l will be the dictionary that will contain information about all the versions of object having prefix obj from bucket specified by user
objver= l['Versions'] #objver will contain list of information about versions of object
objversorted=sorted(objver, key='LastModified') #sorting the list according to the time last modified
desiredobj=objversorted(-2) #second last version of object will get placed at -2 index position that is at second last position
objid=desiredobj['VersionId'] #objid will contain version id of the desiredobj, this desiredobj is actually a dictionary
s3.download_file(bucket, file, file, ExtraArgs={'VersionId': objid}) #to download the desired version of the object
|
dd66b2f6e430640a4372e7ad5a79adda48ce75ec | josemgoujat/adventofcode2019 | /day-1/day-1.py | 652 | 3.71875 | 4 | """
https://adventofcode.com/2019/day/1
"""
with open('day-1.input', 'r') as input_f:
modules_mass = [int(line) for line in input_f.read().splitlines()]
# Star 1
def simple_fuel_calculator(mass):
return mass // 3 - 2
answer_1 = sum(map(simple_fuel_calculator, modules_mass))
print(f'Answer 1: {answer_1}')
# Star 2
def accurate_fuel_calculator(mass):
required_fuel_mass = simple_fuel_calculator(mass)
if required_fuel_mass <= 0:
return 0
else:
return required_fuel_mass + accurate_fuel_calculator(required_fuel_mass)
answer_2 = sum(map(accurate_fuel_calculator, modules_mass))
print(f'Answer 2: {answer_2}')
|
503af83972d7aef051f9603e5b34c5d1c0c09900 | frwp/School | /Semester V/Kripto/exor.py | 2,146 | 3.5 | 4 | # Fungsi enkripsi
def encrypt(plain,password):
plainIntVector = []
for i in range(len(plain)):
plainIntVector.append(ord(plain[i]))
passwordIntVector = []
# inisiasi variabel baru untuk membuat setiap perubahan yang terjadi pada
# password akan menyebabkan avalanche effect
# variabel ini berisi jumlahan dari nilai ascii password dipangkatkan
# panjang password mod 256, agar tidak melebihi jumlah ascii
added_value = pow(sum([ord(i) for i in password]), len(password), 256)
for i in range(len(password)):
passwordIntVector.append((ord(password[i]) + added_value) % 256)
# fungsi lainnya tidak berubah
plainIndex = 0
cipherIntVector = []
while plainIndex < len(plain):
for i in range(len(password)):
if plainIndex == len(plain):
break
oneCharCipher = plainIntVector[plainIndex]^passwordIntVector[i]
cipherIntVector.append(oneCharCipher)
plainIndex += 1
return cipherIntVector
def decrypt(cipherIntVector,password):
passwordIntVector = []
# fungsi yang sama seperti fungsi cipher juga dimasukkan di sini
# agar decipher menghasilkan karakter yang sama
added_value = pow(sum([ord(i) for i in password]), len(password), 256)
for i in range(len(password)):
passwordIntVector.append((ord(password[i]) + added_value) % 256)
cipherIndex = 0
plainIntVector = []
while cipherIndex < len(cipherIntVector):
for i in range (len(password)):
if cipherIndex == len(cipherIntVector):
break
oneCharPlain = cipherIntVector[cipherIndex]^passwordIntVector[i]
plainIntVector.append(oneCharPlain)
cipherIndex += 1
plain = ''
for i in range(len(plainIntVector)):
plain = plain + chr(plainIntVector[i])
return plain
plain = input("Plain text: ")
password = input("Password: ")
cipher = encrypt(plain, password)
print ("Cipher: ", end='')
print(cipher)
print("Cipher in hex:", end=" ")
for i in cipher:
print(f"{i:02X}", end=" ")
print()
print("Plain: " + decrypt(cipher,password))
|
b9a4d347e8439401fb4bec60b41f7efd12eca62c | yashsinghal07/Music-Player | /Project_gui/list_box.py | 744 | 3.765625 | 4 | from tkinter import *
from tkinter import simpledialog,messagebox
def show():
pos=lbl.curselection()
if(len(pos)==0):
messagebox.showerror("NO Selection","please select atleast one of them")
else:
sname=lbl.get(pos[0])
lbl1.config(text="you selected "+sname)
root=Tk()
root.geometry("300x300")
lbl=Listbox(root)
sports=["cricket","football","basketball","kanchey"]
#pos=0
for s in sports:
#lbl.insert(pos,s)
#pos+=1
lbl.insert(END,s)
lbl.grid(row=1,column=0,sticky=W)
btn1=Button(root,text=" Choose game ",command=show)
btn1.grid(row=2,column=0,sticky=W)
lbl1=Label(root)
lbl1.grid(row=3,column=0,sticky=W)
root.mainloop()
# lbl.delete(first,last=none)
# lbl.size() |
f49b9ff6252a022a3c9467c26214269e15301e63 | ihuei801/leetcode | /MyLeetCode/FB/Count and Say.py | 606 | 3.5625 | 4 | ###
# Time Complexity: O(2^n) len grows up to double
# Space Complexity: O(2^n)
###
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return "1"
s = "1"
for i in xrange(1, n):
cnt = 1
tmp = ""
for j in xrange(1, len(s)):
if s[j] != s[j-1]:
tmp += str(cnt) + s[j-1]
cnt = 1
else:
cnt += 1
tmp += str(cnt) + s[-1]
s = tmp
return s |
0e59284ad0349cd83f1a4fcdc85bf0c418b4f1ca | Marusya-ryazanova/Lesson_5 | /Les.5.6.py | 264 | 3.921875 | 4 | some_dict = {'first_color': 'Red', 'second_color': 'Green', 'third_color': None}
def remove_empty(some_dict: dict) -> dict:
some_dict = {key: value for key, value in some_dict.items() if value is not None}
return some_dict
print(remove_empty(some_dict)) |
caf6175abec3ecf7613e926e68acf491b960b6b9 | sachinarya9/python_concepts | /clas_inheritance.py | 378 | 3.875 | 4 | class Bird:
def __init__(self,name,age):
self.name = name
self.age = age
def whoisthis():
print('Bird')
def swim():
print('Swim faster')
class Penguin(Bird):
def __init__(self,name,age):
print('This is a Penguin')
super.__init__(self,name,age)
def whoisthis():
print('Penguin')
def run():
print('Run faster')
peng = Penguin('Penguin',22)
peng.whoisthis() |
0ab76d3e5a8ea11295a06bb63725f9e86facf4b6 | daimingzhong/Leetcode-Python | /src/leetcode/class0/best_practice.py | 331 | 3.78125 | 4 | import sys
from typing import List
# arr: List[int]
def max_int():
max_int_in_python3 = sys.maxsize
min_int_in_python3 = -sys.maxsize - 1
def swap(arr, fast, slow):
# 交换两个数, e.x. arr = [1,3,2]
tmp = arr[fast]
arr[fast]= arr[slow]
arr[slow] = tmp
arr[fast], arr[slow] = arr[slow], arr[fast] |
d17907bce11fca03f4226d3c551909c209026769 | dankoga/URIOnlineJudge--Python-3.9 | /URI_1146.py | 170 | 3.890625 | 4 | number_max = int(input())
while number_max > 0:
numbers_str = ' '.join(str(n) for n in range(1, number_max + 1))
print(numbers_str)
number_max = int(input())
|
a75ed6066d305f785823d93cea5f77104e84bb46 | python20180319howmework/homework | /huangyongpeng/20180328/h8.py | 132 | 3.953125 | 4 |
'''
删除元祖中的所有重复的元素,并生成一个列表
'''
t=(1,1,2,3,5,6,6,5,8)
s=set(t)
l=[]
l.append(s)
print(l)
|
cfe82ad42511f5d827c51366ae1d66faef89520e | rsreenivas2001/LabMain | /Sem 4/ps2/2.py | 407 | 4.09375 | 4 | from math import sqrt
def distance(u, v):
total = 0
for x, y in zip(u, v):
# print(x, y)
total += pow(y - x, 2)
# print(total)
print("The distance is : ", sqrt(total))
if __name__ == '__main__':
u1 = list(map(int, input('Enter CoOrdinates of 1st point : ').split()))
v1 = list(map(int, input('Enter CoOrdinates of 2nd point : ').split()))
distance(u1 ,v1) |
f5c54b3a8c811a3308cee1b57d098838a717cbb8 | Zhenye-Na/leetcode | /python/673.number-of-longest-increasing-subsequence.py | 2,156 | 3.75 | 4 | #
# @lc app=leetcode id=673 lang=python3
#
# [673] Number of Longest Increasing Subsequence
#
# https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/
#
# algorithms
# Medium (38.40%)
# Likes: 2157
# Dislikes: 116
# Total Accepted: 76.3K
# Total Submissions: 197.7K
# Testcase Example: '[1,3,5,4,7]'
#
# Given an integer array nums, return the number of longest increasing
# subsequences.
#
# Notice that the sequence has to be strictly increasing.
#
#
# Example 1:
#
#
# Input: nums = [1,3,5,4,7]
# Output: 2
# Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1,
# 3, 5, 7].
#
#
# Example 2:
#
#
# Input: nums = [2,2,2,2,2]
# Output: 5
# Explanation: The length of longest continuous increasing subsequence is 1,
# and there are 5 subsequences' length is 1, so output 5.
#
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 2000
# -10^6 <= nums[i] <= 10^6
#
#
#
# @lc code=start
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
if not nums or len(nums) == 0:
return 0
n = len(nums)
# initialization
# length[i] represents, the length of LIS ending with nums[i]
# counts[i] represents, how many subarray ending with nums[i] have the max length of LIS
length = [1 for _ in range(n)]
counts = [1 for _ in range(n)]
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]:
if length[j] + 1 > length[i]:
# update length and counts
length[i] = length[j] + 1
counts[i] = counts[j]
elif length[j] + 1 == length[i]:
# current length is already the same
# update counts
counts[i] += counts[j]
max_len = 0
res = 0
for i in range(n):
if length[i] > max_len:
max_len = length[i]
res = counts[i]
elif length[i] == max_len:
res += counts[i]
return res
# @lc code=end
|
ebc0e8c8cc28b943dd5ec0699fcf700c389d6e8d | SimonDef/learn_vocab_web | /app/learnvocab.py | 1,400 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 18 17:35:52 2017
@author: simondefrenet
"""
import random
WORDLIST_FILENAME = "French words - Sheet2Fr.csv"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline().strip() # get the first line in line
word = line.split(',')
global language1
global language2
language1=word[0]
language2=word[1]
dictionnary=[]
line = inFile.readline().strip() # get the first line in line
i=0
while line:
word = line.split(',')
dictionnary+=[word]
line = inFile.readline().strip() # get the next line in line
i+=1
# wordlist: list of strings
return dictionnary
def chooseWord(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
dictionnary = loadWords()
'''
elif test=="chooseenglish":
choose("english")
elif test=="choosecantonese":
choose("cantonese")
'''
|
020362e264c9ba886af0519953b379afdec52ee1 | henridvf/katas | /directorytree.py | 772 | 3.71875 | 4 |
# 1. sort list to make split immediately useable
# 2. split each list item on '/'
# 3. loop through each part and create (nested) folder if needed
def directoryTree(lst):
tree = 'Desktop\n'
for item in sorted(lst):
for part in item.split('/'):
if not part in tree:
if not '.' in part:
tree += f'\{part}'
else:
return tree
files = [
'meetings/2021-01-12/notes.txt',
'meetings/2020_calendar.xlsx',
'meetings/2021-01-12/report.pdf',
'misc/photos/forest_20130430.jpg',
'misc/photos/sunset_20130412.jpg',
'scripts/tree.py',
'meetings/2021-01-24/report.pdf',
]
print(directoryTree(files))
|
66e5b4141e205feed66a7af68567b938855c1f58 | LabForComputationalVision/pyPyrTools | /pyPyrTools/steer2HarmMtx.py | 2,255 | 3.796875 | 4 | import numpy
def steer2HarmMtx(*args):
''' Compute a steering matrix (maps a directional basis set onto the
angular Fourier harmonics). HARMONICS is a vector specifying the
angular harmonics contained in the steerable basis/filters. ANGLES
(optional) is a vector specifying the angular position of each filter.
REL_PHASES (optional, default = 'even') specifies whether the harmonics
are cosine or sine phase aligned about those positions.
The result matrix is suitable for passing to the function STEER.
mtx = steer2HarmMtx(harmonics, angles, evenorodd) '''
if len(args) == 0:
print "Error: first parameter 'harmonics' is required."
return
if len(args) > 0:
harmonics = numpy.array(args[0])
# optional parameters
numh = (2*harmonics.shape[0]) - (harmonics == 0).sum()
if len(args) > 1:
angles = args[1]
else:
angles = numpy.pi * numpy.array(range(numh)) / numh
if len(args) > 2:
if isinstance(args[2], basestring):
if args[2] == 'even' or args[2] == 'EVEN':
evenorodd = 0
elif args[2] == 'odd' or args[2] == 'ODD':
evenorodd = 1
else:
print "Error: only 'even' and 'odd' are valid entries for the third input parameter."
return
else:
print "Error: third input parameter must be a string (even/odd)."
else:
evenorodd = 0
# Compute inverse matrix, which maps to Fourier components onto
# steerable basis
imtx = numpy.zeros((angles.shape[0], numh))
col = 0
for h in harmonics:
args = h * angles
if h == 0:
imtx[:, col] = numpy.ones(angles.shape)
col += 1
elif evenorodd:
imtx[:, col] = numpy.sin(args)
imtx[:, col+1] = numpy.negative( numpy.cos(args) )
col += 2
else:
imtx[:, col] = numpy.cos(args)
imtx[:, col+1] = numpy.sin(args)
col += 2
r = numpy.rank(imtx)
if r != numh and r != angles.shape[0]:
print "Warning: matrix is not full rank"
mtx = numpy.linalg.pinv(imtx)
return mtx
|
4d3d648b6b1f9efefe38f6bdddece5567ac19c1f | whutweihuan/DeepLearing | /main08.py | 279 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
author: weihuan
date: 2020/3/13 19:16
"""
# Pytorch实现基本循环神经网络RNN
import torch
import torch.nn as nn
rnn = nn.RNN(10,20,2)
input = torch.randn(5,3,10)
h0 = torch.randn(2,3,20)
output,hn = rnn(input,h0)
print(output)
print(hn)
|
c12fbd2a27f6208a1ce103ac9ad571e8bc2908f4 | tndud042713/python_class_0914 | /python수업자료/프로젝트/Day12.py | 5,126 | 4.03125 | 4 | # # 예제.1
# lst = [1,2,3]
# print("첫 번째 출력: ",lst)
# lst.append('a')
# print("두 번째 출력: ",lst)
# lst.append([100,200])
# print("세 번째 출력: ",lst)
# #list형도 list에 들어간다
# append의 사전적 정의
# 한글로 "추가" 라는 뜻이다.
# 예제.2
# lst = [1,2,3]
# print("첫 번째 출력: ",lst)
# lst.extend(['a','b','c'])
# print("두 번째 출력: ",lst)
# extend 함수는 리스트형을 리스트 안에 넣는 것이 아니라 리스트에 해당
# 하는 값을 리스트 끝에 추가하는 방식이다. 엄연히 append와 다르다
# extend의 사전적 정의
# 한글로 "넓히다"라는 뜻이다.
# # 예제.3
# lst = [1,2,3]
# print("첫 번째 출력:",lst)
# lst.insert(1,'a')
# # lst[1]자리에 'a'를 끼워넣으라는 뜻이다
# print("두 번째 출력:",lst)
# # insert의 사전적 정의
# # 한글로 "끼워넣다"는 뜻이다.
# # 예제.4
# lst = [1,2,3]; lst2 = ['a','b','c']
# print("첫 번째 출력:",lst)
# lst.pop()
# print("두 번째 출력:",lst)
# num = lst.pop(0)
# print("세 번째 출력:",lst)
# print(num)
# lst2.append(lst.pop())
# print("네 번째 출력:",lst)
# print(lst2)
# #예제.5
# lst = [1,2,3]
# print("첫 번째 출력:",lst)
# num = lst.remove(2)
# print("두 번째 출력:",lst)
# print(num)
# lst.clear()
# print("세 번째 출력:",lst)
# lst = [1,2,3]
# lst2 = lst # 얇은복사
# lst2.clear()
# print(lst)
# # 예제.6
# lst = [1,2,3,4,5,1]
# print(lst)
# print(lst.count(1))
# print(lst.index(3))
# lst.reverse()
# print(lst)
# #예제.7
# lst = [78,12,34,56,80]
# print("정렬전 데이터 출력:",lst)
# lst.sort(reverse=False)
# print("오름차순 정렬 후 데이터 출력:", lst)
# lst.sort(reverse=True)
# print("내림차순 정렬 후 데이터 출력:", lst)
# # Quiz 1 : 리스트 초기값 [ 30, 20, 10 ] 설정 후 아래와 같이 출력 되도록 코드를 작성하세요.
# # 현재 리스트 : [30, 20, 10]
# # append(40) 후의 리스트 : [30, 20, 10, 40]
# # pop() 으로 추출한 값 : 40
# # pop() 후의 리스트 : [30, 20, 10]
# # sort() 후의 리스트 : [10, 20, 30]
# # reverse() 후의 리스트 : [30, 20, 10]
# lst=[30,20,10]
# print("현재 리스트 : ",lst)
# lst.append(40)
# print("append(40) 후의 리스트 : ",lst)
# num=lst.pop()
# print("pop() 으로 추출한 값 : ",num)
# print("pop() 후의 리스트 : ",lst)
# lst.sort(reverse=False)
# # 오름차순이므로 리버스의 값은 False이다
# print("sort() 후의 리스트 : ",lst)
# lst.sort(reverse=True)
# # 내림차순이므로 리버스의 값은 True이다
# print("sort() 후의 리스트 : ",lst)
# # 강사의 풀이
# List = [ 30 , 20 ,10 ]
# # .format으로 list도 출력이 가능하다
# print('현재 리스트 : {}'.format(List))
# List.append(40)
# print('append(40) 후의 리스트 : {}'.format(List))
# print('pop() 으로 추출한 값 : {}' .format(List.pop()))
# print('pop() 후의 리스트 : {}' .format(List))
# List.sort()
# print('sort() 후의 리스트 : {}' .format(List))
# List.reverse()
# print('reverse() 후의 리스트 : {}' .format(List))
# [ Quiz 2 ] : 리스트 초기값 [ 30, 20, 10 ] 설정 후 아래와 같이 출력 되도록 코드를 작성하세요.
# 현재 리스트 : [30, 20, 10]
# 10 값의 위치 : 2
# insert(2,200) 후의 리스트 : [30, 20, 200, 10]
# remove(200) 후의 리스트 : [30, 20, 10]
# extend( [ 555 , 666 , 555 ] ) 후의 리스트 : [30, 20, 10, 555, 666, 555]
# 555 값의 개수 : 2
# List = [ 30 , 20 ,10 ]
# # .format으로 list도 출력이 가능하다
# print('현재 리스트 : {}'.format(List))
# print('10 값의 위치 : {}'.format(List.index(10)))
# List.insert(2,200)
# print('insert(2,200) 후의 리스트 : {}' .format(List))
# List.remove(200)
# print('remove(200) 후의 리스트 : {}' .format(List))
# List.extend([555,666,555])
# print('extend( [ 555 , 666 , 555 ] ) 후의 리스트 : {}' .format(List))
# print('555 값의 개수 : {}'.format(List.count(555)))
# #예제.8
# lst = [100,200,300,400]
# #리스트 안에있는 내용 출력
# for i in lst:
# print(i)
# #리스트의 인덱스를 출력
# for i in range(len(lst)):#범위는 리스트의 length(길이) 만큼
# print(i)
# #위의 예제 복습
# lst=[100,200,300,400,500,600,700,800,900,1000]
# for i in lst:
# print(i,end=" ")
# print()
# for i in range(len(lst)):
# print(i,end=" ")
# # 예제.9 : 2차원 리스트
# aa = [[1,2,3,4],
# [5,6,7,8],
# [9,10,11,12]]
# print(aa)
# print()
# print(aa[0])
# print(aa[1])
# print(aa[2])
# print()
# print(aa[0][0])
# print(aa[0][1])
# print(aa[0][2])
# # aa = [[1,2,3,4],
# # [5,6,7,8],
# # [9,10,11,12]]
# for i in range(3):
# for j in range(4):
# print(aa[i][j],end="\t")
# print()
# Quiz : 코드해석 실습
ls_1 = []; ls_2 = []; value = 1
for i in range(0,3):
for k in range(0,4):
ls_1.append(value)
value+=1
ls_2.append(ls_1)
ls_1=[]
for i in range(0,3):
for k in range(0,4):
print('{}\t'.format(ls_2[i][k]),end='')
print()
print('ls_2 : {}'.format(ls_2)) |
d2fe1c4857a320b06bdd3a7817876ba2afedb912 | refschool/exercice-python | /exo/exo26.py | 534 | 3.921875 | 4 |
import csv
print(csv.__version__)
with open('test.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
"""f = open('test.csv', 'r')
next(f) #skip header
for line in f.readlines():
liste = line.split(',')
print(liste[1], liste[0], liste[2], liste[3])"""
""" ['Yvon', 'Huynh', '45', 'Toulouse\n']
['Jean', 'Dupont', '34', 'Paris\n']
['Fabien', 'Martin', '35', 'Lyon\n']
['Elodie', 'Cartier', '33', 'Tours\n']
faire la phrase : yvon huynh a 45 ans et vit à toulouse
""" |
3fd7ae85312ae79c5c91adb61ab1521335917178 | davidbliu/coding-interview | /arrays/lists_practice.py | 799 | 4.03125 | 4 | class ListNode:
def __init__(self, val):
self.value = val
self.next = None
def construct_list():
node = ListNode(0)
curr = node
for i in range(1, 10):
next = ListNode(i)
curr.next = next
curr = curr.next
return node
def print_list(node):
print 'printing list'
curr = node
while curr != None:
print curr.value
curr = curr.next
def reverse_list(node):
print 'reversing list...'
prev = node
curr = node
next = node.next
while curr != None:
next = next.next
curr.next = prev
prev = curr
curr = next
# print curr.value
# print str(next.value) + ' ' + str(curr.value) + ' ' + str(prev.value)
return prev
if __name__=='__main__':
print 'reversing singly linked ListNode'
n = construct_list()
print_list(n)
r = reverse_list(n)
print 'done'
print_list(r)
|
94a81f9ad035749d2ebd4300e4b03c250dc36709 | BAltundas/linked_list | /linkedList.py | 1,938 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 15:28:51 2021
Implementation of linked list in python
@author: Bilgin
"""
class node:
def __init__(self,data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head=node()
def append(self,data):
new_node = node(data)
cur_node = self.head
while cur_node.next!=None:
cur_node = cur_node.next # this brings the curse ti the last element in cur
cur_node.next = new_node
def length(self):
cur_node = self.head
total =0
while cur_node.next!=None:
total+=1
cur_node = cur_node.next
return total
def display(self):
elems =[]
cur_node =self.head
while cur_node.next!=None:
cur_node=cur_node.next
elems.append(cur_node.data)
print(elems)
def get(self,index):
if index>= self.length():
print("ERROR: 'index' out of range")
return None
cur_idx=0
cur_node = self.head
while True:
cur_node = cur_node.next
if cur_idx ==index:
return cur_node.data
cur_idx+=1
def erase(self,index):
if index>= self.length():
print("ERROR: 'index' out of range")
return None
cur_idx=0
cur_node = self.head
while True:
last_node = cur_node
cur_node = cur_node.next
if cur_idx ==index:
last_node.next = cur_node.next
return
cur_idx+=1
my_list = linked_list()
my_list.append('a')
my_list.append('b')
my_list.append('c')
my_list.append(1)
my_list.display()
print(f'3rd Element in list is {my_list.get(3)}')
my_list.erase(1)
my_list.display()
|
58c0671d928e1aaaa044c10132219ce2a76f80a3 | velillajoseph/Velilla_104079_project01_SnakeyGame | /SnakeyGame.py | 6,527 | 3.78125 | 4 | from graphics import *
from random import *
class Snake:
#Creating the window
win = GraphWin('SNAKEY SNAKE', 800, 985)
win.setBackground('black')
#Defining snake and snake size
size = 2
snake = [0] * size
#Define apple
apple = Rectangle(Point(0, 0), Point(0, 0))
GameOver = Text(Point(300,50),"Game Over. Press any key to exit...")
theScore = 0
def setSize(_size):
Snake.size = _size
def getSize():
return Snake.size
def setSnake(_snake):
Snake.snake = _snake
def getSnake():
return Snake.snake
def setApple(_apple):
Snake.apple = _apple
def getApple():
return Snake.apple
#Creates the text that will be dislplayed
def Title(self):
title = Text(Point(400, 150), "S N A K E Y S N A K E")
title.setFace('courier')
title.setSize(36)
title.setStyle("bold italic")
title.setTextColor("deeppink")
title.draw(self.win)
#Display Score
def Score(self):
score = Text(Point(400, 200), "S C O R E : " + str(self.theScore))
score.setFace('courier')
score.setSize(16)
score.setStyle("bold italic")
score.setTextColor('orchid')
score.draw(self.win)
#Display How to play
def HTP(self):
howToPlay = Text(Point(400, 270), "W - UP\nA - LEFT\nS - DOWN\nD - RIGHT\nESC - END GAME")
howToPlay.setFace('courier')
howToPlay.setSize(12)
howToPlay.setStyle("bold italic")
howToPlay.setTextColor('mediumorchid')
howToPlay.draw(self.win)
#Draw Walls
def Walls(self):
walls = Rectangle(Point(50, 350), Point(750, 950))
walls.setFill('silver')
walls.setOutline('dimgrey')
walls.draw(self.win)
#Draws Where the game is taking place
def GameBoard(self):
gameBoard = Rectangle(Point(60, 360), Point(740, 940))
gameBoard.setFill('yellowgreen')
gameBoard.setOutline('black')
gameBoard.draw(self.win)
#Creating square grid in Game Board
def Cuadricula(GRID, SIZE, self):
lines = int(GRID/SIZE)
x1 = 80
y1 = 380
for i in range(0, lines):
hLine = Line(Point(60, y1), Point(740, y1))
yLine = Line(Point(x1, 360), Point(x1, 940))
hLine.draw(self.win)
yLine.draw(self.win)
x1 = x1 + SIZE
y1 = y1 + SIZE
def spawnSnake(self):
snake = self.getSnake()
for i in range(self.getSize()):
snake[i] = Rectangle(Point(100, 400), Point(120, 420))
snake[i].setFill('grey')
snake[i].setOutline('black')
snake[i].draw(self.win)
self.setSnake(snake)
def moveSnake(direction, self):
snake = self.getSnake()
tiles = self.getSize() - 1
snake[tiles].undraw()
while tiles > 0:
snake[tiles] = snake[tiles - 1]
tiles -= 1
snake[0] = snake[0].clone()
if direction == 1:
snake[0].move(0, 20)
snake[0].draw(self.win)
self.setSnake(snake)
elif direction == 2:
snake[0].move(20, 0)
snake[0].draw(self.win)
self.setSnake(snake)
elif direction == 3:
snake[0].move(-20, 0)
snake[0].draw(self.win)
self.setSnake(snake)
elif direction == 4:
snake[0].move(0, -20)
snake[0].draw(self.win)
self.setSnake(snake)
def growSnake(self):
size = self.getSize() + 1
snake = self.getSnake()
snake.append(snake[0].clone())
self.setSize(size)
self.setSnake(snake)
def Collisions(self):
collided = False
snake = self.getSnake()
max_x1 = snake[0].getP1().getX()
max_x2 = snake[0].getP2().getX()
max_y1 = snake[0].getP1().getY()
max_y2 = snake[0].getP2().getY()
center_x = snake[0].getCenter().getX()
center_y = snake[0].getCenter().getY()
if(max_x1 < 100 or max_x2 > 700 or max_y1 < 400 or max_y2 > 900):
collided = True
return collided
elif((center_x == self.getApple().getCenter().getX()) and (center_y == self.getApple().getCenter().getY())):
self.growSnake(Snake)
self.spawnApple(Snake)
print("Apple collision")
return collided
for j in range(1, Snake.getSize()):
if (center_x == snake[j].getCenter().getX() and center_y == snake[j].getCenter().getY()):
return collided
def gameOver(self):
self.GameOver.setOutline("white")
self.GameOver.setSize(16)
self.GameOver.draw(self.win)
def spawnApple(self):
x = randint(0, 32) * 20
y = randint(0, 27) * 20
apple = self.getApple()
try:
apple.undraw()
except:
print('\nThere is no apple to delete')
anApple = Rectangle(Point(60 + x, 380 + y), Point(80 + x, 400 + y))
self.setApple(anApple)
anApple.setFill('red')
anApple.setOutline('black')
anApple.draw(self.win)
def main():
# Validates game state false - playing / true - gameover
state = False
#Defining snake direction: 1 = dowm, 2 = right, 3 = up, 4 = left.
#By default is set to 1.
direction = 1
#object from class
s = Snake
#Call functions to display window
s.Title(s)
s.Score(s)
s.HTP(s)
s.Walls(s)
s.GameBoard(s)
s.Cuadricula(680, 20, s)
s.spawnSnake(s)
s.spawnApple(s)
while(not state):
key = s.win.checkKey()
time.sleep(0.12)
if(s.Collisions(s) == True):
s.gameOver(s)
state = True
#s.gameOver(s)
if(key == 'w'):
direction = 4
s.moveSnake(direction, s)
elif(key == 'a'):
direction = 3
s.moveSnake(direction, s)
elif(key =='s'):
direction = 1
s.moveSnake(direction, s)
elif(key == 'd'):
direction = 2
s.moveSnake(direction, s)
elif(key == 'esc'):
s.gameOver(s)
else:
s.moveSnake(direction, s)
s.Collisions(s)
print(state)
s.win.getKey()
s.win.close()
main()
|
bc10c7e372210429bdd80e5a2731d0f1af23740b | SenneRoot/AOC2020 | /day_1/task_2.py | 508 | 3.8125 | 4 | def read_integers(filename):
with open(filename) as f:
return [int(x) for x in f]
inputs = read_integers("input.txt")
for i, first in enumerate(inputs):
for j, second in enumerate(inputs[i:]):
for k, third in enumerate(inputs[j:]):
sum = first + second + third
if (sum == 2020):
print("1: " + str(first) + " 2: " + str(second) + " 3: " + str(third) + " sum: " + str(sum))
print(first * second * third)
exit()
|
19a9ce133bdc74c976c78f8ae74b2e199bcb8bfe | alrasyidlathif/leetcode-notes-question-answer-in-python3 | /7.py | 661 | 4.15625 | 4 | '''
Given a signed 32-bit integer x, return x with
its digits reversed. If reversing x causes the
value to go outside the signed 32-bit integer
range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to
store 64-bit integers (signed or unsigned).
Example:
Input: x = 123
Output: 321
'''
class Solution:
def reverse(self, x: int) -> int:
sign = ""
s = str(x)
if x < 0:
sign = "-"
s = s[1:]
res = int(sign + s[::-1])
if res < -(2**31):
return 0
if res > (2**31)-1:
return 0
return res
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.