blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2539e1965cf3e3df19acc8c1e7a9f65c734a4c12 | gelisa/sandbox | /working-with-spark/run_spark.py | 2,129 | 3.8125 | 4 | # run_spark.py
"""
a sandbox to test spark and learn how it works
to run it: put some (at least a couple) text files to the data folder
type in command line: python run_spark.py
or <path to spark home folder>/bin/spark-submit run_spark.py
to understand very basics of spark read: http://mlwhiz.com/blog/2015/09/07/Spark_Basics_Explained/
it is very good
"""
# this is to run with spark: python run_spark.py
from pyspark import SparkConf
from pyspark import SparkContext
# import python packages
import os
import numpy as np
# import my custom class
import custom_class
# set up spark environment
conf = SparkConf()
sc = SparkContext(conf=conf)
# text files shoud be here
folder = 'data/'
# init a list to put filenames in there to work with the files
a_list = []
for datafile in os.listdir(folder):
a_list.append(os.path.join(folder,datafile))
# create a spark rdd from the list of file names
sp_filenames = sc.parallelize(a_list)
# now I use map to create a python class for every file (see custom_class.py for details)
sp_classes = sp_filenames.map(custom_class.Custom_class)
# now we apply a method function to every class.
# If this function creates or updates a class attribute it has to return an object itself
# so that spark has access to it (rdd's are immutable: you have to create a new rdd)
# we'll have [obj1, obj2, obj3 ...]
classes_wt_count = sp_classes.map(lambda x: x.count_lines())
# so no we want calculate some stats for every file.
# we use flatMap which returns seveal items of output for one item of inpet
# we'll have [stat1(dbj1), stat2(ojb1), stat1(obj2) ...]
dicts = classes_wt_count.flatMap(lambda x: x.get_stats())
# now instead of having a long list of key value pair we want to get [key1: list1, key2: list2 ]
# key is a name of stat and each list is a list of the stats for each object
dicts_collected = dicts.groupByKey().mapValues(list)
# now we calculate mean and standard deviation for every stat
stats = dicts_collected.map(lambda x: (x[0], np.mean(x[1]),np.std(x[1])))
# for spark to do the actual calculation we have to call an action
# for example collect()
print(stats.collect()) |
30850c4f1d5a5d986941cd04d8e17178e15a835d | johnabfaria/bambus.py | /main.py | 771 | 3.8125 | 4 | import pic_it
import tweet_it
import txt_it
import drop_it
import pin
import time
"""
This is the main program that will use pin to id inputer from raspberry pi using RPi.GPIO
If input from IR motion sensor is positive, camera will be activated, photo snapped and saved locally
Photo will be tweeted and then uploaded to dropbox
A text message using Twilio will be sent to contact list with twitter link and dropbox direct link
"""
#while True():
for z in range(15)
print("Sensor null, run = {0}".format(z))
if pin.status:
time_snap = "{0}:{1}".format(time.localtime().tm_hour, time.localtime().tm_min)
name = "Bambus_pije_o: " + time
pic_it.snap(name)
tweet_it.send(name)
drop_it.upload(name)
txt_it.go(name)
time.sleep(5)
|
fe957545e1dc512e5d3a2a28defc654281ae82ee | YunYouJun/python-learn | /primer/first_program.py | 437 | 3.984375 | 4 | def isEqual(num1, num2):
if num1 < num2:
print(str(num1) + ' is too small!')
return False
elif num1 > num2:
print(str(num1) + ' is too big!')
return False
else:
print('Bingo!')
return True
from random import randint
num = randint(1, 100)
print('Guess what I think?')
bingo = False
while bingo == False:
answer = input()
if answer:
isEqual(int(answer), num)
|
87de1f7da5274947664161b3e54d2913720b59e9 | Om-Jaiswal/Python | /Python_Programs/FizzBuzz.py | 643 | 4.03125 | 4 | # for number in range(1,101):
# if number % 3 == 0 and number % 5 == 0:
# print("FizzBuzz")
# elif number % 3 == 0:
# print("Fizz")
# elif number % 5 == 0:
# print("Buzz")
# else:
# print(number)
print("Welcome to FizzBuzz!")
Fizz = int(input("Enter a number for fizz :\n"))
Buzz = int(input("Enter a number for buzz :\n"))
print("Here's the solution")
for number in range(1,101):
if number % Fizz == 0 and number % Buzz == 0:
print("FizzBuzz")
elif number % Fizz == 0:
print("Fizz")
elif number % Buzz == 0:
print("Buzz")
else:
print(number)
|
c0549fa722759a574c69585d0e0767c47d8d1be1 | Om-Jaiswal/Python | /Python_Programs_OPP/Dash_Square.py | 326 | 3.5 | 4 | import turtle as t
from turtle import Screen
tim = t.Turtle()
tim.shape("turtle")
def dash_line():
for _ in range(15):
tim.forward(10)
tim.penup()
tim.forward(10)
tim.pendown()
for _ in range(4):
dash_line()
tim.right(90)
screen = Screen()
screen.exitonclick() |
5f168aeaf97ebb2100fafcbaef59928522f86d70 | sha-naya/Programming_exercises | /reverse_string_or_sentence.py | 484 | 4.15625 | 4 | test_string_sentence = 'how the **** do you reverse a string, innit?'
def string_reverser(string):
reversed_string = string[::-1]
return reversed_string
def sentence_reverser(sentence):
words_list = sentence.split()
reversed_list = words_list[::-1]
reversed_sentence = " ".join(reversed_list)
return reversed_sentence
example_1 = string_reverser(test_string_sentence)
print(example_1)
example_2 = sentence_reverser(test_string_sentence)
print(example_2)
|
4196ac75509c5eff3227c1e8bff9ad00cc83ddd0 | frfanizz/PressureChess | /pressurechess.py | 5,374 | 3.75 | 4 | import sys
from pieces import *
'''
Considerations:
allow buring pieces
'''
class tile:
"""
(Board) tile objects
"""
def __init__(self, piece, hp = 6):
"""
Tile classs constructor
:param self tile: the current object
:param piece piece: the current object
:param hp int: the current object
"""
self.piece = piece
self.hp = hp
def lose_hp(self):
"""
Decrements self's hp
:param self tile: the current object
:returns boolean: True if hp was decremented, False o.w.
"""
if self.hp > 0:
self.hp = self.hp - 1
return True
else:
# self.hp = 0
return False
def get_piece(self):
"""
Returns self's piece
:param self tile: the current object
:returns piece: the piece of the current object
"""
return self.piece
def set_piece(self, piece):
"""
Sets self's piece to piece
:param self tile: the current object
:param piece piece: a piece object
:returns:
"""
self.piece = piece
def toString(self):
"""
Returns a string representation of self
:param self tile: the current object
:returns str: a string representation of self
"""
if self.piece is None:
return " " + str(self.hp)
else:
return " " + self.piece.toString() + str(self.hp)
class board:
"""
The chess board, which is an 8x8 array of tiles
"""
def __init__(self, tiles):
"""
Board class constructor
:param self board: the current object
:param tiles [tile]: an array of tiles
:returns:
"""
self.tiles = tiles
# TODO: add curr player to move??
# TODO: def is_in_check(self)
def print_board(self):
"""
Prints the board in a visually athstetic way
:param self board: the current object
:returns:
"""
print(self.toString())
def toString(self):
"""
Returns a string representation of the board in a visually athstetic way
:param self board: the current object
:returns str: The board in a string representation
"""
retString = "\n +---+---+---+---+---+---+---+---+\n"
for row in range(len(self.tiles)-1, -1, -1):
retString += str(row+1) + " "
for tile in range(len(self.tiles[row])):
retString += "|" + self.tiles[row][tile].toString() + ""
retString += "|\n +---+---+---+---+---+---+---+---+\n"
retString += " a b c d e f g h \n"
return retString
class position:
"""
The position on the board, where rank = row (1 : 0), and file = col (a : 0)
"""
def __init__(self, pos_rank, pos_file):
"""
Position class constructor
:param self position: the current object
:param pos_rank int: the rank (row) number from 0 to 7
:param pos_file int: the file (colum) number from 0 to 7
:returns:
"""
self.pos_rank = pos_rank # row
self.pos_file = pos_file # column
def get_rank(self):
"""
Return self's rank
:param self position: the current object
:returns int: self's rank
"""
return self.pos_rank
def get_file(self):
"""
Return self's file
:param self position: the current object
:returns int: self's file
"""
return self.pos_file
def rank_to_string(self):
"""
Return self's rank in a string format from 1 to 8
:param self position: the current object
:returns str: self's rank in a string format
"""
return str(self.pos_rank + 1)
def file_to_string(self):
"""
Return self's rank in a string format from a to h
:param self position: the current object
:returns str: self's rank in a string format
"""
return chr(ord("a")+self.pos_file)
def toString(self):
"""
Return self in a string format (file followed by row)
:param self position: the current object
:returns str: self in a string format
"""
return self.file_to_string() + self.rank_to_string()
board_std = [
[tile(rook(0)), tile(knig(0)), tile(bish(0)), tile(quee(0)),
tile(king(0)), tile(bish(0)), tile(knig(0)), tile(rook(0))],
[tile(pawn(0)), tile(pawn(0)), tile(pawn(0)), tile(pawn(0)),
tile(pawn(0)), tile(pawn(0)), tile(pawn(0)), tile(pawn(0))],
[tile(None), tile(None), tile(None), tile(None),
tile(None), tile(None), tile(None), tile(None)],
[tile(None), tile(None), tile(None), tile(None),
tile(None), tile(None), tile(None), tile(None)],
[tile(None), tile(None), tile(None), tile(None),
tile(None), tile(None), tile(None), tile(None)],
[tile(None), tile(None), tile(None), tile(None),
tile(None), tile(None), tile(None), tile(None)],
[tile(pawn(1)), tile(pawn(1)), tile(pawn(1)), tile(pawn(1)),
tile(pawn(1)), tile(pawn(1)), tile(pawn(1)), tile(pawn(1))],
[tile(rook(1)), tile(knig(1)), tile(bish(1)), tile(quee(1)),
tile(king(1)), tile(bish(1)), tile(knig(1)), tile(rook(1))]
]
def main(argv):
"""
Main application class
:param argv [str]: the terminal/command line inputs
:returns:
"""
field = board(board_std)
print(field.toString())
if __name__ == "__main__":
main(sys.argv)
|
2e61bac1d6b08105532a2c34e96b98e5e6886b0f | rabahbedirina/HackerRankContests | /CatsandaMouse.py | 207 | 3.65625 | 4 | def catAndMouse(x, y, z):
X = abs(x - z)
Y = abs(y-z)
if X < Y:
cat = "Cat A"
elif X > Y:
cat = "Cat B"
else:
cat = "Mouse C"
return cat
catAndMouse(x, y, z)
|
0e599494c99b1d05d0162c5cf66b98f0b0301be1 | rabahbedirina/HackerRankContests | /Big Sorting.py | 526 | 3.625 | 4 | def bigSorting(unsorted):
for i in range(n):
unsorted[i] = int(unsorted[i])
print(unsorted)
list_sorted = sort(unsorted)
print(list_sorted)
for j in range(n-1):
print(str(list_sorted[j]))
return str(list_sorted[-1])
n = 6
unsorted = ['31415926535897932384626433832795', '1', '3', '10', '3', '5']
print(bigSorting(unsorted))
# unsorted = [31415926535897932384626433832795, 1, 3, 10, 3, 5]
# print(bigSorting(unsorted))
# TypeError: sequence item 0: expected str instance, int found
|
a336bb76c0bce019135ea4a775ab09f434a5b01d | skyrusai/code_training | /others/FizzBuzz.py | 327 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 09:44:32 2018
@author: shenliang-006
"""
for l in range(101):
if l==0:
continue
if l%3==0:
if l%5==0:
print("FizzBuzz")
else:
print("Fizz")
elif l%5==0:
print("Buzz")
else:
print(l)
|
e2584e9dda14afad7ca6aa5eebf4f23d56ac01f9 | ardieorden/electrical_circuits | /circuit_initial.py | 6,626 | 3.671875 | 4 | import cmath
import numpy as np
import matplotlib.pyplot as plt
from sympy import Symbol, simplify, Abs
from sympy.solvers import solve
from scipy.signal import sawtooth
# We set our unknowns: vo, vr, ir, ic and il
vo = Symbol("V_O")
vr = Symbol("V_R")
ir = Symbol("I_R")
ic = Symbol("I_C")
il = Symbol("I_L")
r = Symbol("R") # resistance
omega = Symbol("\omega") # angular frequency
c = Symbol("C") # capacitance
l = Symbol("L") # inductance
eq1 = (vr + vo - 1,
ir - ic - il,
vr - ir*r,
# what does 1j mean? (1j represents the imaginary number i)
vo - ic/(1j*omega*c),
vo - 1j*omega*l*il)
# what does the following line do?
sol = solve(eq1, (vo, vr, ir, ic, il))
vos = simplify(sol[vo])
"""
The system of equations is solved for the 5 specified variables.
Subsequently, the variable vo is simplified.
"""
# compare the output of the following line if vos = sol[vo]
print "Simplified: " + str(vos)
print "Unsimplified: " + str(sol[vo])
"""
When 'vos=sol[vo]' instead of 'vos=simplify(sol[vo])', the output is still
the same because the expression is already simplified after solving.
"""
numvalue = {c: 10**-6, l: 10**-3}
# what does subs() do? is vos.subs(c=10**-6, l=10**-3) allowed? Try it.
vosnum = vos.subs(numvalue)
flist = [vosnum.subs({r: 100.0*3**s}) for s in range(0, 4)]
omega_axis = np.linspace(20000, 43246, 100)
"""
'subs()' substitutes a variable expression with an actual number.
Using 'numvalue = {c: 10**-6, l: 10**-3}', the result of the substitution
is i*omega/1000.
"""
# what does 121 in the following line mean?
# what are the other possible parameters of subplot()?
plt.subplot(121)
"""
'121' indicates the position of the subplot. The three numbers represent
numrows, numcols, fignum. fignum ranges from 1 to numrows*numcols.
"""
# describe (python type, dimensions, etc) of the input parameter/s of zip() below
# what does zip(*a) do if a is a 2-D list or numpy array?
plt.plot(omega_axis, zip(*[[abs(f.subs({omega: o})) for o in omega_axis]
for f in flist]))
"""
The input parameter is a 2-D list. It is a list of output voltages
within another list.
When there is an asterisk before the arguments (e.g. zip(*a) where a is 2-D),
it outputs a list of tuples.
"""
plt.xlim(20000, 43246)
plt.ylim(0, 1)
plt.xlabel('$\omega$')
plt.ylabel('$V_O$')
plt.xticks([20000, 30000, 40000])
# Replicate Fig. 2.6, right pane following the code for Fig. 2.6, left pane
"""Code shown below."""
plt.subplot(122)
plt.plot(omega_axis, zip(*[[cmath.phase(f.subs({omega: o})) for o in omega_axis]
for f in flist]))
plt.xlim(20000, 43246)
plt.ylim(-1.5, 1.5)
plt.xlabel('$\omega$')
plt.ylabel('$\phi$')
plt.xticks([20000, 30000, 40000])
plt.tight_layout()
plt.savefig('fig2.6.png', dpi=300)
plt.show()
def vsaw(t, T=1.0):
"""Output a sawtooth wave over a given time array t.
In order to create a sawtooth wave, I utilized 'scipy.signal.sawtooth()'.
The instructions call for a period T = 1.0. However, 'sawtooth()' has a
period T = 2pi.
To get around this, the argument for the 'sawtooth()' function must be
multiplied by 2pi.
"""
return sawtooth(t*2*np.pi)
omegares = 1./np.sqrt(np.prod(numvalue.values()))
alist = (1/np.sqrt(256)) * vsaw(np.arange(256)/256.0)
blist = np.sqrt(256) * np.fft.fft(alist)
def plot3(fac, w):
# add a docstring for this function
"""Plots the output voltage of a sawtooth voltage input.
Parameters
----------
fac : Ratio of input fundamental frequency to the resonance frequency
w : Resistor value
Returns
-------
Output voltage V_out vs. t/T plot showing the filtered sawtooth input.
"""
omegai = fac * omegares
# How were the limits of arange() in the following line chosen?
"""
To be able to multiply 'volist' correctly with 'blist' for the subsequent
inverse Fourier transform, both arrays must be of the same size. Since
'blist' is a numpy array of size 256, 'volist' must also be the same
"""
volist = np.concatenate(([complex(vosnum.subs({omega: omegai*s, r: w}).evalf())
for s in np.arange(1, 129)],
[0.0],
[complex(vosnum.subs({omega: omegai*s, r: w}).evalf())
for s in np.arange(-127, 0)]))
vtrans = np.fft.ifft(blist * volist)
plotlist = np.array([[(k+1)/256., vtrans[k%256]] for k in range(768)])
plt.plot(plotlist[:,0], plotlist[:,1])
# what does the following line do?
plt.axhline(0, color='black')
"""'axhline()' creates a horizontal axis line."""
# add labels
"""Labels shown below."""
plt.xlabel('$t/T$')
plt.ylabel('$V_O(t)$')
fname = 'fig2.7and8_f' + str(fac) + 'r' + str(w) + '.png'
plt.savefig(fname, dpi=300)
plt.show()
plot3(1, 2700.0)
plot3(1/3., 200.0)
plot3(3.0, 5.0)
eq2 = (ir * (r + 1/(1j*omega*c) + 1j*omega*l) + vo - 1,
ir - (1j*omega*c + 1/(1j*omega*l)) * vo)
sol2 = solve(eq2, [vo, vr, ir, ic, il])
vos2 = simplify(sol2[vo])
irs = simplify(sol2[ir])
# why should irs be passed to Abs() before squaring?
"""
'irs' was first passed through an absolute value before squaring to ensure that
the square is solely real-valued.
"""
power = (r**2) * (Abs(irs)**2)
flist3 = [Abs(vos2.subs(numvalue).subs({r: 10.0*3**s})) for s in range(0, 3)]
omega_axis = np.linspace(10000, 70000, 1000)
lines = plt.plot(omega_axis, zip(*[[abs(f.subs({omega: o})) for o in omega_axis]
for f in flist3]))
# what does plt.setp() do?
"""'plt.setp' changes the properties of an artist object"""
plt.setp(lines[0], lw=2, label="$R = 10 \Omega$")
plt.setp(lines[1], ls='--', label="$R = 30 \Omega$")
plt.setp(lines[2], ls='-.', label="$R = 90 \Omega$")
# add labels and ticks
"""Labels and ticks shown below."""
plt.xlabel('$\omega$')
plt.ylabel('|$V_O$|')
plt.xticks([10000, 30000, 50000, 70000])
plt.tight_layout()
plt.minorticks_on()
plt.legend(loc=0)
plt.savefig('fig2.9.png', dpi=300)
plt.show()
# replicate fig. 2.10
"""Code shown below."""
flist4 = [power.subs(numvalue).subs({r: 10.0}) for s in range(0,1)]
lines = plt.plot(omega_axis, zip(*[[f.subs({omega: o}) for o in omega_axis]
for f in flist4]))
plt.xlabel('$\omega$')
plt.ylabel('$P/P_0$')
plt.xticks([10000, 30000, 50000, 70000])
plt.tight_layout()
plt.minorticks_on()
plt.savefig('fig2.10.png', dpi=300)
plt.show() |
18fae6895c6be30f0a3a87531a2fafe965a3c89f | pkdoshinji/miscellaneous-algorithms | /baser.py | 1,873 | 4.15625 | 4 | #!/usr/bin/env python3
'''
A module for converting a (positive) decimal number to its (base N) equivalent, where
extensions to bases eleven and greater are represented with the capital letters
of the Roman alphabet in the obvious way, i.e., A=10, B=11, C=12, etc. (Compare
the usual notation for the hexadecimal numbers.) The decimal number and the
base (N) are entered in the command line: baser.py <base> <decimal number to convert>
'''
import sys
#Character set for representing digits. For (base N) the set is characters[:N]
characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'
#Usage guidelines
def usage():
print('[**]Usage: baser.py <base> <number to convert>')
print(f' <base> must be less than or equal to {len(characters)}')
print(f' <number> must be a nonnegative integer')
#Get the most significant digit (MSD) of the decimal number in (base N)
def getMSD(base, number):
MSD = 1
while True:
if (base ** MSD) > number:
return MSD
MSD += 1
#Convert the decimal number to (base N)
def convert(MSD, base, number):
result = ''
for i in range(MSD - 1, -1, -1):
value = number // (base ** i)
result += chars[value]
number = number % (base ** i)
return result
def main():
#Input sanitization
try:
base = int(sys.argv[1])
except:
usage()
exit()
try:
number = int(sys.argv[2])
except:
usage()
exit()
if base > len(characters):
usage()
exit(0)
if number == 0:
print(0)
exit(0)
if number < 0:
usage()
exit(0)
global chars
chars = characters[:base] #Get the (base N) character set
print(convert(getMSD(base, number), base, number)) #Convert and output
if __name__ == '__main__':
main()
|
60a99e1a6a1a8ab2c8a5827d36b891fdafb5035f | DimitrisParris/Bootcamp-AFDE | /Exercises in Python/ex.8(part2).py | 290 | 3.703125 | 4 | num = input("Give sequence of numbers:")
sum = 0
for i in range(len(num)):
if i%2 == 0 and i<(len(num)-1):
a = int(num[i])*int(num[i+1])
sum+=a
if len(num)%2 !=0 and i==(len(num)-1):
sum += int(num[-1])
print("This is the sum of the sequence:", sum)
|
653e3c2184e36a5a05ea9e77d7f8214e4be9d770 | DimitrisParris/Bootcamp-AFDE | /Exercises in Python/ex.2(part 2).py | 410 | 3.703125 | 4 | number=input('Give 8-bit number:')
num=str(number)
if len(num)!=8:
print('Not an 8-digit number. False. Check again.')
else:
neo=num[:7]
print(neo)
sum=0
for i in neo :
if int(i)==1:
sum+=1
if sum%2==0 :
print('sum even')
else :
print('sum odd')
if (int(num[-1])%2)==(sum%2):
print('Parity OK')
else:
print('Parity not OK')
|
5d9d9ee735c83028145dda4bbc9a615cab916d6c | DSJ-23/DS_Algorithms | /valid_parenthesis.py | 1,039 | 3.890625 | 4 | from stack import Stack
class Solution:
def isValid(self, s):
valid = Stack()
for p in s:
if p == "(" or p == "[" or p =="{":
valid.add(p)
# elif p == ")" or p == "]" or p == "}":
print(valid.get_stack())
return True
a= Solution()
print(a.isValid("()[]{"))
# print(Solution.isValid("()[]"))
class Solution:
def isValid(self, s: str) -> bool:
result = []
print(s)
for i in s:
if i == "(" or i == "[" or i == "{":
result.append(i)
else:
if result != []:
if i == ")" and result[-1] == "(":
result.pop()
if i == "]" and result[-1] == "[":
result.pop()
if i == "}" and result[-1] == "{":
result.pop()
else:
return False
if len(result) > 0:
return False
return True
|
7c53f978351f9de8b446810c5fbd0d87160806cf | DSJ-23/DS_Algorithms | /DS/queue.py | 316 | 3.5 | 4 | class Queue:
def __init__(self):
self.data = []
def push(self, x: int) -> None:
self.data.append(x)
def pop(self):
return self.data.pop(0)
def peek(self):
return self.data[0]
def empty(self):
return bool(self.data == []) |
28b99002de36b734fe2f53b72ac863075f594ebc | DSJ-23/DS_Algorithms | /all_duplicates.py | 549 | 3.578125 | 4 | class Solution:
def findDuplicates(self, nums):
for i in range(1, len(nums) +1):
if i in nums and nums.count(i) == 1:
nums.remove(i)
elif i in nums and nums.count(i) > 1:
self.remove_nums(nums, i)
else:
continue
return nums
def remove_nums(self, list_nums, number):
while list_nums.count(number) != 1:
list_nums.remove(number)
return list_nums
eg = [4,3,2,7,8,2,3,1]
a = Solution()
print(a.findDuplicates(eg)) |
d7cae30b5df626903234bce52cde315a602603cb | DSJ-23/DS_Algorithms | /binary_search.py | 495 | 3.671875 | 4 | a = list(range(1001))
def binary_search(nums, num):
lower = 0
upper = len(nums) - 1
mid = 0
while lower <= upper:
mid = (lower + upper)//2
# print(nums[mid])
if nums[mid] > num:
upper = mid -1
elif nums[mid] < num:
lower = mid + 1
else:
return mid
return -1
# for i in range(1001):
# if binary_search(a, i) != i:
# print('oh no')
# else:
# print('yes')
|
becb9a7d85b964a23e2a9e416b3654a2a4e8b7d5 | tomchor/scivis | /plots/ex0/ex0.py | 665 | 3.9375 | 4 | import numpy as np
from matplotlib import pyplot as plt
# Create some made up simple data
y1=[1,4,6,8]
y2=[1,2,3,4]
# Create a new figure with pre-defined sizes and plot everything
plt.figure(figsize=(3,4))
plt.plot(y1)
plt.plot(y2)
plt.savefig('bad_ex.pdf')
plt.close('all')
# Create another figure with defined sizes
plt.figure(figsize=(3,4))
# Plot with curve labels
plt.plot(y1, label='Speed for runner 1')
plt.plot(y2, label='Speed for runner 2')
# Put axis labels
plt.xlabel('Distance (m)')
plt.ylabel('Speed (m/s)')
# Inlcude title
plt.title('Better version')
# legend() is necessary for the curve labels to appear
plt.legend()
plt.savefig('good_ex.pdf')
|
c901957b592edc23c8b162ab5483e8f005bf3de2 | cbrandao18/python-practice | /math-practice.py | 564 | 4.0625 | 4 | import math
numbers = [5, 8, 27, 34, 71, 6]
n = len(numbers)
def getSum(numbers):
summation = 0
for num in numbers:
summation = summation + num
return summation
def getSD(numbers):
avg = getSum(numbers)/n
numerator = 0
for num in numbers:
numerator = numerator + (num - avg)**2
sd = math.sqrt(numerator/(n-1))
return sd
print "The sum of the numbers is "+ str(getSum(numbers))
print "The average of the numbers is "+ str(getSum(numbers)/n)
print "The standard deviation of the numbers is "+ str(getSD(numbers))
|
fe03952ad6982e0e51a9218b01dc9231df641b41 | cbrandao18/python-practice | /celsius-to-f.py | 226 | 4.1875 | 4 | def celsiusToFahrenheit(degree):
fahrenheit = degree*1.8 + 32
print fahrenheit
celsiusToFahrenheit(0)
celsiusToFahrenheit(25)
n = input("Enter Celsius you would like converted to Fahrenheit: ")
celsiusToFahrenheit(n)
|
edeff33f8b00a449bab826aa2b05a50108ea335f | luciengaitskell/csci-aerie | /csci0160/3-data/athome3_sorting_algos.py | 6,579 | 4.15625 | 4 | """
Sorting Algos Handout
Due: October 7th, 2020
NOTES:
- Reference class notes here: https://docs.google.com/document/d/1AWM3nnLc-d-4nYobBRuBTMuCjYWhJMAUx2ipdQ5E77g/edit?usp=sharing
- Do NOT use online resources.
- If you are stuck or want help on any of them, come to office hours!
Completed by Lucien Gaitskell (LUC)
EXERCISES
1. Suppose we have 243 identical-looking boxes each containing a drone ready to ship, but we remember that one box is
missing instructions! This box will weigh a little less than the rest and there is a scale that can compare weights of
any two sets of boxes. Assuming the worst case scenario, what is the minimum number of weighings needed to determine
which box has the missing instructions?
Hint: review the Tower of Hanoi stuff from class
2. Implement the following sorting algos (Insertion Sort, Merge Sort, and Quick Sort) in Python. Use comments to
denotate which pieces of code refer to the recursive process of divide, conquer, and combine.
Include 3-5 test cases for each algo.
Hint: review the pseudocode from the lecture notes
3. In terms of time complexity, which one is more efficient - Merge Sort or Quick Sort? What about space memory efficiency?
"""
# LUC: Exercise 1
"""
As this is the worst case scenario, all the boxes have to be weighed in some form. As only two boxes can be weighed at
once, one option is to compare pairs of boxes. Two boxes will be paired and only compared against each other.
If the weighing scale could compare more than two boxes, than I would use a binary search approach.
"""
# LUC: Exercise 2
def insertion_sort(l):
""" LUC """
# Validate input
if len(l) < 1 or not isinstance(l, list):
return l
current = 1 # Set element to compare
while current < len(l): # Run until selected element is beyond range
val = l[current] # Get value of selected value to insert
swap_idx = current # Set initial index to compare for swap
while val < l[swap_idx-1] and swap_idx>0:
# If selected value is less than next swap element
swap_idx -= 1 # Decrement swap position
for i in reversed(range(swap_idx, current)):
# Shift up each element after swap position
l[i+1] = l[i]
l[swap_idx] = val # Swap selected element to swap position
current += 1 # Increment comparison index (could increment a second time if swap occurred)
return l
assert insertion_sort([]) == []
assert insertion_sort([1]) == [1]
assert insertion_sort([2,1,5]) == [1, 2, 5]
assert insertion_sort([2,1,5,3,4]) == [1, 2, 3, 4, 5]
assert insertion_sort([5,4,3,2,1]) == [1, 2, 3, 4, 5]
assert insertion_sort([9,2,56,2,1]) == [1, 2, 2, 9, 56]
def merge_sort(l):
""" LUC """
if len(l) <= 1: # Single or empty array -> already sorted
return l
pivot = int(len(l) / 2) # DIVIDE
sublist1 = merge_sort(l[:pivot]) # CONQUER
s1idx = 0
sublist2 = merge_sort(l[pivot:]) # CONQUER
s2idx = 0
for i in range(len(l)): # COMBINE
if (
(not s2idx < len(sublist2)) # If at end of sublist 2
or (s1idx < len(sublist1) and sublist1[s1idx] < sublist2[s2idx])
# or if sublist 1 has remaining elements and selected element is smaller than in list two
):
l[i] = sublist1[s1idx]
s1idx += 1
else:
l[i] = sublist2[s2idx]
s2idx += 1
return l
assert merge_sort([2,1,4,6]) == [1, 2, 4, 6]
assert merge_sort([7,3,10,4]) == [3, 4, 7, 10]
assert merge_sort([7]) == [7]
assert merge_sort([]) == []
import math
DEBUG = False
def quick_sort(l, start=0, end=None):
""" LUC
:param l: Input list, to sort
:param start: First index of range to operate on
:param end: Last index of range to operate on (last element is end-1)
:return: Sorted list
"""
if DEBUG: print("\n\nStarting {}".format(l))
if end is None:
end = len(l)
if DEBUG: print("Operating idx {}->{}-1".format(start, end))
if end - start <= 1: # Empty or single lists are sorted
if DEBUG: print("Ended")
return l
# Select pivot
pidx = math.ceil((end-start)/2) + start - 1
pval = l[pidx]
if DEBUG: print("Pivot: {} (idx {})".format(pval, pidx))
# Move pivot to end
l[pidx] = l[end-1]
l[end-1] = pval
pidx = end-1
while True:
if DEBUG: print("Loop {}".format(l))
#if DEBUG: print(l[start:end])
left = start # Move left selector from start until reaching a value greater than or equal to pivot
while l[left] < pval and left <= end-2:
left += 1
if DEBUG: print("Left:", left)
right = end - 2 # Move right selector from second to last until reaching a value less than or equal to pivot
while l[right] > pval and right >= start:
right -= 1
if DEBUG: print("Right:", right)
#if DEBUG: input()
if left >= right: # selectors have crossed
l[pidx] = l[right+1]
l[right+1] = pval
if DEBUG: print("Crossed swap {}".format(l))
if DEBUG: print("Recurse...")
quick_sort(l, start, left) # Operate on left sublist
quick_sort(l, left+1, end) # Operate on right sublist
return l
else: # intermediate swap
# swap values at left and right selectors
tmp = l[left]
l[left] = l[right]
l[right] = tmp
if DEBUG: print("Intermediate swap {}".format(l))
assert quick_sort([10,3,6,4,11]) == [3,4,6,10,11]
assert quick_sort([10,8,3,6,20,4]) == [3, 4, 6, 8, 10, 20]
assert quick_sort([10,5,3,2,8,3,6,20,4]) == [2, 3, 3, 4, 5, 6, 8, 10, 20]
assert quick_sort([10,8,3,6,20,4,18]) == [3,4,6,8,10,18,20]
assert quick_sort([]) == []
assert quick_sort([1]) == [1]
assert quick_sort([2,1]) == [1,2]
# LUC: Question 3
"""
Quick Sort can be the most efficient, with a potential for O(n). On average, the time complexity is O(nlogn), which is
the same as the consistent values of Merge Sort. However, the inefficient quadratic cases for Quick Sort are very
unlikely and therefore lead it to be more efficient the majority of the time.
Merge Sort also requires O(n) memory, due to the nature of copying elements into new arrays and merging them afterwards.
On the other hand, Quick Sort operates on a single list, in place. Therefore the algorithm only requires O(logn) memory
complexity as the recursive operation will have a call stack of size ~logn.
"""
|
a07ada7c787f741ef1884b2a455b69fdab98f28c | Nawod/Hactoberfest2021-1 | /Python/Guess_Number_Game.py | 1,416 | 4.03125 | 4 | import random
import sys
print('GUESS THE NUMBER')
#function for genarate random numbers according to the levels
def level(lvl):
global randNo
if lvl == 'E':
randNo = random.randint(1,10)
print('Guess a number between 1 & 10..')
elif lvl == 'N':
randNo = random.randint(1,20)
print('Guess a number between 1 & 20..')
elif lvl == 'H':
randNo = random.randint(1,30)
print('Guess a number between 1 & 30..')
else:
sys.exit('Invalid Input')
return randNo
#function for take the guessed numbers
def guessNo(randNo):
print('.......')
print('You have only 3 chances')
for i in range(0,3):
global guess
guess = int(input('Enter your guessed number : '))
if guess < randNo :
print('The number Is Too Low')
elif guess > randNo:
print('The number Is Too High')
else:
break
try:
#get level to generate a randome no
print('Select a level')
print('(Enter the level first letter)')
lvl = input('Easy\t- E\nNormal\t- N\nHard\t- H\n')
randNo = level(lvl)
guessNo(randNo)
#Checking the input number and random number
if guess == randNo:
print('Congradulations! You guessed the number')
else:
print('Wrong guess!\nMy number was '+str(randNo))
except (ValueError):
print("Enter a number only")
|
8040f07a2775078bcdc058cd58e49ef3c9fc2f96 | lydxlx1/icpc | /src/codeforces/_1131F.py | 883 | 3.5625 | 4 | """Codeforces 1131F
Somehow, recursive implementation of Union-Find Algorithm will hit stack overflow...
"""
from sys import *
n = int(stdin.readline())
parent, L, R, left, right = {}, {}, {}, {}, {}
for i in range(1, n + 1):
parent[i] = i
L[i] = R[i] = i
left[i] = right[i] = None
def find(i):
root = i
while parent[root] != root:
root = parent[root]
while i != root:
j = parent[i]
parent[i] = root
i = j
return root
def union(i, j):
i, j = find(i), find(j)
parent[i] = j # j is the new root
a, b, c, d = L[i], R[i], L[j], R[j]
L[j], R[j] = a, d
right[b], left[c] = c, b
for i in range(n - 1):
u, v = stdin.readline().split(' ')
union(int(u), int(v))
ans = []
root = L[find(1)]
for i in range(n):
ans.append(root)
root = right[root]
print(' '.join([str(i) for i in ans]))
|
c49b8274518bd59b4ba0fdfc75e6370afaec562b | lydxlx1/icpc | /src/adventofcode/2021_04.py | 2,430 | 3.53125 | 4 | import sys
import math
def readln_str():
return input().split(" ")
def readln_int():
return [int(i) for i in readln_str()]
class Board:
def __init__(self, A):
self.A = A
self.visited = [ [False for _ in range(len(A[0]))] for _ in range(len(A))]
def place(self, num):
A = self.A
for i in range(len(A)):
for j in range(len(A[0])):
if A[i][j] == num:
self.visited[i][j] = True
return
def win(self):
visited = self.visited
for i in range(len(visited)):
if all(visited[i]):
return True
for j in range(len(visited[0])):
if all(visited[i][j] for i in range(len(visited))):
return True
return False
def unmarked_sum(self):
ans = 0
A, visited = self.A, self.visited
for i in range(len(A)):
for j in range(len(A[0])):
if not visited[i][j]:
ans += A[i][j]
return ans
def part1():
lines = [line.strip() for line in fin.read().strip().split("\n") if line.strip() != '']
seq = [int(token) for token in lines[0].split(",")]
puzzles = []
i = 1
while i < len(lines):
A = []
for _ in range(5):
row = [int(token) for token in lines[i].split(" ") if token.strip() != ""]
A.append(row)
i += 1
puzzles.append(Board(A))
def doit():
for i in seq:
for puzzle in puzzles:
puzzle.place(i)
if puzzle.win():
return i * puzzle.unmarked_sum()
return None
print(doit())
def part2():
lines = [line.strip() for line in fin.read().strip().split("\n") if line.strip() != '']
seq = [int(token) for token in lines[0].split(",")]
puzzles = []
i = 1
while i < len(lines):
A = []
for _ in range(5):
row = [int(token) for token in lines[i].split(" ") if token.strip() != ""]
A.append(row)
i += 1
puzzles.append(Board(A))
ans = None
for i in seq:
for puzzle in puzzles:
if not puzzle.win():
puzzle.place(i)
if puzzle.win():
ans = i * puzzle.unmarked_sum()
print(ans)
with open('in.txt', 'r') as fin:
# part1()
part2()
|
36f9546b9a292d58f205ff22c9895fa65b0a70d9 | Meldanen/kcl | /scientific_programming/algorithm_optimisation/pathing.py | 10,269 | 3.578125 | 4 | from itertools import chain
import math
from algorithmType import AlgorithmType
import numpy as np
def getAdjustedImageArray(image, algorithmType, size=None):
"""
Returns an image with the best path based on the selected method
:param image: The image from which we'll look for the best path
:param size: The image's size
:param algorithmType: The algorithm type (i.e. dynamic)
:return: an image that includes the best path
"""
validateAlgorithmType(algorithmType)
validateImage(image)
return getImageWithBestPath(image, size, algorithmType)
def getImageWithBestPath(image, size, algorithmType):
"""
Returns an image with the best path based on the selected method
:param image: The image from which we'll look for the best path
:param size: The image's size
:param algorithmType: The algorithm type (i.e. dynamic)
:return: an image that includes the best path
:raises: NotImplementedError if the algorithm type is not one of the implemented ones
"""
if algorithmType is algorithmType.BRUTE_FORCE:
return getImageWithBestPathBruteForce(image, size)
elif algorithmType is algorithmType.DYNAMIC:
return getImageWithBestPathDynamic(image)
raise NotImplementedError
def getImageWithBestPathDynamic(image):
"""
Returns an image with the best path
:param image: The image from which we'll look for the best path
:return: an image with the best path
"""
if not isinstance(image, np.ndarray):
image = np.array(image)
costArray, backtrack = getCostAndBacktrackArrays(image)
rows, columns = image.shape
imageWithBestPath = np.zeros((rows, columns), dtype=np.int)
j = np.argmin(costArray[-1])
for i in reversed(range(rows)):
imageWithBestPath[i, j] = 1
j = backtrack[i, j]
return imageWithBestPath
def getCostAndBacktrackArrays(image):
"""
Computes the cost array which contains the best path and a backtrack array to trace the steps
:param image: The image from which we'll look for the best path
:return: a cost array for the best path and the backtrack array
"""
rows, columns = image.shape
cost = image.copy()
backtrack = np.zeros_like(cost, dtype=np.int)
cost[0, :] = 0
for i in range(1, rows):
for j in range(0, columns):
# Make sure we don't try to use a negative index if we're on the left edge
if j == 0:
previousCosts = cost[i - 1, j:j + 2]
costOfCurrentPaths = abs(image[i - 1, j:j + 2] - image[i, j])
indexOfBestNode = np.argmin(previousCosts + costOfCurrentPaths)
backtrack[i, j] = indexOfBestNode + j
costBetweenTheTwoNodes = abs(image[i - 1, indexOfBestNode + j] - image[i, j])
previousCost = cost[i - 1, indexOfBestNode + j]
cost[i, j] = previousCost + costBetweenTheTwoNodes
else:
previousCosts = cost[i - 1, j - 1:j + 2]
costOfCurrentPaths = abs(image[i - 1, j - 1:j + 2] - image[i, j])
indexOfBestNode = np.argmin(previousCosts + costOfCurrentPaths)
backtrack[i, j] = indexOfBestNode + j - 1
costBetweenTheTwoNodes = abs(image[i - 1, indexOfBestNode + j - 1] - image[i, j])
previousCost = cost[i - 1, indexOfBestNode + j - 1]
cost[i, j] = previousCost + costBetweenTheTwoNodes
return cost, backtrack
def getImageWithBestPathBruteForce(image, size):
"""
Creates all the possible paths and then finds the best one
:param image: The image from which we'll look for the best path
:param size: The image's size
:return: an image with the best path
"""
size = getSize(image, size)
validateSize(size)
rows, columns = size
paths = None
for i in range(columns):
if paths is None:
paths = getAllPossiblePathsBruteForce(image, 0, i, rows - 1)
else:
paths = chain(paths, getAllPossiblePathsBruteForce(image, 0, i, rows - 1))
bestPath = getBestPathBruteForce(image, paths)
return convertBestPathToImageWithBestPathBruteForce(image, bestPath, rows, columns)
def convertBestPathToImageWithBestPathBruteForce(image, bestPath, rows, columns):
"""
Converts the best path to an image with the best path
Not entirely sure if we need to return a different type depending on the initial one but I included it just in case
:param image: The image from which we'll look for the best path
:param bestPath: The best path
:param rows: The image's rows
:param columns: The image's columns
:return: an image with the best path
"""
if isinstance(image, np.ndarray):
return getImageWithBestPathForNumpyArray(bestPath, rows, columns)
return getImageWithBestPathForPythonList(bestPath, rows, columns)
def getImageWithBestPathForPythonList(bestPath, rows, columns):
"""
Converts the best path to an python list with the best path
:param bestPath: The best path
:param rows: The image's rows
:param columns: The image's columns
:return: an image with the best path
"""
imageWithBestPath = [[0] * columns for _ in range(rows)]
for i in range(rows):
for j in range(columns):
if (i, j) in bestPath:
imageWithBestPath[i][j] = 1
return imageWithBestPath
def getImageWithBestPathForNumpyArray(bestPath, rows, columns):
"""
Converts the best path to a numpy array with the best path
:param bestPath: The best path
:param rows: The image's rows
:param columns: The image's columns
:return: an image with the best path
"""
imageWithBestPath = np.zeros((rows, columns), dtype=np.int)
for i in range(rows):
for j in range(columns):
if (i, j) in bestPath:
imageWithBestPath[i, j] = 1
return imageWithBestPath
def getBestPathBruteForce(image, paths):
"""
Evaluates all paths in the image to find the best one
:param image: The image from which we'll look for the best path
:param paths: All the possible paths
:return: The best path
"""
bestScore = math.inf
bestPath = None
for path in paths:
score = 0
for i, j in path:
# Stop if we reached the last node
if i + 1 < len(path):
x = path[i][0]
y = path[i][1]
w = path[i + 1][0]
z = path[i + 1][1]
value1 = image[x][y]
value2 = image[w][z]
score += abs(value1 - value2)
if score < bestScore:
bestScore = score
bestPath = path
return bestPath
def getAllPossiblePathsBruteForce(image, i, j, rows, current_path=None):
"""
Calculates all the possible paths in the image
:param image: The image from which we'll look for the best path
:param i: The current row
:param j: The current column
:param rows: The total rows
:param current_path: The current path
:return: a list with all possible paths
"""
if current_path is None:
current_path = [(i, j)]
if i == rows:
yield current_path
else:
for x, y in getPossibleNeighbors(image, i, j):
if (x, y) not in current_path:
for path in getAllPossiblePathsBruteForce(image, x, y, rows, current_path + [(x, y)]):
yield path
def getPossibleNeighbors(image, i, j):
"""
Finds the possible neighbours from the current point
:param image: The image from which we'll look for the best path
:param i: The current row
:param j: The current column
:return:
"""
for x, y in getAdjacentCells(i, j):
if 0 <= x < len(image[0]) and 0 <= y < len(image):
yield (x, y)
def getAdjacentCells(i, j):
"""
Returns the direction of movement from the current node
:param i: The current row
:param j: The current column
:return: The direction of movement from the current node
"""
yield (i + 1, j - 1)
yield (i + 1, j)
yield (i + 1, j + 1)
def validateAlgorithmType(algorithmType):
"""
:param algorithmType: The solution method (i.e. dynamic)
:raises ValueError: if the algorithm type is invalid
"""
if algorithmType is None or not isinstance(algorithmType, AlgorithmType):
raise TypeError("Please use a valid algorithm type")
def validateImage(image):
"""
:param image: The image from which we'll look for the best path
:raises ValueError: if the image is invalid
"""
if image is None or len(image) == 0:
raise ValueError("Image is empty or null")
def validateSize(size):
"""
:param size: The image's size
:raises ValueError: if the size is invalid
"""
if size is None or size[0] <= 0 or size[1] <= 0:
raise ValueError("Dimensions must be greater than zero")
def getSize(image, size):
"""
Get the size of the image
:param image: The image from which we'll look for the best path
:param size: If it's provided, we assume the user knows what they are doing
:return: the size of the image
"""
if size is not None:
return size
if isinstance(image, np.ndarray):
return getNumpyArraySize(image)
return getPythonListSize(image)
def getNumpyArraySize(image):
"""
Get the size of the image for numpy arrays
:param image: The image from which we'll look for the best path
:return: the size of the image
"""
return image.shape
def getPythonListSize(image):
"""
The size of the image for python lists.
If the length of a sublist is inconsistent (i.e. [[1,2,3], [1,2], [1,2,3]]) we raise an exception
:param image: The image from which we'll look for the best path
:return: the size of the image
:raises ValueError: For inconsistent image dimensions
"""
rows = len(image)
columns = None
for column in image:
if columns is None:
columns = len(column)
if len(column) != columns or columns != rows:
raise ValueError("Image dimensions are inconsistent")
return rows, columns
|
4b01cbf0895f080bfee152a52c3bcceed8b2df6e | nicoleta23-bot/instructiunea-if-while-for | /prb2.py | 151 | 3.921875 | 4 | import math
n=int(input("dati numarul natural nenegativ n="))
s=0
for i in range (1,n+1):
s+=(math.factorial(i))
print("suma 1!+2!+...n!= ",s) |
1a7fcc21c19fe743f7517e5221b4de3fe871cf7c | tbgdwjgit/python3 | /baseTest/first.py | 6,425 | 4.15625 | 4 | __author__ = 'Test-YLL'
# -*- coding:utf-8 -*-
import os
print("Hello Python interpreter!")
print("中文也没问题!")
print('翻倍'*3)
print('45+55')
print(45+55)
#注释
'''
多行
print("Hello World")
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
变量名只能包含以下字符:
• 小写字母(a~z)
• 大写字母(A~Z)
• 数字(0~9)
• 下划线(_)
名字不允许以数字开头。
'''
'''
列表
'''
# letters =[2,22,'2cd',5]
# print(letters[1])
# #append()和 extend()的区别
# letters.append('vvv')
# letters.extend(['mmm'])
# letters.extend('mmm')
# letters.insert(3,'55')
# print(letters)
# letters.remove('55')
# print(letters)
# del letters[0]
# print(letters)
# print(letters.pop(1))
# print(letters.pop(1))
# print(letters.pop(0))
# print(letters)
# letters.sort()#改变你提供的原始列表,而不是创建一个新的有序列表
# print(letters)
# letters.reverse()
# print(letters)
'''
集合
[] 能创建一个空列表
{} 会创建一个空字典
空集输出为 set()
'''
print(set())
s_test ={1,2,3,4}
s_test.add('a')
print(s_test)
"""
控制流
"""
# print('What is your name?')
# name = input()
# print('What is your age?')
# age = input()
#
# if name == 'Alice':
# print('Hi, Alice.')
# elif int(age) < 12:
# print('You are not Alice, kiddo.')
# else:
# print('You are neither Alice nor a little kid.')
# while True:
# print('Who are you?')
# name = input()
# if name != 'Joe':
# continue
# print('Hello, Joe. What is the password? (It is a fish.)')
# password = input()
# if password == 'swordfish':
# break
# print('Access granted.')
# print('My name is')
# for i in range(5):
# print('Jimmy Five Times (' + str(i) + ')')
# import random
# for i in range(5):
# print(random.randint(1, 10))
#
# import sys
# sys.exit()
'''
函数
'''
# def hello(name):
# print('Hello ' + name)
#
# hello('Alice')
# hello('Bob')
def printMyNameBig():
print(" CCCC A RRRRR TTTTTTT EEEEEE RRRRR ")
print(" C C A A R R T E R R ")
print("C A A R R T EEEE R R ")
print("C AAAAAAA RRRRR T E RRRRR ")
print(" C C A A R R T E R R ")
print(" CCCC A A R R T EEEEEE R R")
print()
# for i in range(2):
# printMyNameBig();
'''类'''
class Dog():
'''一次模拟小狗的简单尝试'''
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
#特殊方法是 __str__(),它会告诉 Python 打印(print)一个对象时具体显示什么内容。
def __str__(self):
msg = "Hi, I'm a " + self.name + " " + str(self.age) + " ball!"
return msg
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " rolled over!")
d = Dog('jack',10)
# d.sit()
# print(d)
'''继承'''
# class Car():
# """一次模拟汽车的简单尝试"""
#
# def __init__(self, make, model, year):
# self.make = make
# self.model = model
# self.year = year
# self.odometer_reading = 0
#
# def get_descriptive_name(self):
# long_name = str(self.year) + ' ' + self.make + ' ' + self.model
# return long_name.title()
#
# def read_odometer(self):
# print("This car has " + str(self.odometer_reading) + " miles on it.")
#
# def update_odometer(self, mileage):
# if mileage >= self.odometer_reading:
# self.odometer_reading = mileage
# else:
# print("You can't roll back an odometer!")
#
# def increment_odometer(self, miles):
# self.odometer_reading += miles
#
# class ElectricCar(Car):
# """电动汽车的独特之处"""
#
# def __init__(self, make, model, year):
# """初始化父类的属性"""
# super().__init__(make, model, year)
#
# my_tesla = ElectricCar('tesla', 'model s', 2016)
# print(my_tesla.get_descriptive_name())
'''
文件处理
os.getcwd()取当前目录
os.path.dirname(os.getcwd())取当前目录上一级目录
'''
import re
def transformCodec(re_data):#ascii (gbk) 转 unicode
try:
re_data = re_data.decode('gbk')
except Exception as error:
print(error)
print('delete illegal string,try again...')
pos = re.findall(r'decodebytesinposition([\d]+)-([\d]+):illegal',str(error).replace(' ',''))
if len(pos)==1:
re_data = re_data[0:int(pos[0][0])]+re_data[int(pos[0][1]):]
re_data = transformCodec(re_data)
return re_data
return re_data
textFile = open(os.path.pardir +'\\readme.txt')
# textFile ='C:\\Users\\Test-YLL\\PycharmProjects\\python3\\test.txt'
# textFile =u'test.txt'
print(textFile)
print(os.path.dirname(os.getcwd()) +'\\readme.txt')
textFile = os.path.dirname(os.getcwd()) +'\\readme.txt'
# with open('test.txt') as file_object:
with open(textFile) as file_object:
contents = file_object.read()
print(contents)
# print(os.getcwd())
# print(os.path.dirname(os.getcwd()))
# textFile =os.path.dirname(os.getcwd())+r'\readme.txt'
# print(textFile)
# with open(textFile,'rb') as file_object:
# # with open(textFile,'r', encoding='gbk') as file_object:
# # contents = file_object.read()
# contents = transformCodec( file_object.read()) #转码
# print(contents)
'''
Python数据可视化:Matplotlib
pip install matplotlib
pip install pandas
pip install xlrd
'''
# a = 5
# matplotlib.lines
# from matplotlib.pyplot import plot
# plot(a, a**2)
# import matplotlib.pyplot as plt
# import pandas as pd
# # import seaborn as sns
# import numpy as np
#
# # 0、导入数据集
# df = pd.read_excel('first.xlsx', 'Sheet1')
#
# var = df.groupby('BMI').Sales.sum()
# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.set_xlabel('BMI')
# ax.set_ylabel('Sum of Sales')
# ax.set_title('BMI wise Sum of Sales')
# var.plot(kind='line')
#
# plt.show()
|
ebc8d4374db54e557755d67cfe9d39631575fb3e | chm7374/linera_algebra_final | /linear_algebra_final/main.py | 3,078 | 3.625 | 4 | import numpy as np
import fractions
def create_matrix():
print("2x2 matrix:\n[ m11 m12 ]")
print("[ m21 m22 ]")
m11 = float(input("Enter the value of m11: "))
m12 = float(input("Enter the value of m12: "))
m21 = float(input("Enter the value of m21: "))
m22 = float(input("Enter the value of m22: "))
mat = np.matrix([[m11,m12], [m21, m22]])
mat_array = np.array([[m11,m12], [m21, m22]])
print(mat)
print("\nExponential of Matrix: ")
print(np.dot(np.array([[m11,m12],[m21,m22]]), np.array([[m11,m12],[m21,m22]])))
return mat, mat.trace(), mat_array
def transpose_matrix(mat):
mat_trs = np.matrix.getT(mat)
print(mat_trs)
return mat_trs
def invert_matrix(mat):
mat_inv = np.matrix.getI(mat)
print(mat_inv)
return mat_inv
def determinant_matrix(mat):
mat_det = np.linalg.det(mat)
print(str(round(mat_det, 4)))
return mat_det
def rref(A, tol=1.0e-12):
m, n = A.shape
i, j = 0, 0
jb = []
while i < m and j < n:
# Find value and index of largest element in the remainder of column j
k = np.argmax(np.abs(A[i:m, j])) + i
p = np.abs(A[k, j])
if p <= tol:
# The column is negligible, zero it out
A[i:m, j] = 0.0
j += 1
else:
# Remember the column index
jb.append(j)
if i != k:
# Swap the i-th and k-th rows
A[[i, k], j:n] = A[[k, i], j:n]
# Divide the pivot row i by the pivot element A[i, j]
A[i, j:n] = A[i, j:n] / A[i, j]
# Subtract multiples of the pivot row from all the other rows
for k in range(m):
if k != i:
A[k, j:n] -= A[k, j] * A[i, j:n]
i += 1
j += 1
# Finished
return A, jb
def eigen_matrix(mat):
eigval_mat, eigvec_mat = np.linalg.eig(mat)
print(eigval_mat)
print("\nEigenvectors of Matrix: ")
print(eigvec_mat)
# The main function is the first thing the program will run when started.
if __name__ == '__main__':
# Makes it so the output is printed as fractions instead of decimals.
np.set_printoptions(formatter={'all': lambda x: str(fractions.Fraction(x).limit_denominator())})
print("Matrix Equation Solver Thingy!\nby Cameron MacDonald | chm7374\n")
mat, mat_trace, mat_array = create_matrix()
print("\nTranspose of matrix: ")
mat_trs = transpose_matrix(mat)
print("\nInverse of matrix: ")
mat_inv = invert_matrix(mat)
print("\nDeterminant of matrix: ", end="")
mat_det = determinant_matrix(mat)
print("\nReduced row matrix: ")
rref_mat, j = rref(mat)
print(rref_mat)
print("\nRank of Matrix:", np.linalg.matrix_rank(mat))
str_trace = str(mat_trace)[2:]
str_trace = str_trace[:1]
print("Trace of Matrix:", str_trace)
np.set_printoptions(precision=5)
print("\nEigenvalues of Matrix: ")
eigen_matrix(mat_array)
|
5c9d24c0cc24a7f0346fe7cee3239a467c51dd6d | zainiftikhar52422/Perceptron-learning-gates-given-theta | /perceptron learning And gate.py | 1,127 | 3.71875 | 4 | import random
def andGate():
# Or gate Learning
# in and gate you can increase decimal points as much as you want
weight1=round(random.uniform(-0.5,0.5), 1) # to round the out to 1 decimal point
weight2=round(random.uniform(-0.5,0.5), 1) # to round the out to 1 decimal point
print("Weighted intialization",weight1,weight2)
thetha=0.2
alpha=0.1
flage=True # flage will be false when convergence reaches
output=1
andGate=((0,0,0),(0,1,0),(1,0,0),(1,1,1))
while(flage==True):
flage=False
for examp in andGate:
value=(examp[0]*weight1)+(examp[1]*weight2)
if(value>=thetha): #if perceptoron excited
output=1
else:
output=0
if((output-examp[2])!=0):
weight1=round(weight1+(alpha*(examp[2]-output)*examp[0]),1) # to round the out to 1 decimal point
weight2=round(weight2+(alpha*(examp[2]-output)*examp[1]),1) # to round the out to 1 decimal point
flage=True
print(weight1,weight2)
for i in range(5):
andGate() |
3009d64a201ffd4616985588111ec747f510925c | m-blue/prg105-Ex-16.1-Time | /Time.py | 331 | 4.09375 | 4 | class Time():
"""
This will hold an object of time
attributes: hours, minutes, seconds
"""
def print_time(hour, minute, sec):
print '%.2d:%.2d:%.2d' % (hour, minute, sec)
time = Time()
time.hours = 4
time.minutes = 30
time.seconds = 45
print_time(time.hours, time.minutes, time.seconds)
|
2cee626ca8bbdd1c78751e9df019279d323d1e06 | Philngtn/pythonDataStructureAlgorithms | /Arrays/ArrayClass.py | 1,291 | 4.15625 | 4 | # # # # # # # # # # # # # # # # # # # # # # # #
# Python 3 data structure practice
# Chap 1: Implementing Class
# Author : Phuc Nguyen (Philngtn)
# # # # # # # # # # # # # # # # # # # # # # # #
class MyArray:
def __init__(self):
self.length = 0
# Declare as dictionary
self.data = {}
# Convert the class object into string
def __str__(self):
# convert all the class object to dictionary type {length, data}
return str(self.__dict__)
def get(self,index):
return self.data[index]
def push(self, item):
self.data[self.length]= item
self.length +=1
def pop(self):
lastitem = self.data[self.length - 1]
del self.data[self.length - 1]
self.length -= 1
return lastitem
def delete(self, index):
deleteditem = self.data[index]
# Shifting the data to one slot
for i in range(index, self.length -1):
self.data[i] = self.data[i+1]
# Delete the last array slot
del self.data[self.length - 1]
self.length -= 1
return deleteditem
newArray = MyArray()
newArray.push("Hello. ")
newArray.push("How")
newArray.push("are")
newArray.push("you")
newArray.push("!")
newArray.delete(1)
print(newArray)
|
e96d19e436a77fcca9e16e143a81ea58eee15997 | Philngtn/pythonDataStructureAlgorithms | /String.py | 3,163 | 4 | 4 | # # # # # # # # # # # # # # # # # # # # # # # #
# Python 3 data structure practice
# Chap 0: String
# Author : Phuc Nguyen (Philngtn)
# # # # # # # # # # # # # # # # # # # # # # # #
# Strings in python are surrounded by either single quotation marks, or double quotation marks.
print("Hello World")
print('Hello World 2')
# You can assign a multiline string to a variable by using three quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
##################### Strings are Arrays ######################
a = "Hello, World"
print(a[1])
# Output: e
# Looping Through a String
for x in "philngtn":
print(x)
# Output: philngtn
# String Length
print(len(a))
# Check String
txt = "The best things in life are free!"
print("free" in txt)
# Check NOT in String
txt = "The best things in life are free!"
print("expensive" not in txt)
##################### Slicing Strings ######################
b = "Hello, World2"
print(b[2:5])
# Output: llo,
# Slice From the Start
b = "Hello, World3"
print(b[:5])
# Output: Hello,
# Slice To the End
b = "Hello, World!"
print(b[2:])
# Negative Indexing
# Use negative indexes to start the slice from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
# From: "o" in "World!" (position -5) to, but not included: "d" in "World!" (position -2):
##################### Modify Strings ######################
# The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
# Lower Case
a = "Hello, World!"
print(a.lower())
# Remove Whitespace
# The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
# Replace String
a = "Hello, World!"
print(a.replace("H", "J"))
# Split String
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
##################### String Concatenation ######################
a = "Hello"
b = "World"
c = a + b
print(c)
##################### String Format ######################
# The format() method takes the passed arguments, formats them,
# and places them in the string where the placeholders {} are:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
# You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
##################### Escape Characters ######################
# To insert characters that are illegal in a string, use an escape character.
txt = "We are the so-called \"Vikings\" from the north."
# \' Single Quote
# \\ Backslash
# \n New Line
# \r Carriage Return
# \t Tab
# \b Backspace
# \f Form Feed
# \ooo Octal value
# \xhh Hex value
|
9fb22d73c2c5983d48283c648ab5ef1527cb4c1e | Philngtn/pythonDataStructureAlgorithms | /LinkedList/LinkedListClass.py | 3,734 | 4.03125 | 4 | # # # # # # # # # # # # # # # # # # # # # # # #
# Python 3 data structure practice
# Chap 3: Linked List
# Author : Phuc Nguyen (Philngtn)
# # # # # # # # # # # # # # # # # # # # # # # #
from typing import NoReturn
class Node:
def __init__(self, data):
self.value = data
self.next = None
def __str__(self):
return str(self.__dict__)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def __str__(self):
return str(self.__dict__)
def append(self,value):
newNode = Node(value)
if (self.length == 0):
self.head = newNode
self.tail = self.head
self.length += 1
else:
self.tail.next = newNode
self.tail = newNode
self.length += 1
def prepend(self, value):
newNode = Node(value)
if (self.length == 0):
self.head = newNode
self.tail = self.head
self.length += 1
else:
newNode.next = self.head
self.head = newNode
self.length += 1
def insert(self, value, location):
newNode = Node(value)
temp = self.head
count = 0
if (self.length == 0):
self.head = newNode
self.tail = self.head
self.length += 1
return 0
while (True):
if location > self.length:
self.append(value)
break
elif location == 0:
self.prepend(value)
break
else:
if (count != (location - 1)):
temp = temp.next
count += 1
else:
newNode.next = temp.next
temp.next = newNode
self.length +=1
return 0
def remove(self,location):
temp = self.head
count = 0
while(True):
if location > self.length or location < 0:
return print("Error: location should be within length: " + str(self.length))
if (count != (location-1)):
temp = temp.next
count += 1
else:
temp2 = temp.next
temp.next = temp2.next
temp2 = None
self.length -= 1
return 0
def reverse(self):
temp = self.head
# set the tail at the beginning
self.tail = self.head
temp2 = temp.next
if (self.length == 0):
return "Empty list"
if (self.length == 1):
return 0
while (temp2 != None):
temp3 = temp2.next
temp2.next = temp
temp = temp2
temp2 = temp3
self.head.next = None
# set the head at the end of reverse list
self.head = temp
def printList(self):
temp = self.head
while temp != None:
print(temp.value, end= ' ')
temp = temp.next
print()
print('Length = ' + str(self.length))
myLinkedList = LinkedList()
myLinkedList.append(22)
myLinkedList.append(223)
myLinkedList.append(221)
myLinkedList.prepend(2123)
myLinkedList.prepend(88)
myLinkedList.prepend(53)
myLinkedList.insert(1,22)
myLinkedList.insert(42,0)
myLinkedList.insert(1,4)
myLinkedList.remove(4)
myLinkedList.remove(99)
print("--------------------")
print("Linklist:")
myLinkedList.printList()
print("--------------------")
print("Revered Linklist:")
myLinkedList.reverse()
myLinkedList.printList()
|
280fbe40b133e0b47f101f5855014fdb1fcb8815 | Philngtn/pythonDataStructureAlgorithms | /Algorithm/Sorting/BubbleSort.py | 338 | 4.0625 | 4 | def bubble_sort(array):
count = len(array)
while(count):
for i in range(len(array) - 1) :
if(array[i] < array[i+1]):
temp = array[i]
array[i] = array[i + 1]
array[i + 1] = temp
count -= 1
a = [1,2,4,61,1,2,3]
bubble_sort(a)
print(a)
|
875635c71286360aef3af5b485e87d195974fa32 | sepej/162P | /Lab6/main.py | 478 | 3.859375 | 4 | # Joseph Sepe CS162P Lab 6B
from helper import *
def main():
employees = []
# get number of employees to enter
print("How many employees work at the company?")
num_employees = get_integer(5, 10)
# create an employee and add it to the list for num_employees
for i in range(num_employees):
new_employee = create_employee()
employees.append(new_employee)
display_employees(employees)
exit()
if __name__ == '__main__':
main() |
bc1fb8b5ec979d6031e2dfaf934defff52e6d45b | sepej/162P | /Lab1/functions.py | 4,197 | 4.03125 | 4 | # Display instructions
def display_instructions():
print('\nWelcome to Tic-Tac-Toe\nTry to get 3 in a row!')
# Reset board, rewrites the board list with ''
def init_board(board):
for idx, value in enumerate(board):
board[idx] = ''
# Get the player name, Returns X or O
# Adds the possibility of letting players type their own names in.
def player_name(player):
if player == 0:
return 'X'
else:
return 'O'
def player_char(player):
if player == 0:
return 'X'
else:
return 'O'
# Display the board
def show_board(board):
for idx, value in enumerate(board):
if value == '':
value = str(idx+1)
if (idx+1) % 3 == 0:
print('[' + value + ']')
else:
print('[' + value + ']', end='')
print('')
# Returns the valid move
def valid_moves(board):
validMoves = []
for idx, value in enumerate(board):
if value == '':
validMoves.append(idx+1)
return validMoves
# Enter the player's move
def get_move(board, player):
# Print player's name, calling function
print("\nIt's " + player_name(player) + "'s turn\n")
show_board(board)
# Get a list of valid moves for the current board
valid = valid_moves(board)
# Enter the players move into the list
while True:
print("Move: ")
choice = input()
choice_int = int(choice)
if choice_int in valid:
board[choice_int-1] = player_char
break
else:
print("Please choose a valid move")
show_board(board)
# Check win condition, returns true or false
def check_win(board):
# Check two squares, if they are the same then check the next in the sequence
if board[4] == board[0] and board[4] != '':
if board[4] == board[8]:
# Player won, change the array to display a line where they won.
board[0] = '\\'
board[4] = '\\'
board[8] = '\\'
show_board(board)
return True
if board[4] == board[2] and board[4] != '':
if board[4] == board[6]:
board[2] = '/'
board[4] = '/'
board[6] = '/'
show_board(board)
return True
if board[4] == board[1] and board[4] != '':
if board[4] == board[7]:
board[1] = '|'
board[4] = '|'
board[7] = '|'
show_board(board)
return True
if board[0] == board[3] and board[0] != '':
if board[0] == board[6]:
board[0] = '|'
board[3] = '|'
board[6] = '|'
show_board(board)
return True
if board[8] == board[5] and board[8] != '':
if board[8] == board[2]:
board[2] = '|'
board[5] = '|'
board[8] = '|'
show_board(board)
return True
if board[8] == board[7] and board[8] != '':
if board[8] == board[6]:
board[6] = '-'
board[7] = '-'
board[8] = '-'
show_board(board)
return True
if board[4] == board[3] and board[4] != '':
if board[4] == board[5]:
board[3] = '-'
board[4] = '-'
board[5] = '-'
show_board(board)
return True
if board[0] == board[1] and board[0] != '':
if board[0] == board[2]:
board[0] = '-'
board[1] = '-'
board[2] = '-'
show_board(board)
return True
return False
# Check draw, if no win's then return true
def check_draw(board):
if check_win(board) == False:
return True
# Play again question
def play_again():
return yes_no("Do you want to play again? (y/n)")
# Passes in the question and then returns true or false for yes or no
def yes_no(question):
valid = ['y', 'n']
while True:
print(question)
choice = input()
choice = choice.lower()
if choice in valid:
if choice == 'y':
return True
else:
return False
else:
print("Please type y or n") |
8557893e7488d2eb1993bbaf96b4e87a88a91bc4 | sepej/162P | /Lab6/Sepe_Lab6A/employee.py | 460 | 3.671875 | 4 | from person import *
class Employee:
# init employee class composition
def __init__(self, first_name = "", last_name = "", age = None):
self.__person = Person(first_name, last_name, age)
# return employee name
def get_employee_name(self):
return self.__person.get_first_name() + " " + self.__person.get_last_name()
# return employee age
def get_employee_age(self):
return self.__person.get_age()
|
6470b470180117635b5e5515ee39d08951ca1118 | Spencer-Weston/DatatoTable | /datatotable/typecheck.py | 4,509 | 4.125 | 4 | """
Contains type checks and type conversion functions
"""
from datetime import datetime, date
from enum import Enum
def set_type(values, new_type):
"""Convert string values to integers or floats if applicable. Otherwise, return strings.
If the string value has zero length, none is returned
Args:
values: A list of values
new_type: The type to coerce values to
Returns:
The input list of values modified to match their type. String is the default return value. If the values are
ints or floats, returns the list formatted as a list of ints or floats. Empty values will be replaced with none.
"""
if new_type == str:
coerced_values = [str(x) for x in values]
elif new_type == int or new_type == float:
float_values = [float(x) for x in values]
if new_type == int:
coerced_values = [int(round(x)) for x in float_values]
else:
coerced_values = float_values
else:
raise ValueError("{} not supported for coercing types".format(new_type.__name__))
return coerced_values
def _set_type(values, new_type):
"""Transforms a list of values into the specified new type. If the value has zero length, returns none
Args:
values: A list of values
new_type: A type class to modify the list to
Returns:
The values list modified to the new_type. If an element is empty, the element is set to None.
"""
new_vals = []
for i in values:
if len(i) > 0: # Some values may have len(0); we convert them to None to put into sql db
new_vals.append(new_type(i))
else:
new_vals.append(None)
return new_vals
def get_type(values):
"""Return the type of the values where type is defined as the modal type in the list.
Args:
values: A list or value to get the type for.
Returns:
The modal type of a list or the type of the element. Can be integer, float, string, datetime, or none
"""
if hasattr(values, "__len__") and (type(values) != type): # Checks if the object is iterable
val_types = []
for i in values:
val_types.append(_get_type(i))
type_set = set(val_types)
if len(type_set) == 1:
return type_set.pop()
elif len(type_set) == 2 and {None}.issubset(type_set): # None value allowance
return type_set.difference({None}).pop()
elif len(type_set) <= 3 and {int, float}.issubset(type_set):
diff = type_set.difference({int, float})
if not bool(diff) or diff == {None}:
return float
else:
return str
else: # All other possible combinations of value must default to string
return str
elif isinstance(values, Enum): # For enum objects, pass the value to the get_type function (right choice? IDK)
return _get_type(values.value)
else:
return _get_type(values)
def _get_type(val):
"""Return the type of the value if it is a int, float, or datetime. Otherwise, return a string.
Args:
val: A value to get the type of
Returns:
The type of the value passed into the function if it is an int, float, datetime, or string
Raise:
Exception: An exception raised if the val is not int, float, datetime, None, or string.
"""
if isinstance(val, int):
return int
elif isinstance(val, float):
return float
elif isinstance(val, datetime):
return datetime
elif isinstance(val, date):
return date
elif isinstance(val, str):
return str
elif isinstance(val, bool):
return bool
elif val is None:
return None
elif is_python_type(val): # Handles types that are passed explicitly
return val
else:
raise Exception("Val is not an int, float, datetime, string, Bool, or None")
def is_int(x):
"""Return true if X can be coerced to a integer. Otherwise, return false."""
try:
int(x) # Will raise ValueError if '.2'; will not raise error if .2
return True
except ValueError:
return False
def is_float(x):
"""Return true if X can be coerced to a float. Otherwise, return false."""
try:
float(x)
return True
except ValueError:
return False
def is_python_type(x):
if x in [int, float, datetime, str, bool, None]:
return True
else:
return False
|
f371d7904f943099dd17d251df171b63592d8c9c | hhost-madsen/prg105-drawingObject | /House.py | 633 | 3.515625 | 4 | import turtle
bob = turtle.Turtle()
alice = turtle.Turtle()
def square(t):
for i in range(4):
t.fd(100)
t.lt(90)
square(bob)
square(alice)
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
square(bob, 100)
def polygon(t, n, length):
angle = 360 / n
for i in range(n):
t.fd(length)
t.lt(angle)
bob.lt(90)
bob.fd(100)
bob.rt(90)
polygon(bob, 3, 100)
bob.rt(90)
bob.fd(100)
bob.lt(90)
bob.fd(40)
bob.lt(90)
bob.fd(50)
bob.rt(90)
bob.fd(20)
bob.rt(90)
bob.fd(50)
turtle.done()
|
d3c36626dce89bafc3df9b8e63adaab05bdd4c30 | etx77/protostar-write-up | /alpha.py | 170 | 4.0625 | 4 | #!/usr/bin/env python
import string
# this program is generate string to calculate return address
text = ""
for c in string.ascii_uppercase:
text += c*4
print text
|
9d7b65b56e55b02b6ff598018da15c9ce16ac4e2 | yitu257/pythondemo | /filterSquareInteger.py | 902 | 3.765625 | 4 | #过滤出1~100中平方根是整数的数:
import math
def is_sqr(x):
return math.sqrt(x)%1==0
templist=filter(is_sqr,range(1,101))
newlist=list(templist)
print(newlist)
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
print(globals())
#a=input("input:")
#print(a)
v=memoryview(bytearray("abcdef",'utf-8'))
print(v[1])
print(v[-1])
print(v[-2])
print(v[1:4])
print(v[1:4].tobytes())
print(v)
lst_t=("a",77,"bbcc",("user1","name","sex","age"))
print(lst_t[:2])
print(lst_t[:-3:-1])
print(lst_t[:3:2])
print(lst_t[::2])
print(lst_t[::-2])
dict = "abcd efgh";
print(dict)
print(repr(dict))
print(str(dict))
RANGE_NUM = 100
for i in (math.pow(x,2) for x in range(RANGE_NUM)): # 第一种方法:对列表进行迭代
# do sth for example
print(i)
|
ba97831c540e5109dd1cfe338c885f4004b191b8 | avshrudai1/recommedation_engine_chrome | /main.py | 1,044 | 3.625 | 4 | # importing the module
import pandas as pd
import csv
import numpy
from googlesearch import search
# taking input from user
val = input("Enter your command: ")
#splitting the command to subparts
K = val.split()
T = len(K)
def queryreform():
search_name = 'Brooks'
with open('tmdb_5000_movies.csv', 'r') as file:
output = re.findall(f'{search_name}.*', file.read())
for row in output:
items = row.split(',')
print(items[0], '>>' ,items[1])
def similar():
def searchit():
from googlesearch import search
for i in search(query, tld="co.in", num=1, stop=10, pause=2):
print(i)
#splitting the cases based on command length
if T == 0:
print("Error: no commands!")
elif T == 1:
query = "allintext:"
query = query.append(#columns)
searchit()
print(x)
elif T == 2:
query = "allintext:"
query = query.append(#columns)
searchit()
elif T == 3:
query = "allintext:"
query = query.append(#columns
searchit()
else:
print("Error: Too many commands!")
|
b9bdcf609dd73187034012475399c0eda465fb79 | yarlagaddalakshmi97/python-solutions | /python_set1_solutions/set1-4a.py | 173 | 3.5 | 4 | '''
a) The volume of a sphere with radius r is 4/3pr3. What is the volume of a sphere with radius 5?
Hint: 392.7 is wrong!
'''
r=5
volume=(4/3)*3.142*(r*r*r);
print(volume) |
5ab66decbeb7f56a685d621d6eb7695d6021ac47 | yarlagaddalakshmi97/python-solutions | /python_practice/cmd-args1.py | 470 | 4.0625 | 4 | from sys import argv
if(len(argv)<3):
print("insufficient arguments..can't proceed..please try again..")
elif argv[1]>argv[2] and argv[1]>argv[3]:
print("argument 1 is largest..")
elif argv[1]>argv[2] and argv[1]<argv[3]:
print("argument 3 is largest..")
elif argv[2]>argv[1] and argv[2]>argv[3]:
print("argument 2 is largest..")
elif argv[2] > argv[1] and argv[3] > argv[2]:
print("argument 3 is largest..")
else:
print("the numbers are same..") |
1b2b5047eaa337f94083a7b09e7b8103cc8170ca | yarlagaddalakshmi97/python-solutions | /python_practice/nested for loop.py | 792 | 4.0625 | 4 | '''
for i in range(1,10):
for j in range(1,i+1):
print(i,end=" ")
print("\n")
for i in range(1,10):
for j in range(1,i):
print(j,end=" ")
print("\n")
for i in range(1,10):
for j in range(1,i):
print("*",end=" ")
print("\n")
for i in range(1,5):
for j in range(1,5):
print("*",end=" ")
print("\n")
'''
'''
n=int(input("enter a number:\n"))
for i in range(1,n+2):
for j in range(1,i):
print("*",end=" ")
print("\n")
'''
'''
i=1
while(i<=5):
print(i)
i=i+1
'''
'''
i=1
while(i<=5):
print(i)
if(i==3):
print("you have reached the limit....")
print("bye")
break
i=i+1
'''
i=1
while(i<=5):
print(i)
i = i + 1
if(i==3):
print(i)
continue
|
9c3f2d4f7813d13d83db9c1b19108ac1dc2260ed | yarlagaddalakshmi97/python-solutions | /python_set3_solutions/set3-8.py | 617 | 4.0625 | 4 | '''
8.Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok).
How many abecedarian words are there? (i.e) "Abhor" or "Aux" or "Aadil" should return "True" Banana should return "False"
'''
def abecedarian(words):
for i in words:
for j in (0,len(i)):
if ord(i[j])>ord[j+1]:
print(i[j])
break
elif i[j]==i[len[i]-1]:
return i
else:
continue
words = input("enter words:\n").split(" ")
print(words)
print(abecedarian(words))
|
0606f08dfe5a4f9f41b38c60330ed5de7852c64e | yarlagaddalakshmi97/python-solutions | /python_practice/factorial.py | 101 | 3.578125 | 4 | def fact(n):
if n>0:
return 1
else:
return n*fact(n-1)
res=fact(7)
print(res) |
e3814888ad456dbcd5e9fc3ae048ff8395dfad80 | yarlagaddalakshmi97/python-solutions | /python_set2_solutions/set2-6.py | 790 | 4 | 4 | '''
6.Implement a function that satisfies the specification. Use a try-except block.
def findAnEven(l):
"""Assumes l is a list of integers
Returns the first even number in l
Raises ValueError if l does not contain an even number"""
'''
'''
try:
list1 = list(input("enter list of integers..:\n"))
num = 0
for l in list1:
if int(l) % 2 == 0 and num == 0 and int(l)!=0:
print(l)
num = l
if num == 0:
raise ValueError
except ValueError:
print("list does not contain an even number")
'''
list1=list(input("enter list\n"))
def findAnEven(l):
for i in l:
if int(i) % 2 == 0:
return i
else:
raise ValueError
try:
print(findAnEven(list1))
except ValueError:
print("no even numbers in list")
|
94c4554eea473193dff5415d66e7fe3253fd7d36 | yarlagaddalakshmi97/python-solutions | /python_set2_solutions/set2-4.py | 229 | 4.03125 | 4 | '''
4.Write a program that computes the decimal equivalent of the binary number 10011?
'''
string1='10011'
count=len(string1)-1
number=0
for char in string1:
number=number+(int(char)*(2**count))
count-=1
print(number)
|
7842f4fb35ab747fba9c8207b7eb4f1ec7a20a92 | MDLR29/python_class | /entrenamiento.py | 243 | 3.828125 | 4 | np=int(input(" usuarios a evaluar: "))
lm=1
sumed=0
while lm<=np :
genero=input(" cual es tu genero: ")
edad=int(input("escriba su edad: "))
lm = lm + 1
sumed=sumed+edad
promedio=sumed/np
print("el promedioes: ",promedio)
|
b515031a176de8d788207e9a53fafa3ae2e86559 | wnsdud4206/stockauto | /test2.py | 809 | 3.5625 | 4 | # from datetime import datetime
# t_now = datetime.now()
# t_9 = t_now.replace(hour=9, minute=0, second=0, microsecond=0)
# t_start = t_now.replace(hour=9, minute=5, second=0, microsecond=0)
# t_sell = t_now.replace(hour=15, minute=15, second=0, microsecond=0)
# t_exit = t_now.replace(hour=15, minute=20, second=0,microsecond=0)
# today = datetime.today().weekday()
# print('t_now: ' + str(t_now))
# print('t_9: ' + str(t_9))
# print('t_start: ' + str(t_start))
# print('t_sell: ' + str(t_sell))
# print('t_exit: ' + str(t_exit))
# print('week: ' + str(today))
def test_1():
global myText
myText = "awesome-text"
print("hello, world - 1 " + myText)
test_1()
def test_2():
print("hello, world - 2 " + myText)
test_2()
# myList = ["a", "b", "c"]
# print(len(myList))
# print(1 <= 1) |
8e17ae60197afe42c01addf2cf79aafcae6cd01e | Abhra-Debroy/Udacity-ML-Capstone | /utilties.py | 6,889 | 3.6875 | 4 | ## Disclaimer : Reuse of utility library from Term 1 course example
###########################################
# Suppress matplotlib user warnings
# Necessary for newer version of matplotlib
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
#
# Display inline matplotlib plots with IPython
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
###########################################
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score
from sklearn.cluster import KMeans,MiniBatchKMeans
from sklearn.model_selection import learning_curve
from sklearn.metrics import roc_auc_score
# my_pca function was taken from class notes and altered
def my_pca(data, n_components = None):
'''
Transforms data using PCA to create n_components, and provides back the results of the
transformation.
INPUT: n_components - int - the number of principal components , default is None
OUTPUT: pca - the pca object after transformation
data_pca - the transformed data matrix with new number of components
'''
pca = PCA(n_components)
data_pca = pca.fit_transform(data)
return pca, data_pca
def plot_pca(pca):
'''
Creates a scree plot associated with the principal components
INPUT: pca - the result of instantian of PCA i
OUTPUT:
None
'''
n_components=len(pca.explained_variance_ratio_)
ind = np.arange(n_components)
vals = pca.explained_variance_ratio_
plt.figure(figsize=(10, 6))
ax = plt.subplot(111)
cumvals = np.cumsum(vals)
ax.bar(ind, vals)
ax.plot(ind, cumvals)
for i in range(n_components):
ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]), va="bottom", ha="center", fontsize=12)
ax.xaxis.set_tick_params(width=0)
ax.yaxis.set_tick_params(width=2, length=12)
ax.set_xlabel("Principal Component")
ax.set_ylabel("Explained Variance (%)")
plt.title('Explained Variance vs Principal Component')
def pca_results(good_data, pca):
'''
Create a DataFrame of the PCA results
Includes dimension feature weights and explained variance
'''
# Dimension indexing
dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
# PCA components
components = pd.DataFrame(np.round(pca.components_, 4), columns = list(good_data.keys()))
components.index = dimensions
# PCA explained variance
ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
variance_ratios.index = dimensions
# Return a concatenated DataFrame
return pd.concat([variance_ratios, components], axis = 1)
def features_of_component(pca, component, column_names):
'''
Map weights for the component number to corresponding feature names
Input:
pca : the pca object after transformation
component (int): component number to map to feature
column_names (list(str)): column names of DataFrame for dataset
Output:
df_features (DataFrame): DataFrame with feature weight sorted by feature name
'''
weight_array = pca.components_[component]
df_features = pd.DataFrame(weight_array, index=column_names, columns=['Weight'])
variance = pca.explained_variance_ratio_[component].round(2)*100
df_features= df_features.sort_values(by='Weight',ascending=False).round(2)
return variance, df_features
def get_minikmeans_score(data, nu_clusters, batch_size=50000):
'''
returns the kmeans score regarding SSE for points to centers
INPUT:
data - the dataset you want to fit kmeans to
center - the number of centers you want (the k value)
OUTPUT:
score - the SSE score for the kmeans model fit to the data
'''
#instantiate kmeans
kmeans = MiniBatchKMeans(n_clusters=nu_clusters, batch_size=batch_size, random_state=42)
# Then fit the model to your data using the fit method
model = kmeans.fit(data)
# Obtain a score related to the model fit
score = np.abs(model.score(data))
# both inertia_ and score gives same output
#inertia = model.inertia_
return score
def get_minikmeans_silhouette_score(data, nu_clusters, batch_size=50000, sample_size =50000):
'''
returns the kmeans silhouette_score ts to centers
INPUT:
data - the dataset you want to fit kmeans to
center - the number of centers you want (the k value)
OUTPUT:
score - silhouette_score for the kmeans model fit to the data
'''
#instantiate kmeans
kmeans = MiniBatchKMeans(n_clusters=nu_clusters, batch_size=batch_size, random_state=42)
# Then fit the model to your data using the fit method
#kmeans.fit(data)
#cluster_labels = kmeans.labels
cluster_labels = kmeans.fit_predict(data)
# Obtain a score related to the model fit
s_score = silhouette_score(data, cluster_labels,sample_size=sample_size, metric='euclidean',random_state=42)
return s_score
def draw_learning_curves(estimator, x, y, training_num):
'''
Draw learning curve that shows the validation and training auc_score of an estimator
for training samples.
Input:
X: dataset
y: target
estimator: object type that implements the “fit” and “predict” methods
training_num (int): number of training samples to plot
Output:
None
'''
train_sizes, train_scores, validation_scores = learning_curve(
estimator, x, y, train_sizes =
np.linspace(0.1, 1.0, training_num),cv = None, scoring = 'roc_auc')
train_scores_mean = train_scores.mean(axis = 1)
validation_scores_mean = validation_scores.mean(axis = 1)
plt.grid()
plt.ylabel('AUROC', fontsize = 14)
plt.xlabel('Training set size', fontsize = 14)
title = 'Learning curves for ' + str(estimator).split('(')[0]
plt.title(title, fontsize = 15, y = 1.03)
plt.plot(np.linspace(.1, 1.0, training_num)*100, train_scores_mean, 'o-', color="g",
label="Training score")
plt.plot(np.linspace(.1, 1.0, training_num)*100, validation_scores_mean, 'o-', color="y",
label="Cross-validation score")
plt.yticks(np.arange(0.45, 1.02, 0.05))
plt.xticks(np.arange(0., 100.05, 10))
plt.legend(loc="best")
print("")
plt.show()
print("Roc_auc train score = {}".format(train_scores_mean[-1].round(2)))
print("Roc_auc validation score = {}".format(validation_scores_mean[-1].round(2)))
|
358c68067412029677c59023d1f4b35af58c54ff | yuniktmr/String-Manipulation-Basic | /stringOperations_ytamraka.py | 1,473 | 4.34375 | 4 | #CSCI 450 Section 1
#Student Name: Yunik Tamrakar
#Student ID: 10602304
#Homework #7
#Program that uses oython function to perform word count, frequency and string replacement operation
#In keeping with the Honor Code of UM, I have neither given nor received assistance
#from anyone other than the instructor.
#----------------------
#--------------------
#method to get number of words in string
def wordCount(a):
b = a.split(" ")
count = 0
for word in b:
count = count + 1
print("The number of words is {}".format(count))
#method to get the most repititive word
def mostFrequentWord(b):
c = b.split(" ")
dict = {}
#mapping word with its wordcount.
for word in c:
dict[word] = c.count(word)
max = 0
for word in dict:
if (dict[word] > max):
max = dict[word]
for word in dict:
if(dict[word] == max):
print('The word with max occurence is', word)
#method to replace the words in the string
def replaceWord(a, d ,c):
words = a.split(" ")
wordCheck = False
for word in words:
if d == word:
wordCheck = True
if wordCheck:
print("\nOriginal is ",a)
print("The new string after replacement is ",a.replace(d,c))
else:
print("Word not found")
#main method to call the functions
a= input("Enter a word\n")
wordCount(a)
mostFrequentWord(a)
b = input("\nEnter a word you want to be replaced. Separate them with a space\n")
c = b.split(" ")
#invoke the replaceWord method
replaceWord(a, c[0], c[1])
|
189da51101c163022df6d8b417da004cba11c649 | annamunhoz/learningpython | /exercise01.py | 476 | 4 | 4 | # Exercise 01: create a python program that takes 2 values
# and then select between sum and sub. Show the result.
print("Submit your first number")
first_number = float(input())
print("Submit your second number")
second_number = float(input())
print("Choose the basic arithmetic: type SUM for sum or SUB for subtraction")
arithmetic = input()
if arithmetic == "SUM":
print(first_number + second_number)
else:
print(first_number - second_number)
|
904398e1e75159b8047dc94757e5a7ac0dfb16e8 | wxb-gh/py_test | /demo3.py | 363 | 3.796875 | 4 | # coding:gbk
colours = ['red', 'green', 'blue']
names = ['a', 'b', 'c']
for colour in colours:
print colour
for i, colour in enumerate(colours):
print i, ' -> ', colour
for colour in reversed(colours):
print colour
for colour in sorted(colours, reverse=True):
print colour
for name, colour in zip(names, colours):
print name, '->',colour
|
7345117ef887ad5049d57e2688e1ce8d5601f001 | AndrewsDutraDev/Algoritmos_2 | /Tabelas/Teste.py | 886 | 3.53125 | 4 | from Tabelas import Table
tamanho_tabela = 5
tabela = Table(tamanho_tabela) # Inicializa a tabela com tamanho 3
tabela.insert("xyz", "abc") #Insere um valor e uma key
tabela.insert("dfg","dfb") #Insere um valor e uma key
tabela.insert("ffg","dfb") #Insere um valor e uma key
tabela.insert("hfg","dfb") #Insere um valor e uma key
tabela.insert_sort("abc","dfb") #Insere um valor e uma key de maneira ordenada
print('Size: '+str(tabela.size())) #Retorna o tamanho da tabela
print(tabela.search('lin_bin', "ffg")) # Faz o search pela key passando como primeiro parâmetro o tipo de busca. 'bin' para binária e '' para linear. Retorna a posição
print(tabela.__repr__()) #Retorna a tabela
#print(tabela.search_bin("ffg", 0, tamanho_tabela)) #Pesquisa diretamente usando a busca binária. Retorna a posição
#print(tabela.search('', 'ffg'))
#print(tabela.destroy()) #Destrói a tabela
|
5ccf9390ee5678a3c21acbd019df5673c7ff08a5 | AndrewsDutraDev/Algoritmos_2 | /Recursão/recursao2.py | 1,623 | 3.734375 | 4 | # Busca Encadeada Recursiva
def busca_encadeada():
if (len(lista) == 0):
return
else:
if (lista[0] == produto):
return cont
else:
cont = cont + 1
return busca_encadeada(lista[1:], produto, cont)
# Busca Linear Recursiva
def busca_linear_recursiva(lista, produto, cont):
if (len(lista) == 0):
return
else:
if (lista[0] == produto):
return cont
else:
cont = cont + 1
return busca_linear_recursiva(lista[1:], produto, cont)
# Ordenação para busca binária em tabela
def ordena(lista2):
cont = 1
for i in range(len(lista2) - 1, 0, -1):
for j in range(i):
if lista2[j] > lista2[j + 1]:
(lista2[j], lista2[j + 1]) = (lista2[j + 1], lista2[j])
return lista2
#Função que executa os dois tipos de listas
def busca(lista, tipo, produto):
if (tipo == 'bin'):
listaOrd = ordena(lista)
return busca_linear_recursiva(listaOrd, produto, cont)
else:
return busca_linear_recursiva(lista, produto, cont)
#Função de busca binária
def search_bin(lista, produto, inicio, fim): #função para buscar de forma binária
if len(lista):
mid = ((inicio + fim) // 2)
if lista[mid] == produto:
return mid + 1
if (produto < lista[mid]):
return self.search_bin(lista, produto, inicio, mid - 1)
else:
return self.search_bin(lista, produto, mid + 1, fim)
return
cont = 1
lista = [5,3,1,2,8]
tipo = 'lin'
produto = 2
print(busca(lista, tipo, produto)) |
3b2a0f4b8f0a7c1f9e480ded60b1a2aaf2c75603 | taniarebollohernandez/progAvanzada | /ejercicio7.py | 85 | 3.6875 | 4 | n = float(input('Inserta un numero positivo: '))
print('suma',int(((n*(n+1)/2))))
|
124e7250acd99e2668d71cf4717f0b54db63f7ab | taniarebollohernandez/progAvanzada | /ejercicio5.py | 792 | 4.03125 | 4 | #In many jurisdictions a small deposit is added to drink containers to encourage peopleto recycle them. In one particular jurisdiction, drink containers holding one liter or less have a $0.10 deposit, and drink containers holding more than one liter have a $0.25 deposit. Write a program that reads the number of containers of each size from the user. Your program should continue by computing and displaying the refund that will be received for returning those containers. Format the output so that it includes a dollar sign and always displays exactly two decimal places.
poquitos = float(input('¿cuantos envases de 1 litro o menos tiene?'))
muchos = float(input('¿cuantos envases de mas de 1 litro tiene?'))
print('Tu reembolso total es de $', 0.10 * poquitos + 0.25 * muchos) |
de52a7dc06b7dcd402a07e8d76a00f487f5e84b8 | kazimuth/python-mode-processing | /examples/misc/triflower/triflower.pde | 999 | 3.65625 | 4 | """
Adapted from the TriFlower sketch of Ira Greenberg
"""
#
# Triangle Flower
# by Ira Greenberg.
#
# Using rotate() and triangle() functions generate a pretty
# flower. Uncomment the line "# rotate(rot+=radians(spin))"
# in the triBlur() function for a nice variation.
#
p = [None]*3
shift = 1.0
fade = 0
fillCol = 0
rot = 0
spin = 0
def setup():
size(200, 200)
background(0)
smooth()
global fade,spin
fade = 255.0/(width/2.0/shift)
spin = 360.0/(width/2.0/shift)
p[0] = PVector (-width/2, height/2)
p[1] = PVector (width/2, height/2)
p[2] = PVector (0, -height/2)
noStroke()
translate(width/2, height/2)
triBlur()
def triBlur():
global fillCol,rot
fill(fillCol)
fillCol+=fade
rotate(spin)
# another interesting variation: uncomment the line below
# rot+=radians(spin) rotate(rot)
p[0].x+=shift p[0].y-=shift p[1].x-=shift p[1].y-=shift p[2].y+=shift
triangle (p[0].x, p[0].y, p[1].x, p[1].y, p[2].x, p[2].y)
if p[0].x<0:
# recursive call
triBlur()
|
f6a909d7e0d878aaf314109c6b594bc80964da83 | LucasFerreira06/ExercicioProva4Dupla | /Questao2.py | 1,306 | 3.921875 | 4 | def adicionarSorteado(sorteados):
numAdd = random.randint(0, 100)
sorteados.append(numAdd)
print(sorteados)
def adicionarAluno(alunos, matricula, nome):
alunos[matricula] = nome
def exibirAlunos(alunos):
for chave, valor in alunos.items():
print("Matricula:", chave, "Aluno:", valor)
def buscarAluno(alunos, matricula):
for achado, nome in alunos.items():
if(achado == matricula):
print("Matricula encontrado! ->", achado, "Aluno:", nome)
def Menu():
contador = 0
while(contador == 0):
escolha = eval(input("1 para adicionar um numero a lista, 2 para adicionar um aluno a lista, 3 para exibir os alunos, 4 para buscar aluno e 5 para sair."))
if(escolha == 1):
adicionarSorteado(sorteados)
elif(escolha == 2):
matricula = eval(input("Digite a matricula para adicionar: "))
nome = input("Digite o nome do aluno: ")
adicionarAluno(alunos, matricula, nome)
elif(escolha == 3):
exibirAlunos(alunos)
elif(escolha == 4):
matricula = eval(input("Digite a matricula a ser buscada: "))
buscarAluno(alunos, matricula)
else:
contador = 1
Menu()
|
48c6bbe599a6444304766b3f23a51a43adb8103a | PrashantMittal54/Data-Structures-and-Algorithms | /String/Look-and-Say Sequence String.py | 927 | 4.09375 | 4 | # Look-and-Say Sequence
# To generate a member of the sequence from the previous member, read off the digits of the previous member
# and record the count of the number of digits in groups of the same digit.
#
# For example, 1 is read off as one 1 which implies that the count of 1 is one. As 1 is read off as “one 1”,
# the next sequence will be written as 11 where 1 replaces one. Now 11 is read off as “two 1s” as the count
# of “1” is two in this term. Hence, the next term in the sequence becomes 21.
def next_number(s):
idx = 0
output = []
while idx < len(s):
count = 1
while idx+1 < len(s) and s[idx] == s[idx+1]:
count += 1
idx += 1
output.append(str(count))
output.append(s[idx])
idx += 1
return ''.join(output)
s = "1"
print(s)
n = 8
for i in range(n-1):
s = next_number(s)
print(s)
|
5e1c85a492b786dcb674a436f3bb7fb9ad6f8559 | PrashantMittal54/Data-Structures-and-Algorithms | /LinkList/Deletion.py | 1,778 | 3.796875 | 4 | # Deletion by Value and Position
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linklist:
def __init__(self):
self.head = None
def delete_node_at_pos(self, pos):
cur = self.head
if pos == 0:
self.head = cur.next
cur = None
return
count = 0
prev = None
while cur and count != pos:
prev = cur
cur = cur.next
count += 1
if not cur:
return None
prev.next = cur.next
cur = None
def delete_node(self, key):
cur = self.head
if cur and cur.data == key:
self.head = cur.next
# cur.data = None
cur = None
return
prev = None
while cur:
prev = cur
cur = cur.next
if cur and cur.data == key:
prev.next = cur.next
# cur.data = None
cur = None
return
else:
return print('Node does not exist')
def append(self, data):
new_node = Node(data)
curr = self.head
if curr is None:
self.head = new_node
return
while curr.next:
curr = curr.next
curr.next = new_node
def print_list(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
llist = Linklist()
llist.append("A")
llist.append("B")
llist.append("C")
llist.append("D")
llist.print_list()
llist.delete_node("B")
llist.print_list()
llist.delete_node("E")
llist.delete_node_at_pos(1)
llist.print_list()
|
19013fbbb00b4c43c334ccf48a52b13c278932ee | PrashantMittal54/Data-Structures-and-Algorithms | /LinkList/Move Tail to Head.py | 1,023 | 3.859375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linklist:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
curr = self.head
if curr is None:
self.head = new_node
return
while curr.next:
curr = curr.next
curr.next = new_node
def print_list(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
def move_tail_to_head(self):
if not self.head:
return
curr = self.head
prev = None
while curr.next:
prev = curr
curr = curr.next
curr.next = self.head
self.head = curr
prev.next = None
llist = Linklist()
llist.append("A")
llist.append("B")
llist.append("C")
llist.append("D")
# llist.print_list()
llist.move_tail_to_head()
llist.print_list()
|
db4df4d10e3392349cb74bb36f5614c794e59eff | PrashantMittal54/Data-Structures-and-Algorithms | /Array/Arbitrary Precision Increment Array.py | 353 | 3.65625 | 4 | def plus_one(A):
A[-1] += 1
carry = 0
for x in range(1,len(A)+1):
if (A[-x] + carry) == 10:
carry = 1
A[-x] = 0
else:
A[-x] += carry
break
if A[0] == 0:
A[0] = 1
A.append(0)
return A
print(plus_one([2,9,9]))
print(plus_one([9,9,9]))
|
5ee72868552ba9c802f653357564b241c00ca020 | bsspirit/mytool | /src/md5_rdict.py | 282 | 3.875 | 4 | # -*- coding: utf-8 -*-
#读字典文件
def dict_read(file):
lines = []
f = open(file,"r")
line = str(f.readline())
lines.append(line.split(','))
while line:
line = f.readline()
lines.append(line.split(','))
f.close()
return lines |
e5098b5399a500afcf7d5c140b2a5aed46d613f7 | hdjewel/Markov-Chains | /lw_markov.py | 3,792 | 3.765625 | 4 | #!/usr/bin/env python
from sys import argv
import random, string
def make_chains(corpus):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
# read lines --- we don't need to read the lines. We are reading it as one long string
# strip newlines, punctuation, tabs and make lower case
exclude = string.punctuation
exclude2 = "\n" + "\t"
new_corpus = "" #created new string because corpus string is immutable
for char in corpus:
if char in exclude:
continue
elif char in exclude2:
# new_corpus += "" -- doesn't work because it took away all the spaces at new lines
new_corpus += " " #works, but creates double space at new lines. Should not be a problem
#because we will split at a space
else:
new_corpus += char
new_corpus = new_corpus.lower()
# create list of words on line
list_of_words = new_corpus.split()
# create a dictionary where key = tuple of two words (prefix) and value = a list
# of words that follow the prefix.
d = {}
# for i in range(len(list_of_words)):
# Wendy thinks the following two lines will throw an IndexError
for i in range( (len(list_of_words) - 2) ): #Wendy's version to avoid IndexError
# print 0.01, IndexError
# if IndexError:
# break
# else:
prefix = (list_of_words[i], list_of_words[i+1])
suffix = list_of_words[i+2]
"""
if prefix not in d:
add the prefix as a key to d and setting suffix as the prefix's value
else
append suffix to the value of the prefix in d
"""
if prefix not in d:
d[prefix] = [suffix] #intializes the suffix as a list
else:
d[prefix].append(suffix)
# make a key of the last 2 words and it's value = first word of the text
return d
def make_text(chains):
"""Takes a dictionary of markov chains and returns random text
based off an original text."""
# so to build our text the first prefex and suffix are random
# then we build our text from the suffix to a new prefix
# random_prefix = random.sample(chains.keys(), 1)
random_prefix = random.choice(chains.keys())
# get random suffix from the list
random_suffix = random.choice(chains[random_prefix])
markov_text = ""
# and the loop control is at this time arbitrary
# for i in range(4):
for word in random_prefix:
markov_text += word + " "
markov_text += random_suffix
"""
take the second value of the random_prefix make it the first value and
make the suffix the second value of the new key
the last word is handled how in our dictionary??
--- we add to the dictionary (in make_chains) as key, the last two words
in the list, and as it's value, the first word in the list.
"""
#get new random prefix
print 2, random_prefix
print 2.0, chains[random_prefix]
print 2.1, random_suffix
print 2.2, markov_text
# markov_text = random_prefix + random_prefix01...
return "Here's some random text."
def main():
script, filename = argv
# args = sys.argv
# print 1, args[1]
# print 1.0, type(args[1])
# Change this to read input_text from a file
# input_text = open(args[1])
input_text = open(filename)
# content = input_text.read()
# input_text = input_text.read().replace(\n)
input_text = input_text.read()
# print 1.1, input_text
# print 1.2, type(input_text)
# do read
chain_dict = make_chains(input_text)
random_text = make_text(chain_dict)
# print random_text
if __name__ == "__main__":
main() |
5649dabbf39457cb906368ebc3591f964108713c | ijoshi90/Python | /Python/hacker_rank_staricase.py | 460 | 4.3125 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 30-Oct-19 at 08:06
"""
# Complete the staircase function below.
"""def staircase(n):
for stairs in range(1, n + 1):
print(('#' * stairs).rjust(n))
"""
def staircase(n):
for i in range(n-1,-1,-1):
for j in range(i):
print (" ",end="")
for k in range(n-i):
print("#",end="")
print("")
if __name__ == '__main__':
staircase(6) |
cc0dbeccd0b265b09bf10f8aa12881d5e245acae | ijoshi90/Python | /Python/loop_while.py | 534 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 20:47:00 2019
@author: akjoshi
"""
import time
# While Loop
x = 5
y = 1
print (time.timezone)
while x >=1:
print (time.localtime())
time.sleep (1)
print ("X is "+ str (x))
x-=1
while y <= 5:
time.sleep(1)
print ("Y is "+str(y))
y+=1
# While Loop
i=0
while i <=10:
i=i+1
if i == 5:
break
print ("I is "+str(i))
j = 0
while j < 6:
j += 1
if j == 3:
continue
print ("J is "+str(j))
|
035e8af4d681ae42fa9ce31a9a22f2430aaa1531 | ijoshi90/Python | /Python/array_operations.py | 579 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 18:21:20 2019
@author: akjoshi
"""
from array import *
arr = array('i', [])
l = int (input ("Enter the length : "))
print ("Enter elements")
for i in range (l):
x = int (input("Enter the " + str (i) + " value : "))
arr.append(x)
key = int (input ("Enter value to search : "))
for i in range (l):
if key == arr[i]:
print (str(key) + " is in position " + str(i))
else:
print ("element is not in array")
print (arr.index(key))
# Sum of Array
new_arr = [1,2,3,4,5,6,7,8,9,10]
print(max(new_arr)) |
e3b10157dafc23d144d1a2db892f055a8f2d608f | ijoshi90/Python | /Python/prime_or_not.py | 391 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 24 16:40:46 2019
@author: akjoshi
"""
# Prime or not
number = int (input ("Enter a number to print prime numbers between 0 and number : "))
for num in range(2,number + 1):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num) |
4c951106721a49a06d1e6a95f6461e5d8da18c44 | ijoshi90/Python | /Python/dictionary.py | 1,448 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 18:05:09 2019
@author: akjoshi
"""
#dictionary
dictionary_car = {
"Brand" : "BMW",
"Model" : "X1",
"Year" : "2020",
"Owner" : "Sanaksh"
}
print (dictionary_car)
# Accessing
this_dictionary = dictionary_car["Model"]
print (this_dictionary)
print (dictionary_car["Year"])
print (dictionary_car.get("Owner"))
dictionary_car["Owner"]="Adi Shankara"
print (dictionary_car.get("Owner"))
for x in dictionary_car:
print (x + " : " +dictionary_car[x])
for x in dictionary_car.values():
print (x)
for x, y in dictionary_car.items():
print (x, y)
if "Brand" in dictionary_car:
print ("Brand is present")
if "BMW" in dictionary_car.values():
print ("BMW is there")
print ("Length of dictionary : "+str(len(dictionary_car)))
# Adding to dictionary
dictionary_car["Type"]="Petrol"
print (dictionary_car)
# Removing from dictionary
dictionary_car.pop("Year")
print (dictionary_car)
# del
del dictionary_car["Model"]
print (dictionary_car)
# Copying a dictionary
new_dictionary=dictionary_car.copy()
print (new_dictionary)
new_dictionary=dict(dictionary_car)
print (new_dictionary)
dictionary_car.clear()
print (dictionary_car)
# Copying a dictionary
new_dictionary=dictionary_car.copy()
print (new_dictionary)
del dictionary_car
# dict() : Constructor
dictionary = dict(brand="BMW",model="3 Series")
print (dictionary) |
75aabcea6f84ac4f13a725080c9858954074472c | ijoshi90/Python | /Python/maps_example.py | 1,385 | 4.15625 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 19-12-2019 at 11:07
"""
def to_upper_case(s):
return str(s).upper()
def print_iterator(it):
for x in it:
print(x, end=' ')
print('') # for new line
#print(to_upper_case("akshay"))
#print_iterator("joshi")
# map() with string
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
# Map iterator with tuple
map_iterator = map(to_upper_case, (1, "ab", "xyz"))
print_iterator(map_iterator)
# Map with list
map_iterator = map(to_upper_case, [1, 2, "Aksh"])
print_iterator(map_iterator)
# Converting map to list, tuple or set
map_iterator = map(to_upper_case, ['a,b', 'b', 'c'])
my_list = list(map_iterator)
print (type(my_list))
print(my_list)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_set = set(map_iterator)
print(type(my_set))
print(my_set)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_tuple = tuple(map_iterator)
print(type(my_tuple))
print(my_tuple)
# Map with
list_numbers = [1, 2, 3, 4]
mapite = map(lambda x: x * 2, list_numbers)
print(type(mapite))
for i in mapite:
print(i)
# Map with multiple arguments
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
mapitnow = map(lambda x,y : x * y, list_numbers, tuple_numbers)
for each in mapitnow:
print("From multiple arguments in lambda : {}".format(each)) |
00e0422cf41f40f287b9d72f42881b3afcb93ce1 | ijoshi90/Python | /Python/bubble_sort_trial.py | 364 | 3.984375 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 09-01-2020 at 10:15
"""
list = [1, 3, 8, 9, 2, 5, 2, 3, 6, 5, 8, 10, 19, 12, 14, 7, 20]
def bubble (list):
for i in range(len(list)):
for j in range(i+1, len(list)):
if list [i] > list [j]:
list [i], list [j] = list [j], list[i]
bubble(list)
print(list) |
6fc2d2631238c25c2d2e30ed887c4abbe8a0083c | ijoshi90/Python | /Python/set.py | 851 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 6 20:40:20 2019
@author: akjoshi
"""
# Set Example
thisset = {"1 apple", "2 banana", "3 cherry","4 kiwi"}
print(thisset)
for i in thisset:
print (i)
print ("5 banana" in thisset)
print ("2 banana" in thisset)
thisset.add("5 Strawberry")
print (thisset)
thisset.update(["6 Raspberry","7 Blueberry"])
print (thisset)
print ("Set length : "+str(len(thisset)))
# Remove will raise error if item is not there
thisset.remove("7 Blueberry")
print (thisset)
# Discard will not raise error if item is not there
thisset.discard("4 kiwi")
print(thisset)
# Pop removes last item
x=thisset.pop()
print (x)
print (thisset)
# Del deletes the set completely
del (thisset)
#print (thisset)
# Set constructor
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset) |
3f28a1970aa458cfde8700646e1adecf1bb63634 | ijoshi90/Python | /Python/string_operations.py | 421 | 4 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 17-12-2019 at 14:43
"""
string = "Hello, World!"
# Strings as array
print (string[2])
# Slicing
print (string[2:5])
# Negative indexing - counts from the end
print (string[-5:-2])
# Replace
print (string.replace("!","#"))
print((string.replace("Hello", "Well Hello")))
#Split
print(string.split(","))
print(string)
# Join
print(",".join(string))
|
2733ce9698980790023690e311fd8ab37e46fb8f | ijoshi90/Python | /Python/iterator.py | 383 | 3.859375 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 18-12-2019 at 15:18
"""
# Iter in tuple
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
# Iter in strings
string = "Akshay"
myit1 = iter(string)
print(next(myit1))
print(next(myit1))
print(next(myit1))
next(myit1)
next(myit1)
print(next(myit1)) |
bbcdeafd4fdc92f756f93a1a4f990418d295c643 | ijoshi90/Python | /Python/variables_examples.py | 602 | 4.375 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 26-Sep-19 at 19:24
"""
class Car:
# Class variable
wheels = 2
def __init__(self):
# Instance Variable
self.mileage = 20
self.company = "BMW"
car1 = Car()
car2 = Car()
print ("Wheels : {}".format(Car.wheels))
# Override the value of wheels with 4
Car.wheels = 4
print (car1.company, car1.mileage, car1.wheels)
print (car2.company, car2.mileage, car2.wheels)
# Changing values of Car 2
car2.company = "Mini"
car2.mileage = "25"
car2.wheels = "3"
print (car2.company, car2.mileage, car2.wheels) |
d17f55a72be36d93dd6c5dc553d312e5c26beda4 | romilpatel-developer/CIS2348_projects | /Homework 4/pythonProject24/main.py | 1,398 | 3.671875 | 4 | # Romilkumar Patel
# 1765483
# Homework 4 (Zybooks 14.13)
# Global variable
num_calls = 0
# TODO: Write the partitioning algorithm - pick the middle element as the
# pivot, compare the values using two index variables l and h (low and high),
# initialized to the left and right sides of the current elements being sorted,
# and determine if a swap is necessary
def partition(user_ids, i, k):
pivot = user_ids[k] # pivot is the middle item in the list
index = i - 1
for j in range(i, k):
if user_ids[j] <= pivot:
index += 1
user_ids[index], user_ids[j] = user_ids[j], user_ids[index]
user_ids[index+1], user_ids[k] = user_ids[k], user_ids[index+1]
return index+1
# TODO: Write the quicksort algorithm that recursively sorts the low and
# high partitions. Add 1 to num_calls each time quisksort() is called
def quicksort(user_ids, i, k):
if i < k:
piv = partition(user_ids, i, k)
quicksort(user_ids, i, piv-1)
quicksort(user_ids, piv+1, k)
if __name__ == "__main__":
user_ids = []
user_id = input()
while user_id != "-1":
user_ids.append(user_id)
user_id = input()
# Initial call to quicksort
quicksort(user_ids, 0, len(user_ids) - 1)
num_calls = int(2 * len(user_ids) - 1)
# Print number of calls to quicksort
print(num_calls)
# Print sorted user ids
for user_id in user_ids:
print(user_id) |
69b5f175d2e3f8d6899fac183143e2ad75eef120 | Faeylayn/Phonebook-Excercise | /phonebook.py | 4,698 | 3.859375 | 4 | import sys
import os
def create_phonebook(phonebook_name):
filename = '%s.txt' % phonebook_name
if os.path.exists(filename):
raise Exception("That Phonebook already exists!")
with open(filename, 'w') as f:
pass
def add_entry(name, number, phonebook_name):
if not os.path.exists('%s.txt' % phonebook_name):
raise Exception("That Phonebook does not exist!")
with open('%s.txt' % phonebook_name, 'r') as f:
for line in f:
entry_name, entry_number = line.strip().split('\t')
if entry_name == name:
raise Exception('That Entry Already Exists! Please use the Update function!')
with open('%s.txt' % phonebook_name, 'a') as f:
f.write('%s\t%s' % (name, number))
f.write('\n')
pass
def remove_entry(name, phonebook_name):
name_list = []
number_list = []
if not os.path.exists('%s.txt' % phonebook_name):
raise Exception("That Phonebook does not exist!")
with open('%s.txt' % phonebook_name, 'r') as f:
for line in f:
entry_name, entry_number = line.strip().split('\t')
if entry_name != name:
name_list.append(entry_name)
number_list.append(entry_number)
with open('%s.txt' % phonebook_name, 'w') as f:
pass
for z in range(len(name_list)):
add_entry(name_list[z], number_list[z], phonebook_name)
pass
def lookup_entry(name, phonebook_name):
if not os.path.exists('%s.txt' % phonebook_name):
raise Exception("That Phonebook does not exist!")
with open('%s.txt' % phonebook_name, 'r') as f:
for line in f:
entry_name, entry_number = line.strip().split('\t')
if entry_name == name:
print entry_name, entry_number
pass
def update_entry(name, number, phonebook_name):
name_list = []
number_list = []
if not os.path.exists('%s.txt' % phonebook_name):
raise Exception("That Phonebook does not exist!")
with open('%s.txt' % phonebook_name, 'r') as f:
for line in f:
entry_name, entry_number = line.strip().split('\t')
if entry_name != name:
name_list.append(entry_name)
number_list.append(entry_number)
with open('%s.txt' % phonebook_name, 'w') as f:
pass
for z in range(len(name_list)):
add_entry(name_list[z], number_list[z], phonebook_name)
with open('%s.txt' % phonebook_name, 'a') as f:
f.write('%s\t%s' % (name, number))
f.write('\n')
pass
def reverse_lookup_entry(number, phonebook_name):
if not os.path.exists('%s.txt' % phonebook_name):
raise Exception("That Phonebook does not exist!")
with open('%s.txt' % phonebook_name, 'r') as f:
for line in f:
entry_name, entry_number = line.strip().split('\t')
if entry_number == number:
print entry_name, entry_number
pass
if __name__ == "__main__":
arguments = sys.argv[:]
script = arguments.pop(0)
if not arguments:
raise Exception ('Command required')
command = arguments.pop(0)
if command == "create":
if not arguments:
raise Exception ('Phonebook Name required')
phonebook_name = arguments.pop(0)
create_phonebook(phonebook_name)
elif command == "add":
if len(arguments) != 3:
raise Exception ("Name, Number, Phonebook Name Required.")
name, number, phonebook_name = arguments
add_entry(name, number, phonebook_name)
elif command == "update":
if len(arguments) != 3:
raise Exception ("Name, Number, Phonebook Name Required.")
name, number, phonebook_name = arguments
update_entry(name, number, phonebook_name)
elif command == "remove":
if len(arguments) != 2:
raise Exception ("Name, Phonebook Name Required.")
name, phonebook_name = arguments
remove_entry(name, phonebook_name)
elif command == "lookup":
if len(arguments) != 2:
raise Exception ("Name, Phonebook Name Required.")
name, phonebook_name = arguments
lookup_entry(name, phonebook_name)
elif command == "reverse-lookup":
if len(arguments) != 2:
raise Exception ("Number, Phonebook Name Required.")
number, phonebook_name = arguments
reverse_lookup_entry(number, phonebook_name)
else:
raise Exception ("Invalid Command.")
|
f3cf383e0ff6bf61193548a33fec789b12ac58e5 | JuanMVP/repoPastis | /raspberry/motores1.py | 527 | 3.5 | 4 | import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
Motor1A = 16
Motor1B = 18
Motor1E = 22
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)
print "Going forwards"
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(2)
print "Going backwards"
GPIO.output(Motor1A,GPIO.LOW)
GPIO.output(Motor1B,GPIO.HIGH)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(2)
print "Now stop"
GPIO.output(Motor1E,GPIO.LOW)
GPIO.cleanup()
|
8c7beedf3a39bb9db58390f80df6e2beaa200ab4 | Fuzerii/CIV5-Drafter | /Drafter.py | 1,119 | 3.515625 | 4 | import random
Civit = ["Morocco", "Goths", "Greece", "Assyria", "Songhai", "Rome", "Germany", "Celts", "Poland", "Russia",
"Franks", "Persia", "Carthage", "Australia", "England", "Jerusalem", "Indonesia", "India",
"Sumeria", "Sweden", "Vietnam", "Ethiopia", "Denmark", "Norway", "Iroquoes", "Spain", "Polynesia",
"Belgium", "Portugal", "Austria", "Aztec", "Hitties", "Babylon", "Manchuria", "Japan", "Maya", "Inca",
"Brazil", "Shoshone", "Egypt", "Siam", "Canada", "Ayybis", "Korea", "Zulu", "Sioux", "Ottoman", "Byzantum",
"Italy", "America", "Netherlands", "China", "Ukraine", "Normandy", "Boeres"]
valinta = []
for i in range(0, 8*4):
x = random.choice(Civit)
while x in valinta:
x = random.choice(Civit)
valinta.append(x)
print("pelaaja 1: "+str(valinta[0:3]))
print("pelaaja 2: "+str(valinta[4:7]))
print("pelaaja 3: "+str(valinta[8:11]))
print("pelaaja 4: "+str(valinta[12:15]))
print("pelaaja 5: "+str(valinta[16:19]))
print("pelaaja 6: "+str(valinta[20:23]))
print("pelaaja 7: "+str(valinta[24:27]))
print("pelaaja 8: "+str(valinta[28:31]))
|
e41d966e65b740a9e95368d7e5b9286fe587f2cb | donwb/whirlwind-python | /Generators.py | 537 | 4.28125 | 4 | print("List")
# List - collection of values
L = [n ** 2 for n in range(12)]
for val in L:
print(val, end=' ')
print("\n")
print("Generator...")
# Generator - recipie for creating a list of values
G = (n ** 2 for n in range(12))
#generator created here, not up there...
for val in G:
print(val, end=' ')
# Generators can only be used once,
# but they can be stopped/started
GG = (n**2 for n in range(12))
for n in GG:
print(n, end=' ')
if n > 30: break
print("\ndoing something in between")
for n in GG:
print(n, end=' ')
|
08a9f4d381c95ec311c6df11fc06a3bc1ae7b10e | ashishkhiani/Daily-Coding-Problems | /challenges/problem_237/Node.py | 633 | 3.515625 | 4 | import json
from typing import List
class Node(object):
def __init__(self, name, children=None):
"""
:type name: str
:type children: List[Node]
"""
if children is None:
children = []
self._name = name
self._children = children
def __repr__(self):
return json.dumps(self, default=lambda o: o.__dict__, indent=2)
def name(self):
return self._name
def children(self):
return self._children
def set_children(self, children):
self._children = children
def is_leaf(self):
return not self._children
|
3e9a48e9fc4349e668fe26e26a55f38aa6de3068 | ashishkhiani/Daily-Coding-Problems | /challenges/problem_001/unit_test.py | 1,191 | 3.515625 | 4 | import unittest
from challenges.problem_001.solution import problem_1
class SumsToK(unittest.TestCase):
def test_example_1(self):
num_list = [10, 15, 3, 7]
k = 17
actual = problem_1(num_list, k)
self.assertTrue(actual)
def test_example_2(self):
num_list = [10, -15, 3, 7]
k = -5
actual = problem_1(num_list, k)
self.assertTrue(actual)
def test_example_3(self):
num_list = [1]
k = 1
actual = problem_1(num_list, k)
self.assertFalse(actual)
def test_example_4(self):
num_list = []
k = 1
actual = problem_1(num_list, k)
self.assertFalse(actual)
def test_example_5(self):
num_list = [10, -15, 3, 7]
k = 10
actual = problem_1(num_list, k)
self.assertTrue(actual)
def test_example_6(self):
num_list = [10, -15, 3, 7, 10, 9, 15, -23, 49, 8, 16, 33]
k = 49
actual = problem_1(num_list, k)
self.assertTrue(actual)
def test_example_7(self):
num_list = [20, 10, 10, 40, 40, 30]
k = 50
actual = problem_1(num_list, k)
self.assertTrue(actual)
|
96e9b049e63ad519eebcf39dc26a6e73f684b716 | amanda-posey/python_basics | /basic_loops.py | 365 | 3.765625 | 4 | monday_temperatures = [9.1, 8.8, 7.6]
for temperature in monday_temperatures:
print(round(temperature))
#for letter in 'hello':
# print(letter)
colors = [11, 34.1, 98.2, 43, 45.1, 54, 54]
for color in colors:
if isinstance(color, int):
print(color)
for color in colors:
if (isinstance(color, int)) and (color > 50):
print(color)
|
9dbe30b304d60b787ecea043d7fa43aa558cc4d8 | marcospb19/python_brasil_19_talk | /arquivos/1.py | 350 | 3.546875 | 4 | import re
# Ver todas as funções e constantes
# print(dir(re))
from re import findall
print(re.findall("f" , "fff"))
result = re.findall("xu" , "xu")
print(type(result) , len(result))
print(result)
result = re.findall("xu" , "xuxu")
print(type(result) , len(result))
print(result)
# Como é feita a leitura?
print(re.findall("ff" , "fff"))
|
cbc5fc685a74b4ebd5ec15b4f022adb78c8625a2 | pradeesi/IoT_Framework | /google_drive_test.py | 1,845 | 3.578125 | 4 | from google_drive.google_drive_upload import gDrive
Obj = gDrive()
#Upload a file (if file is not in current directory pass full path)
print "Uploading file on Google Drive:"
print "File ID:"
file_id = Obj.upload_File('test.txt')
print file_id
#Upload a file in a Folder (if file is not in current directory pass full path)
print
print "=========================================================="
print "Uploading file on Google Drive FOLDER:"
print "File ID:"
file_id = Obj.upload_File('test.txt',Obj.get_GDrive_Folder_ID('pradeep'))
print file_id
#Create Folder on Google Drive
print
print "=========================================================="
print "Create Folder on Google Drive"
print "Folder ID:"
folder_id =Obj.create_GDrive_Folder('Don')
print folder_id
#Create a Folder inside another Folder
print
print "=========================================================="
print "Create SUB Folder on Google Drive"
print "Folder ID:"
folder_id =Obj.create_GDrive_Folder('Amitabh', Obj.get_GDrive_Folder_ID('Don'))
print folder_id
#List all files
print
print "=========================================================="
print "File List (All Files in all Folders):"
Obj.get_GDrive_File_List()
#List all files in a Folder
print
print "=========================================================="
print "File List in a Folder:"
Obj.get_GDrive_File_List(Obj.get_GDrive_Folder_ID('pradeep'))
#List all Folders
print
print "=========================================================="
print "Folder List (including subfolders):"
Obj.get_GDrive_Folder_List()
#List all Folders in a Folder
print
print "=========================================================="
print "Folder List in a Folder:"
Obj.get_GDrive_Folder_List(Obj.get_GDrive_Folder_ID('pradeep'))
|
46ae324b58a1f33734ef18f4828db11599d408fa | marwa-mohamed-dev/Matrice_couts_alignements_Python | /DM5.py | 4,040 | 3.578125 | 4 | #########################################################
# DM5 : matrice de score d'alignement #
#########################################################
#Introduction DM 5
import time
print("Bienvenue dans notre programme!!!")
time.sleep (1)
print("Celui-ci permettra de calculer les coûts d\'alignement des séquences nucléotidiques de votre choix.")
print("Il affichera le résultat sous forme d'une matrice.")
time.sleep (2)
print("\nLes paramètres de mismatch, gap, et score d'identité seront fixés par l'utilisateur.\n")
time.sleep(3)
# ====================================================================================================================
## Fonction validant la séquence entrée
def valide(seq) :
for base in seq : # Pour chaque base de la séquence
if not (base in "ATCGagct") : # Si la lettre de correspond pas à la liste de lettres données
print("La séquence suivante :",sequence," n'est pas valide.") # Affichage erreur
seq = input("Veillez entrer une séquence correcte : ") # Demande d'entrée une nouvelle séquence
seq = seq.upper() # Mettre la séquence en majuscule
return(seq) # Retourne la séquence
# ====================================================================================================================
## Fonction créant la matrice
def creationMatrice (nbL, nbC, seq1, seq2) : # nbL : nombre de lignes, nbC : nombre de colonnes
MAT = [[0.0] * (nbC) for _ in range (nbL)] # Création de la matrice
for j in range(2,nbC) : # Ajout séquence2 sur ligne 0
MAT[0][j]=seq1[j-2]
for i in range(2,nbL) : # Ajout séquence1 sur colonne 0
MAT[i][0]=seq2[i-2]
for j in range(2,nbC) : # Initialisation des gap sur la ligne
MAT[1][j]=(MAT[1][j-1]+gap)
for i in range(2,nbL) : # Initialisation des gap sur la colonne
MAT[i][1]=(MAT[i-1][1]+gap)
return (MAT) # Retourne la matrice
# ====================================================================================================================
## Fonction remplissant la matrice
def remplissageMatrice(nbL, nbC, MAT) :
for i in range (2,nbL) : #
for j in range (2,nbC) :
a = MAT[i][j-1] + gap # Gap colonne
b = MAT[i-1][j] + gap # Gap ligne
if(MAT[i][0] == MAT[0][j]) : # Si les nucléotides sont égales
c = MAT[i-1][j-1] + identite # Ajout du score identité à la valeur de la diagonale en haut à gauche
else : # Sinon
c = MAT[i-1][j-1] + mismatch # Ajout du score mismatch à la valeur de la diagonale en haut à gauche
MAT[i][j]= min(a, b, c) # La cellule à remplir garde seulement la valeur minimale des 3
return (MAT) # Retoune la matrice remplie
# =====================================================================================================================
## Fonction affichant la matrice
def affichageMatrice (MAT, nbL) :
for j in range(nbL):
print(matrice[j]) # Affiche matrice ligne par ligne
##########################################
# main #
##########################################
# Déclaration de variables
# Entrée des scores gap, identité et mismatch
gap = float(input("Entrer le score gap : "))
identite = float(input("Entrer le score d'identite : "))
mismatch = float(input("Entrer le score mismatch : "))
# Entrée et vérification des séquences
sequence1 = input("Entrer la première séquence : ")
sequence1 = valide(sequence1)
sequence2 = input("Entrer la deuxième séquence : ")
sequence2 = valide(sequence2)
# +2 pour éviter le chevauchement des 2 séquences
colonnes = len(sequence1)+2
lignes = len(sequence2)+2
# Création, remplissage et affichage de la matrice
matrice = creationMatrice(lignes, colonnes, sequence1, sequence2)
matrice = remplissageMatrice(lignes, colonnes, matrice)
affichageMatrice(matrice, lignes)
|
c7c0ad43ffa4af13130fe893b0e33a8c730f6fcf | hemakl/reader-flask-project | /readerwishlist/booklist.py | 2,032 | 3.5625 | 4 | """
booklist.py
Adding or listing all books associated to one user
endpoint - /users/<id>/books
"""
from readerwishlist.db import query_db, get_db
from flask import (g, request, session, url_for, jsonify)
from flask_restful import Resource, reqparse
class BookList(Resource):
def get(self, user_id):
""" retrieves the wishlist for the given user
"""
user = query_db('SELECT u.id from user u where u.id = ?', (user_id,))
if user is None:
return "User not found", 404
books = query_db('SELECT * FROM book WHERE userId = ? ORDER BY \
publication_date DESC', (user_id,))
if books is None:
return "No books found in wishlist", 404
else:
response = jsonify(books)
response.status_code = 200
return response
def post(self, user_id):
""" creates or adds a new book to the given user's wishlist
"""
user = query_db('SELECT id from user where id = ?', (user_id,))
if user is None:
return "User not found", 404
parser = reqparse.RequestParser()
parser.add_argument("title")
parser.add_argument("author")
parser.add_argument("isbn")
parser.add_argument("publication_date")
args = parser.parse_args()
title = args["title"]
author = args["author"]
isbn = args["isbn"]
publication_date = args["publication_date"]
book = query_db('SELECT b.id, b.isbn FROM book b WHERE b.isbn == ?', (isbn,))
if book is None:
if title is "" or author is "" or isbn is "" or publication_date is "":
return "Bad user data", 400
book_id = query_db('INSERT into book (title,author,isbn,publication_date,userId) \
VALUES (?, ?, ?, ?, ?)', (title, author, isbn, publication_date, user_id), \
commit=True)
return book_id, 201
else:
return "Book already exists", 400
def delete(self, user_id):
""" deletes all books associated with the given user
"""
user = query_db('SELECT id from user where id = ?', (user_id,))
if user is None:
return "User not found", 404
query_db('DELETE from book where userId = ?', (user_id,), commit=True)
return "", 204
|
d3dd23e8f5e164ca4378e7817f983fca0bf89e1b | DylanGuidry/PythonFunctions | /dictionaries.py | 1,098 | 4.375 | 4 | #Dictionaries are defined with {}
friend = {
#They have keys/ values pairs
"name": "Alan Turing",
"Cell": "1234567",
"birthday": "Sep. 5th"
}
#Empty dictionary
nothing = {}
#Values can be anything
suoerhero = {
"name": "Tony Stark",
"Number": 40,
"Avenger": True,
"Gear": [
"fast car",
"money",
"iron suit",
],
"car": {
"make": "audi",
"model": "R8"
},
"weakness": "his ego"
}
#Get values with key names:
print(suoerhero)
#Get method also works, and can have a "fallback"
print(suoerhero.get("name", "Uknown"))
#Access to all values aof all keys:
print(suoerhero.values())
#Searching for a keys in a dictionary:
if "weakness" in suoerhero:
print("bad guys might win")
else:
print("bad guys go home")
#Updating values:
suoerhero["avenger"] == "fartbutt"
print(suoerhero)
#Deleting from a dictionary:
del suoerhero["gear"]
#Accessing data:
print(suoerhero["name"])
for item in suoerhero["Gear"]:
print(item)
# for key, value in suoerhero:items():
# print(f"Suoerhero's {key} is")
# print(value) |
5db196a739555685758fa3ff22e38a948b114b99 | kkandiah/Prime-Factors_Revisited | /tests/test_prime.py | 1,634 | 4.03125 | 4 | #test_prime.py
"""
A unit test module for prime module
"""
import prime
def test_valueerror():
"""
asserts that when prime_factors is called with a data type
that is not an integer (e.g. a string or float), a ValueError is raised.
"""
p_1 = prime.PrimeFactors('a')
assert p_1.number == ValueError
def test_one():
"""
asserts that when prime_factors is called with 1,
an empty list will be generated
"""
p_1 = list(prime.PrimeFactors(1))
assert p_1 == []
def test_two():
"""
asserts that when prime_factors is called with 2,
the list [2] will be generated
"""
p_1 = list(prime.PrimeFactors(2))
assert p_1 == [2]
def test_three():
"""
asserts that when prime_factors is called with 3,
the list [3] will be generated
"""
p_1 = list(prime.PrimeFactors(3))
assert p_1 == [3]
def test_four():
"""
asserts that when prime_factors is called with 4,
the list [2, 2] will be generated
"""
p_1 = list(prime.PrimeFactors(4))
assert p_1 == [2, 2]
def test_six():
"""
asserts that when prime_factors is called with 6,
the list [2, 3] will be generated
"""
p_1 = list(prime.PrimeFactors(6))
assert p_1 == [2, 3]
def test_eight():
"""
asserts that when prime_factors is called with 8,
the list [2, 2, 2] will be generated
"""
p_1 = list(prime.PrimeFactors(8))
assert p_1 == [2, 2, 2]
def test_nine():
"""
asserts that when prime_factors is called with 9,
the list [3, 3] will be generated
"""
p_1 = list(prime.PrimeFactors(9))
assert p_1 == [3, 3]
|
1251944a75d11f26744bd86a72b32ca6cf6610ad | amisha-tamang/json | /question3.py | 188 | 3.625 | 4 | # Q.3 Python object ko json string mai convert karne ka program likho?
import json
a={'nisha': 3 , 'komal': 5 , 'amisha': 8 , 'dilshad': 12}
mystring = json.dumps(a)
print(mystring)
|
109aebf88bfac4cd1e7e097b085d3a3f909923fa | helinamesfin/guessing-game | /random game.py | 454 | 4.15625 | 4 | import random
number = random.randrange(1,11)
str_guess= input("What number do you think it is?")
guess= int(str_guess)
while guess != number:
if guess > number:
print("Not quite. Guess lower.")
elif guess < number:
print("Not quite. Guess higher.")
str_guess= input("What number do you think it is?")
guess= int(str_guess)
if guess==number:
print("Great job! You guessed right.")
|
2b36b5442c034edfccbeeed712c571f63b55c2e1 | fhylinjr/2020-PYTHON-PROJECTS | /Hash Tables.py | 3,080 | 3.921875 | 4 | class HashTables:
def __init__(self, size): # constructor which initializes object.
self.size = size # set number of buckets you want in your hashmap
self.hashtable = self.create_buckets() # creates hashtable with createbucket method.
def create_buckets(self):
return [[] for i in range(self.size)] # return a mega list of smaller specified buckets.
# Function to add or update items in hashmap.
def set_value(self, key, value):
hashed_index = hash(key) % self.size # hash(key)%self.size uses modulo to bring the index stored in memory from
# a larger number to an index contained in your bucket size.
bucket = self.hashtable[hashed_index] # this index is used to locate your bucket/ sub list in hash table
found_key = False
for index, record in enumerate(bucket): # to loop through multiple items and index in a single sublist/ bucket
record_key, record_value = record
if key == record_key: # checks if key input equals key in bucket
found_key = True
break
if found_key:
bucket[index] = (key, value) # if found updates the item at current index
else:
bucket.append((key, value)) # if not appends item to bucket/ sublist in entire hashmap.
# Function to retrieve value of a specified key in hashmap.
def get_value(self, key):
hashed_index = hash(key) % self.size
bucket = self.hashtable[hashed_index]
found_key = False
for index, record in enumerate(bucket):
record_key, record_value = record
if key == record_key:
found_key = True
break
if found_key:
return record_value
else:
return "No record value associated with specified email."
# Function to remove item of specified key from hashmap
def delete_value(self, key):
hashed_index = hash(key) % self.size
bucket = self.hashtable[hashed_index]
found_key = False
for index, record in enumerate(bucket):
record_key, record_value = record
if key == record_key:
found_key = True
break
if found_key:
bucket.pop(index)
return "Item deleted from bucket"
else:
return "No record value associated with specified email."
def __str__(self):
return "".join(str(item) for item in self.hashtable) # removes commas separating sublists and joins them and
#outputs hashmap as a string.
hashtable1 = HashTables(100)
print(hashtable1)
hashtable1.set_value('philip.boakye@minerva.kgi.edu', {'first_name': 'Philip', 'last_name': 'Boakye'})
hashtable1.set_value('evgeny@example.com', {'first_name': 'Evgeny', 'last_name': 'CoderElite'})
hashtable1.set_value('nwayoe@gmail.com', {'first_name': 'Nicholas', 'last_name': 'Wayoe'})
print(hashtable1)
print(hashtable1.get_value('nwayoe@gmail.com'))
print(hashtable1.delete_value('evgeny@example.com'))
|
a2fd87ae78e812b344d5eedc9a2547cf9270eaf8 | KiD21606/PicoCTF | /Codes and Commands/CaesarDecoder.py | 345 | 4.09375 | 4 | Ciphertext = "ynkooejcpdanqxeykjrbdofgkq"
Ciphertext = Ciphertext.upper()
Ciphertext = [ord(Letter)-65 for Letter in Ciphertext]
for Shift in range(26):
print("Shift:{}, plantext:{} or {}".format(
Shift, "".join([chr( (Int+Shift)%26 + 65 ) for Int in Ciphertext]), "".join([chr( (Int+Shift)%26 + 97 ) for Int in Ciphertext])
)) |
723023c06cb8f8cdbdcaa543fa18ad3a2984affe | johnywith1n/InterviewStreet | /Equations/equations.py | 1,538 | 3.71875 | 4 | import sys
def getPrimeNumbers (upperBound):
result = [True] * (upperBound + 1)
primes = [i for i in range(2, upperBound+1) if i*i <= upperBound]
for i in primes:
if result[i]:
for j in range(i*i, upperBound + 1, i):
result[j] = False;
return [i for i in range(2, upperBound+1) if result[i]]
"""
Returns Multiplicity of PRIME in the prime factorization of N
see http://homepage.smc.edu/kennedy_john/NFACT.PDF
"""
def getMultiplicity (n, prime):
scratch = n
multiplicity = 0
while scratch > 0:
scratch = scratch // prime
multiplicity += scratch
return multiplicity
"""
Input: N for the equation (1/x) + (1/y) = 1/(N!)
Output: the number of integral solutions to the aforementioned equation
Returns (2*m1 + 1) * (2*m2 +1) * ... * (2*m_n + 1) where m_i is the
multiplicity of the i^th prime in the prime factorization of N
"""
def getNumberOfSolutions (n):
# There will be no prime numbers if n is 1, might as well skip all that work.
if n == 1:
return 2 * 0 + 1
primes = getPrimeNumbers(n)
primeMultiplicities = []
for p in primes:
primeMultiplicities.append(getMultiplicity(n, p))
return reduce(lambda x,y: x*y, [2*x+1 for x in primeMultiplicities])
def getAnswer (n):
return getNumberOfSolutions(n) % 1000007
def main(*args):
N = int(raw_input())
print getAnswer(N)
if __name__ == '__main__':
sys.exit(main(*sys.argv)) |
9bbdd57d6ea5652874b270fc2fb118ad94d96fd4 | asktalk/Ubuntu16.04-llaptop-Code | /PycharmProjects/TestPython20180515/Python3_1.py | 3,504 | 3.84375 | 4 | #! /usr/bin/python3
if True:
print("XiaoGongwei10")
print("good")
else:
print("XiaoXiao")
print("AAA")
all_array = {"Xiao","Gong","Wei"}
#input("\n\ninput Enter:")
import sys
x = "runoob"
sys.stdout.write(x + "\n")
if 1==2:
print(x)
elif True:
print(x + "aaa")
else:
print("Error")
print("a"); print("b")
print("a",end = "")
print("b",end = "")
'''
aaaaaaa
aaaaa
'''
print("AAAA")
"""
aaaaaa
aaaa
"""
print("AAAA")
print(9//4.0)
a = 10;
b = 20;
a**=2;
if not (a > b):
print('OUT')
print(a)
else:
print('IN')
print(b)
print("xiaogongwei Age:",24);
list_arry = {10,20,11};
a=10
if (a not in list_arry):
print("a in list");
else:
print("a not in lise");
print("temp");
print(0 and b);
a = 20;
print(a is b);
print(id(a),"->",id(b))
print(complex(a,b))
j=1
import math as myMath
import random
sequ = [1,2,3,4];
print(random.choice(range(10)))
print(range(10))
myMath.fabs(-1)
myMath.exp(2)
str1 = r"hello\bbgb\nqaqqq";
print(str1);
print(str1.capitalize());
print(str1);
print(str1.center(30,"*"));
list_arry = [100,20,2010]
print(str1.__len__())
list_arry.append(10)
list_arry.insert(1,20000)
print(len(list_arry),list_arry*2,max(list_arry))
new_list = list_arry.copy()
list_arry[0] = 'C'
print(list_arry,"->",new_list)
print(id(list_arry),"->",id(new_list))
print(type(list_arry))
list_2d = [[0,1,2,3],[1,2,2]]
print(len(list_2d))
a,b = 0,1;
try:
maxNum = int(input("maxNum:"))
except ValueError:
print("Input Error")
maxNum = 100
print(maxNum)
while b < maxNum:
print(b,end = ',')
a,b = b,a+b;
print("")
for i in range(3,15,1):
if i == 5:
pass
print(i,end = ',');
print("")
my_iter = iter(list_arry)
while True:
try:
print(next(my_iter),end = ',')
except StopIteration:
break
print("")
def arrayN(n=10):
b = n;
a = 0;
while a <= n:
arrytemp = [a,b];
yield arrytemp;
a += 1;
b += 1;
fN = arrayN(4);
import sys
while True:
try:
arryTemp = next(fN);
print(arryTemp[0],end = ',');
except StopIteration:
print('exit');
break;
print("")
def myNameFun(n):
yield n;
for x in myNameFun(10):
print(x)
print(type(list_arry))
def multParm(var1,*multVal):
print("Val1:",var1);
for varParm in multVal:
print(varParm);
print(type(list_2d));
return;
multParm(1000,a,111,list_2d)
mylamdaFun = lambda arg1:arg1*2;
print(mylamdaFun(10))
NumParm = 100;
def changeParm():
global NumParm;
print(NumParm)
NumParm = 10000;
print(NumParm);
ainer = 99;
def inerfun():
nonlocal ainer;
ainer = 999;
inerfun();
print(ainer);
changeParm();
print(NumParm)
myList = [1,2,3,4,5];
mycell =(1,2,3,4,5);
myList.append(6)
myList.pop()
marixNum = [[1,2,3,4],
[4,5,6,4],
[7,8,9,4]
];
print(marixNum)
transMatrix = [[row[i] for row in marixNum] for i in range(4) ];
print(transMatrix)
collectionMy = set('aaabbbccc');
print(collectionMy)
a = {x for x in 'abbccdd' if x not in 'ac'}
print(a)
print(list_arry)
import printHello
printHello.printHelloME('from model')
print(printHello.Hellestr)
from printHello import printHello2
printHello2()
print(dir(printHello))
print("xiao{0:20}wei,age:{1:2d},sex:{2:3d}".format('gong',1,1));
dictNames = {'Xiao':999,'Cao':100};
print(dictNames);
print('xiao{0[Xiao]:d};Cao{0[Cao]:d}'.format(dictNames));
print('xiao{Xiao:d};Cao{Cao:d}'.format(**dictNames));
print(*dictNames)
|
69c02edda8ceb27210487f5ce97bbe69a595be44 | mapkn/Other-Examples | /dictionaries.py | 3,474 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 11:38:32 2018
@author: patemi
"""
#https://chrisalbon.com/python/basics/compare_two_dictionaries/
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict1 = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict2 = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict3 = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict4 = dict([(1,'apple'), (2,'ball')])
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
#print(my_dict)
# add item to dictionary
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
#print(my_dict)
# How to check if the keys in two dictionaries are exactly the same
#print(set(my_dict1.keys()) == set(my_dict3.keys()))
# Retrieve an item from dictionary using given key
d=my_dict.get('address')
print(my_dict[1])
importers = {'El Salvador' : 1234,
'Nicaragua' : 152,
'Spain' : 252
}
exporters = {'Spain' : 252,
'Germany' : 251,
'Italy' : 1563
}
for key in my_dict:
print (key, 'corresponds to', my_dict[key])
# Duplicate key
# Find the intersection of importers and exporters
print(importers.keys() & exporters.keys())
# Difference in keys
# Find the difference between importers and exporters
#y= dict(importers.keys() - exporters.keys())
print(importers.keys() - exporters.keys())
# Key, value pairs in common
# Find countries where the amount of exports matches the amount of imports
print(importers.items() & exporters.items())
def dict_compare(d1, d2):
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
added = d1_keys - d2_keys
removed = d2_keys - d1_keys
modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
same = set(o for o in intersect_keys if d1[o] == d2[o])
print(added)
print(removed)
print(modified)
print(same)
return added, removed, modified, same
x = dict(Category='Equity', IssueCountry='AU', IssuerSector='Fin')
y = dict(Category='Equity', IssueCountry='*', IssuerSector='*')
added, removed, modified, same = dict_compare(x, y)
def check_diffs(d):
# Input: dictionary of differences
# Value will be a two element tuple
# l=[]
# for key in d:
# l[]
list2=['T' for key in d if d[key][0]=='AU']
#{TRUE for key,value in my_dict.items() if d[key]=='*'}
return list2
#list3=[x for x in list1 if x>0]
# dicitonary of dictoinaries, adding to a dicitonary
FromAttributes={1:{'EquityCountry':'AU', 'IndexID':'*', 'IssueID':'*','IssuerCountry':'*','IssuerID':'*', 'IssuerIsLargeCap':'*', 'IssuerSector':'*'},
2:{'EquityCountry':'NZ', 'IndexID':'*', 'IssueID':'*','IssuerCountry':'*','IssuerID':'*', 'IssuerIsLargeCap':'*', 'IssuerSector':'*'},
3:{'EquityCountry':'*', 'IndexID':'*', 'IssueID':'*','IssuerCountry':'*','IssuerID':'*', 'IssuerIsLargeCap':'*', 'IssuerSector':'*'},}
# New dictionary
New = {'EquityCountry':'US', 'IndexID':'*', 'IssueID':'*','IssuerCountry':'*','IssuerID':'*', 'IssuerIsLargeCap':'*', 'IssuerSector':'*'}
# Add new dictionary to existing
FromAttributes[4]=New |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.