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 |
|---|---|---|---|---|---|---|
f9bb9ba4696b2e12a6085f993ff5f479f14a0fab | erben22/fib | /fibonacci.py | 1,206 | 3.984375 | 4 | """Class that provides function(s) related to calcuations of
Fibonacci numbers.
TODO: Add some additional error handling:
- How do I handle desiredSequence and ensuring it is an integer.
TODO: Overflow handling?
TODO: Can I cleanup the calculation
"""
class Fibonacci:
"""This class provides Fibonacci sequence information."""
def __init__(self, desired_sequence):
"""Initialization of the Fibonacci instance.
Arguments:
desired_sequence: Fibonacci sequenece to compute a value for.
"""
self.desired_sequence = desired_sequence
def calculate(self):
"""Implementation of the calculcation of a Fibonacci value for
the sequenece of this instance.
"""
if self.desired_sequence < 0:
raise TypeError("Negative values are unsupported.")
if self.desired_sequence == 0:
return self.desired_sequence
prev_value = 0
fibonacci_value = 1
for _ in range(1, self.desired_sequence):
swap_value = fibonacci_value
fibonacci_value += prev_value
prev_value = swap_value
else:
return fibonacci_value
|
4af2f35beec4452f5c5d77e52c6634083022bc94 | esmullen21/OO-ModuleProject | /Route.py | 6,617 | 3.828125 | 4 | import math
from Lookup import *
from itertools import permutations
class Route:
"""This class finds all the permutations of the list of airports, calculates the cost of each leg then finds the best cost for the entire journey"""
def __init__(self, look):
self.look=look # assigns the object look as an attribute of route
def getAirports(self,name): #if an employee's name is selected, this function gets their visit list and then calls permutations() to fins the best route
for anemployee in self.look.employee_info.values():
if anemployee.name==name:
employee=anemployee
airports = anemployee.visitList()
bestRoute=self.permutatuions(airports)
return bestRoute
def permutatuions(self, airports):
six,seven, =[],[]
itins = [airports[:1] + list(x) + airports[-1:] for x in permutations(airports[1:-1])]
#Above takes the home city off the list(first and last) and gets the each permutation of the visiting cities, using the itertools module
for c in range(len(itins)): #This adds in the extra city
combo=itins[c]
for e in airports[0:4]:
for i in range(5,0,-1):
newcombo=combo[:]
newcombo.insert(i,e)
itins.append(newcombo)
while len(itins)>312: #This gets rid of all the itineraries that have two cities the same side by side (e.g. DUB, DUB). It pops them from the list. 312 is the miniumu number of itineraries there can be. Gotten trial and error
for each in itins:
index=0
for c in range(len(each)-1):
if each[c] == each[c+1]:
itins.pop(itins.index(each))
itineraries =[] #This loop makes sure there are no duplicates by adding the itineraries to a new list but before doing this, checking it's not already in there
for each in itins:
if each not in itineraries:
itineraries.append(each)
for each in itineraries[:24]: #Gets the first 24 itineries and adds them to a list (called six as there are 6 cities).
six.append(each)
legcost=self.legs(six) #Sends them to the function legs to get the cost for each leg
for each in itineraries[25:]:#Gets the rest of the itineraries and adds them to a seperate list.
seven.append(each)
costs,itincost=self.sumCosts(six,seven, legcost)#Sends both lists six and seven, to the sumCosts function to be summed.
bestCost=self.costCompare(costs) # compares the cost
index=0
for each in costs:
if each==bestCost: # finds the entry in costs that matches the best cost returned
i=index
index += 1
return (itincost[i])#uses the index of the match in costs, to find the itinerary in itincost and returns it to the function call
def legs(self, six):
"""This calculates the cost of each leg (e.g. DUB, JFK) for all the possible city combinations and returns the list"""
cities=[]
leg=[]
for each in six:
c=0
while c<5:
leg=(each[c],each[c+1])
if leg not in cities:
cities.append(leg)#If the leg is not already in the list, it is added
c+=1
#Below compiles a list of each leg and the cost
legcost=[]
for each in cities:
cost=self.calcCosttLeg(each[0], each[1]) # Gets the cost of the leg
legs=[each[0],each[1], cost] # Creates a list called leg containing the citys and the cost
legcost.append(legs) # Appends leg to the list leg cost
return legcost
def calcCosttLeg(self, airport1, airport2):
"""This looks up the airports for each leg, sends them to the function that calculates the distance, it finds the
currency for airport1, sends both to the function that calculates the cost and returns the value to the function call"""
airports=(self.look.LookupLatandLong(airport1, airport2))
distance=self.calDistance(airports)
currency=self.look.findCurrency(airport1)
cost=distance*currency
return cost
def calDistance(self, airports):
"""Calcualtes the distance between two airports"""
#the latitudes are assigned to theta1 and theta 2 and the longitudes to phi1 and phi2
theta1=float(airports[1])
theta2=float(airports[3])
phi1=90.0-float(airports[0])
phi2=90.0-float(airports[2])
rad=(2.0*(math.pi)/360.0)
rEarth=6373
radtheta1=(theta1*(rad))#the following 4 lines changes the lat and longs to radians
radtheta2=(theta2*(rad))
radphi1=(phi1*(rad))
radphi2=(phi2*(rad))
partA=math.sin(radphi1)*math.sin(radphi2)*math.cos(radtheta1-radtheta2)+ math.cos(radphi1)*math.cos(radphi2)#This and below computes the distance
distance=(math.acos(partA))*rEarth
return distance
def sumCosts(self, six, seven,legcost):
"""Sums the cost of each leg for each itinerary and appends it to the end of each itinerary"""
price=[]
for each in six: #For every itinerary in the list six, this function gets each leg(or two cities)
tot=0
c=0
while c<5:
i=0
leg=(each[c],each[c+1])
for cities in legcost: #for each in legcost, it finds the match of leg and adds the price to tot
eachleg=(cities[0],cities[1])
if leg== eachleg:
tot=tot+float(cities[2])
c+=1
price.append(int(tot))#Appends tot to price and at the end of each itinerary
each.append(int(tot))
for each in seven:#Does the same as it does for six
tot=0
c=0
while c<6:
i=0
leg=(each[c],each[c+1])
for cities in legcost:
eachleg=(cities[0],cities[1])
if leg== eachleg:
tot=tot+float(cities[2])
c+=1
price.append(int(tot))
each.append(int(tot))
itincosts=six+seven #The lists of itineraries are added together
return price,itincosts
def costCompare(self, allCosts):
"""This finds the lowest cost in the list of costs and returns the lowest value"""
best=min(i for i in allCosts)
return best
|
bac9eeaeb959e1c48e5d9ff34b056a2c78839db9 | mxochicale/my-cortex | /tex/figures/pretty_function.py | 532 | 3.578125 | 4 | """Plot the function sin(1 / XY)."""
import matplotlib.pyplot as plt
import numpy as np
# Compute sin(1 / xy)
sz = 5000
X = np.linspace(-1, 1, sz)
Y = np.linspace(-1, 1, sz)
X, Y = np.meshgrid(X, Y)
Z = np.sin(1 / (X * Y))
# Plot it
fig, ax = plt.subplots(1)
im = ax.imshow(Z, cmap=plt.get_cmap("plasma"),
origin="lower", extent=(-1, 1, -1, 1))
plt.colorbar(im, shrink=1, aspect=10)
ax.set_xlabel("X", fontsize=16)
ax.set_ylabel("Y", fontsize=16)
# Save it
fig.savefig("pretty_function.pdf", bbox_inches="tight")
|
e68ebd9fb2eca7f826bfad34e254f2cad33ea6e7 | naim2206/Complex-Numbers-Calculator | /operaciones_complejos.py | 2,621 | 3.703125 | 4 | import math
def suma(a1, b1, a2, b2):
return f"Result: {a1 + a2} + {b1 + b2}i"
def resta(a1, b1, a2, b2):
return f"Result: {a1 - a2} + {b1 - b2}i"
def multi(a1, b1, a2, b2):
return f"{a1*a2 - b1*b2} + {a1*b2 + a2*b1}i"
def div(a1, b1, a2, b2):
return f"{(a1*a2 + b1*b2)/(a2**2 + b2**2)} + {(a2*b1 - a1*b2)/(a2**2 + b2**2)}i"
def arg(a1, b1):
if a1 == 0 and b1 == 0:
return -1
elif b1 == 0:
if a1 > 0:
return 0
else:
return math.pi
elif a1 == 0:
if b1 > 0:
return math.pi/2
else:
return -math.pi/2
elif a1 > 0:
return (math.atan(b1/a1))
elif b1 > 0:
return (math.pi + math.atan(b1/a1))
else:
return (-(math.pi) + math.atan(b1/a1))
def modulo(a1, b1):
return (((a1**2) + (b1**2))**(1/2))
def raiz(a1, b1):
raiz = int(input("Which root do you want? "))
mod = modulo(a1, b1)
argu = arg(a1, b1)
r = mod**(1/raiz)
for k in range(0, raiz):
teta = (argu + (2*k*math.pi))/raiz
b = r*math.sin(teta)
a = r*math.cos(teta)
print(f"{a} + {b}i")
def potencia(a1, b1):
potencia = int(input("What power do you want? "))
mod = modulo(a1, b1)
argu = arg(a1, b1)
r = mod**potencia
teta = (argu*mod + argu*mod)
a = r*(math.cos(teta))
b = r*(math.sin(teta))
return f"{a} + {b}i"
def inverso(a1, b1):
return f"{a1/(a1**2 + b1**2)} - {b1/(a1**2 + b1**2)}i"
operacion = input("What operation would you like? (+,-,*,/,modulus,argument,root,power,inverse) ")
a1 = float(input("Enter the real part 1: "))
b1 = float(input("Enter the imaginary part 1: "))
print(f"Your complex number is {a1} + {b1}i\n")
if operacion == "+" or operacion == "-" or operacion == "*" or operacion == "/":
a2 = float(input("Enter the real part 2: "))
b2 = float(input("Enter the imaginary part 2: "))
print(f"Your second complex number is {a2} + {b2}i\n")
if operacion == "+":
print(suma(a1, b1, a2, b2))
elif operacion == "-":
print(resta(a1, b1, a2, b2))
elif operacion == "*":
print(multi(a1, b1, a2, b2))
elif operacion == "/":
print(div(a1, b1, a2, b2))
elif operacion == "argument":
print(arg(a1, b1))
elif operacion == "modulus":
print(modulo(a1, b1))
elif operacion == "power":
print(potencia(a1, b1))
elif operacion == "root":
raiz(a1, b1)
elif operacion == "inverse":
print(inverso(a1, b1))
else:
print("Error")
|
223127abf6808a49397784324016e389604d46ee | afrinh/CompetitiveProgramming | /Week3/Day3/FindDuplicateBEASTMODE.py | 1,097 | 3.796875 | 4 | import unittest
def find_duplicate(int_list):
# print(int_list)
# Find a number that appears more than once ... in O(n) time
list2=[]
length=len(int_list)
for i in range(0,length):
index = int_list[i]%length
int_list[index] = int_list[index]+length
# print(int_list)
for i in range(0,length):
if(int_list[i]/length)>1:
return i
# Tests
class Test(unittest.TestCase):
def test_just_the_repeated_number(self):
actual = find_duplicate([1, 1])
expected = 1
self.assertEqual(actual, expected)
def test_short_list(self):
actual = find_duplicate([1, 2, 3, 2])
expected = 2
self.assertEqual(actual, expected)
def test_medium_list(self):
actual = find_duplicate([1, 2, 5, 5, 5, 5])
expected = 5
self.assertEqual(actual, expected)
def test_long_list(self):
actual = find_duplicate([4, 1, 4, 8, 3, 2, 7, 6, 5])
expected = 4
self.assertEqual(actual, expected)
unittest.main(verbosity=2) |
df635eeac89b0a77af043544d73e74da636c3e54 | afrinh/CompetitiveProgramming | /Week2/Day6/InPlaceShuffle.py | 379 | 3.96875 | 4 | import random
def shuffle(the_list):
length=len(the_list)
for i in range(length-1,0,-1):
j = random.randint(0,i)
the_list[i],the_list[j] = the_list[j], the_list[i]
# Shuffle the input in place
sample_list = [1, 2, 3, 4, 5]
print 'Sample list:', sample_list
print 'Shuffling sample list...'
shuffle(sample_list)
print sample_list |
55ba7fe0d292373dc01bd2619720dd8792092827 | ldrunner100/fizz_buzz | /fizzbuzz.py | 365 | 4.0625 | 4 | try:
n = range(int(raw_input("Fizz buzz counting up to ")))
except ValueError:
print("Please only input integers.")
n = range(int(raw_input("Fizz buzz counting up to ")))
for i in n:
if i % 3 == 0 and i % 5 == 0:
print("fizz buzz")
elif i % 5 == 0:
print("buzz")
elif i % 3 == 0:
print("fizz")
else:
print(i)
|
ebd7d39e55aa5a0200a680629a31442a9795ba72 | suman9868/Python-Code | /class.py | 863 | 4.125 | 4 | """
this is simple program in python for oops implementation
submitted by : suman kumar
date : 1 january 2017
time : 9 pm
"""
class Employee:
emp_count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.emp_count = Employee.emp_count + 1
def count_emp(self):
#print "total employee ", Employee.emp_count
print "total employee %d " %Employee.emp_count # both line works
def emp_details(self):
print "name ", self.name
print "salary ", self.salary
emp1 = Employee("raju",10000)
emp2 = Employee("kaju",20000)
emp3 = Employee("maju",30000)
emp1.name = "sumti"
#del emp1.salary #delete salary attribute of emp1
print Employee.emp_count
emp1.count_emp()
emp2.count_emp()
#print emp1.name
emp1.emp_details()
emp2.emp_details()
|
a655c9a58ccbe8679fbd3271eb312a6894e62520 | Jun-Lizst/ProbeDesign | /maskprobes/fasta.py | 14,122 | 4 | 4 | import os
import re
import string
class Fasta:
""" Stores contents of a FASTA file with useful retreival methods
Usage:
>> fa = fasta.Fasta('/path/to/yourfavgene.fasta')
or
>> seq = 'ACTATCTACTACTTTCATACTTATACTCTATC'
>> fa = fasta.Fasta(s,True)
Author:
Marshall J. Levesque 2011-2013
"""
""" here we store the file contents. """
def __init__(self,file,strflag=False):
""" Creates a Fasta object from provided FASTA filename or string
Input:
file - /path/to a Fasta file or a raw Fasta sequence string
strFlag - must be True if filename argument is a Fasta string
"""
self.path = ''
self.filename = ''
self.headers = []
self.seqs = []
self.introns = []
self.exons = []
self.CDS = []
if strflag:
self.parse_fasta(file)
else:
self.read_fasta_file(file)
# The validation step (below) is for checking for "bad" characters
# However, many people put in stuff with numbering, etc. Easiest thing
# to do is just to strip out those characters. We'll do that in one_line
#self.validate()
def read_fasta_file(self,filename):
"""Open provided filename,read and parse file contents"""
curdirpath = os.path.join(os.getcwd(),filename)
if os.path.exists(curdirpath): # input was a filename in current dir
self.path = os.getcwd()
self.filename = filename
elif os.path.exists(filename): # input was a full path to a fasta
(self.path,self.filename) = os.path.split(filename)
else:
msg = "Could not locate input Fasta file %s" % filename
raise Exception(msg)
print "Opening file %s" % curdirpath
f = open(os.path.join(self.path,self.filename),'r')
self.parse_fasta(f.read())
self.parse_headers()
f.close()
def parse_fasta(self,raw):
"""Breaks up fasta file into .headers and .seqs"""
seq = '' # temporary sequence storage we build line-by-line
lines = raw.split('\n')
for line in lines: # for each line in the FASTA
line.strip() # remove leading and trailing whitespace
if line is '': # empty line
continue
if line[0] is '>': # we are at a header line
if seq is not '': # >1 entry in this fasta, append seqs
self.seqs.append(seq)
seq = ''
self.headers.append(line)
else:
seq += line
if seq is not '': # add the last or only sequence
self.seqs.append(seq)
#TODO: Validation of the fasta sequences and parsing of header info"""
if len(self.seqs) == 0:
msg = "No sequences in FASTA %s" % self.filename
raise Exception(msg)
self.mark_exon_intron_CDS()
def mark_exon_intron_CDS(self):
"""Identify each sequence as EXON,CDS,INTRON
Given the FASTA uses the following UCSC genomic sequence export style:
1) EXONS in UPPERCASE, everything else lowercase
2) One FASTA record per region (exon, intron, etc.)
3) Split UTR and CDS parts of an exon into separate FASTA records
Then we can label the sequences in the Fasta.seqs list as exon, intron, CDS
and store this info as a list of indicies
CDS sequences are a subset of the EXON sequences. So for example, we could
have EXONS and CDS annotation like this:
self.EXONS = [0 1 3 5 7 8]
self.CDS = [1 3 5 7]
which indicates that there is a 5'UTR exon adjacent to the translation start
codon and a 3'UTR just after the stop codon.
This logic and tracking of parts of a gene is separate from FASTA parsing
so it can change when there are updates to UCSC or the way we want to handle
this type of data."""
START_CODONS = ['ATG']
STOP_CODONS = ['TGA','ACC']
CDS_FLAG = False
for (i,seq) in enumerate(self.seqs):
if seq.islower(): # intron
self.introns.append(i)
else: # EXON
self.exons.append(i)
if self.seqs[i][0:3] in START_CODONS:
CDS_FLAG = True
if CDS_FLAG:
self.CDS.append(i)
if self.seqs[i][-3:] in STOP_CODONS: # 3' UTR
CDS_FLAG = False
def parse_headers(self):
"""Gets the information out of UCSC fasta headers
example:
>mm9_refGene_NM_010028_0 range=chrX:12858148-12858238
We are hoping to find these vaules in the header for each sequence:
seqID: str identifying the sequence
chr: str for chromosome (e.g. chr19 or chrX)
start: int for starting genomic position
end: int for starting genomic position
strand: str (+/-)
repeats: str indicating if there is repeat masking ('none' or 'N' or 'n')
There are object instance attributes with these same names
"""
n = len(self.seqs)
self.seqID = ['']*n
self.chr = ['']*n
self.strand = ['']*n
self.start = [-1]*n
self.end = [-1]*n
self.repeats = ['']*n
re_seqID = re.compile('>(\w+)')
re_chr_and_range = re.compile('range=(\w+):(\d+)-(\d+)')
re_strand = re.compile('strand=(\W)')
re_repeats = re.compile('repeatMasking=(\w+)')
for (i,head) in enumerate(self.headers):
attrs = head.split(' ')
for a in attrs:
"""Go through all known header elements using string matching"""
if re_seqID.match(a):
# TODO: We can do genomic build here
self.seqID[i] = re_seqID.match(a).group(1)
elif re_chr_and_range.match(a): # range=chrX:12858148-12858238
results = re_chr_and_range.match(a)
self.chr[i] = results.group(1)
self.start[i] = int(results.group(2))
self.end[i] = int(results.group(3))
elif re_strand.match(a):
self.strand[i] = re_strand.match(a).group(1)
elif re_repeats.match(a):
self.repeats[i] = re_repeats.match(a).group(1)
def seq_in_range(self,start,end,onlyexon=False):
"""Returns (str) sequence for the provided range (start to end on + strand)
The returned sequence is inclusive for the position coordinates provided.
Input:
start - (int) 5' genomic position on + strand
end - (int) 3' genomic position on + strand
"""
# check if we even have position information extracted from headers
if -1 in self.start or -1 in self.end:
raise Exception('Missing sequence range information in this FASTA')
# check if we even have strand information extracted from headers
if '' in self.strand:
raise Exception('Missing DNA strand information in this FASTA')
# check if we were given numbers
# sanity checks
if end < start:
msg = 'Provided range [' + str(start) + ' - ' + str(end) + '] '
msg += 'was not valid for + strand genomic coordinates'
raise Exception(msg)
# TODO: ensure that start/end values match sequence lengths
# TODO: ensure that start/end values are exclusive and continuous
# Find the sequences in the FASTA that contain the start and end positions
# of the provided range. Ensure they make sense
seq_start = -1
seq_end = -1
for i in range(len(self.seqs)):
if start >= self.start[i] and start <= self.end[i]:
seq_start = i
if end >= self.start[i] and end <= self.end[i]:
seq_end = i
if seq_start == -1 or seq_end == -1:
msg = 'Could not find sequences for the provided range: '
msg += '[' + str(start) + ' - ' + str(end) + '] '
raise Exception(msg)
# For both the start and end genomic posiiton, we have the seq_index
# We need to map genomic position to index of the characters in the seqs.
if self.strand[seq_start] == '+':
index_start = start - self.start[seq_start]
else: # minus strand
index_start = self.start[seq_start] - start
if self.strand[seq_end] == '+':
index_end = end - self.end[seq_end]
else: # minus strand
index_end = self.end[seq_end] - end
# construct the eequence
subseq = ''
seqs = [seq_start,seq_end]
seqs.sort()
for i in range(seqs[0],seqs[1]+1):
if onlyexon and i in self.introns:
continue
from_index = to_index = None
if i == seq_start:
if self.strand[seq_start] == '+':
from_index = index_start
else: # minus strand
to_index = index_start
if i == seq_end:
if self.strand[seq_end] == '+':
to_index = index_end
else: # minus strand
from_index = index_end
if to_index == 0: # handles [n:0] case
to_index = None
subseq += self.seqs[i][from_index:to_index]
return subseq
def range_of_seq(self,seq):
"""A substring match but returns genomic coordinates [5',3']
"""
oneseq = ''
if self.strand[0] == '-':
seq = seq.
for i in range(
def one_line(self):
"""Converts a raw FASTA string to a string w/o new-line characters
We find that a useful format when dealing with FASTA sequences is
to treat it as single-line string (no newline or other whitespace
characters) and to split up a multi-sequence FASTA with '>'
characters. This design allows for simple indexing of nucleotide
position, if you remember to include '>'.
TODO: A more 'sophisticated' approach may be to have structured data
for FASTA headers and sequences. For now this works since current
methods don't care about this information, only sequence.
"""
one_line_seq = ''
headerLine = False
for c in self.raw:
if c == '>':
headerLine = True
one_line_seq += c
elif c in ('\r','\n'):
headerLine = False
elif not headerLine:
if c in ('a','A','c','C','t','T','g','G','n','N'):
one_line_seq += c
one_line_seq = one_line_seq.rstrip() # remove any trailing whitespace
return one_line_seq.lower()
def validate(self):
"""Returns True if input Fasta string is valid format.
We allow 'n' or 'N' as a valid character for pre-masked sequences.
"""
anybad = re.search('[^>aAcCtTgGnN]',self.one_line())
if anybad:
msg = "Found invalid characters [^>aAcCtTgGnN] in the input sequence"
raise Exception(msg)
def to_substrings(self,mer_length,delimchar):
''' Convert one-line version of the FASTA into n-mer subsequences
From the FASTA (multi) sequence file, creates a string made up of
n-mer subsequences separated by user-specified character. This is
useful for performing alignments of subsequences to a reference
sequence and masking for hits (eg BLAST or bowtie).
Arguments:
mer_length -- int between 5-30
delimchar -- 't' for tab, 'c' for comma, 's' for space, '>' for
a valid FASTA sequence with numbered headers corresponding to
the character index when using the Fasta.one_line() function
Returns the FASTA subsequence string
'''
inseq = self.one_line()
substrings = ''
if mer_length not in range(5,31):
raise Exception('Provided n-mer length must be between 5-30')
if delimchar in 'tcsn>':
if delimchar is 't':
delimchar = '\t'
elif delimchar is 'c':
delimchar = ','
elif delimchar is 's':
delimchar = ' '
elif delimchar is 'n':
delimchar = '\n'
else:
delimchar = '>'
# iterate over each nucleotide char in the FASTA one-line str
# from char[i] up to but not including i+n
for i in range(0,len(inseq)-mer_length+1):
subseq = inseq[i:i+mer_length]
if '>' in subseq: # skip the header characters
pass
else:
if delimchar == '>':
# make a multi-seq FASTA with char-index as header
substrings += '>%d\n%s\n' % (i,subseq)
else:
substrings += '%s%c' % (subseq,delimchar) # append
return substrings
# TODO Look up python static method styling
def revcomp(self,seq=''):
"""The reverse complement string for the sequence provided. If no
sequence is provided, we used the FASTA's entire sequence
Input Args:
seq - (str)
"""
# if no sequence is provided, use this FASTA's entire sequence
if seq == '':
for i in len(self.seqs):
seq += self.seqs[i]
complement = string.maketrans('ATCGNatcgn', 'ATCGNtagcn')
return seq.lower().translate(complement)[::-1]
|
ffd768bd21bbfd25c208500da8e35241210ae820 | SabinaBeisembayeva/WEB-dev | /lab_python_django/python_informatics/5-g.py | 126 | 3.8125 | 4 | a = int(input())
arr = []
for i in range(a):
x = int(input())
arr.append(x)
for i in arr:
arr.reverse()
print(arr) |
77f27e01be7161901f28d68801d67c3d1e1e8c83 | Nikola011s/portfolio | /work_with_menus.py | 2,539 | 4.6875 | 5 |
#User enters n, and then n elements of the list
#After entering elements of the list, show him options
#1) Print the entire list
#2) Add a new one to the list
#3) Average odd from the whole list
#4) The product of all elements that is divisible by 3 or by 4
#5) The largest element in the list
#6) The sum of those that is higher than the average of the whole list
# User choose an option and based on that option you print
n = int(input("Enter list lenth: "))
list_elements = []
for i in range(n):
number = int(input("Enter number:"))
list_elements.append(number)
print(list_elements)
while True:
print("""
1) Print the entire list
2) Add a new one to the list
3) Average odd from the whole list
4) The product of all elements that is divisible by 3 or by 4
5) The largest element in the list
6) The sum of those that is higher than the average of the whole list
0) Exit program
""")
option = int(input("Choose an option:"))
if option == 0:
print("End of the line")
exit(1)
elif option == 1:
print(list_elements)
elif option == 2:
number = int(input("Enter new element to the list: "))
list_elements.append(number)
elif option == 3:
sum = 0
counter = 0
lenth_list = len(list_elements)
for i in range(lenth_list):
if list_elements[i] % 2 != 0:
sum = sum + list_elements[i]
counter = counter + 1
if counter != 0:
average = sum / counter
print(" Average odd from the whole list is {average}")
else:
print("No odd elements")
elif option == 4:
product = 1
for i in range(n):
if list_elements[i] % 3 == 0 or list_elements[i] % 4 == 0:
product = product * list_elements[i]
print("Product is {product}")
elif option == 5:
maximum = list_elemens[0]
for number in list_elements:
if number > maximum:
maximum = number
print(maximum)
elif option == 6:
sum_higher = 0
sum = 0
for number in list_elements:
sum += number
average = sum / len(list_elements)
for number in list_elements:
if number > average:
sum_higher += number
print(sum_higher)
|
08abab6476720aee96923352443d6f7d127c17ae | faustoandrade/METODOS_TALLER | /metodosOrd.py | 3,295 | 3.875 | 4 | def insercionDirecta (lista,tam):
for i in range(1, tam):
v = lista[i]
j = i - 1
while j >= 0 and lista[j] > v:
lista[j + 1] = lista[j]
j = j - 1
lista[j + 1] = v
def mergeSort(lista):
#("Desordenado ",alist)
if len(lista)>1:
mid = len(lista)//2
lefthalf = lista[:mid]
righthalf = lista[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
lista[k]=lefthalf[i]
i=i+1
else:
lista[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
lista[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
lista[k]=righthalf[j]
j=j+1
k=k+1
#print("Ordenando ",alist)
def heapsort(aList):
length = len(aList) - 1
leastParent = length / 2
for i in range(leastParent, -1, -1):
moveDown(aList, i, length)
# flatten heap into sorted array
for i in range(length, 0, -1):
if aList[0] > aList[i]:
swap(aList, 0, i)
moveDown(aList, 0, i - 1)
def moveDown(aList, first, last):
largest = 2 * first + 1
while largest <= last:
# right child exists and is larger than left child
if (largest < last) and (aList[largest] < aList[largest + 1]):
largest += 1
# right child is larger than parent
if aList[largest] > aList[first]:
swap(aList, largest, first)
# move down to largest child
first = largest
largest = 2 * first + 1
else:
return # force exit
def swap(A, x, y):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
def quicksort(lista, izq, der):
i = izq
j = der
x = lista[(izq + der) / 2]
while (i <= j):
while lista[i] < x and j <= der:
i = i + 1
while x < lista[j] and j > izq:
j = j - 1
if i <= j:
aux = lista[i];
lista[i] = lista[j];
lista[j] = aux;
i = i + 1;
j = j - 1;
if izq < j:
quicksort(lista, izq, j);
if i < der:
quicksort(lista, i, der);
def count_sort(arr, max):
m = max + 1
counter = [0] * m
for i in arr:
counter[i] += 1
a = 0
for i in range(m):
for k in range(counter[i]):
arr[a] = i
a += 1
return arr
def radix_sort(random_list):
len_random_list = len(random_list)
modulus = 10
div = 1
while True:
# empty array, [[] for i in range(10)]
new_list = [[], [], [], [], [], [], [], [], [], []]
for value in random_list:
least_digit = value % modulus
least_digit /= div
new_list[least_digit].append(value)
modulus = modulus * 10
div = div * 10
if len(new_list[0]) == len_random_list:
return new_list[0]
random_list = []
rd_list_append = random_list.append
for x in new_list:
for y in x:
rd_list_append(y)
|
2e3920524acf1c91f5f71a479b56402f59e76cd3 | SethCerca/UNCC-Fall-2020 | /Intro-to-AI/Local_Search.py | 5,505 | 4.03125 | 4 | import random
import math
class Board():
def __init__(self, numRowsCols):
self.cells = [[0] * numRowsCols for i in range(numRowsCols)]
self.numRows = numRowsCols
self.numCols = numRowsCols
# negative value for initial h...easy to check if it's been set or not
self.h = -1
# Print board
def printBoard(self):
for row in self.cells:
print(row)
# Randomize the board
def rand(self):
self.cells = [[0] * self.numRows for i in range(self.numRows)]
for row in self.cells:
i = random.randint(0, self.numCols - 1)
row[i] = 1
# Swap two locations on the board
def swapLocs(self, a, b):
temp = self.cells[a[0]][a[1]]
self.cells[a[0]][a[1]] = self.cells[b[0]][b[1]]
self.cells[b[0]][b[1]] = temp
# Cost function for a board
def numAttackingQueens(board):
# Collect locations of all queens
locs = []
for r in range(len(board.cells)):
for c in range(len(board.cells[r])):
if board.cells[r][c] == 1:
locs.append([r, c])
# print 'Queen locations: %s' % locs
result = 0
# For each queen (use the location for ease)
for q in locs:
# Get the list of the other queen locations
others = [x for x in locs if x != q]
# print 'q: %s others: %s' % (q, others)
count = 0
# For each other queen
for o in others:
# print 'o: %s' % o
diff = [o[0] - q[0], o[1] - q[1]]
# Check if queens are attacking
if o[0] == q[0] or o[1] == q[1] or abs(diff[0]) == abs(diff[1]):
count = count + 1
# Add the amount for this queen
result = result + count
return result
# Move any queen to another square in the same column
# successors all the same
def getSuccessorStates(board):
result = []
for i_row, row in enumerate(board.cells):
# Get the column the queen is on in this row
# [0] because list comprehension returns a list, even if only one element
# This line will crash if the board has not been initialized with rand() or some other method
i_queen = [i for i, x in enumerate(row) if x == 1][0]
# For each column in the row
for i_col in range(board.numCols):
# If the queen is not there
if row[i_col] != 1:
# Make a copy of the board
bTemp = Board(board.numRows)
bTemp.cells[:] = [r[:] for r in board.cells]
# Now swap queen to i_col from i_queen
bTemp.swapLocs([i_row, i_col], [i_row, i_queen])
# bTemp.printBoard()
result.append(bTemp)
return result
# Returns the new T value
def linearScheduling(T, decayRate):
return T * decayRate
# Prints the size of the board
def printHeader(boardSize):
print("\n ==================")
print(" Board Size: " + str(boardSize))
print(" ==================")
# prints the decay rate and the T threshold
def printValues(tThreshold, decayRate):
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Decay Rate: " + str(decayRate) + ", T Threshold: " + str(tThreshold))
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# Executes Simulated Annealing to get the next board
def simAnnealing(boards, board, T, decayRate, tThreshold):
prob = 0
# Finds the next board in the sequence
while T > tThreshold:
T = linearScheduling(T, decayRate)
rand = random.randint(0, 11)
newBoard = boards[rand]
deltaE = numAttackingQueens(board) - numAttackingQueens(newBoard)
if deltaE > 0:
board = newBoard
else:
prob = math.exp(deltaE / T)
r = random.random()
if prob > r:
board = newBoard
return board
# Calculates and prints the average h-cost
def getAverage(hAverage):
h = 0
# print("hAverage = " + str(hAverage))
for x in hAverage:
h += x
print("H = " + str(h))
h = h / len(hAverage)
print('Average h-cost of final solutions: ' + str(h))
def main():
decayRates = [0.9, 0.75, 0.5]
tThresholds = [0.000001, 0.0000001, 0.00000001]
boardSize = [4, 8, 16]
# Iterates through all of the board sizes
for i in boardSize:
board = Board(i)
printHeader(i)
# iterates through all of the value states
for j in range(len(decayRates)):
printValues(tThresholds[j], decayRates[j])
T = 100
hAverage = []
# Generates the next 10 boards in the sequence
for x in range(0, 10):
print("\nRun: " + str(x))
print("Initial board: ")
board.rand()
board.printBoard()
print("h-value: " + str(numAttackingQueens(board)))
board = simAnnealing(getSuccessorStates(board), board, T, decayRates[j], tThresholds[j])
h = numAttackingQueens(board)
hAverage.append(h)
print("Final board h-value: " + str(h))
board.printBoard()
getAverage(hAverage)
if __name__ == '__main__':
main()
print('\nExiting normally')
|
731d24bb396d7af45d3601da31c9773ca2f6e055 | fatterZhang/leetcodeComments | /128_elegant_subarray.py | 1,389 | 3.75 | 4 | # -*- coding: utf-8 -*-#
# Name: 128_eligent_subarray
# Author: ARCHI
# Date: 2020/4/21
# Description:
# -------------------------------------------------------------------------------
from typing import List
def numberOfSubarrays(nums: List[int], k: int) -> int:
if len(nums) < k:
return 0
# 初始化窗口 (left, right]
left, right = -1, 0
odd_cnt = 0
while right < len(nums):
if nums[right] % 2 == 1:
odd_cnt += 1
if odd_cnt == k:
break
right += 1
# 整个数组都不满足条件
if odd_cnt != k:
return 0
rst = 0
# 开始缩减左右区间指针
print('beging zone ', left, right)
while right < len(nums):
# right指针向右移动,找到下一个奇数,记录下走的步数
after = right + 1
while after < len(nums) and nums[after] % 2 == 0:
after += 1
right_step = after - right
right = after
# left指针向右移动,找到
after = left + 1
while after <= right and nums[after] % 2 == 0:
after += 1
left_step = after - left
left = after
print(left_step, right_step)
rst += left_step * right_step
return rst
if __name__ == "__main__":
nums = [1, 1, 2, 1, 1]
k = 3
print(numberOfSubarrays(nums, k))
|
ba564bd38231baac9bec825f4eaac669c00ff6a5 | desingh9/PythonForBeginnersIntoCoding | /Day6_Only_Answers/Answer_Q2_If_Else.py | 353 | 4.21875 | 4 | #1.) Write a program to check whether a entered character is lowercase ( a to z ) or uppercase ( A to Z ).
chr=(input("Enter Charactor:"))
#A=chr(65,90)
#for i in range(65,90)
if (ord(chr) >=65) and (ord(chr)<=90):
print("its a CAPITAL Letter")
elif (ord(chr>=97) and ord(chr<=122)):
print ("its a Small charector")
else:
print("errrrr404") |
24b053c54c9e1de72aac7df28d284805f78802fa | desingh9/PythonForBeginnersIntoCoding | /Day2/asciiExplain.py | 286 | 3.828125 | 4 | print(chr(65))
print(ord("B"))
# loops will be clear later on but to clarify
# here we are CREATING (new list of characterS) FROM (list of number).
listOfNo= [1,2,3,4,5,6,7,8,9,10]
listOfCharacters=[]
for no in listOfNo:
listOfCharacters.append(chr(no+64))
print(listOfCharacters) |
e21b670ea1df1c62ec1c25b0959e221e49bb9f7a | desingh9/PythonForBeginnersIntoCoding | /Day6_Only_Answers/Answer10 July 19_percentage.py | 344 | 3.609375 | 4 | A=int(input("enter your percentage in \"A\"")) #Variable
B=int(input("enter your percantage in \"B\"")) #Variable
if (A>=55) and (B>=45):
print("Pass [Grade 1] ")
elif(A>=45) and (A<=55) and (B>=55):
print ("pass [Grade]2")
elif(B<45) and (A>=65):
print ("you are allwed to reappear")
else:
print("fail - game over! Try Again") |
7be2d577af8b2c87f844ec785a742e44167fa306 | desingh9/PythonForBeginnersIntoCoding | /Day6_Only_Answers/Answer9_def.py | 1,016 | 3.9375 | 4 | hardness = int (input("Enter the hardness:" ))
carbonContent = float (input("Enter the carbon content:" ))
tensileStrength = int (input("Enter the tensile strength:" ))
def IsCondition1Passed():
if hardness>50:
return True
else:
return False
def IsCondition2Passed():
if carbonContent<0.7:
return True
else:
return False
def IsCondition3Passed():
if tensileStrength>5600:
return True
else:
return False
if (IsCondition1Passed() and IsCondition2Passed() and IsCondition3Passed ()):
print ("your Steel Grade is 10")
elif (IsCondition1Passed() and IsCondition2Passed()):
print ("your steel Grade is 9")
elif (IsCondition2Passed() and IsCondition3Passed()):
print("your Steel Grade is 8")
elif (IsCondition1Passed() and IsCondition3Passed()):
print("your Steel Grade is 7")
elif (IsCondition1Passed() or IsCondition2Passed() or IsCondition3Passed()):
print("your Steel Grade is 6")
else:
print("your Steel Grade is 5") |
4fd4a832d17bd36622e15261490d868f6cd40076 | desingh9/PythonForBeginnersIntoCoding | /Day4_loops/For_loop_table.py | 184 | 4.3125 | 4 | #Print a table using for loop
t=int(input("enter the number : "))
for table in range (1,10+1): # this will print from 1- 10 number as given
print (t, "x",table, "=", t * table ) |
dea948a20c0c3e4ad252eb28988f2ae935e79046 | desingh9/PythonForBeginnersIntoCoding | /Q4Mix_A1.py | 776 | 4.28125 | 4 | #1) Write a program to find All the missing numbers in a given integer array ?
arr = [1, 2,5,,9,3,11,15]
occurranceOfDigit=[]
# finding max no so that , will create list will index till max no .
max=arr[0]
for no in arr:
if no>max:
max=no
# adding all zeros [0] at all indexes till the maximum no in array
for no in range(0,max+1):
occurranceOfDigit.append(0)
# original array
print(arr)
# marking index in occurrance array to 1 for all no in original array. marking indexes that are present in original array
for no in arr:
occurranceOfDigit[no]=1
print("Missing elements are: ")
i=1
# accesing all indexes where values are zero. i.e no. are not present in array
while i<=max:
if occurranceOfDigit[i]==0:
print(i,end=" ")
i+=1
|
d58778a994c202c98ff855a5845c6218200d72ce | desingh9/PythonForBeginnersIntoCoding | /Day6_Only_Answers/answer Q6 Day6.py | 441 | 4.09375 | 4 | #Q=7 Given a point (x, y), write a program to find out if it lies on the x-axis,
# y-axis or at the origin, viz. (0, 0).
x=int(input("enter the point in \"x\"")) #Variable
y=int(input("enter the point in \"y\"")) #Variable
#int(input("Enter the point{x.y}"))
if (x==0 and y==0):
print("Point lies on the Origin\n")
elif(x==0):
print("point lies on y- axis")
elif(y==0):
print("point lies on x- axis")
else:
print ("Error")
|
f7b15de5e73135519571b13d16a80f061fd962c5 | sifatmahmud/snake-water-gun-game-1.0-using-Python | /main.py | 2,849 | 3.796875 | 4 | try:
pc_point = 0
player_point = 0
roundn = 0
while roundn < 10:
roundn = roundn + 1
import random
list2 = ["snake", "water", "gun"]
list1 = random.choice(list2)
print("\n snake , water , gun")
inp1 = input("choose one of this : ") # user input
# if else statement start here
if list1 == "snake" and inp1 == "water":
print("computer choice", list1)
print("computer won this round")
pc_point += 1
elif list1 == "water" and inp1 == "snake":
print("computer choice", list1)
print("you won this round")
player_point += 1
elif list1 == "gun" and inp1 == "water":
print("computer choice", list1)
print("you won this round")
player_point += 1
elif list1 == "water" and inp1 == "gun":
print("computer choice", list1)
print("computer won this round")
pc_point += 1
elif list1 == "gun" and inp1 == "snake":
print("computer choice", list1)
print("computer won this round")
pc_point += 1
elif list1 == "snake" and inp1 == "gun":
print("computer choice", list1)
print("you won this round")
player_point += 1
elif list1 == "snake" and inp1 == "snake":
print("computer choice", list1)
print("both are winners this round")
pc_point += 1
player_point += 1
elif list1 == "gun" and inp1 == "gun":
print("computer choice", list1)
print("both are winners this round")
pc_point += 1
player_point += 1
elif list1 == "water" and inp1 == "water":
print("computer choice", list1)
print("both are winners this round")
pc_point += 1
player_point += 1
else:
print("your input maybe wrong ! please try again")
# finished code
print("you have finished", roundn, "round , and you have", 10 - roundn, "left")
if roundn == 10 and player_point < pc_point:
print("\nGame is over")
print("your point =", player_point, "and compuer point =", pc_point)
print("Computer the winner of this game")
elif roundn == 10 and player_point > pc_point:
print("\nGame is over")
print("your point =", player_point, "and compuer point =", pc_point)
print("You are the winner of this game")
elif roundn == 10 and player_point == pc_point:
print("\nGame is over")
print("your point =", player_point, "and compuer point =", pc_point)
print("Both are the winner of this game")
except Exception as k:
print(k)
|
0ce43db33d529e28974bdbfff6bfb6b7a53aa0f7 | kdmgs110/NP-Automation | /ex50/bin/never-be-a-pm/autoTweet.py | 9,936 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import tweepy
import random # ランダムでツイートを選ぶときに使う
"""
Procedure
* Sign in Twitter Accout
* Make list object that contains tweet content
* Randomly select one tweet content, and tweet
* automate tweeting
"""
# First, sign in to Twitter API
# 各種キーをセット
CONSUMER_KEY = 'psWut2vFh9e1dX0gCV5ICj5rk'
CONSUMER_SECRET = '5MXkpqqEe00Kn5ue1Ie6esBpQa8ocNub7gBCSGXqc4ylNmiMFp'
ACCESS_TOKEN = '718015800133586944-owT6LAObdpEesmHiWbsv80P3acRsmeI'
ACCESS_SECRET = 'sIPWThSDgTB2pp8l3f5d1Na7w7KXkk6sjI4Dww1g0HwFj'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
#APIインスタンスを作成
api = tweepy.API(auth)
#ツイートをリストに格納
tweets = [
#''' 1'''
"【Python初心者向け】データの取得・操作・結合・グラフ化をStep by Stepでやってみる - pandas, matplotlib - #はてなブログ" #1
+ "{}".format("http://review-of-my-life.blogspot.com/2017/09/python-data-analyse.html"),
#''' 2'''
"【R】テキストマイニングを利用して、東京ちんこ倶楽部と暇な女子大生を分析する #はてなブログ" #2
+ "{}".format("http://review-of-my-life.blogspot.com/2017/08/r-text-mining.html"),
#''' 3'''
"【ノンプログラマでも5分でできる】面倒な情報収集はGoogle Spreadsheetに自動でやらせよう #はてなブログ" #3
+ "{}".format("http://review-of-my-life.blogspot.com/2017/07/google-spreadsheet-information.html"),
#''' 4'''
"次に私は小論文を書くことを教えようとしました。でもそれはまず不可能だとわかりました。学生たちは単に押し付けられた考え方に従うだけだったのです。#はてなブログ " #4
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/06/python-cloud9-automatically-execute-python-program.html"),
#''' 5'''
"【Pythonで定期処理】 Cloud9を利用して、Seleniumでherokuから定期実行する #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/06/python-cloud9-automatically-execute-python-program.html"),
#''' 6'''
"PythonでTinder APIを使ってネトストとサイバーナンパ師やってみた #はてなブログ" #6
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/06/pythontinder-api-cyber-hockup.html"),
#''' 7'''
"PythonでTinderのAPIをいじる #はてなブログ" #7
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/06/get-tinder-api-by-python.html"),
#''' 8'''
"『Pythonによるスクレイピング&機械学習 開発テクニック』レビュー #はてなブログ" #4
+ "{}".format("http://review-of-my-life.blogspot.com/2017/09/python-scraping.html"),
#''' 9'''
"金がないのにFacebook広告を無駄に運用してみた #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/09/facebook-pr-for-individual-blog.html"),
#''' 10'''
"『無敵の思考 ---誰でも得する人になれるコスパ最強のルール21』ひろゆきの書評を書いてみた #はてなブログ" #6
+ "{}".format("http://review-of-my-life.blogspot.com/2017/08/hiroyuki-book.html"),
#''' 11'''
"スマホで読書しない人生なんて絶対にもったいない!! #はてなブログ" #7
+ "{}".format("http://review-of-my-life.blogspot.com/2017/07/kindle-on-mobile-is-way-better.html"),
#''' 12'''
"就活して最後の最後に気付いた、誰も教えてくれなかった3つのこと" #4
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/07/3-things-no-one-told-me-.html"),
#''' 13'''
"【学校不要論】頭いい人にとって義務教育はいらないという真実 #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.com/2017/03/noHighSchool.html"),
#''' 14'''
"【保存版】相関分析・重回帰分析・クロス集計の結果を、英語でレポートするためのテンプレート #はてなブログ" #6
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/01/howToReportStats.html") ,
#''' 15'''
"脚本から興行収入を事前に予測できる?『機械脳の時代』(加藤エルテス)を読んでみました #はてなブログ" #7
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/09/machine-brain.html"),
#''' 16'''
"企業内保育の何がすごいのか #はてなブログ" #4
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/08/kindergarten-in-company.html"),
#''' 17'''
"【本屋の社会学】専門書を安く買いたければ、教育所得水準の高い地域の本屋へ行こう #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/06/go-bookstore-and-you-can-see-educational-and-income-level.html"),
#''' 18'''
"英語を学ぶべきたった一つの理由" #6
+ "{}".format("http://review-of-my-life.blogspot.com/2017/05/the-reason-why-we-should-learn-english.html"),
#''' 19'''
"【データで見る】性的少数者(LGBT)がどれだけ差別されているか調べてみた #はてなブログ" #7
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/04/lgbt-is-difficult.html"),
#''' 20'''
"【歴史でひも解く】なぜ日本の義務教育は画一的なのか #はてなブログ" #4
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/04/WhyEducationIsSoUniform.html"),
#''' 21'''
"【英語を話せる外国から学ぶ】なぜ日本人は英語を話せないのか #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/04/JapaneseDonotLearnEnglish.html"),
#''' 22'''
"【顔面格差】イケメンとブサメンの年収格差がやばい件について" #6
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/04/goodLookingEarnMore.html"),
#''' 22'''
"【データで見る】性的少数者(LGBT)がどれだけ差別されているか調べてみた #はてなブログ" #7
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/03/isRecruitmentByAcademicCredentialValid.html"),
#''' 23'''
"学歴フィルターは差別なのか考えてみた #はてなブログ" #4
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/04/WhyEducationIsSoUniform.html"),
#''' 24'''
"【マシュマロテスト・ペリー幼稚園・GRIT】教育学全般の面白い研究まとめ(心理学・社会学・経済学領域) #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/01/interestingStudyOnEducation.html"),
#''' 25'''
"東大生もハーバード生も、親の年収が頭おかしい件について" #6
+ "{}".format("http://review-of-my-life.blogspot.jp/2016/12/UniversityOfTokyoVsHarvard.html"),
#''' 26'''
"教育格差の再生産:人生は想像以上にただの課金ゲーだった話 #はてなブログ" #4
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/04/WhyEducationIsSoUniform.html"),
#''' 27'''
"【大学4年間を振り返る】そもそも、大学に行く意味はあるのか?大学に行く2つのメリット #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.jp/2016/05/4.html"),
#''' 22'''
"【顔面格差】イケメンとブサメンの年収格差がやばい件について" #6
+ "{}".format("http://review-of-my-life.blogspot.jp/2016/12/educationismoney.htmll"),
#''' 22'''
"【データで見る】性的少数者(LGBT)がどれだけ差別されているか調べてみた #はてなブログ" #7
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/03/isRecruitmentByAcademicCredentialValid.html"),
#''' 23'''
"学歴フィルターは差別なのか考えてみた #はてなブログ" #4
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/04/WhyEducationIsSoUniform.html"),
#''' 24'''
"【マシュマロテスト・ペリー幼稚園・GRIT】教育学全般の面白い研究まとめ(心理学・社会学・経済学領域) #はてなブログ" #5
+ "{}".format("http://review-of-my-life.blogspot.jp/2017/01/interestingStudyOnEducation.html"),
#''' 25'''
"東大生もハーバード生も、親の年収が頭おかしい件について" #6
+ "{}".format("http://review-of-my-life.blogspot.jp/2016/12/UniversityOfTokyoVsHarvard.html"),
]
try:
tweet = random.choice(tweets)
print("以下のツイートを取得しました。ツイートを開始します。: {}:".format(tweet))
api.update_status(tweet)
print("成功しました!")
except Exception as e:
print("ツイートに失敗しました:{}".format(e))
|
2b99e0c3f6ba81f5c8a8226a47036f4bc59f4a0b | EvertonAlvesGomes/Curso-Python | /pesoPessoas.py | 1,755 | 3.90625 | 4 | ### pesoPessoas.py
## Cadastre pessoas pelo nome e peso em kg. Ao final,
## Retorne a quantidade de pessoas cadatradas, as mais pesadas e as mais leves
pessoas = list()
dado = list() # lista temporária para armazenar dados de uma única pessoa
mais_leves = list() # lista das pessoas mais leves
mais_pesadas = list() # lista das pessoas mais pesadas
s_n = 'S' # variável para continuar ou finalizar o cadastro
maior_peso = 0 # maior peso
menor_peso = 0 # menor peso
# Por padrão, a primeira pessoa cadastrada será a de maior peso.
cont = 0
print("\n******* CADASTRO DE PESSOAS *******\n")
while s_n == 'S':
dado.append(input('Nome: '))
dado.append(int(input('Peso: ')))
cont += 1 # incrementa o contador de cadastros
pessoas.append(dado[:])
if cont == 1: # se há apenas uma pessoa cadastrada, maior e menor peso são iguais
maior_peso = pessoas[0][1]
menor_peso = pessoas[0][1]
else :
if dado[1] > maior_peso:
maior_peso = dado[1]
if dado[1] < menor_peso: # atualiza o menor peso
menor_peso = dado[1]
dado.clear()
s_n = str(input('Quer continuar? [S/N] ')).upper()
while (s_n != 'S') and (s_n != 'N'):
print('Comando inválido.')
s_n = str(input('Quer continuar? [S/N] ')).upper()
print("\n")
for p in pessoas:
if p[1] == maior_peso:
mais_pesadas.append(p[0])
else :
if p[1] == menor_peso:
mais_leves.append(p[0])
# Resultados
print(f"Foram cadastradas {len(pessoas)} pessoas.")
print(f'Menor peso: {menor_peso} kg. Peso de {mais_leves}')
print(f'Maior peso: {maior_peso} kg. Peso de {mais_pesadas}') |
f00c15c9471ecefdbbee77caf4015416c1710938 | EvertonAlvesGomes/Curso-Python | /jogador_futebol.py | 886 | 3.703125 | 4 | ### jogador_futebol.py
jogador = dict()
gols = list()
jogador = {'nome': '', 'gols': gols, 'n_partidas': 0}
jogador['nome'] = str(input("Nome do jogador: "))
jogador['n_partidas'] = int(input(f"Quantas partidas {jogador['nome']} jogou? "))
for n in range(0,jogador['n_partidas']):
gols.append(int(input(f"Quantos gols marcados na partida {n}? ")))
# ----- Resultados ----- #
print()
print("Dados do jogador:")
print(jogador)
print("-="*35)
print(f"Nome do jogador: {jogador['nome']}")
print(f"Gols marcados: {jogador['gols']}")
print(f"Total de partidas: {jogador['n_partidas']}")
print("-="*30)
print(f"O jogador {jogador['nome']} jogou {jogador['n_partidas']} partidas.")
for i in range(0,jogador['n_partidas']):
print(f" Na partida {i}, {jogador['nome']} fez {jogador['gols'][i]} gols.")
print(f"Total de gols marcados: {sum(jogador['gols'])}") |
152920d0c317bb528f19c39d56dfead8bc0d9952 | EvertonAlvesGomes/Curso-Python | /listas.py | 1,525 | 4.5625 | 5 | ### listas.py
## Estudando listas em Python
moto = ['Rodas','Motor','Relação','Freios'] # lista inicial
moto.append('Embreagem') # adicona elemento ao final da lista
moto.insert(2, 'Transmissão') # insere o elemento 'Transmissão' na posição 2,
# sem substituir o elemento atual dessa posição.
# O elementos subsequentes serão deslocados para a direita
moto.remove('Motor') # remove o elemento, deslocando para a esquerda os elementos seguintes
# Alternativa: del moto[1] -> remove o elemento da posição 1
# Alternativa 2: moto.pop(1) -> remove o elemento da posição 1
# Observação: o método pop geralmente é utilizado para remover o último elemento da lista.
moto.pop() # remove o último elemento
# ---------------
print(moto)
# ----------
valores = [8,2,4,10,1,3,6]
valores.sort() # organiza em ordem crescente
valores.sort(reverse=True) # organiza em ordem decrescente
print(valores)
print(f'A lista valores tem {len(valores)} elementos.')
# Uma maneira elegante de declarar uma lista é pelo construtor list(),
# uma vez que list é objeto da classe de mesmo nome.
# Exemplo: lista = list() # cria uma lista vazia
# Atribuição de listas em Python:
# a = [2, 4, 5, 9]
# b = a # as listas b, a são interligadas. Qualquer alteração em uma das listas altera a outra
# b = a[:] # o conteúdo de a é copiado para b, sem estabeler uma relação entre elas. |
b97fe6ef13c9e35f1ea45aa71198d80a21aefd93 | hanylovescode/ezgame | /src/helpers/vector.py | 5,290 | 3.671875 | 4 | import logging
from random import randint
import math
# TODO: try to make class Vector inherit from a Sequence (list, tuple, ...)
# TODO: check the difference between this and the Verlet method:
# https://gamedev.stackexchange.com/a/41917
class Vector:
"""
Implementation of a 2D Euclidean Vector and its methods.
"""
logger = logging.getLogger('Vector')
def __init__(self, x: float = 0, y: float = 0):
self.x = x
self.y = y
self.logger.info(f'init -> Vector({x},{y})')
@classmethod
def from_tuple(cls, input_tuple: tuple[float, float]):
"""Initialize a Vector from a tuple"""
return cls(input_tuple[0], input_tuple[1])
@classmethod
def create_from_random(cls, rand_min: int, rand_max: int):
"""Initialize a new Vector with a random x and y values"""
return cls(randint(rand_min, rand_max), randint(rand_min, rand_max))
def copy(self):
"""Returns a new instance with the current Vector values"""
return Vector(self.x, self.y)
def randomize_values(self, rand_bound: int, magnitude: float):
"""Changes the current Vector to random values"""
self.x = randint(-rand_bound, rand_bound) * magnitude
self.y = randint(-rand_bound, rand_bound) * magnitude
def __eq__(self, other_vector):
"""Overriding == operator"""
if not other_vector:
return False
return self.x == other_vector.x and self.y == other_vector.y
def __repr__(self):
"""Overriding the __repr__ method; for debugging"""
return f'Vector({self.x}, {self.y})'
def __str__(self):
"""Overriding the __str__ method; for debugging"""
return f'({self.x}, {self.y})'
# Don't use this method, It's just for testing
def __getitem__(self, i: int) -> float:
"""Overriding the __getitem__ method; for debugging"""
self.logger.warning('You are using __getitem__, use .x or .y instead!')
if i == 0:
return self.x
elif i == 1:
return self.y
else:
raise IndexError
# Don't use this method, It's just for testing
def __add__(self, other_vector):
"""
Overriding the addition operator.
WARNING: It creates a new instance.
"""
Vector.__confirm_is_vector(other_vector)
x = self.x + other_vector.x
y = self.y + other_vector.y
self.logger.warning('You created a new instance of the class Vector')
return Vector(x, y)
# Don't use this method, It's just for testing
def __sub__(self, other_vector):
"""
Overriding the subtraction operator.
WARNING: It creates a new instance.
"""
Vector.__confirm_is_vector(other_vector)
x = self.x - other_vector.x
y = self.y - other_vector.y
self.logger.warning('You created a new instance of the class Vector')
return Vector(x, y)
def add(self, other_vector):
Vector.__confirm_is_vector(other_vector)
self.x += other_vector.x
self.y += other_vector.y
def subtract(self, other_vector):
Vector.__confirm_is_vector(other_vector)
self.x -= other_vector.x
self.y -= other_vector.y
def multiply(self, magnitude: float):
"""scalar multiplication of the Vector"""
self.x *= magnitude
self.y *= magnitude
def divide(self, magnitude: float):
"""scalar division of the Vector"""
if magnitude == 0:
raise ValueError('Dividing by zero!')
self.multiply(1 / magnitude)
def get_magnitude(self) -> float:
"""
returns the magnitude of the Vector
using the formula c^2 = a^2 + b^2
"""
return math.sqrt(self.x * self.x + self.y * self.y)
def normalize(self):
"""changes the Vector to a unit Vector"""
return self.divide(self.get_magnitude())
def set_magnitude(self, magnitude: float):
"""change the magnitude of the vector to a specific value"""
self.normalize()
self.multiply(magnitude)
def limit(self, bound: float):
"""Bounds the Vector values to specific limits"""
# TODO: find if there's a better implementation
if self.x > bound:
self.x = bound
elif self.x < -bound:
self.x = -bound
if self.y > bound:
self.y = bound
elif self.y < -bound:
self.y = -bound
def set(self, x: float, y: float):
self.x = x
self.y = y
@staticmethod
def distance(vector_a, vector_b) -> float:
"""Returns the Euclidean distance between two Vectors"""
Vector.__confirm_is_vector(vector_a)
Vector.__confirm_is_vector(vector_b)
# TODO: see if math.isclose() has better performance than math.dist()
return math.dist((vector_a.x, vector_a.y), (vector_b.x, vector_b.y))
@staticmethod
def __confirm_is_vector(var):
"""Check if the variable is an instance of type Vector, and raise a TypeError if not"""
if type(var) is not Vector:
error_msg = f'{var} is an instance of class {type(var).__name__} and not of class Vector'
raise TypeError(error_msg)
|
6d1b6eee9d586df27b6a18d83341a911ccb285cd | veetarag/Data-Structures-and-Algorithms-in-Python | /LeetCode/friend_cricles_UnionFind.py | 951 | 3.671875 | 4 | class DisjointSet:
def __init__(self, matrix):
self.matrix = matrix
self.nodesCount = len(matrix)
self.parent = [i for i in range(self.nodesCount)]
def find(self, x):
if self.parent[x] == x:
return x
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
u = self.find(x)
v = self.find(y)
if u==v:
return
self.parent[u] = v
def addFriendList(self):
for i in range(self.nodesCount):
for j in range(self.nodesCount):
if self.matrix[i][j] == 1:
self.union(i, j)
def findCircles(self):
self.addFriendList()
cnt = 0
for i in range(self.nodesCount):
if self.parent[i] == i:
cnt+=1
return cnt
mat = [[1,1,0],
[1,1,1],
[0,1,1]]
uf = DisjointSet(mat)
print(uf.findCircles())
|
be06a70e1eef93540bb5837ae43220ae29d7d7fa | veetarag/Data-Structures-and-Algorithms-in-Python | /Interview Questions/Rotate Image.py | 592 | 4.125 | 4 | def rotate(matrix):
l = len(matrix)
for row in matrix:
print(row)
print()
# Transpose the Matrix
for i in range(l):
for j in range(i, l):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
print(row)
print()
# Row Reverse
for i in range(l):
for j in range(l//2):
matrix[i][l-j-1], matrix[i][j] = matrix[i][j], matrix[i][l-j-1]
for row in matrix:
print(row)
return matrix
# Rotate the image 90 degree clockwise
rotate([
[1,2,3],
[4,5,6],
[7,8,9]
]) |
432c2ef039a742686610f06640afc7e2a064e64d | veetarag/Data-Structures-and-Algorithms-in-Python | /Interview Questions/Maximum Chair at a Party.py | 2,255 | 3.671875 | 4 | """
arr[] = {1, 2, 10, 5, 5}
dep[] = {4, 5, 12, 9, 12}
Below are all events sorted by time. Note that in sorting, if two
events have same time, then arrival is preferred over exit.
Time Event Type Total Number of Guests Present
------------------------------------------------------------
1 Arrival 1
2 Arrival 2
4 Exit 1
5 Arrival 2
5 Arrival 3 // Max Guests
5 Exit 2
9 Exit 1
10 Arrival 2
12 Exit 1
12 Exit 0
"""
def maximumChairs(arrival, leave):
arrival.sort()
leave.sort()
l = len(arrival)
chairs_now = 1
max_chairs = 1
time_of_mx_chairs = arrival[0]
# First One take as arrival
i = 1
j = 0
while i<l and j<l:
# If the arrival is less then add arrival
if arrival[i] <= leave[j]:
chairs_now+=1
if chairs_now > max_chairs:
max_chairs = chairs_now
time_of_mx_chairs = arrival[i]
i+=1
# Leave time is less
else:
chairs_now-=1
j+=1
return max_chairs, time_of_mx_chairs
print(*maximumChairs([1, 2, 10, 5, 5], [4, 5, 12, 9, 12]))
# import heapq
#
#
# class Solution:
# def __init__(self):
# pass
#
# def minChairs(self, S, E):
#
# # Form interval pairs (start time, end time)
# intervals = [[S[i], E[i]] for i in range(len(S))]
#
# # Sort intervals based on start time
# intervals.sort(key=lambda x: x[0])
#
# heap = []
# res = 0
#
# for interval in intervals:
# if not heap or heap[0] > interval[0]:
# # If no chair is free allocate new chair
# res += 1
# heapq.heappush(heap, interval[1])
# else:
# # If any chair is free
# heapq.heappop(heap)
# heapq.heappush(heap, interval[1])
#
# return res
#
#
# s = Solution()
# print(s.minChairs([1, 2, 10, 5, 5], [4, 5, 12, 9, 12]))
|
0e7ed5d0d93126fa87651d01591db594b85a2c0c | veetarag/Data-Structures-and-Algorithms-in-Python | /DataStructure/bfs.py | 892 | 3.578125 | 4 | def bfs(n, m, edges, s):
# initializing graph
graph = {i: [] for i in range(1, n + 1)}
# taking the edges input
visited, queue, level = [False] * (n + 1), [], [0] * (n + 1)
# push start node
queue.append(s)
visited[s] = True
level[s] = 0
# iterate until queue is empty
while queue:
vertex = queue.pop(0)
for neighbor in graph[vertex]:
if visited[neighbor] == False:
level[neighbor] = level[vertex] + 6
queue.append(neighbor)
visited[neighbor] = True
return level
if __name__ == '__main__':
q = int(input())
for _ in range(q):
n, m = map(int, input().split())
edges = []
for _ in range(m):
edges.append(list(map(int, input().rstrip().split())))
s = int(input())
result = bfs(n,m,edges,s)
print(result) |
cdea0cb65d41a67aa98441438a387efa5069f3a9 | veetarag/Data-Structures-and-Algorithms-in-Python | /Interview Questions/Check Linked List Palindrome.py | 513 | 3.6875 | 4 | # Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
def isListPalindrome(l):
# Use a stack to move from left to right. Then pop from right and check again with traversing
stck = []
head = l
while head != None:
stck.append(head.value)
head = head.next
while l != None:
if stck.pop(-1) != l.value:
return False
l = l.next
return True
|
17c6813b90aea51bf990a8d3b0973038fe152d27 | veetarag/Data-Structures-and-Algorithms-in-Python | /Dynamic Programming/longest_palindrome_length.py | 552 | 3.578125 | 4 | def longest_palindrome_length(string):
N = len(string)
cache = [[None]*N for _ in range(N)]
left, right = 0, 0
def find_length(i, j):
if(cache[i][j]!=None):
return cache[i][j]
if(i>j):
return 0
if(i==j):
return 1
if(string[i]==string[j]):
return find_length(i+1, j-1) + 2
ans = max(find_length(i+1, j), find_length(i, j-1))
cache[i][j] = ans
return ans
return find_length(0, N-1)
print(longest_palindrome_length("bbbab")) |
059cd17df17100c619386fb61793efa4efd6e18a | veetarag/Data-Structures-and-Algorithms-in-Python | /Interview Questions/First Duplicate in Array.py | 291 | 3.890625 | 4 | def firstDuplicate(array):
l = len(array)
for i in range(l):
if array[abs(array[i])-1] < 0:
return abs(array[i])
# Make the found value index negative
array[abs(array[i])-1] = -array[abs(array[i])-1]
print(firstDuplicate([2,1,1]))
# [2, -1, 1] |
97cb2080244ceb7295c891736cfdd4ff6675e547 | veetarag/Data-Structures-and-Algorithms-in-Python | /graph/detect_cycle_directed_dfs.py | 798 | 3.515625 | 4 | from collections import defaultdict
def dfs_visit(node, graph, color, time, d, f):
time+=1
color[node] = 'Gray'
d[node] = time
for neighbour in graph[node]:
if(color[neighbour]=='Black'):
continue
elif(color[neighbour]=='Gray'):
return True
elif(dfs_visit(neighbour, graph, color, time, d, f)==True):
return True
color[node] = 'Black'
time+=1
f[node] = time
return False
def isCyclic(n, graph):
color = ['White']*(n+1)
d = [0]*(n+1)
f = [0]*(n+1)
for i in range(n+1):
if(color[i]=='White'):
if(dfs_visit(i,graph,color, 0, d, f)):
return True
return False
d = defaultdict(list)
d[0].append(0)
d[0].append(1)
# print(d)
print(isCyclic(2,d)) |
52e733fa1990f4d8815d6560a7150da78874ae17 | veetarag/Data-Structures-and-Algorithms-in-Python | /Dynamic Programming/longest_increasing_sequence_LIS.py | 812 | 3.671875 | 4 | def LIS(array):
l = len(array)
cache = [None]*(l+1)
dir = [-1]*(l+1)
def longest(i):
if cache[i]!=None:
return cache[i]
maxi = 0
for j in range(i+1, l):
if(array[j]> array[i]):
if longest(j) > maxi:
maxi = longest(j)
dir[i] = j
cache[i] = 1 + maxi
return cache[i]
def print_path(start):
print(f"Path: {start}", end=" ")
while(dir[start]!=-1):
print(dir[start], end=" ")
start = dir[start]
lis = 0
start = -1
for i in range(l):
if (longest(i)>lis):
lis = longest(i)
start = i
print(f"Longest LIS: {lis} from staring at {start}")
print_path(start)
LIS([5,0,9,2,7,3,7,8,9])
|
9077f94ae39d9dd034cb95db552b714d2ecc540d | veetarag/Data-Structures-and-Algorithms-in-Python | /Interview Questions/Unique Email Addresses.py | 484 | 3.5 | 4 | def uniqueEmails(emails):
uniq_mails = set()
for email in emails:
formatted_email = ''
splits = email.split('@')
flag = True
for c in splits[0]:
if c=='+':
flag=False
if c=='.':
continue
if flag:
formatted_email+=c
uniq_mails.add(formatted_email+'@'+splits[1])
return len(list(uniq_mails))
print(uniqueEmails(["test.email+alex@leetcode.com","test.email.leet+alex@code.com"]))
|
97880a186f59ee58b83e9487e2d5c9c4e3366788 | mnazimy/blocks-world | /bw.py | 2,650 | 3.59375 | 4 | """
The Blocks World AI problem implemented and sovled with Python.
Creator: Apostolos Anastasios Kouzoukos, dai17038
Email: kouzoukos97@gmail.com
Github: https://github.com/kouzapo
"""
import time
import sys
import os
from state import State
from searching import breadth_first_search, depth_first_search, heuristic_search
from utilities import read_input_file, write_output_file
def main():
st = time.perf_counter() #Start a time counter.
if len(sys.argv) == 4: #If the length of the keyword arguments is four...
method = sys.argv[1] #The second argument is the method/algorithm used to find a solution.
input_file = sys.argv[2] #The third argument is a .txt file containing the initial and final state of the problem.
output_file = sys.argv[3] #The fourth argument is a .txt file containing the solution of the problem.
initial_state, goal_state = read_input_file(filename = input_file) #Read the input file and return two state objects.
if method == 'breadth': #Check which method is selected and solve the problem accordingly.
solution = breadth_first_search(current_state = initial_state, goal_state = goal_state, timeout = 300)
elif method == 'depth':
solution = depth_first_search(current_state = initial_state, goal_state = goal_state, timeout = 300)
elif method == 'best':
solution = heuristic_search(current_state = initial_state, goal_state = goal_state, method = 'best', timeout = 300)
elif method == 'astar':
solution = heuristic_search(current_state = initial_state, goal_state = goal_state, method = 'astar', timeout = 300)
else: #If the method argument is none of the above, print a usage message.
solution = None
print('Usage: python bw.py <method> <input filename> <output filename>')
if solution == goal_state: #If the solution is equal to the goal state...
number_of_moves = write_output_file(solution = solution, filename = output_file) #Write the solution file and return the number of moves.
print('Solution found!')
print('Number of blocks:', len(initial_state.layout.keys()))
print('Method:', method)
print('Number of moves:', number_of_moves)
print('Execution time:', str(round(time.perf_counter() - st, 4)))
else: #Else, if the length of the keyword arguments is not equal to four, print a usage message.
print('Usage: python bw.py <method> <input filename> <output filename>')
if __name__ == '__main__':
main() |
4312eb44292879e0a6ad3b8b7582a1e6b677883f | J0ul/main | /12.2-8.py | 4,218 | 3.90625 | 4 | # 12.2 Напишите программу, которая для целочисленного списка из 1000 случайных
# элементов определяет, сколько отрицательных элементов располагается между его
# максимальным и минимальным элементами.
import random
import statistics
s = []
for i in range(20):
s.append(random.randint(-10, 100))
print(s)
a = s.index(min(s))
b = s.index(max(s))
if a < b:
ss = s[a + 1:b]
else:
ss = s[b + 1:a]
count = 0
for i in ss:
if i < 0:
count += 1
print("Отрицательных элементов между максимальным и минимальным элементами списка: ", count)
# 12.3 Найти элемент, наиболее близкий к среднему значению всех элементов списка
avg = statistics.mean(s)
print("Среднее значение списка: ", avg)
print("Элемент, наиболее близкий к среднему: ", min(s, key=lambda num: abs(num - avg)))
# 12.4 Найти сумму простых чисел в списке
pr = []
for i in s:
for x in range(2, abs(i)):
if i % x == 0:
break
elif i == 0:
break
else:
pr.append(i)
print("Сумма простых чисел из списка: ", sum(pr))
# 12.5
# Дан список целых чисел. Определить, есть ли в нем хотя бы одна пара соседних
# нечетных чисел. В случае положительного ответа определить номера элементов первой из
# таких пар.
no = 0
for i in s:
if i % 2 != 0 and s.index(i) != len(s) - 1 and s[s.index(i) + 1] % 2 != 0:
# print(s.index(i), s.index(i)+1)
no += 1
break
if no == 0:
print("Нет соседних нечетных чисел")
# 12.6
# Дан список целых чисел. Определить количество четных элементов и количество
# элементов, оканчивающихся на цифру 5.
chet = 0
for i in s:
if i % 2 == 0 and i != 0:
chet += 1
print("Четных чисел: ", chet)
fif = 0
fif_split = []
for i in s:
fif_split = list(str(i))
if int(fif_split[-1]) == 5:
fif += 1
print("Чисел, оканчивающихся на 5: ", fif)
# 12.7
# Задан список из целых чисел. Определить процентное содержание элементов,
# превышающих среднеарифметическое всех элементов списка.
avg = statistics.mean(s)
cnt = 0
for i in s:
if i > avg:
cnt += 1
print("Элементов, превышающих среднеарифметическое: ", (cnt / len(s)) * 100, "%")
# 12.8
# Задан список из целых чисел. Определить количество участков списка, на котором
# элементы монотонно возрастают (каждое следующее число больше предыдущего).
mono = 0
for i in s:
if s.index(i) < len(s) - 2 and s[s.index(i) + 1] > i and s[s.index(i) + 2] < s[s.index(i) + 1]:
mono += 1
elif s.index(i) < len(s) - 1 and s[s.index(i) + 1] > i and s.index(i) + 1 == len(s) - 1:
mono += 1
print("Количество участков списка, на котором элементы монотонно возрастают: ", mono)
# 12.9
# Дан список из 20 элементов. Найти пять соседних элементов, сумма значений которых
# максимальна.
sum5, beg, end = 0, 0, 0
s5 = []
for i in s:
if s.index(i) < 16:
s5 = s[s.index(i):s.index(i)+5]
if sum(s5) > sum5:
sum5 = sum(s5)
beg = s.index(i)
end = beg + 4
print("Пять соседних элементов, сумма значений которых максимальна: ", s[beg:end+1])
|
3e46644256108dd4af3ceed69e96ed4e2df5637c | J0ul/main | /13.1-2.py | 1,877 | 4.0625 | 4 | # 13.1
# Напишите программу, проверяющую четность числа, вводимого с клавиатуры.
# Выполните обработку возможных исключений
try:
x = int(input("Введите целое число: "))
if x % 2 > 0:
print(x, " - нечетное число")
else:
print(x, " - четное число")
except ValueError:
print("Ошибка, это не целое число")
# 13.2
# Напишите программу, которая будет генерировать матрицу из случайных целых
# чисел. Пользователь может указать число строк и столбцов, а также диапазон целых чисел.
# Произведите обработку ошибок ввода пользователя.
from random import randint
try:
a = int(input("Введите число строк: "))
if a <= 0:
print("Ошибка, должно быть целое положительное число")
raise SystemExit
b = int(input("Введите число столбцов: "))
if b <= 0:
print("Ошибка, должно быть целое положительное число")
raise SystemExit
y = int(input("Задайте начало диапазона целый чисел матрицы: "))
z = int(input("Задайте конечное число диапазона: "))
if z < y:
print("Ошибка, конечное число диапазона должно быть больше начального")
raise SystemExit
M = [[randint(y, z) for i in range(a)] for j in range(b)]
except ValueError:
print("Ошибка, это не целое число")
print(*M, sep='\n')
|
219d0100864e2e8b1777cb935a9b5e61ca52ef8a | osalpekar/RSA-Encrypter | /rsa.py | 620 | 4.15625 | 4 | '''
Main function instantiates the Receiver class
Calls encrypt and decrypt on user-inputted message
'''
from receiver import Receiver
def main():
message = raw_input("Enter a message you would like to encrypt/decrypt: ")
receiver = Receiver()
encrypted_message = receiver.encrypt(message)
decrypted_message = receiver.decrypt(encrypted_message)
print "Your original message was: " + message
print "Your encrypted message is: " + ''.join([str(num) for num in encrypted_message])
print "Your decrpyted message is: " + decrypted_message
return
if __name__ == "__main__":
main()
|
cef0c8680f1f374708d3029d5e6e4d60616310b6 | KJCook/sedov-solution | /VH1/output/10sm/animate_hydro.py | 1,628 | 3.546875 | 4 | #Base animation code written by Nathan Parzuchowski
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0.0, 0.4), ylim=(0, 3.0e5)) # change the axis limits here
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
k = str(i)
k = (3-len(k))*'0'+k
fl = open('10sm1'+k+'.dat','r') #file name here
xr =[]
yr =[]
for roak in fl:
broken = roak.strip().split()
xr.append(float(broken[0])) # x column
yr.append(float(broken[1])*float(broken[0])*float(broken[0])*4*np.pi) # y column
x=np.array(xr)
y=np.array(yr)
line.set_data(x, y)
fl.close()
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
# number of frames needs to be input. Interval will determine the framerate
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=50, blit=True)
# save the animation as an mp4. This requires ffmpeg or mencoder to be
# installed. The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5. You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
|
3d29b57b143e7d20205b780c22d7e4a4e82dd5b2 | XARXALINUX/myfipypro | /calc.py | 723 | 3.90625 | 4 | print("IF IT DOESN'T WORKING READ README")
print("To learn the commands type hlp()")
def calc():
a = input()
b = input()
print("The sum is:", a + b)
def mu():
c = input()
d = input()
print("The sum is:", c * d)
def ext():
print("CLOSING")
exit()
def hlp():
print("To subtract two numbers type sub()")
print("To add two numbers type calc()")
print("To multiply two numbers type mu()")
print("To divide two numbers type div()")
print("To exit type ext()")
def div():
s = input()
d = input()
print("The sum is:", s / d)
def sub():
j = input()
h = input()
print("The sum is:", j - h)
|
8858083bbd2a1ff2bd63cdde91462bc1efbeb4c7 | HenriqueSilva29/infosatc-lp-avaliativo-06 | /atividade 1.py | 624 | 4.1875 | 4 | #O método abs () retorna o valor absoluto do número fornecido.
# Exemplo :
# integer = -20
#print('Absolute value of -20 is:', abs(integer))
numero=0
lista = [2,4,6,8]
def rotacionar(lista, numero):
numero=int(input("Algum número positivo ou negativo :"))
if numero >= 0:
for i in range(numero):
ultimoNumero = lista.pop(-1)
lista.insert(0, ultimoNumero)
else:
for i in range(abs(numero)):
primeiroNumero = lista.pop(0)
lista.append(primeiroNumero)
return
rotacionar(lista, numero)
print (lista)
|
792a5e835c06afadcad8f0957227331042a61fd4 | nnguyen150468/newGitTest | /hangman2.py | 1,033 | 3.703125 | 4 | x=100
#declare variables
word='dog'
letter_left=list(word)
score_board=['_']*len(word)
stages=['','________ ','| | ','| O ','| | ','| /|\ ','| / \ ','| ']
wrong_guesses=0
win=False
#welcome
print('Welcome to Hang Man!')
print('It\'s a ',len(word),'-letter word:')
print(''.join(score_board))
#loop
while wrong_guesses<len(stages)-1:
guess=input('\nGuess a letter: ')
if guess in letter_left:
character_index=letter_left.index(guess)
score_board[character_index]=guess
letter_left[character_index]='*'
print(''.join(score_board))
else:
wrong_guesses+=1
if wrong_guesses+1==len(stages):
print('\n'.join(stages[0:wrong_guesses+1]))
print('You lost! The word is',word)
break
print('\nIncorrect!')
print(''.join(score_board))
print('\n'.join(stages[0:wrong_guesses+1]))
if '_' not in score_board:
print(''.join(score_board))
print('Congrats! The word is',word)
win=True
break
|
990c1a77124dff17c594ffcce78b9af9be483226 | sherbold/Python-Programmierkurs | /examples/sample_package/sqrt.py | 161 | 3.84375 | 4 | def my_sqrt(x):
"""Returns the square root of x"""
guess = 1
while(abs(guess*guess-x)>0.0001):
guess = (1/2)*(guess+x/guess)
return guess |
29bd5a30f30e9d05bd61a34967ee1eb92fad4731 | dallangoldblatt/befunge-interpreter | /interpreter.py | 8,112 | 3.578125 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
class Interpreter():
def __init__(self, lines, visualize):
self.visualize = visualize
# Set pointer bounds
self.rows = len(lines)
self.cols = len(max(lines, key=len))
# Covert program source into a two dimentional array of characters
# Right-pad each string to the appropriate number of columns
self.source = [[*line.ljust(self.cols)] for line in lines if len(line) > 0]
# Pointer move directions in order: North, East, South, West
self.move_directions = {0: [-1, 0], 1: [0, 1], 2: [1, 0], 3: [0, -1]}
self.directions = [0, 1, 2, 3]
# Set pointer initital values
self.pointer = [0, 0]
self.direction = 1
# Create program stack
self.stack = []
self.stringmode = False
self.done = False
def interpret(self):
while not self.done:
command = self.source[self.pointer[0]][self.pointer[1]]
if self.visualize:
self.print_source(command)
# Perform the command
self.interpret_command(command)
# Move the pointer
self.move_pointer()
def print_source(self, command):
print(f'Command: {command} Stack: {self.stack}')
for y, row in enumerate(self.source):
line = ''.join([str(c) for c in row])
if y == self.pointer[0]:
line = line[:self.pointer[1]] + '█' + line[self.pointer[1]+1:]
print(line)
# Pause for user input
_ = input()
def safe_pop(self):
# If the stack has run out of values, return 0
try:
return self.stack.pop(-1)
except IndexError:
return 0
def interpret_command(self, command):
# Perform the operation
if command == '"':
# Toggle stringmode
self.stringmode = not self.stringmode
elif self.stringmode:
# Push each character's ASCII value
self.stack.append(ord(command))
elif command == '+':
# Addition: Pop two values a and b, then push the result of a+b
self.stack.append(self.safe_pop() + self.safe_pop())
elif command == '-':
# Subtraction: Pop two values a and b, then push the result of b-a
a = self.safe_pop()
b = self.safe_pop()
self.stack.append(b - a)
elif command == '*':
# Multiplication: Pop two values a and b, then push the result of a*b
self.stack.append(self.safe_pop() * self.safe_pop())
elif command == '/':
# Integer division: Pop two values a and b, then push the result of b/a, rounded down.
# According to the specifications, if a is zero, ask the user what result they want.
a = self.safe_pop()
b = self.safe_pop()
if a == 0:
valid = False
while not valid:
try:
a = int(input('Division by zero - enter a denominator: '))
valid = True
except:
print('Invalid input')
self.stack.append(b // a)
elif command == '%':
# Modulo: Pop two values a and b, then push the remainder of the integer division of b/a.
a = self.safe_pop()
b = self.safe_pop()
self.stack.append(b % a)
elif command == '!':
# Logical NOT: Pop a value. If the value is zero, push 1; otherwise, push zero.
value = self.safe_pop()
if value == 0:
self.stack.append(1)
else:
self.stack.append(0)
elif command == '`':
# Greater than: Pop two values a and b, then push 1 if b>a, otherwise zero.
if self.safe_pop() < self.safe_pop():
self.stack.append(1)
else:
self.stack.append(0)
elif command == '>':
# PC direction right
self.direction = 1
elif command == '<':
# PC direction left
self.direction = 3
elif command == '>':
# PC direction right
self.direction = 1
elif command == '^':
# PC direction up
self.direction = 0
elif command == 'v':
# PC direction down
self.direction = 2
elif command == '?':
# Random PC direction
self.direction = random.choice(self.directions)
elif command == '_':
# Horizontal IF: pop a value; set direction to right if value=0, set to left otherwise
if self.safe_pop() == 0:
self.direction = 1
else:
self.direction = 3
elif command == '|':
# Vertical IF: pop a value; set direction to down if value=0, set to up otherwise
if self.safe_pop() == 0:
self.direction = 2
else:
self.direction = 0
elif command == ':':
# Duplicate top stack value
value = self.safe_pop()
self.stack.append(value)
self.stack.append(value)
elif command == '\\':
# Swap top stack values
value1 = self.safe_pop()
value2 = self.safe_pop()
self.stack.append(value1)
self.stack.append(value2)
elif command == '$':
# Pop (remove) top stack value and discard
self.safe_pop()
elif command == '.':
# Pop top of stack and output as integer
print(self.safe_pop(), end = '')
elif command == ',':
# Pop top of stack and output as ASCII character
print(chr(self.safe_pop()), end = '')
elif command == '#':
# Bridge: jump over next command in the current direction of the current PC
# This is handled by moving the pointer twice
self.move_pointer()
elif command == 'g':
# A "get" call (a way to retrieve data in storage).
# Pop two values y and x, then push the ASCII value of the character
# at that position in the program. If (x,y) is out of bounds, push 0
y = self.safe_pop()
x = self.safe_pop()
if x in range(0, self.cols) and y in range(0, self.rows):
self.stack.append(ord(str(self.source[y][x])))
else:
self.stack.append(0)
elif command == 'p':
# A "put" call (a way to store a value for later use).
# Pop three values y, x and v, then change the character at the
# position (x,y) in the program to the character with ASCII value v
y = self.safe_pop()
x = self.safe_pop()
v = self.safe_pop()
self.source[y][x] = chr(v)
elif command == '&':
# Get integer from user and push it
valid = False
while not valid:
try:
self.stack.append(int(input('Enter an integer: ')))
valid = True
except:
print('Invalid input')
elif command == '~':
# Get character from user and push it
valid = False
while not valid:
try:
self.stack.append(ord(input('Enter a character: ')))
valid = True
except:
print('Invalid input')
elif command == '@':
# End program
self.done = True
elif command.isdigit():
# Push corresponding number onto the stack
self.stack.append(int(command))
def move_pointer(self):
move = self.move_directions[self.direction]
y = (self.pointer[0] + move[0]) % self.rows
x = (self.pointer[1] + move[1]) % self.cols
self.pointer = [y, x]
|
9847616b6403b437507d2fc7c3414ca32b571b61 | nogicoder/sorting-algorithm | /test1.py | 729 | 3.84375 | 4 | import pyglet
a = [0, 1, -3, 6, 2, 10]
numbers = [[str(item) for item in a]]
def bubble_sort_algo(lst):
move = []
for t in range(len(lst)):
swap = False
for i in range(len(lst) - 1):
move.append(('n', lst[i], lst[i + 1]))
if lst[i + 1] < lst[i]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
swap = True
print(lst)
move.append(('y', lst[i], lst[i + 1]))
if swap == False:
break
return move
move = bubble_sort_algo(a)
# for lst in list:
# num_obj_list = []
# for number in lst:
# num_obj_list.append(number)
# numbers.append(num_obj_list)
for item in move:
print(item)
|
b297fbeb7560eae165bcb27592832253562d8f00 | AnnieJeez/Pythons | /class_cd.py | 215 | 3.515625 | 4 | class Potato():
def __init__(self):
self.name = "Jim Bob, Chubbbbby Donkey & Choompa"
def displayChubsters(self):
print(self.name)
print(self.name)
p1 = Potato()
p1.displayChubsters() |
2a1558cef42d9302cb114202c9eb2586aa4a46d3 | AnnieJeez/Pythons | /testing.py | 228 | 4.03125 | 4 | message = input("Enter message")
charCount=0
wordCount =1
for i in message:
charCount=charCount+1
print(i+str(charCount))
if(i==" "):
wordCount=wordCount+1
print("Word count" + str(wordCount))
|
395e1f0a23abb1d2e6bc2c08310d44f4171b438b | AnnieJeez/Pythons | /mode.py | 243 | 3.671875 | 4 | from collections import Counter
numbers = [1,2,3,4,5,6,7,8,4,5,6,7,8,6]
print(Counter(numbers))
z = Counter(numbers)
max = 0
for p in z:
if z[p]> max:
max = z[p]
for p in z:
if z[p]== max:
print(p)
|
69da6775487c8b27702302afdc60c7ceef53f148 | NoroffNIS/Code-2019-Week-5 | /16 - Documenting_Practical.py | 2,826 | 4.1875 | 4 | class Car:
def __init__(self):
self.type = ""
self.model = ""
self.wheels = 4
self.doors = 3
self.seets = 5
def print_model(self):
print("This car is a {model}: {type}, Wow!".format(model=self.model,type= self.type))
def print_space(self):
print("The car has {0} doors and {1} seets".format(self.doors, self.seets))
def __str__(self):
return """
This car is a {s.model}: {s.type}, Wow!
The car has {s.doors} doors and {s.seets} seets""".format(s=self)
class BMW(Car):
def __init__(self, **arg):
Car.__init__(self)
self.model = "BMW"
self.type = "{} Series".format(arg.get("type"))
self.doors = arg.get("doors")
self.fuel = arg.get("fuel")
class Mercedes(Car):
def __init__(self, **arg):
Car.__init__(self)
self.model = "Mercedes"
self.type = "{} Class".format(arg.get("type"))
self.doors = arg.get("doors")
self.fuel = arg.get("fuel")
class Fuel:
def __init__(self, **arg):
self.liters = arg.get("liters")
self.type = arg.get("type")
def __str__(self):
return """It uses {s.liters}L of {s.type}¢.""".format(s=self)
class CarFactory:
def __init__(self, **kwargs):
self.car = kwargs.get("type")(type=kwargs.get("car_type"),doors=kwargs.get("doors"),fuel=Fuel(liters=kwargs.get("liters"),type=kwargs.get("fuel_type")))
def get_car(self):
"""Returns a Mercedes"""
return self.car
class CarStore:
inventory = []
def __init__(self, **kwargs):
self._car_factory = CarFactory(type=kwargs.get("type"), car_type=kwargs.get("car_type"),doors=kwargs.get("doors"),liters=kwargs.get("liters"),fuel_type=kwargs.get("fuel_type"))
self.inventory.append(self._car_factory.get_car())
def show_car(self, car=None):
if not car:
car = self._car_factory.get_car()
print(car)
print(car.fuel)
def show_inventory(self):
for i in self.inventory:
self.show_car(i)
def __str__(self):
return "".join([str(i) for i in self.inventory])
store = CarStore(type=Mercedes, car_type= "E", doors=2, liters = 2,fuel_type = "Disel")
store2 = CarStore(type=Mercedes, car_type= "C", doors=4, liters = 2,fuel_type = "Disel")
store3 = CarStore(type=BMW, car_type="1", doors= 3, liters= 2.5, fuel_type = "Gasoline")
store.show_inventory()
print("\n","-"*100)
class Lada(Car):
def __init__(self, **arg):
Car.__init__(self)
self.model = "Lada"
self.type = "{}".format(arg.get("type"))
self.doors = arg.get("doors")
self.fuel = arg.get("fuel")
store = CarStore(type=Lada, car_type="VAZ-2107",doors=2,liters=1.2,fuel_type="Octane Gasoline")
store.show_inventory() |
bd42b81d7d008bab809a365e99c4d410876b453c | rocky-recon/mycode | /farm_challange.py | 704 | 4.5 | 4 | #!/usr/bin/env python3
# Old Macdonald had a farm. Farm.
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}]
# Write a for loop that returns all the animals from the NE Farm!
#for s in farms:
# print(farms[1])
yuck= ["carrots","celery", "apples", "bananas", "oranges"]
num= input("""
Choose a farm by number:
0. NE Farm
1. W Farm
2. SE Farm
>""")
for critters in farms[num].get("agriculture"):
if critters not in yuck:
print(critters)
|
b985436c5371ffcbd94fa1f53fde8d83b06b95f2 | rocky-recon/mycode | /projects/losdice.py | 660 | 3.5625 | 4 | #!/usr/bin/env python3
# always add shebang on top of page
# standard library first!
from random import randint
class Player:
def __init__(self):
self.dice = []
def roll(self):
# Clear current dice
self.dice = []
for i in range(6):
self.dice.append(randint(1,6))
def get_dice(self):
return self.dice
class Dependapotomus(Player):
def love(self, dependa: Player):
dependa.dice = [randint(1,3) for i in range(6)]
p1 = Player()
p2 = Dependapotomus()
p1.roll()
p2.roll()
print(p1.get_dice())
print(sum(p1.get_dice()))
p2.love(p1)
print(p1.get_dice())
print(sum(p1.get_dice()))
|
7806dc4a7767918fd48cecd05dfb0eb586da0ee9 | rocky-recon/mycode | /projects/hw2.py | 1,987 | 4.03125 | 4 | #!/usr/bin/env python3
# always add shebang on top of page
"""The puropose of this program is to display every NFL players data. By: Damian Mercado"""
# standard library first!
import random
#import os
#import shutil
import csv
# This will print every line in a csv file
#def print_csv(data):
# for row in data:
# print(', '.join(row))
# This will print a random row
#def print_random_row(data):
# nfl_data = data.read().split()
# nfl_player = random.choice(nfl_data)
# print(nfl_player)
# This will print a random column
def print_random_column(data):
csv_reader = csv.reader(data)
nfl_player_data = list(csv_reader)
random_question = random.choice(nfl_player_data)
print(random_question)
#nfl_data = data.read().split()
def print_random_player(data):
csv_reader = csv.reader(data)
random_nfl_player = list(csv_reader)
random_nfl_player_question = random.choice(random_nfl_player)
print(random_nfl_player_question)
""" User Story:
The purpose of this function is to pull a random college a nfl player went to.
When I'm viewing NFL spreadsheet ..."""
# open csv file that I want to loop across
with open("nflalltime.txt", "r") as nfl_file:
# The user will type in the function print_random_player
while True:
user_input = input('Enter a print_random_player to pull random nfl player information: ')
if user_input in locals() and callable(locals()[user_input]):
user_input = locals()[user_input]
break
else:
print("Invalid name, please try again...")
# print_random_player grabs csv.reader and random.choice in order to print a random row.
def print_random_player(data):
csv_reader = csv.reader(data)
random_nfl_player = list(csv_reader)
random_nfl_player_question = random.choice(random_nfl_player)
print(random_nfl_player_question)
"""I want to print a random row..."""
print_random_column(nfl_file)
|
6c3c75fc6f5c9dd7a74f02fb29c2a69975f2a541 | HelenaSILS/geo_computer | /tester.py | 823 | 4.03125 | 4 | class tester:
"""
tester class verifies the input
"""
def __init__(self):
pass
def test_string(self,address):
"""
Function to test if the type is a string
:param address: string
:return: assert
"""
t=type(address) == str
assert t, "not a string"
def test_alnum(self, address):
"""
Function to verify if all characters are alphanumeric
:param address: string
:return: assert
"""
t=address.replace(" ", "").isalnum()
assert t, "it only accept digits and letters"
def test_is_valid(self, address):
"""
Set of functions to verify the input.
:param address:
:return:
"""
self.test_string(address)
self.test_alnum(address) |
8e9b5073b1ee0d0c77522913d27bb22ecb237047 | ewinge2/WebApp | /CarlStats.py (stop updating this one?) | 5,806 | 3.734375 | 4 | #!/usr/bin/python
'''
File:webapp.py
Authors: Anne Grosse and Jialun "Julian" Luo
Last edited: 2013/10/10
This program will generate a html to the browser to display. It will print a summary or results
when user inputs are detected.
'''
import cgi
import DataSource
import cgitb
cgitb.enable()
class CarlStats:
'''
@summary: A class for generating a webpage specialized for our design. (Putting the content into a class
so that instance variables are easier to manage.
'''
def __init__(self):
'''
initiate the Strings
'openingHtml': contains <html> and the header info
'closingHtml': contains </body></html>
load the names of majors from a .txt file into a list (this is a stub)
'''
self.openingHtml = open('CarlStats.html').read()
self.content = ''
self.closingHtml = '''</body></html>'''
self.startYear = 2013
self.endYear = 2013
self.gender = "T"
self.isQueried = False
self.rowAltTemplate = '<tr class="alt">%s</tr>'
self.rowTemplate = '<tr>%s</tr>'
self.dataTemplate = '<td>%s</td>'
self.tableHeadingTemplate = '<th rowspan="%s">%s</th>'
self.tableTemplate = '<table class="resultTable" border="1" cellpadding="7">%s</table>'
self.rowColor = 0
self.tableHtml = ''
self.majorList = open('majorList.txt').read().splitlines()
self.majorInput = {}
self.initializeMajorInput()
self.genderList = ['Male', 'Female', 'Both']
self.debug = 0
def initializeMajorInput(self):
for major in self.majorList:
self.majorInput[major] = 0
def displayChosenGender(self):
self.showAsSelected(self.gender, "checked")
def displayChosenYears(self):
yearTag = ' selected="selected"'
self.showAsSelected(self.startYear, yearTag)
endYearIndex = self.openingHtml.find(str('endYear'))
self.showAsSelected(self.endYear, yearTag, endYearIndex)
def displayChosenMajors(self):
majorCheckTag = "checked"
for major in self.majorList:
if self.majorInput.get(major) == 1:
self.showAsSelected(major, majorCheckTag)
def showAsSelected(self, name, tag, indexToStartLooking=0):
index = self.findIndexForSelectionTag(name, indexToStartLooking)
self.insertSelectionTag(index, tag)
def findIndexForSelectionTag(self, name, indexToStartLooking=0):
nameQuotes = '\"' + str(name) + '\"'
return self.openingHtml.find(nameQuotes, indexToStartLooking) + len(nameQuotes)
def insertSelectionTag(self, index, tag):
self.openingHtml = self.openingHtml[:index] + tag + self.openingHtml[index:]
def getMajorInput(self, form):
for major in self.majorList:
'''
get user inputs in the checkboxes
'''
if major in form:
self.majorInput[major]= int(form[major].value)
self.isQueried = True
def getYearInput(self, form):
if 'startYear' in form and 'endYear' in form:
try: self.startYear = int(form['startYear'].value)
except Exception, e:
pass
try: self.endYear = int(form['endYear'].value)
except Exception, e:
pass
if self.endYear < self.startYear:
self.endYear = self.startYear
### if startYear or endYear isn't an int, assigns them default value of 2013
### there will still be an issue when using DataSource.py if startYear > endYear
def getGenderInput(self, form):
if "gender" in form:
if form["gender"].value == "M" or form["gender"].value == "F" or form['gender'].value == 'T':
self.gender = form["gender"].value
### if user messes with URL and gender isn't male or female, it's assigned default value of "both"
def getInput(self):
'''
Get user inputs from the python
'''
form = cgi.FieldStorage()
self.getYearInput(form)
self.getMajorInput(form)
self.getGenderInput(form)
def generateResult(self):
self.content = open('CarlStatsResult.html').read() % self.tableHtml
#also do other stuff...
def generateTableDataRow(self, majorName, listData):
'''
Add a row to the instance variable tableHtml
'''
row = self.dataTemplate % majorName
for elem in listData:
row = ''.join( [ row, self.dataTemplate % elem ] )
if (self.rowColor % 2):
row = self.rowTemplate % row
else:
row = self.rowAltTemplate % row
self.rowColor += 1
self.tableHtml = ''.join([self.tableHtml, row])
def generateTableYearRow(self):
'''
Generate the top row which depends on the year span
'''
row = self.tableHeadingTemplate % (1, 'YEAR')
for year in range(self.startYear, self.endYear + 1):
row = ''.join([row, self.tableHeadingTemplate % (2, year)])
row = self.rowTemplate % row
majorHeading = self.tableHeadingTemplate % (1, 'MAJOR')
row = ''.join([row, self.rowTemplate % majorHeading])
self.tableHtml = ''.join([self.tableHtml, row])
def generateTable(self):
self.tableHtml = self.tableTemplate % self.tableHtml
def queryData(self):
if self.isQueried:
database = DataSource.DataSource()
self.generateTableYearRow()
for major in self.majorList:
if self.majorInput[major] != 0:
'''
@todo: gender specification hasn't been implemented yet!!!
'''
majorName = major
majorData = database.getNumGraduateInYearSpan(self.startYear, self.endYear, majorName, self.gender)
self.generateTableDataRow(majorName, majorData)
self.generateTable()
self.generateResult()
def generate(self):
'''
Calling this to complete the html file
@todo: stubs!!!
'''
print "Content-type: text/html\r\r\n\n",
self.displayChosenYears()
self.displayChosenGender()
self.displayChosenMajors()
output = ''.join([self.openingHtml, self.content, self.closingHtml])
print output
if __name__ == "__main__":
site = CarlStats()
site.getInput()
site.queryData()
site.generate()
|
c758366a22e1ab6095ada44d366394395b6797bf | MieMieSheep/Learn-Python-By-Example | /python3/2 - 数据类型与变量/1.py | 1,684 | 4.375 | 4 | #encoding:utf-8
#!/user/bin/python
'''
前面两行#encoding:utf-8
#!/user/bin/python
的作用:
第一行:#encoding:utf-8
用于声明当前文件编码,防止程序乱码出现
第二行: #!/user/bin/python
用于声明python文件
养成良好编码习惯,敲代码时习惯添加这两行注释。
'''
'''
变量:仅仅使用字面意义上的常量很快就会引发烦恼——
我们需要一种既可以储存信息 又可以对它们进行操作的方法。
这是为什么要引入 变量 。
变量就是我们想要的东西——它们的值可以变化,
即你可以使用变量存储任何东西。变量只是你的计算机中存储信息的一部分内存。
与字面意义上的常量不同,你需要一些能够访问这些变量的方法,因此你给变量名字。
'''
#数据类型 int
num1 = 50 #这里的num1就是一个变量名 可以自己更换变量名
num2 = 60
#去除前面的注释即可 解除封印~~ 查看代码效果
#print('num1 = ',num1)
#print('num2 = ',num2)
#print(num1+num2)
#str类型的数据(字符类型)
name = "Jaydenchan"
str1 = "My name is "
#去除前面的注释即可 解除封印~~ 查看代码效果
#print(str1 + name) # 字符串中 可用 + 号作为连接符 可以理解为把两串字符串成一串
#布尔类型数据
'''
布尔类型数据可以理解为一个开关
True即为 开
False即为 关
详细的用法后面会解答
'''
a = True
b = False
#字典,列表,元组 我们会后面再讲
#现在,我们只介绍一些简单的数据类型
'''自己尝试修改程序,看看有没有什么新发现''' |
c66cf6ba9742afaabdc349c8d4631018d611ddf3 | krnorris65/python-exercises | /sets/cars.py | 1,408 | 4.0625 | 4 | # Create an empty set named showroom.
showroom = set()
# Add four of your favorite car model names to the set.
showroom.add('Honda')
showroom.add('Ford')
showroom.add('Dodge')
showroom.add('RAM')
# Print the length of your set.
print(len(showroom))
# Pick one of the items in your show room and add it to the set again.
showroom.add("Honda")
# Print your showroom. Notice how there's still only one instance of that model in there.
print(showroom)
# Using update(), add two more car models to your showroom with another set.
showroom.update({"Truck", "Car"})
# You've sold one of your cars. Remove it from the set with the discard() method.
showroom.discard("Car")
# Now create another set of cars in a variable junkyard. Someone who owns a junkyard full of old cars has approached you about buying the entire inventory. In the new set, add some different cars, but also add a few that are the same as in the showroom set.
junkyard = {"Honda", "Smart", "RAM", "BMW"}
# Use the intersection method to see which cars exist in both the showroom and that junkyard.
inBoth = showroom.intersection(junkyard)
# Now you're ready to buy the cars in the junkyard. Use the union method to combine the junkyard into your showroom.
buyCars = showroom.union(junkyard)
# Use the discard() method to remove any cars that you acquired from the junkyard that you do not want in your showroom.
buyCars.discard("BMW")
|
2d5360aca816845779d66f742760757ae60d4aef | krnorris65/python-exercises | /dictionaries/stocks.py | 1,089 | 3.578125 | 4 | stockDict = {
"GM": "General Motors",
"CAT":"Caterpillar",
"EK":"Eastman Kodak",
"GE": "General Electric"
}
purchases = [
( 'GE', 100, '10-sep-2001', 48 ),
( 'CAT', 100, '1-apr-1999', 24 ),
( 'GE', 200, '1-jul-1998', 56 )
]
for purchase in purchases:
stock_abrv = purchase[0]
stock_name = stockDict[stock_abrv]
cost = purchase[1] * purchase[3]
print(f"I purchased {stock_name} stock for ${cost}")
purchase_summary = dict()
for purchase in purchases:
stock_abrv = purchase[0]
if(stock_abrv in purchase_summary.keys()):
purchase_summary[stock_abrv].append(purchase)
else:
purchase_summary[stock_abrv] = [purchase]
for (key, value) in purchase_summary.items():
print()
print(f"----{key}----")
total_value = 0
for purchase in value:
shares = purchase[1]
amount = purchase[3]
date = purchase[2]
total_value += shares*amount
print(f"{shares} shares at {amount} dollars each on {date}")
print()
print(f"Total value of stock in portfolio: ${total_value}") |
f92fa5880c9022d5ef4b3a69f23c98681d62b5b5 | A284Philipi/1008_Salario_Python | /1008 - Salário.py | 178 | 3.65625 | 4 | numero = int(input())
horas = int(input())
salario = float(input())
salario = float(salario * horas)
print("NUMBER = {}".format(numero))
print("SALARY = U$ %.2f" %(salario)) |
a85ee24b796906873366ac5c0e57671d3eb067cd | tinysheepyang/python_scripts | /leetcode/字符串/9求解回文数.py | 481 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/13 23:27
# @Author : chenshiyang
# @Site :
# @File : 9求解回文数.py 判断一个数是否是回文数
# @Software: PyCharm
def isPalindrome(n):
if n < 0:
return False
sum = 0
origin = n
while n:
num = n % 10
sum = sum*10 + num
n /= 10
print(sum)
if sum == origin:
return True
else:
return False
print(isPalindrome(121)) |
bad2a831f59ceeabcc4c103259b183393ce2da0d | tinysheepyang/python_scripts | /leetcode/数组/121买卖股票最佳时机.py | 675 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/10/26 23:01
# @Author : chenshiyang
# @Site :
# @File : 121买卖股票最佳时机.py
# @Software: PyCharm
class Solution:
def maxProfit(self, prices):
if prices is None:
return 0
minPrices = prices[0]
maxProfit = 0
for index, value in enumerate(prices):
if prices[index] < minPrices:
minPrices = prices[index]
elif prices[index] - minPrices > maxProfit:
maxProfit = prices[index] -minPrices
return maxProfit
dataList = [7,1,5,3,6,4]
test = Solution()
print(test.maxProfit(dataList)) |
c9b7dc854359b2d3eaa583b90407006a3b956fb1 | tinysheepyang/python_scripts | /leetcode/树/04.04检查平衡性.py | 1,221 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/11 17:18
# @Author : chenshiyang
# @Site :
# @File : 04.04检查平衡性.py
# @Software: PyCharm
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.flag = True
def create(self, dataList):
root = TreeNode(dataList[0])
if len(dataList) >= 2:
root.left = self.create(dataList[1])
if len(dataList) >= 3:
root.right = self.create(dataList[2])
return root
def isBalanced(self, root:TreeNode) -> bool:
self.dfs(root)
return self.flag
def dfs(self, root):
if not root:return -1
l = self.dfs(root.left)
r = self.dfs(root.right)
print('l----------------------', l)
print('r----------------------', r)
print('abs---------', abs(l-r))
if abs(l-r) > 1:
self.flag = False
return max(l,r) + 1
if __name__ == "__main__":
dataList = [1,[2,[3, [4],[4]],[3]],[2]]
node = Solution()
tree = node.create(dataList)
print(node.isBalanced(tree)) |
9abd57de2effe8b69393b790a582ef1b3817c761 | tinysheepyang/python_scripts | /leetcode/数组/167两数之和2.py | 1,054 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/28 23:43
# @Author : chenshiyang
# @Site :
# @File : 167两数之和2.py
# @Software: PyCharm
def twoSum(nums, target):
"""
双指针实现
两数之和
"""
assert len(nums) >= 2
l, r = 0, len(nums)-1
while l < r:
if nums[l] + nums[r] == target:
return l+1, r+1
if nums[r] + nums[l] < target:
l += 1
else:
r -= 1
print('The input has no solution')
def twoSum1(nums, target):
"""
二分查找法
两数之和
"""
assert len(nums) >= 2
for i in nums:
second_num = target - nums[i]
l, r = 0, len(nums) -1
while l <= r:
mid = (l+r)//2
if nums[mid] == second_num:
return i+1, mid+1
if nums[mid] < second_num:
l = mid +1
else:
r = mid -1
print('The input has no solution')
numbers = [2,7,8,12,15,19,21]
print(twoSum1(numbers, 27)) |
1e3d0b63fc565980a5625233263241cfd31b8847 | coblax/Python-Exploit | /reverse_convert_to_utf-8.py | 102 | 3.546875 | 4 | #!/usr/bin/python
with open ('reversed.txt') as text_reversed:
print(text_reversed.read()[::-1])
|
1913960882c3ca12dbdbe23ff406b8ca14b919dc | zxq8132/learning | /iteration/moudule_01.py | 1,256 | 3.578125 | 4 | #by zxq
# 模块的分类:
# 一、标准库
# 1、时间模块
# time和datetime
# a、格式化表示的时间
# '2017-10-26-16:48:01'
# b、时间戳
# 本质就是秒数
# 从1970年01月01日0分0时0秒开始到当前的秒数
# ex1:
# import time
# x=time.time()#单位是秒
# print(x/3600/24/365)#1970+47=2017
# #c、 元组的表示方式
# print(time.localtime())
# print(time.timezone/3600)#和utc时间的差值
# print(help(time.gmtime()))
# y=time.localtime()
# print(time.mktime(y))#将元组表达方式的时间转换为时间戳
# print(time.strftime("%Y-%m-%d %H:%M:%S ",y))#格式化输出
# print(time.strftime("%Y-%m-%d %H:%M:%S ",time.localtime()))#定义格式就行,和位置无关
# print(time.asctime())#英文格式输出,如果没有传值,则默认本地时间信息
# print(time.ctime())#传入的是秒,和asctime接受的元组,ctime接受的是时间戳
import datetime#它是对time的高度封装
print(datetime.datetime.now())#获取当前时间
print(datetime.datetime.now()+datetime.timedelta(-3))#timedelta不能单独使用,要和now一起结合用
print(datetime.datetime.now()+datetime.timedelta(hours=-12))#timedelta不能单独使用,12小时前
# 二、开源模块
# 三、自定义模块 |
762006b4118526ee432aa561f348f2b444e1b7a4 | zxq8132/learning | /iteration/generator.py | 547 | 3.8125 | 4 | #by zxq
#斐波拉契数列的实现,用函数实现
# def fib(max):
# n,a,b=0,0,1
# while n<max:
# print(b)
# a,b=b,a+b
# n=n+1
# return 'end'
# fib(10)
#斐波拉契数列的生成器,关键字是yield
#函数值能连续输出,就可以用生成器的方式定义?
def fib(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,a+b
n=n+1
return 'end'
a=fib(10)
print(a.__next__())
print("--------")
print(a.__next__())
print("--------")
print(a.__next__())
print("--------")
|
14e68af4c1a647adfbec43a817d0118aee73055a | zxq8132/learning | /function_operation/fun_recursion.py | 326 | 3.5625 | 4 | #by zxq
#函数内部调用函数本身叫递归(recursion)
# python最多内部调用997次数
#1、必须有一个明确结束条件
#2、递归效率不高
#3、每次递归,问题规模要比上次递归有所减少
def calc(i):
print(i)
if int(i/2)>0:
return calc(i/2)
print("--->>",i)
calc(5)
|
a658fec2fdfc867fb137a756a100cee78d5fa69e | WangXu1997s/store | /小跳蛙.py | 264 | 3.75 | 4 | a=20
b=0
num=0
while True :
if b<a:
b+=3
num+=1
if b<a:
b-=2
else:
print("第",num,'天能跳出来')
break
else:
print("第", num, '天能跳出来')
break
|
db852fa295bed837efa39df3ca81e77006f7c894 | WangXu1997s/store | /统计列表中每个数出现的次数.py | 196 | 3.671875 | 4 |
List = [1,4,7,5,8,2,1,3,4,5,9,7,6,1,10]
setL = set(List)
#print(setL.pop())
for i in range(len(setL)):
view = setL.pop()
print("{0}出现了{1}次。".format(view,List.count(view))) |
eda075a19350e70fd5bc3c2e04c87ff998993948 | tt-n-walters/saturday-python | /first-class-example-2.py | 269 | 3.703125 | 4 |
def add(amount):
def func(value):
return value + amount
return func
adds_5 = add(5)
adds_10 = add(10)
adds_1000 = add(1000)
print(adds_5(60))
print(adds_5(15))
print(adds_5(995))
print(adds_1000(60))
print(adds_1000(15))
print(adds_1000(995)) |
89cc6b02e44f2c8c22cb68601e93de4facc18fd8 | tt-n-walters/saturday-python | /data-model-example.py | 805 | 4.03125 | 4 |
class Polynomial:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __repr__(self):
return "Polynomial({}x^2 + {}x + {})".format(self.a, self.b, self.c)
def __add__(self, other):
return Polynomial(self.a + other.a, self.b + other.b, self.c + other.c)
def __len__(self):
return 2 if self.a > 0 else 1 if self.b > 0 else 0
def __getitem__(self, name):
if name == 0:
return self.c
if name == 1:
return self.b
if name == 2:
return self.a
poly1 = Polynomial(1, 5, 9) # x^2 + 5x + 9
poly2 = Polynomial(2, 4, 0) # 2x^2 + 4x
print(poly1[2])
print(poly2[1])
poly3 = poly1 + poly2
print(poly3)
poly4 = Polynomial(0, 2, 3)
print(len(poly4))
|
6dce087cb7a81d81dfb4bec0f50bc8e10413cf44 | amitdivekar30/Clustering_by_python | /Hierarchial_Clustering_CrimeData.py | 2,078 | 3.578125 | 4 | #Hierarchail Clustering
#Perform Clustering for the crime data and identify the number of clusters formed and draw inferences.
#
#Data Description:
#Murder -- Muder rates in different places of United States
#Assualt- Assualt rate in different places of United States
#UrbanPop - urban population in different places of United States
#Rape - Rape rate in different places of United States
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
crime_data = pd.read_csv('crime_data.csv')
#Normalization Function
def norm_func(i):
x = (i-i.mean())/(i.std())
return (x)
# Normalized data frame (considering the numerical part of data)
df_norm = norm_func(crime_data.iloc[:,1:])
from scipy.cluster.hierarchy import linkage
import scipy.cluster.hierarchy as sch # for creating dendrogram
type(df_norm)
#p = np.array(df_norm) # converting into numpy array format
help(linkage)
z = linkage(df_norm, method="complete",metric="euclidean")
plt.figure(figsize=(15, 5));plt.title('Hierarchical Clustering Dendrogram');plt.xlabel('Index');plt.ylabel('Distance')
sch.dendrogram(
z,
leaf_rotation=0., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
plt.show()
# Now applying AgglomerativeClustering choosing 3 as clusters from the dendrogram
from sklearn.cluster import AgglomerativeClustering
h_complete = AgglomerativeClustering(n_clusters=4, linkage='complete',affinity = "euclidean").fit(df_norm)
cluster_labels=pd.Series(h_complete.labels_)
crime_data['clust']=cluster_labels # creating a new column and assigning it to new column
crime_data = crime_data.iloc[:,[5,0,1,2,3,4]]
crime_data.head()
# getting aggregate mean of each cluster
crime_data.iloc[:,2:].groupby(crime_data.clust).mean()
crime_data.columns
crime_data.columns = ['clust', 'State', 'Murder', 'Assault', 'UrbanPop', 'Rape']
# creating a csv file
crime_data.to_csv("CrimeData_hClust.csv",encoding="utf-8")
|
7dae7b15c23415aa639d273a19152762da9a0f5c | ua-ants/webacad_python | /lesson02_old/hw/script7.py | 550 | 3.796875 | 4 | import random as r
# generate array:
arr=[]
n = r.randint(2, 20)
while(n):
arr.append(r.randint(100, 999))
n -= 1
print(arr)
# task 7. Дан список из целых чисел длинной в три числа. Вернуть
# список отсортированный в обратном порядке, не используя метод .reverse()
def reverse_array(arr):
i = 1
res = []
while(i <= arr.__len__()):
res.append(arr[arr.__len__() - i])
i += 1
return res
print(reverse_array(arr)) |
db6b22e0d6c051b508dbdff4cab4babcbd867c6e | ua-ants/webacad_python | /lesson01_old/hw/script3.py | 485 | 4.15625 | 4 | while True:
print('To quit program enter "q"')
val1 = input('Enter a first number: ')
if val1 == 'q':
break
val2 = input('Enter a second number: ')
if val2 == 'q':
break
try:
val1 = int(val1)
val2 = int(val2)
except ValueError:
print('one of entered value is not integer')
continue
if val1 > val2:
print(val1-val2)
elif val1 < val2:
print(val1+val2)
else:
print(val1)
|
265a3d593c820ebc354bcd04b15da5489ba51f6d | ua-ants/webacad_python | /lesson02_old/hw/script3.py | 336 | 4.3125 | 4 | # given array:
arr = [1, 3, 'a', 5, 5, 3, 'a', 5, 3, 'str01', 6, 3, 'str01', 1]
# task 3. Удалить в массиве первый и последний элементы.
def remove_last_and_first(arr):
del arr[0]
del arr[-1]
return arr
print("Array before: ", arr)
print("Array after: ", remove_last_and_first(arr)) |
6af244e2bbc7d8935d7cc4abbdee85481d61f5c9 | yoonjeewoo/DataScience | /matrix.py | 669 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 27 16:24:54 2016
@author: JEEWOOYOON
"""
A = [[1, 2, 3],
[4, 5, 6]]
B = [[1, 2],
[3, 4],
[5, 6]]
def shape(A):
num_rows = len(A)
num_cols = len(A[0]) if A else 0
return num_rows, num_cols
def get_row(A, i):
return A[i]
def get_col(A, j):
return [A_i[j] for A_i in A]
def make_matrix(num_rows, num_cols, entry_fn):
return [[entry_fn(i, j)
for j in range(num_cols)]
for i in range(num_rows)]
def is_diagonal(i, j):
return 1 if i==j else 0
identity_matrix = make_matrix(5, 5, is_diagonal)
for mat in identity_matrix :
print mat , "\n" |
12794f17cffae439d9b0f9faaac24cca73be2857 | wescleytorres/Python-Introducao | /Introducao/Func01.py | 658 | 3.625 | 4 | from time import sleep
def lin():
print('-=' * 20)
def contador(i, f, p):
if p < 0:
p *= -1
if p == 0:
p = 1
print(f'Contagem de {i} até {f} de {p} em {p}')
sleep(2.5)
if i < f:
cont = i
while cont <= f:
print(cont, end=' ')
sleep(0.4)
cont += p
print('FIM!')
else:
cont = i
while cont >= f:
print(cont, end=' ')
sleep(0.4)
cont -= p
print('FIM!')
contador(1, 10, 1)
lin()
contador(10, 0, 2)
lin()
contador(i=int(input('Inicio: ')), f=int(input('Fim: ')), p=int(input('Passo: ')))
lin()
|
3a26d1912702f2074d97e3ea8f7610d7ba367c6e | wescleytorres/Python-Introducao | /Introducao/DicCadast94.py | 1,071 | 3.71875 | 4 | dados = dict()
lista = list()
somaidade = 0
while True:
dados['nome'] = input('Nome: ')
while True:
dados['sexo'] = str(input('Sexo [M/F]: ')).upper()
if dados['sexo'] == 'M' or dados['sexo'] == 'F':
break
print('Erro. favor informar M ou F.')
dados['idade'] = int(input('Idade: '))
somaidade += dados['idade']
lista.append(dados.copy())
print('-=' * 30)
while True:
r = input('Deseja continuar? [S/N]: ').upper()
if r in 'NS':
break
print('Erro. Por favor digite S ou N.')
if r in 'N':
break
m = (somaidade/len(lista))
print('-='*30)
print(f'- {len(lista)} Pessoas foram cadastradas!')
print(f'- A média de idade do grupo foi de {m:.0f} anos.')
print('- Mulheres no grupo: ', end='')
for v in lista:
if v['sexo'] in 'F':
print(v['nome'], end='. ')
print()
print(f'- Pessoas com idade acima da média {m:.0f}: ')
for c in lista:
if c['idade'] > m:
for k, v in c.items():
print(f'{k} = {v};', end=' ')
print()
|
c6086e5149ac1602aa1c7f79d190e7975671532f | sujonict07/Python | /decorator/decorating_functions_with_arguments.py | 317 | 3.734375 | 4 | from decorator.decorators import do_twice
"""
Returning Values From Decorated Functions
"""
@do_twice
def greet(name):
print(f"Hello {name}")
print(greet("sujon"))
@do_twice
def return_greating(name):
print("Creating greading")
return f"Hi {name}"
hi_emon = return_greating("Emon")
print(hi_emon) |
5f638c2f50487b667f8e4847f98f51626df9acbd | sujonict07/Python | /decorator/inner_functions.py | 541 | 3.984375 | 4 | """
It’s possible to define functions inside other functions.
Such functions are called inner functions
"""
def parent():
print("printing from the parent() function")
def first_child():
print("printing from the first_child() function")
def second_child():
print("printing from the second_child() function")
second_child()
first_child()
a = parent()
print(a)
"""
output :
printing from the parent() function
printing from the second_child() function
printing from the first_child() function
""" |
7917204479189e2db870651438617faaa40b610d | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex072.py | 1,165 | 4.0625 | 4 | # Ex: 072 - Crie um programa que tenha uma tupla totalmente preenchida com uma
# contagem por extenso, de zero até vinte.
# Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por
# extenso.
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 072
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
contagem = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete',
'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze',
'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
continuar = 'S'
while continuar == 'S':
while True:
num = int(input('Digite um número entre 0 e 20: '))
if 0 <= num <= 20:
break
print('Tente Novamente.')
print(f'Você digitou o número -{contagem[num]}-.\n')
while True:
continuar = str(input('Deseja Continuar? [S/N] ')).upper().strip()[0]
if continuar in 'SN':
print('')
break
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
3bcdcbc338e89c239b62ee743e13ccc0c27a640b | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex002.py | 340 | 3.984375 | 4 | print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 002
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
nome = input('Digite seu Nome: ')
print(f'Seja bem vindo {nome}!')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
23b0bf7288672ad81c27e25daec3a6afe4ca707f | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex096.py | 654 | 4.25 | 4 | # Ex: 096 - Faça um programa que tenha uma função chamada área(), que receba
# as dimensões de um terreno retangular(largura e comprimento) e mostre a
# área do terreno.
def area(a, b):
print("\n--Dados finais:")
print(f"Área de um terreno {a}x{b} é de {a * b}m².")
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 096
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
print("--Preencha:")
l = float(input("Largura (m): "))
c = float(input("Comprimento (m): "))
area(l, c)
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
b3a51cbf148e888c3b6671002af0076741cc768e | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex027.py | 655 | 4.03125 | 4 | # Ex: 027 - Faça um programa que leia o nome completo de uma pessoa mostrando em
# seguida o primeiro e o último nome separadamente.
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 027
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
n = input('Digite seu nome completo: ').split()
print('Prazer em te conhecer!')
print(f'Seu primeiro nome é {n[0]}')
print(f'Seu último nome é {n[len(n) - 1]}')
# O 'len' começa a contagem no 1, por isso o '-1' (tabela começa pelo 0)
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
fff59cf15424d077cdecd2f1212e40ca1f6ec1c0 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex005.py | 426 | 4 | 4 | print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 005
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
n = int(input('Digite um Número: '))
print(f'\nAnalisando o valor {n} \n'
f'\nSeu sucessor é: {n + 1} '
f'\nSeu antecessor é: {n - 1}')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
f6be53d05eb1b961a31026c54fb7e7098f0835c5 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex044.py | 2,749 | 3.890625 | 4 | # Ex: 044 - Elaborar um programa que calcule o valor a ser pago por um
# produto, considerando o seu preço normal e condeção de pagamento:
# À vista dinheiro/cheque - 10% de desconto; À vista no cartão - 5% de
# desconto; Em até 2x no cartão - preço normal; 3x ou mais no cartão -
# 20% de juros.
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 044
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
print('--Valor Final da Mercadoria\n'
'--Preencha os Dados')
valor_produto = float(input('Valor do Produto: R$'))
print('''\nFormas de Pagamento:
[ 1 ] À vista (dinheiro/cheque) = 10% de desconto
[ 2 ] À vista (cartão) = 5% de desconto
[ 3 ] Em até 2x no cartão = Preço normal
[ 4 ] 3x ou mais no cartão = 20% de juros''')
condicao_pagamento = int(input('Digite a opção: '))
print('')
if condicao_pagamento > 4:
print('Condição Inválida. Tente Novamente.')
else:
if condicao_pagamento == 1:
desconto = valor_produto * 10 / 100
valor_final = valor_produto - desconto
print(f'--Dados Finais\n'
f'Preço Inicial: R${valor_produto}\n'
f'Desconto: R${desconto:.2f}\n'
f'Preço Final: R${valor_final:.2f}')
elif condicao_pagamento == 2:
desconto = valor_produto * 5 / 100
valor_final = valor_produto - desconto
print(f'--Dados Finais\n'
f'Preço Inicial: R${valor_produto}\n'
f'Desconto: R${desconto:.2f}\n'
f'Preço Final: R${valor_final:.2f}')
elif condicao_pagamento == 3:
desconto = 0
valor_final = valor_produto
preco_parcelado = valor_final / 2
print(f'--Dados Finais\n'
f'Preço Inicial: R${valor_produto}\n'
f'Desconto: Sem Desconto\n'
f'Preço das Parcelas: R${preco_parcelado:.2f} (2x)\n'
f'Preço Final: R${valor_final:.2f}')
else:
parcelas = int(input('Quantidade de parcelas: '))
juros = valor_produto * 20 / 100
valor_final = valor_produto + juros
preco_parcelado = valor_final / parcelas
print(f'--Dados Finais\n'
f'Preço Inicial: R${valor_produto}\n'
f'Total de Juros: R${juros:.2f}\n'
f'Preço das Parcelas: R${preco_parcelado:.2f} ({parcelas}x)\n'
f'Preço Final: R${valor_final:.2f}')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
762da45f442ce9137535d13f7d776e59f6bfbebe | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex108/ex108.py | 765 | 4.0625 | 4 | # Ex: 108 - Adapte o código do desafio 107, criando uma função adicional
# chamada moeda() que consiga mostrar os valores como um valor monetário
# formatado.
import moeda as m
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 108
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
m.escreva("Análise de preço")
preco = float(input("Digite o preço: R$"))
print(f"""\n--Análise final
Metade de {m.moeda(preco)}: {m.moeda(m.metade(preco))}
Dobro de {m.moeda(preco)}: {m.moeda(m.dobro(preco))}
Aumentado em 15%: {m.moeda(m.aumentar(preco, 15))}
Diminuido em 12%: {m.moeda(m.diminuir(preco, 12))}""")
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
20c58b946dbd60868c57fc25f42b53898a0cd8f0 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex057.py | 761 | 3.96875 | 4 | # Ex: 057 - Faça um programa que leia o sexo de uma pessoa, mas só aceite os
# valores 'M' ou 'F'. Caso esteja errado, peça a digitação novamente até ter
# um valor correto.
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 057
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
print('--Verificador de Sexo\n'
'--Preencha os Dados')
sexo = str(input('Sexo [M/F]: ')).upper().strip()[0]
while sexo not in 'MF':
print('Sexo Inválido. Digite novamente...')
sexo = str(input('Sexo [M/F]: ')).upper().strip()[0]
print(f'\nSexo {sexo} registrado com sucesso!')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
aed12fae37f7d357e59bd77f622ee3d8397dafbb | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex015.py | 528 | 3.828125 | 4 | print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 015
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
d = int(input('Quantidade de Dias alugado: '))
km = float(input('Quantidade de Km percorridos: '))
precod = d * 60
precokm = km * 0.15
print('-' * 5, 'Preços', '-' * 5, f'\nDia: R${precod:.2f} \nKm: R${precokm:.2f} \nTotal: R${precod + precokm:.2f}')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
34033ea6ed96aad27da2eaa7e407b52f81ad1759 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex109/ex109.py | 825 | 4.0625 | 4 | # Ex: 109 - Modifique as funções que foram criadas no desafio 107 para que
# elas aceitem um parãmetro a mais, informando se o valor retornado por elas
# vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108.
import moeda as m
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 109
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
m.escreva("Análise de preço")
preco = float(input("Digite o preço: R$"))
print(f"""\n--Análise final
Metade de {m.moeda(preco)}: {m.metade(preco, True)}
Dobro de {m.moeda(preco)}: {m.dobro(preco, True)}
Aumentado em 15%: {m.aumentar(preco, 15, True)}
Diminuido em 12%: {m.diminuir(preco, 12, True)}""")
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
0d3ed7021b6e129475af59523ffb2b4bb71a6af2 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex085.py | 767 | 4.0625 | 4 | # Ex: 085 - Crie um programa onde o usuário possa digitar sete valores numéricos e
# cadastre-os em uma lista única que mantenha separados os valores pares e ímpares.
# No final, mostre os valores pares e ímpares em ordem crescente.
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 085
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
nums = [[], []]
for cont in range(1, 8):
num = int(input(f"Digite o {cont}º número: "))
nums[0].append(num) if num % 2 == 0 else nums[1].append(num)
print(f'''\n--Dados finais
Números pares: {sorted(nums[0])}
Números ímpares: {sorted(nums[1])}''')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
18a98ca174b9c50a8d1d3a2bf84cabe8e968c39a | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex045.py | 1,738 | 3.96875 | 4 | # Ex: 045 - Crie um programa que faça o computador jogar JOKENPÔ com você.
from random import randint
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 045
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
print('--Jogo: Pedra, Papel ou tesoura')
print('''--Você acha que consegue ganhar de mim?!! Tente!!
[ 1 ] Para Pedra
[ 2 ] Para Papel
[ 3 ] Para Tesoura''')
opcao = int(input('Qual você irá escolher? '))
print('')
if opcao > 3:
print('Opção Inválida. Tente Novamente')
else:
lista = ('Pedra', 'Papel', 'Tesoura')
sorteado = randint(0, 2)
if sorteado == 0:
if opcao == 2:
print(f'Droga!! Você ganhou, eu tinha escolhido {lista[sorteado]}')
elif opcao == 1:
print(f'Droga, empatamos, eu tinha escolhido {lista[sorteado]}')
else:
print(f'Eba!! Ganhei, eu tinha escolhido{lista[sorteado]}')
elif sorteado == 1:
if opcao == 3:
print(f'Droga!! Você ganhou, eu tinha escolhido {lista[sorteado]}')
elif opcao == 2:
print(f'Droga, empatamos, eu tinha escolhido {lista[sorteado]}')
else:
print(f'Eba!! Ganhei, eu tinha escolhido{lista[sorteado]}')
else:
if opcao == 1:
print(f'Droga!! Você ganhou, eu tinha escolhido {lista[sorteado]}')
elif opcao == 3:
print(f'Droga, empatamos, eu tinha escolhido {lista[sorteado]}')
else:
print(f'Eba!! Ganhei, eu tinha escolhido {lista[sorteado]}')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
0b164f76b93c57eb2e187d1a664cbfe463c58ae1 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex112/ex112.py | 677 | 3.546875 | 4 | # Ex: 112 - Dentro do pacote utilidadesCeV que criamos no desafio 111,
# temos um módulo chamado dado. Crie uma função chamada leiaDinheiro()
# que seja capaz de funcionar como uma validação de dados para aceitar
# apenas valores que sejam monetários.
from utilidadescev import moeda, dados
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 112
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
moeda.escreva("Análise de preço")
preco = dados.leiaDinheiro("Digite o preço: R$")
moeda.resumo(preco, 10, 10)
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
7640d24a194f8c478d40869a1b13a2d84422c0b2 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex110/ex110.py | 579 | 4.0625 | 4 | # Ex: 110 - Adicione ao módulo moeda.py criado nos desafios anteriores, uma
# função chamada resumo(), que mostre na tela algumas informações que já
# temos no módulo criado até aqui.
import moeda
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 110
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
moeda.escreva("Análise de preço")
preco = float(input("Digite o preço: R$"))
moeda.resumo(preco, 80, 10)
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
1814f6fbdbf5a3c28a73efa51323d42a0a3e2fe9 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex095.py | 2,045 | 4.1875 | 4 | # Ex: 095 - Aprimore o DESAFIO 093 para que ele funcione com vários jogadores,
# incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador.
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 095
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
jogadores = list()
resp = 's'
while resp == 's':
jogador = dict()
print("--Preencha o formulário abaixo: ")
jogador['Nome'] = input("Nome: ").title().strip()
jogador['Partidas'] = int(input("Partidas jogadas: "))
if jogador['Partidas'] > 0:
gols = list()
total_gols = 0
for partida in range(0, jogador['Partidas']):
x = int(input(f"Gols na {partida + 1}ª partida: "))
gols.append(x)
total_gols += x
jogador['Gols'] = gols
jogador['Total_Gols'] = total_gols
jogadores.append(jogador)
del(jogador)
while True:
resp = input("\nDeseja adicionar mais um jogador? [S/N] ").lower()
if resp == 's' or resp == 'n':
print()
break
print("--Valor Inválido")
print(f"--Dados finais \n {'n°':<5}{'Nome':<10}{'Partidas':<10}{'Gols':<10}{'Total':<10}")
for num, v in enumerate(jogadores):
print(f" {num:<5}{v['Nome']:<10}{v['Partidas']:<10}{str(v['Gols']):<10}{v['Total_Gols']:<10}")
while True:
resp = int(input("\nMostrar algum jogador? [999 para sair] "))
if resp == 999:
break
if resp not in range(0, len(jogadores)):
print("--Valor Inválido")
else:
print(f"\n--O jogador {jogadores[resp]['Nome']} jogou {jogadores[resp]['Partidas']} partidas.\n")
print(''.join(f'=> Na {cont+1}° partida, fez {gols} gols.\n' for cont, gols in enumerate(jogadores[resp]['Gols'])))
print(f"--Dando um total de {jogadores[resp]['Total_Gols']} gols.")
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
f4b83fb8b66baabe97524968fa0dabf401a98b33 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex068.py | 1,320 | 4 | 4 | # Ex: 068 - Faça um programa que jogue par ou ímpar com o computador. O jogo só
# será interrompido quando o jogador PERDER, mostrando o total de vitórias
# consecutivas que ele conquistou no final do jogo.
from random import randint
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 068
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
vitoria = 0
tipo = ' '
while True:
while tipo not in 'PI':
tipo = str(input('Par ou Ímpar? [P/I] ')).upper().strip()[0]
jogador = int(input('Digite um valor: '))
computador = randint(0, 10)
soma = computador + jogador
if tipo == 'P' and soma % 2 == 0:
vitoria += 1
resultado = 'PAR'
print(f'O computador jogou {computador} e você {jogador}. Total de {soma} deu {resultado}.')
print(f'Você Venceu!!')
elif tipo == 'I' and soma % 2 != 0:
vitoria += 1
resultado = 'ÍMPAR'
print(f'O computador jogou {computador} e você {jogador}. Total de {soma} deu {resultado}.')
print(f'Você Venceu!!')
else:
print(f'GAME OVER! Você venceu {vitoria} vezes.')
break
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado pelo uso!
--Desenvolvido por Thalles Torres
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
|
927c3152f1b8d4cbc0e9a0ce8ef753cd8d80d1cd | sangarfield/WebScrapingWithPython | /Chapter9/139_SubmitForm.py | 258 | 3.609375 | 4 | '''
填写一个提交表单
http://pythonscraping.com/pages/files/form.html
'''
import requests
url = 'http://pythonscraping.com/files/processing.php'
params = {'firstname' : 'Kevin', 'lastname' : 'Liu'}
r = requests.post(url, params)
print(r.text) |
940ee3ad025a05f9a10a2330c81ddbc22c353813 | milknsoda/start_camp | /day4/day4-1.py | 4,070 | 3.71875 | 4 | """
Python dictionary 연습 문제
"""
# 1. 평균을 구하시오.
score = {
'수학': 80,
'국어': 90,
'음악': 100
}
# 아래에 코드를 작성해 주세요.
print('==== Q1 ====')
sume = 0
for s in score.values():
sume = sume + s
average = sume / len(score)
print(f'평균: {average}')
# 풀이 : 반복문
result = 0
count = 0
for score_value in score.values():
# result = result + score_value
# count = count + 1
result += score_value
count += 1
# 풀이 : sum 함수 활용하기
result = sum(score.values())
count = len(score)
print(result / len(score))
# 2. 반 평균을 구하시오. -> 전체 평균
scores = {
'a': {
'수학': 80,
'국어': 90,
'음악': 100
},
'b': {
'수학': 80,
'국어': 90,
'음악': 100
}
}
# 아래에 코드를 작성해 주세요.
print('==== Q2 ====')
result = 0
for key in scores:
sumee = 0
for score in scores[key]:
sumee = sumee + scores[key][score]
sumee = sumee / len(scores[key])
print(f'{key}의 평균 : {sumee:.1f}')
result = result + sumee
print(f'전체평균 : {result / len(scores):.1f}')
# 풀이
total_score = 0
count = 0
for per_scores in scores.values():
for per_score in per_scores.values():
total_score += per_score
count += 1
print(total_score / count)
# 3. 도시별 최근 3일의 온도입니다.
city = {
'서울': [-6, -10, 5],
'대전': [-3, -5, 2],
'광주': [0, -2, 10],
'부산': [2, -2, 9],
}
# 3-1. 도시별 최근 3일의 온도 평균은?
# 아래에 코드를 작성해 주세요.
print('==== Q3-1 ====')
"""
출력 예시)
서울 : 값
대전 : 값
광주 : 값
부산 : 값
"""
for ct in city:
av = 0
for tem in city[ct]:
av += tem
print(f'{ct} : {av/3:.2f}')
# 풀이
for name, temp in city.items():
avg = sum(temp)/len(temp)
print(f'{name} : {avg:.2f}') # f-string : 3.6+
print('{0} : {1:.2f}'.format(name, avg)) # format-string
print(name,':',avg)
# 3-2. 도시 중에 최근 3일 중에 가장 추웠던 곳, 가장 더웠던 곳은?
# 아래에 코드를 작성해 주세요.
print('==== Q3-2 ====')
# tem_max = []
# tem_min = []
# for ct in city:
# tem_tot = []
# for tem in city[ct]:
# tem_tot.append(tem)
# tem_max.append((ct, max(tem_tot)))
# tem_min.append((ct, min(tem_tot)))
# print(tem_max, tem_min)
# max_temp = []
# min_temp = []
# for i in tem_max:
# max_temp.append(i[1])
# for i in tem_min:
# min_temp.append(i[1])
# result_x = max(max_temp)
# result_n = min(min_temp)
tem_max = []
tem_min = []
for i in city:
tem_max.append(max(city[i]))
tem_min.append(min(city[i]))
print('3일 중에 가장 더웠던 곳 : ', end='')
for i in city:
if max(tem_max) in city[i]:
print(i, end=' ')
print('3일 중에 가장 추웠던 곳 : ', end='')
for i in city:
if min(tem_min) in city[i]:
print(i, end=' ')
# 풀이
min_temp = 0
max_temp = 0
min_city = ''
max_city = ''
count = 0
# 모든 지역의 온도를 모두 확인하면서,
for name, temp in city.items():
# 첫번째 반복때는 모두 다 저장해!
if count == 0:
min_city = name
max_city = name
min_temp = min(temp)
max_temp = max(temp)
count += 1
# 가장 추우면, 해당 도시와 기온을 기록
if min(temp) < min_temp:
min_city = name
min_temp = min(temp)
# 더울 때도, 해당 도시와 기온을 기록
if max(temp) > max_temp:
max_city = name
max_temp = max(temp)
print(f'추운 곳은 {min_city}, 더운 곳은 {max_city}')
# 3-3. 위에서 서울은 영상 2도였던 적이 있나요?
# 아래에 코드를 작성해 주세요.
print('==== Q3-3 ====')
for ct in city:
if ct == '서울':
if 2 in city[ct]:
print('서울은 2도였던 적이 있다.')
else:
print('서울은 2도였던 적이 없다.')
# 풀이
if 2 in city['서울']:
print('네')
else:
print('아니오')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.