blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4cc114a55d3d1a2960f70b6cda136f97acaa4b2f
rogesson/hacker_rank
/python/find_second_maximum_number_in_a_list.py
323
3.890625
4
""" find the runing-up """ def find_score(runners): """ find runner in a list """ runners = list(set(runners)) runners.sort() if len(runners) == 1: return runners[0] return runners[-2] print find_score([2, 3, 6, 6, 5]) # 5 print find_score([1]) # 1 print find_score([57, 57, -57, 57])# -57
6250e424492cf983ef297eeb462aa42a8df96bf8
jsearfoo/beginner-project-solutions
/Mean_Median_Mode.py
1,109
4
4
def mean(list): sum=0 for item in list: sum += item mean=sum/len(list) return mean def median(list): sortedlist=sorted(list) print("Sorted list = \n", sortedlist) mid=int(len(list)/2) return list[mid] def mode(list): sortedlist=sorted(list) modes = [] currentStreak = 0 highestStreak = 0 uniqueNums = set(sortedlist) for i, num in enumerate(uniqueNums): currentStreak = sortedlist.count(num) if (currentStreak > highestStreak): highestStreak = currentStreak modes.clear() modes.append(num) elif (currentStreak == highestStreak): modes.append(num) print("Mode:") for mode in modes: print(mode, end=' ') print("") num=int(input("How many numbers you want to input in the list?\n")) list=[] for i in range(1,num+1): list.append(int(input("input number {} here".format(i)))) print("your list of number is ready ", list) print("Mean =",mean(list)) print("Median =",median(list)) mode(list)
00037278c97964573ac74535f6761450b5e1216b
Manpreet1398/Mr.Perfecto
/widget_fitting_layout.py
425
4.5625
5
from tkinter import * root=Tk() one=Label(root,text="One",bg="red",fg="white") one.pack() two=Label(root,text="Two",bg="green",fg="black") # this will fill the complete widget as wide # as parent window is two.pack(fill=X) # three=Label(root,text="Three",bg="blue",fg="red") # # this will fill the complete window at left as wide as # # left part of window is three.pack(side=LEFT,fill=Y) root.mainloop()
dbb65b275f54285d8c6d4faa8e0dc1286048d57d
danylo-boiko/HackerRank
/Problem Solving/Basic/counting_sort_2.py
518
3.71875
4
# https://www.hackerrank.com/challenges/countingsort2/problem # !/bin/python3 def countingSort(arr): count = [0] * (max(arr) + 1) for num in arr: count[num] += 1 sortedArr = [] for i in range(len(count)): while count[i] != 0: count[i] -= 1 sortedArr.append(i) return sortedArr if __name__ == '__main__': n = int(input().strip()) arr = list(map(int, input().rstrip().split())) result = countingSort(arr) print(' '.join(map(str, result)))
6026f45e501b8b27938addd96fa891dc80a69239
Gaydarenko/PY-111
/Tasks/c0_fib.py
806
4.40625
4
def fib_recursive(n: int) -> int: """ Calculate n-th number of Fibonacci sequence using recursive algorithm :param n: number of item :return: Fibonacci number """ # print(n) if n < 0: raise ValueError if n == 0: return 0 if n == 1: return 1 return fib_recursive(n - 1) + fib_recursive(n - 2) def fib_iterative(n: int) -> int: """ Calculate n-th number of Fibonacci sequence using iterative algorithm :param n: number of item :return: Fibonacci number """ # print(n) if n < 1: raise ValueError if n == 1 or n == 2: return n - 1 a, b = 0, 1 for _ in range(n-1): a, b = b, a + b return b if __name__ == '__main__': print(fib_iterative(3)) print(fib_recursive(3))
2f4ee77b13a7a0c3ed76af0c38fac2aa1d243c22
Aadesh-Shigavan/Python_Daily_Flash
/Day 4/04-DailyFlash_Solutions/17_Jan_Solutions_Two/Python/program3.py
607
4.09375
4
def check(age, sex, status) : if(sex == 'f' or sex == 'F'): print("She will work in Urban areas") elif(age >= 20 and age <= 40): print("He will work in any areas") else : print("He will work in urban areas") print("Enter age, sex(m/f), Marital Status(y/n)") try: age = int(raw_input()) sex = raw_input() status = raw_input() except ValueError as e: print("Error") exit(0) if(age < 20 or age > 60 or (sex != 'f' and sex != 'F' and sex != 'm' and sex != 'M') or (status != 'y' and status != 'Y' and status != 'n' and status != 'N')): print("Error") else: check(age, sex, status)
1955e5c8575eb8f91e0ea435031ac52adc6c9384
rhitchcock/advent-of-code-2017
/day11/part2.py
609
3.6875
4
#!/usr/bin/env python3 import math def main(): with open("input.txt") as f: directions = f.read().strip().split(",") n = 0 ne = 0 nw = 0 furthest_distance = 0 for direction in directions: if direction == "s": n -= 1 elif direction == "n": n += 1 elif direction == "ne": ne += 1 elif direction == "se": nw -= 1 elif direction == "sw": ne -= 1 elif direction == "nw": nw += 1 furthest_distance = max(furthest_distance, abs(n) + abs(ne) + max(0, abs(nw) - abs(ne))) print(furthest_distance) if __name__ == "__main__": main()
4e290482725a4cbaec8f6885f25a6dd27d1628d7
Nitheesh1305/Innomatics_Internship_APR_21
/Task - 2 (Python Programming)/15.py
284
3.796875
4
#Question 15- Set .symmetric_difference() Operation n = int(input()) english_students = set(list(map(int, input().split()))) b = int(input()) french_students = set(list(map(int, input().split()))) print(len(list(english_students.symmetric_difference(french_students))))
f295d9b8ce70483792141ce1980493c8e3261adc
deanc474/myrepo
/TrigInterp.py
1,453
3.890625
4
import numpy as np import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt %matplotlib inline def TrigInterp(x,y,Nnew): #Trigonometric Interpolation #Input #x = Interpolation nodes (vector of length N) #y = Interpolation nodes (Vector of length N) #Nnew = New length of the data vector #Output #P = New vector of appropriate length Nnew #Note This function does not output an x vector. #Define out interpolation points N=len(x) X = np.linspace(x[0],x[N-1],Nnew) y = np.asmatrix(y) #Necessary for matrix multiplication xi = np.linspace(x[0],x[N-1],Nnew)#New x data points h=2/N scale = (x[2]-x[1])/h x = x/scale x=np.asmatrix(x) #Necessary for matrix multiplication xi = xi/scale xi = np.asmatrix(xi) #Necessary for matrix multiplication #evaluate the interpolation points Y = np.zeros(Nnew) Y = np.asmatrix(Y) #To avoid using a for loop we instead use matrix multiplication h=np.ones(N) h=np.asmatrix(h) k=np.ones(Nnew) k=np.asmatrix(k) Y = Y + np.dot(y,TrigInt(np.transpose(np.dot(np.transpose(xi),h))-np.dot(np.transpose(x),k),N)) # [1xNnew] = [1xNnew] + [1xN] * (([1xNnew]'*[1xN])' - ([1xN]'*[1xNnew])) # [1xNnew] = [1xNnew] + [1xN] * [NxNnew] Y = np.transpose(Y) return X,Y
e8ba8723a08a2140b8ee4232606f10e07997528c
karolinanikolova/SoftUni-Software-Engineering
/2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/00-Exam-Prep/01_Mid_Exam_Prep/05-Programming-Fundamentals-Mid-Exam/02-MuOnline.py
2,429
3.78125
4
# Problem 2. Mu Online # You have initial health 100 and initial bitcoins 0. You will be given a string, representing the dungeons rooms. # Each room is separated with '|' (vertical bar): "room1|room2|room3…" # Each room contains a command and a number, separated by space. The command can be: # • "potion" # o You are healed with the number in the second part. But your health cannot exceed your initial health (100). # o First print: "You healed for {amount} hp.". # o After that, print your current health: "Current health: {health} hp.". # • "chest" # o You've found some bitcoins, the number in the second part. # o Print: "You found {amount} bitcoins." # • In any other case you are facing a monster, you are going to fight. The second part of the room, contains the attack of the monster. # You should remove the monster's attack from your health. # o If you are not dead (health <= 0) you've slain the monster, and you should print ("You slayed {monster}.") # o If you've died, print "You died! Killed by {monster}." and your quest is over. Print the best room you`ve manage to reach: "Best room: {room}". # If you managed to go through all the rooms in the dungeon, print on the next three lines: # "You've made it!", "Bitcoins: {bitcoins}", "Health: {health}". dungeon_rooms = input().split("|") initial_health = 100 initial_bitcoins = 0 health = initial_health bitcoins = initial_bitcoins is_managed_all_rooms = True for room_index in range(len(dungeon_rooms)): room = dungeon_rooms[room_index].split() command = room[0] number = int(room[1]) if command == "potion": if health + number > initial_health: healed = initial_health - health health = initial_health else: healed = number health += number print(f"You healed for {healed} hp.") print(f"Current health: {health} hp.") elif command == "chest": print(f"You found {number} bitcoins.") bitcoins += number else: health -= number monster = command if health > 0: print(f"You slayed {monster}.") else: print(f"You died! Killed by {monster}.") print(f"Best room: {room_index + 1}") is_managed_all_rooms = False break if is_managed_all_rooms: print(f"You've made it!") print(f"Bitcoins: {bitcoins}") print(f"Health: {health}")
1531e31e18e4b827a4e35fb91427f9da7fd9af20
rafamancan/python_estudo
/aulas/app2/descontos.py
865
3.515625
4
# -*- coding: UTF-8 -*- # descontos.py class Desconto_por_cinco_intens(object): def __init__(self): self._proximo_desconto = None def adicionar_proximo_desconto(self, proximo_desconto): self.__proximo_desconto = proximo_desconto def calcular(orcamento): if(orcamento.total_itens > 5): return orcamento.valor * 0.1 else: return self._proximo_desconto.calcular(orcamento) class Desconto_por_mais_de_quinhetos_reais(object): def adicionar_proximo_desconto(self, proximo_desconto): self.__proximo_desconto = proximo_desconto def __init__(self): self._proximo_desconto = None def calcular(orcamento): if(orcamento.valor > 500): return orcamento.valor * 0.07 else: return self._proximo_desconto.calcular(orcamento) class Sem_desconto(object): def calcula(self, orcamento): return 0
7ad2a7cf4a696e6dac117f531ba933693fe27b13
JeremyBakker/Scala-PySpark-and-Spark
/pyspark.py
11,813
3.765625
4
# Create RDD lines = sc.textFile("README.md") # Basic Filter with lambda pythonLines = lines.filter(lambda line: "Python in line") # Basic Count pythonLines.count() # Pull the first line pythonLines.first() # Persist an RDD in memory -- useful when needing to use an intermediate RDD # multiple times pythonLines.persist # Parallelize data to create an RDD lines = sc.parallelize(["pandas", "i like pandas"]) # Create an RDD of a log file and filter on "ERROR" and "WARNING" inputRDD = sc.textFile("log.txt") errorsRDD = inputRDD.filter(lambda x: "ERROR" in x) warningsRDD = inputRDD.filter(lambda x: "WARNING" in x) badLinesRDD = errorsRDD.union(warningsRDD) # Print results print("Input had " + str(badLinesRDD.count()) + " concerning lines") print("Here are 10 examples:") for line in badLinesRDDtake(10): print(line) # Filter by passing in a function def containsError(line): return "ERROR" in line word = inputRDD.filter(containsError) # Basic map function nums = sc.parallelize([1, 2, 3, 4]) squared = nums.map(lambda x: x * x).collect() for num in squared: print ("%i " % (num)) # Basic flat map function lines = sc.parallelize(["hello world", "hi"]) words = lines.flatMap(lambda line: line.split(" ")) words.first() nums_two = sc.parallelize([3,4,5,6]) nums.union(nums_two) nums.intersection(nums_two) nums.cartesian(nums_two).collect() nums.reduce(lambda x,y: x + y) # Read in data from csv df = spark.read.format("csv").option("inferSchema", "true").option("header", "true").load("/Users/jeremybakker/Desktop/flight_data.csv") # Transform dataframe into a table df.createOrReplaceTempView("flight_data_2017") # SQL Query to find number of originating flights by destination sql = spark.sql("""SELECT ORIGIN, count(1) FROM flight_data_2017 GROUP BY ORIGIN ORDER BY count(1) DESC""") # Same query with dataframe from pyspark.sql.functions import desc dfQuery = df.groupBy("ORIGIN").count().sort(desc("count")) # Show the Spark physical plans - The underlying plans are the same. sql.explain() # OUT # == Physical Plan == # *Sort [count(1)#96L DESC NULLS LAST], true, 0 # +- Exchange rangepartitioning(count(1)#96L DESC NULLS LAST, 200) # +- *HashAggregate(keys=[ORIGIN#13], functions=[count(1)]) # +- Exchange hashpartitioning(ORIGIN#13, 200) # +- *HashAggregate(keys=[ORIGIN#13], functions=[partial_count(1)]) # +- *FileScan csv [ORIGIN#13] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/jeremybakker/Desktop/flight_data.csv], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<ORIGIN:string> dfQuery.explain() # OUT== Physical Plan == # *Sort [count#292L DESC NULLS LAST], true, 0 # +- Exchange rangepartitioning(count#292L DESC NULLS LAST, 200) # +- *HashAggregate(keys=[ORIGIN#13], functions=[count(1)]) # +- Exchange hashpartitioning(ORIGIN#13, 200) # +- *HashAggregate(keys=[ORIGIN#13], functions=[partial_count(1)]) # +- *FileScan csv [ORIGIN#13] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/jeremybakker/Desktop/flight_data.csv], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<ORIGIN:string> # Print schema of the dataframe, which deines the column names and types of a DataFrame df.printSchema() df.schema # Two ways to create columns from pyspark.sql.functions import col, column col("columnName") column("columnName") # See all columns listed df.columns # See first row df.first() # Create a row from pyspark.sql import Row myRow = Row("Hello", None, 1, False) # Access data from Row myRow[0] # Add a column that specifies whether the destination and origin country are the same df.selectExpr("*", "(DEST_COUNTRY = ORIGIN_COUNTRY) as WithinCountry").show(2) # Aggregate over the entire dataframe with selectExpr df.selectExpr("avg(NONSTOP_MILES)", "count(distinct(DEST_COUNTRY))").show() # Add a literal value with an alias df.select(expr("*"), lit(1).alias("One")).show(2) # Add a column using withColumn - withColumn takes to arguments: name and expression to create the value for a given row df.withColumn("numberOne", lit(1)).show(2) # Rename column df.withColumnRenamed("DEST_COUNTRY", "Destination Country") # Drop column df.drop("DEST_COUNTRY") # Two different ways to filter - explain() outputs are the same colCondition = df.filter(col("NONSTOP_MILES") > 1000) conditional = df.where(col("NONSTOP_MILES") > 1000) # Find number of distinct origins df.select("ORIGIN").distinct().count() spark.sql("""SELECT count(distinct origin) from flight_data_2017""").show() #Random Sample seed = 5 withReplacement = False fraction = 0.5 df.sample(withReplacement, fraction, seed) # Randomly Split Data dataFrames = df.randomSplit([0.25, 0.75],seed) # Sort df.sort("NONSTOP_MILES") # sortWithinPartitions can help with optimization df.sortWithinPartitions("NONSTOP_MILES") # limit df.limit(5).show() # find number of partitions df.rdd.getNumPartitions() # repartition df.repartition(5) # repartition by column df.repartition(col("NONSTOP_MILES")) # repartition by column with defined number of partitions df.repartition(5, col("NONSTOP_MILES")) # combine partitions without a full shuffle df.repartition(5, col("NONSTOP_MILES")).coalesce(2) # load retail data df = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load("/Users/jeremybakker/Desktop/WA_Sales_Products.csv") # use Booleans to filter data - simple df.where(col("Product line") == "Camping Equipment").select("Order method type", "Retailer type", "Product").show(5, False) # filter with and/or eyeWearFilter = col("Product type") == "Eyewear" revenueFilter = col("Revenue") > 4000 quarterFilter = col("Quarter") == "Q1 2012" df.withColumn("isProfitable", revenueFilter & (eyeWearFilter | quarterFilter)).where("isProfitable").select("Product", "isProfitable") # working with numbers df.select(expr("Product type"),fabricatedQuantity.alias("realQuantity"), col("Quantity")) # round, lit, bround from pyspark.sql.functions import lit, round, bround df.select(round(col("Revenue"), 1).alias("rounded"), col("Revenue")).show(5) df.select(round(lit("2.5")),bround(lit("2.5"))).show(2) # Pearson coefficient for quantityt and revenue df.select(corr("Quantity", "Revenue")).show() # summary statistics df.describe().show() # capitalize words from pyspark.sql.functions import initcap df.select(initcap(col("Product line"))).show(2, false) # upper,lower from pyspark.sql.functions import upper,lower df.select(col("Product type"), lower(col("Product type")), upper(lower(col("Product type")))).show(2) # add or remove white space from pyspark.sql.functions import lit,trim,ltrim,rtrim,rpad,lpad df.select(ltrim(lit(" HELLO ")).alias("ltrim"), rtrim(lit(" HELLO ")).alias("rtrim"), trim(lit(" HELLO ")).alias("trim"), lpad(lit("HELLO"), 3," ").alias("lp"), rpad(lit("HELLO"), 10, " ").alias("rp")).show(2) # regex replace from pyspark.sql.functions import regexp_replace df.select(regexp_replace(col("Retailer type"), "Outdoors", "Indoors").alias("Moved Indoors"),col("Retailer type")).show(2) # translate characters from pyspark.sql.functions import translate df.select(translate(col("Product type"), "okin", "1347"),col("Product type")).show(2) # find items with "Master" in the product column from pyspark.sql.functions import instr containsMaster = instr(col("Product"), "Master") >= 1 df.withColumn("hasMaster", containsMaster).filter("hasMaster").select("Product").show(3, False) # simple UDF - better to write in Scala to control memory costs val udfExampleDf = spark.range(5).toDF("num") def power3(number:Double):Double = { number * number * number } val power3udf = udf(power3(_:Double):Double) udfExampleDF.select(power3udf(col("num"))).show() # Aggregations from pyspark.sql.functions import count df.select(count("Product")).collect() from pyspark.sql.functions import countDistinct df.select(countDistinct("Product")).collect() from pyspark.sql.functions import approx_count_distinct df.select(approx_count_distinct("Product", 0.1)).collect() from pyspark.sql.functions import first,last df.select(first("Product"), last("Product")).collect() from pyspark.sql.functions import min, max df.select(min("Gross margin"), max("Gross margin")).collect() from pyspark.sql.functions import sum df.select(sum("Revenue")).show() from pyspark.sql.functions import sumDistinct df.select(sumDistinct("Quantity")).show() from pyspark.sql.functions import sum, count, avg, expr df.select(count("Quantity").alias("total_transactions"),sum("Quantity").alias("total_purchases"),avg("Quantity").alias("avg_purchases"),expr("mean(Quantity)").alias("mean_purchases")).selectExpr("total_purchases/total_transactions","avg_purchases","mean_purchases").collect() from pyspark.sql.functions import var_pop, stddev_pop, var_samp, stddev_samp df.select(var_pop("Quantity"),var_samp("Quantity"),stddev_pop("Quantity"),stddev_samp("Quantity")).collect() df.groupBy("Product","Product type").count().show() df.groupBy("Product").agg(count("Quantity").alias("quan"),expr("count(Quantity)")).show() df.groupBy("Product").agg(expr("avg(Quantity)"),expr("stddev_pop(Quantity)")).show() # Joins person = spark.createDataFrame([(0, "Bill Chambers", 0, [100]), (1, "Matei Zaharia", 1, [500, 250, 100]), (2, "Michael Armbrust", 1, [250, 100])]).toDF("id", "name", "graduate_program", "spark_status") graduateProgram = spark.createDataFrame([(0,"Masters", "School of Information", "UC Berkeley"),(2, "Masters", "EECS", "UC Berkeley"),(1, "Ph.D.", "EECS", "UC Berkeley")]).toDF("id", "degree","department","school") sparkStatus = spark.createDataFrame([(500, "Vice President"),(250, "PMC Member"),(100,"Contributor")]).toDF("id","status") person.createOrReplaceTempView("person") graduateProgram.createOrReplaceTempView("graduateProgram") sparkStatus.createOrReplaceTempView("sparkStatus") # Inner Joins joinExpression = person.graduate_program == graduateProgram.id person.join(graduateProgram, joinExpression).show() person.join(graduateProgram, joinExpression, "inner").show() # Outer Joins person.join(graduateProgram, joinExpression, "outer").show() person.join(graduateProgram, joinExpression, "left_outer").show() person.join(graduateProgram, joinExpression, "right_outer").show() # Semi Joins - can be thought of as filter graduateProgram.join(person, joinExpression, "left_semi").show() gradProgram2 = graduateProgram.union(spark.createDataFrame([(0, "Masters", "Duplicated Row", "Duplicated School")])) gradProgram2.createOrReplaceTempView("gradProgram2") gradProgram2.join(person, joinExpression, "left_semi") # Anti Join - can be considered a NOT filter graduateProgram.join(person, joinExpression, "left_anti").show() # Cross - same as inner join here graduateProgram.join(person, joinExpression, "cross").show() # Cross - explicit call to crossJoin - DANGEROUS person.crossJoin(graduateProgram).show() # Spark SQL spark.sql("""CREATE TABLE flights(DEST_COUNTRY_NAME STRING, ORIGIN_COUNTRY_NAME STRING, count LONG) USING JSON OPTIONS (path'/Users/jeremybakker/workspace/linkage/flight_data_2015.json')""") spark.sql("""CREATE VIEW just_usa_view AS SELECT * FROM flights WHERE dest_country_name = 'United States'""") spark.sql("""DROP VIEW IF EXISTS just_usa_view""") spark.sql("""CREATE DATABASE some_db""") spark.sql("""USE some_db""") # Struct for nested data spark.sql("""CREATE VIEW IF NOT EXISTS nested_data AS SELECT (DEST_COUNTRY_NAME, ORIGIN_COUNTRY_NAME) as country, count FROM flights""") spark.sql("""SELECT country.DEST_COUNTRY_NAME, count FROM nested_data""") # Working with sets and lists spark.sql("""SELECT DEST_COUNTRY_NAME AS new_name, collect_list(count) as flight_counts, collect_set(ORIGIN_COUNTRY_NAME) as origin_set FROM flights GROUP BY DEST_COUNTRY_NAME""")
16c7ce1f668ee538c4ef72a6ca64894aec0a4186
fightpf/pythontest
/pythonclass/Fibonacci.py
289
4.03125
4
def Fibonacci(n): if n==1: return 1 if n==2: return 1 return Fibonacci(n-1)+Fibonacci(n-2) print(Fibonacci(10)) def Fibonacci2(n): a,b=1,1 answer=a for i in range(n-2): answer=a+b a,b=b,answer return answer print(Fibonacci2(10))
0463d59a9d30958f8fb3ad9f1769d7c292cfe5fe
gschen/sctu-ds-2020
/1906101004-唐娜/day0226/作业5.py
401
3.671875
4
#5. (使用循环和判断)输入三个整数x,y,z,请把这三个数由小到大输出。 x = input('请输入第一个整数:') y = input('请输入第二个整数:') z = input('请输入第三个整数:') arr = [x,y,z] for i in range(0,3): for j in range(i,3): if int(arr[i])>int(arr[j]): k = arr[i] arr[i] = arr[j] arr[j] = k print(arr)
4a6369af1278af85c1ac5d650c716c283898da32
swapnil2188/python-myrepo
/tests/practice/age_name.py
214
3.8125
4
#!/usr/bin/python name = raw_input("Your name please: ") print name age = raw_input("Enter your age: ") age = int(age) print age s = (100 - age) r = (s + 2019) print name ,"will be 100 years old in the year", r
510c69d30b33403c2c105c00078532184f9a1dd1
Thotasivaparvathi/siva
/program31.py
96
3.90625
4
string=input() char=0 word=0 for i in string: char+=1 if i==' ': word+=1 print(char-word)
bc69a4b5619da70de1d8f5367151d1f6003b7046
jpro6679/kopo_univ
/test.py
340
3.59375
4
import math th = math.radians(1) # 각도 10도를 라디안으로 변환하여 th 에 대입 print("θ =", th, "rad =", math.degrees(th), "°\n") # 라디안과 각도 출력 print( "sin =", math.sin(th)) # 사인 (Sine) print( "cos =", math.cos(th)) # 코사인(Cosine) print ("tan =", math.tan(th) ) # 탄젠트(Tangent)
3b35d6e92bd215c4a43428ae7ad5020e32ed6d7a
swagMASTER99swag/ComputationalThinking
/CaeserCypher.py
566
3.90625
4
message = input('message: ') key = 13 mode = 'decrypt' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' translated = '' message = message.upper() for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) if mode == 'encrypt': num = num + key elif mode == 'decrypt': num = num - key if num >= len(LETTERS): num = num - len(LETTERS) elif num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print(translated)
62ad0cdecbb43d25fbae24b2514210a2cd9e56dc
amarjeet-kaloty/Data-Structures-in-Python
/linkedList.py
1,320
4.125
4
class node: def __init__(self, data=None): self.data=data self.next=None class linkedList: def __init__(self): self.head = node() #Insert new node in the Linked-List def append(self, data): new_node = node(data) cur_node = self.head while (cur_node.next != None): cur_node = cur_node.next cur_node.next = new_node #Display the Linked-List def display(self): elems = [] cur_node = self.head while (cur_node.next != None): cur_node = cur_node.next elems.append(cur_node.data) print(elems) #Length of the Linked-List def length(self): total=0 cur_node = self.head while (cur_node.next != None): cur_node = cur_node.next total+=1 return total #Delete the last node def delete(self): if(self.head.next == None): return None cur_node = self.head while(cur_node.next.next != None): cur_node = cur_node.next cur_node.next = None return cur_node myList = linkedList() myList.delete() myList.display() myList.append(40) myList.display() myList.delete() myList.display()
a8037f60d639438806c963aa08f69effae8a4e5a
VeigerBroth/xo_game
/xo.py
4,095
3.703125
4
import os from random import randint from time import sleep def checker(): ### check if X has winning combination if ( field[0]==x and field[1]==x and field[2]==x or field[3]==x and field[4]==x and field[5]==x or field[6]==x and field[7]==x and field[8]==x or field[0]==x and field[3]==x and field[6]==x or field[1]==x and field[4]==x and field[7]==x or field[2]==x and field[5]==x and field[8]==x or field[0]==x and field[4]==x and field[8]==x or field[2]==x and field[4]==x and field[6]==x ): print('Win X') fields() quit() return 1 ### check if O has winning combination elif ( field[0]==o and field[1]==o and field[2]==o or field[3]==o and field[4]==o and field[5]==o or field[6]==o and field[7]==o and field[8]==o or field[0]==o and field[3]==o and field[6]==o or field[1]==o and field[4]==o and field[7]==o or field[2]==o and field[5]==o and field[8]==o or field[0]==o and field[4]==o and field[8]==o or field[2]==o and field[4]==o and field[6]==o ): print('Win O') fields() quit() return 1 elif i==9: print('Draw! To play - run game again!') fields() quit() def fields(): print(field[0]+'|'+field[1]+'|'+field[2]) print('-'*5) print(field[3]+'|'+field[4]+'|'+field[5]) print('-'*5) print(field[6]+'|'+field[7]+'|'+field[8]) def clear_terminal(): os.system('cls' if os.name == 'nt' else 'clear') def pc_move(field): rand = randint(0, 8) if field[rand] == str(rand+1): field[rand] = o else: pc_move(field) def enter_value(input_message, error_message, input_type_convertion, first_condition_value=None, second_condition_value=None): while True: try: if input_type_convertion == int: enter_value = int(input(input_message)) if enter_value <= first_condition_value \ and enter_value != second_condition_value: break else: print(error_message) except: print(error_message) return enter_value x="x" o="o" field = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] i=0 rand_first_move = randint(0, 1) clear_terminal() while True: start_question = enter_value('Play with PC - 1; '+ 'Play with another player - 2; Close game - 3: ', 'Value incorrect - choose only numbers from 1 to 3!', int, 3, 0) if start_question==1 or start_question==2: while i<9: if (start_question==1 and rand_first_move==1): i+=1 print('PC move!') sleep(1) rand_first_move-=1 pc_move(field) if checker() == 1: break elif (rand_first_move==0 and start_question==1) or start_question==2: i+=1 fields() if rand_first_move%2==0: print('X move') else: print('O move') move = enter_value('Choose your move: ', 'Value incorrect - choose only numbers from 1 to 9!', int, 9, 0) if field[move-1] == str(move): if (start_question==2 and rand_first_move==1): rand_first_move-=1 field[move-1] = o if checker() == 1: break else: rand_first_move+=1 field[move-1] = x if checker() == 1: break else: print('Char X or O was chosen!') i-=1 elif start_question==3: quit()
5326d72c3c6b7a3109cd5b8e4672c73fa372d094
JacobLiebenow/Waves-In-Motion
/datacls/organization.py
1,487
3.671875
4
#Written by: Jacob S Liebenow # # # #A organization is a conglomerate of contacts, each with their own associated role (which might or might not be #specified). Bands are scheduled to play at various venues during certain days. They might also frequent #venues, and be worked with promoters. from datacls import contact class Organization: def __init__(self, name, stateName, cityName, address, zip, phone, links, members, email, notes, contacts=None, roles=None): self.organizationName = name self.stateName = stateName self.cityName = cityName self.address = address self.zip = str(zip) self.phone = str(phone) self.links = links self.members = members self.email = email self.notes = notes if contacts is None: self.contacts = [] else: self.contacts = contacts if roles is None: self.roles = [] else: self.roles = roles def addRole(self, roleName, contact): #Eventually, because of the chance of multiple same-titled roles occuring within the organization, the user #should be told that a organization role exists if already put in, and should be allowed the chance to confirm #if "yes" or "y" is input, and to avoid adding for any other input. # #For now, however, we are assuming roles are singular, and thus only noted once. if roleName not in self.roles: contact.addBandRole(self.bandName, roleName) self.roles.append(roleName) if contact not in self.contacts: self.contacts.append(contact)
ca15d5eaf0a18e35c51bff75c1e474e293f108f4
gladius99/Destroy_the_Kilge
/kilge/main2.py
17,893
3.890625
4
#program goes here from main.py then from here goes to "program start" def start_point(): print "you enter the bunker, wandering what will happen..." import main as a import time time.sleep(1) a.checkpoint = 1 first_room() #location functions def first_room(): import main as a print "this is the bunker entrance." print "there is no sign of activity, but" print "all the systems are running fine." while True: fr_choice = raw_input("you can go to the long hallway, or the iron gate. ") if fr_choice == "menu": a.menu_call() elif fr_choice == "l": long_hallway() elif fr_choice == "i": a.iron_gate() else: print "user error. unrecognized input." def long_hallway(): import main as a print " " print "this is the long hallway." while True: print """ you can go to the main room, the first room, room1, room2, room3, room4, room5, room6, room7, or room8.""" lh_input = raw_input(">>> ") if lh_input == "menu": a.menu_call() elif lh_input == "m": main_room() elif lh_input == "f": first_room() elif lh_input == "1": room1() elif lh_input == "2": room2() elif lh_input == "3": room3() elif lh_input == "4": room4() elif lh_input == "5": room5() elif lh_input == "6": room6() elif lh_input == "7": room7() elif lh_input == "8": room8() else: print "user error. unrecognized input." def gate(): import main as a import time if a.Gate == 0: print "enter the password." print "password format:" print "XX:XX:XX:XX:XX:XX:XX:XX" print "(enter the colons as well)" password = raw_input(">>> ") if password == "09:58:47:99:42:43:81:78": print " " print "the gate opens..." print "it sounds like another door opened as well." print " " time.sleep(1.5) a.Gate = 1 a.r2door = 1 else: print " " print "that is incorrect." print "you have to open to the gate to" print "progress farther." print "returning to long hallway..." print " " long_hallway() else: pass #numbered rooms def room1(): import main as a small_drone() a.waterget() print " " print "this is room1." print '"78" is written on the wall with a large "8" next to it.' print " " while True: r1_input = raw_input("you can go back to the long hallway. ") if r1_input == "l": long_hallway() elif r1_input == "menu": a.menu_call() else: print "user error. unrecognized input." def room2(): import main as a global r2door small_drone() small_drone() a.waterget() print " " print "this is room2." print '"81" is written on the wall with a large "7" next to it.' print " " if a.r2door == 0: while True: r2_input = raw_input("you can go back to the long hallway. ") if r2_input == "l": long_hallway() elif r2_input == "menu": a.menu_call() else: print "user error. unrecognized input." elif a.r2door == 1: while True: r2_input = raw_input("you can go to the secret room or back to the long hallway. ") if r2_input == "l": long_hallway() elif r2_input == "menu": a.menu_call() elif r2_input == "s": secret_room() else: print "user error. unrecognized input." else: print "something went wrong with the r2door variable most likely." a.error() def secret_room(): import main as a print " " print "this is the secret room" print " " if 60 not in a.weaponlist: if 40 in a.weaponlist: a.weaponlist.append(60.0) a.weaponlist.remove(40.0) a.weapon = 60.0 print " " print "you found an upgrade for your mechsuit." print " " while True: sr_input = raw_input("you can go to the room2. ") if sr_input == "menu": a.menu_call() elif sr_input == "2": room2() def room3(): import main as a small_drone() a.waterget() print " " print "this is room3." print '"42" is written on the wall with a large "5" next to it.' print " " while True: r3_input = raw_input("you can go back to the long hallway. ") if r3_input == "l": long_hallway() elif r3_input == "menu": a.menu_call() else: print "user error. unrecognized input." def room4(): import main as a small_drone() a.waterget() print " " print "this is room4." print '"09" is written on the wall with a large "1" next to it.' print " " while True: r4_input = raw_input("you can go back to the long hallway. ") if r4_input == "l": long_hallway() elif r4_input == "menu": a.menu_call() else: print "user error. unrecognized input." def room5(): import main as a small_drone() a.waterget() print " " print "this is room5." print '"43" is written on the wall with a large "6" next to it.' print " " while True: r5_input = raw_input("you can go back to the long hallway. ") if r5_input == "l": long_hallway() elif r5_input == "menu": a.menu_call() else: print "user error. unrecognized input." def room6(): import main as a small_drone() a.waterget() print " " print "this is room6." print '"47" is written on the wall with a large "3" next to it.' print " " while True: r6_input = raw_input("you can go back to the long hallway. ") if r6_input == "l": long_hallway() elif r6_input == "menu": a.menu_call() else: print "user error. unrecognized input." def room7(): import main as a small_drone() a.waterget() print " " print "this is room7." print '"58" is written on the wall with a large "2" next to it.' print " " while True: r7_input = raw_input("you can go back to the long hallway. ") if r7_input == "l": long_hallway() elif r7_input == "menu": a.menu_call() else: print "user error. unrecognized input." def room8(): import main as a small_drone() a.waterget() print " " print "this is room8." print '"99" is written on the wall with a large "4" next to it.' print " " while True: r8_input = raw_input("you can go back to the long hallway. ") if r8_input == "l": long_hallway() elif r8_input == "menu": a.menu_call() else: print "user error. unrecognized input." def main_room(): import main as a gate() small_drone() combat_robot() a.waterget() print " " print "this is the main room." print " " while True: mr_input = raw_input("you can go to the long hallway, the much-too-waxed hall, or the inner entrance. ") if mr_input == "menu": a.menu_call() elif mr_input == "l": long_hallway() elif mr_input == "m": waxed_floor() elif mr_input == "i": inner_entrance() else: print "user error. unrecognized input." def waxed_floor(): import main as a print " " print "this is the much-too-waxed hall" print " " while True: wf_input = raw_input("you can go to the control room, or the main room. ") if wf_input == "menu": a.menu_call() elif wf_input == "m": main_room() elif wf_input == "c": control_room() else: print "user error. unrecognized input." def control_room(): import main as a small_drone() combat_robot() a.waterget() print " " print "this is the control room." print " " if a.controlrwhat == 0: print "control panels, switches, and buttons line the room," print "completely filling the entire area. Moniters also stand" print "in a row. Wait...Something moved in one of them." print "didnt it?" print " " a.controlrwhat = 1 else: pass while True: cr_input = raw_input("you can go to the much-too-waxed hall or the ventilation shaft. ") if cr_input == "m": waxed_floor() elif cr_input == "menu": a.menu_call() elif cr_input == "v": ventilation_shaft() else: print "user error. unrecognized input." def ventilation_shaft(): import main as a AC() heat() print " " print "this is the ventilation_shaft." print "nothing here but some old mustard..." print " " while True: vs_input = raw_input("you can go to the large vent or the control room. ") if vs_input == "menu": a.menu_call() elif vs_input == "c": control_room() elif vs_input == "l": large_vent() else: print "user error. unrecognized input." def large_vent(): import main as a AC() heat() print " " print "this is the large vent" print " " while True: mv_input = raw_input("You can go to the ventilation shaft or the air duct. ") if mv_input == "menu": a.menu_call() elif mv_input == "v": ventilation_shaft() elif mv_input == "a": air_duct() else: print "user error. unrecognized input." def air_duct(): import main as a AC() heat() if a.Note == 0: print " " print "there is a letter on the ground." print "It reads:" print " " print "My name is Josh Rhames. I survived the bombs." print "The bombs hit hard. I am the only survivor from" print "my city. It has been 8 months since the bombing now" print "and I have built a stronghold. Rumors have begun to" print "spread about a second attack." print " " print "It will start with a scout who will come to find us." print "That scout will report back to the headquarters to direct" print "a more accurate bombing. I dont know if anyone out there" print "survived, but if anyone can hear this, come to my stronghold." print "I am the Kilge. I will protect you." print " " a.opinion = 5 print "what is this?" print " " print "this is the air duct." print " " a.Note = 1 else: pass while True: ad_input = raw_input("you can go to the large vent or the main room. ") if ad_input == "menu": a.menu_call() elif ad_input == "l": large_vent() elif ad_input == "m": print " " print "you fell down into the main room." print " " main_room() else: print "user error. unrecognized input." def inner_entrance(): import main as a small_drone() combat_robot() a.waterget() print " " print "this is the inner entrance." print "there is a ward that looks like a squid." print " " while True: ie_input = raw_input("you can go to the main room, the ward, or the corner room. ") if ie_input == "menu": a.menu_call() elif ie_input == "m": main_room() elif ie_input == "w": ward() elif ie_input == "c": corner_room() else: print "user error. unrecognized input." def ward(): import main as a a.waterget() a.waterget() a.waterget() print " " print "this is the ward, a safe place from enemies." print " " while True: w_input = raw_input("you can go to the inner entrance, or the suspiciously opened vault. ") if w_input == "menu": a.menu_call() elif w_input == "i": inner_entrance() elif w_input == "s": opened_vault() else: print "user error. unrecognized input." def corner_room(): import main as a small_drone() small_drone() small_drone() combat_robot() combat_robot() a.waterget() print " " print "this is the corner room. Lots of enemies hang out here." print " " while True: cr_input = raw_input("you can go to the inner entrance or the suspiciously opened vault. ") if cr_input == "menu": a.menu_call() elif cr_input == "i": inner_entrance() elif cr_input == "s": opened_vault() else: print "user error. unrecognized input." def opened_vault(): import main as a small_drone() combat_robot() a.waterget() print " " print "this is the suspiciously opened vault." print " " while True: ov_input = raw_input("you can go to the ward, corner room, or the armory. ") if ov_input == "menu": a.menu_call() elif ov_input == "w": ward() elif ov_input == "c": corner_room() elif ov_input == "a": armory() else: print "user error. unrecognized input." def armory(): import main as a small_drone() combat_robot() a.waterget() if 100 not in a.weaponlist: a.weaponlist.append(100) a.weapon = 100 print " " print "you found an even better mech suit!" print "better not just leave it lying around." print " " print " " print "this is the armory." print " " while True: a_input = raw_input("you can go to the suspiciously opened vault, or the prominent hallway. ") if a_input == "menu": a.menu_call() elif a_input == "s": opened_vault() elif a_input == "p": prominent_hallway() else: print "user error. unrecognized input." def prominent_hallway(): import main as a small_drone() small_drone() small_drone() combat_robot() combat_robot() combat_robot() print " " print "this is the prominent hallway." print " " while True: ph_input = raw_input("you can go to the vault or the narrow hallway. ") if ph_input == "menu": a.menu_call() elif ph_input == "v": opened_vault() elif ph_input == "n": narrow_hallway() else: print "user error. unrecognized input." def narrow_hallway(): import main as a small_drone() small_drone() small_drone() combat_robot() combat_robot() combat_robot() print " " print "this is the narrow hallway." print " " while True: nh_input = raw_input("you can go to the prominent hallway or the strategy room. ") if nh_input == "menu": a.menu_call() elif nh_input == "p": prominent_hallway() elif nh_input == "s": if a.Note != 0: stratagy_room() else: print "you cant go to the strategy room yet." print "search around and come back later." else: print "user error. unrecognized input." def stratagy_room(): battle_again() shelter() def shelter(): import time time.sleep(2) print " " print " " print "you enter the shelter..." time.sleep(5) print " " print " " print '"Please dont kill us again," she pleads.' time.sleep(5) quit() #battle functions def small_drone(): import random import main as a sd_chance = random.randint(1,5) if sd_chance == 2: print " " print "a small drone zips in out of nowhere!" print " " enemy = 500 while True: number = random.randint(1,13) * a.hit_miss() enemy_damage = random.randint(0,100) * a.change * a.attack_number() print "health =", a.health print "enemy health =", enemy print "you have", a.water, "water." action = raw_input( """ 1. basic attack 2. special attack 3. drink water """ ) if action == "1": enemy = enemy - a.user_damage * a.weapon * a.hit_miss() elif action == "2": enemy = enemy - number * a.weapon * a.hit_miss() elif action == "3": if a.water >= 1: print 'you drank water and gained 30 health points.' a.health = a.health + 30 a.water = a.water - 1 if a.water == 0: print "you dont have any water to drink." else: print "user error. unrecognized input." pass if enemy <= 0: print 'you defeated the enemy.' break a.health = a.health - enemy_damage * a.attack_number() if a.health <= 0: quit( "you died. " ) print 'the small drone hit you', a.attack_number(), 'times for', enemy_damage, 'damage.' else: pass else: pass def combat_robot(): import random import time import main as a cr_chance = random.randint(0,7) if cr_chance == 3: print " " print "a combot robot wheels toward you." print " " time.sleep(1.5) enemy = 600 while True: number = random.randint(1,13) * a.hit_miss() enemy_damage = random.randint(30,40) * a.change * a.attack_number() print "health =", a.health print "enemy health =", enemy print "you have", a.water, "water." action = raw_input( """ 1. basic attack 2. special attack 3. drink water """ ) if action == "1": enemy = enemy - a.user_damage * a.weapon * a.hit_miss() elif action == "2": enemy = enemy - number * a.weapon * a.hit_miss() elif action == "3": if a.water >= 1: print 'you drank water and gained 30 health points.' a.health = a.health + 30 a.water = a.water - 1 if a.water == 0: print "you dont have any water to drink." else: print "user error. unrecognized input." pass if enemy <= 0: print 'you defeated the enemy.' break a.health = a.health - enemy_damage * a.attack_number() if a.health <= 0: quit( "you died. " ) print 'the combat robot hit you', a.attack_number(), 'times for', enemy_damage, 'damage.' else: pass def battle_again(): import main as a import time import random enemy = 2000 time.sleep(1) print " " print " " print " " print "A MECH SUIT STANDS IN FRONT OF YOU." print " " print " " print " " time.sleep(3) while True: number = random.randint(1,13) * a.hit_miss() enemy_damage = random.randint(20,400) * a.change * a.attack_number() print "health =", a.health print "enemy health =", enemy print "you have", a.water, "water." action = raw_input( """ 1. basic attack 2. special attack 3. drink water """ ) if action == "1": enemy = enemy - a.user_damage * a.weapon * a.hit_miss() elif action == "2": enemy = enemy - number * a.weapon * a.hit_miss() elif action == "3": if a.water >= 1: print 'you drank water and gained 30 health points.' a.health = a.health + 30 a.water = a.water - 1 if a.water == 0: print "you dont have any water to drink." else: print "user error. unrecognized input." pass if enemy <= 0: print 'you defeated the mech suit.' break a.health = a.health - enemy_damage * a.attack_number() if a.health <= 0: quit( "you died. " ) print 'the mech suit hit you', a.attack_number(), 'times for', enemy_damage, 'damage.' else: pass #ventilation battle functions def heat(): import main as a import random import time hchance = random.randint(0,4) if hchance == 2: time.sleep(1.5) print " " print "Oh no! Someone turned on the heat!" print " " time.sleep(1.5) a.health = a.health - 40 a.water = 0 print "the hot air burned you, but you'll be ok." print "all your water evaporated." def AC(): import main as a import random import time ACchance = random.randint(0,6) if ACchance == 5: time.sleep(1.5) print " " print "Oh no! Someone turned on the AC!" print " " time.sleep(1.5) a.health = a.health - 60 print "the cold air really shook you up."
ce7f989222dfefda911392e7e8341e62f558c210
Yasaman1997/My_Python_Training
/Practice/Practice/Tic Tac Toe/draw/+_Check.py
3,416
4.15625
4
# Python Exercises http://www.practicepython.org/ # Exercise 27 - Tic Tac Toe Draw # Exercise to draw Tic Tac Toe gameboard the game board getting input from Player 1 and Player 2 # Last updated: 17/02/2016 # # - gets input from two players # - checks the input for correctness: row,col # - exits if board is full or there is a winner # initialise the game board gameboard = [(['.'] * 3) for i in range(3)] # variables for input and turn count row_col = [0] turn = 1 # checks that the input is valid # - that it is in the format "row,col" # - that the position is free def input_valid(values): # input has only two values if len(values) != 2: print "Input must be two numbers in format row,col e.g. 1,2 " return 0 # input is a number between 1 and 3 (inclusive) try: if (1 <= int(values[0]) <= 3) and (1 <= int(values[1]) <= 3): # checks if the position on the board is alreay filled if gameboard[int(values[0]) - 1][int(values[1]) - 1] != '.': print "Position on board already taken." return 0 return 1 else: print "Input values must be numbers between 1 and 3 (inclusive)" return 0 except ValueError: print "Input values must be numbers between 1 and 3 (inclusive)" return 0 # draw the board def draw_board(values, player): # changes the value to X or O gameboard[int(values[0]) - 1][int(values[1]) - 1] = player # print the gameboard for row in gameboard: print row # calculate if game is over (no more '.' or has winner) def game_over(): searcht = '.' # check win by row for i in range(3): if len(set(gameboard[i])) == 1: if gameboard[i][1] == '.': continue elif gameboard[i][1] == 'X': print "Game over - Player 1 wins" # elif gameboard[i][1] == 'O': else: print "Game over - Player 2 wins" return 1 # check win by column for i in range(3): if gameboard[0][i] == gameboard[1][i] == gameboard[2][i]: if gameboard[0][i] == '.': continue elif gameboard[0][i] == 'X': print "Game over - Player 1 wins" else: print "Game over - Player 2 wins" return 1 # check win by diagonal if (gameboard[0][0] == gameboard[1][1] == gameboard[2][2]) or ( gameboard[0][2] == gameboard[1][1] == gameboard[2][0]): if gameboard[1][1] == 'X': print "Game over - Player 1 wins" elif gameboard[1][1] == 'O': print "Game over - Player 2 wins" else: return 0 return 1 # check board is full for sublist in gameboard: if searcht in sublist: return 0 print "Game over - the board is filled" return 1 # main function that runs the game while board is not full while not game_over(): piece = '.' # Player input - checks for input correctness while not input_valid(row_col): player = turn % 2 if player == 0: player = 2 piece = 'O' else: piece = 'X' p1 = raw_input('Player ' + str(player) + ' input: ') row_col = p1.split(",") draw_board(row_col, piece) row_col = [0] turn += 1
967f803d07edc5714f0f8a4d85b546947370252f
zacharyDWelch/Electrodynamics
/Drawing copy.py
5,049
4.09375
4
from tkinter import * import math as m """ *************** Things to think about ************************* At some point get the circle to be randomly be placed in the grid. TODO: """ class Drawing: def __init__(self): self.master = Tk() self.master.title("Drawing of Circle and Charge Points") self.master.minsize(300,300) self.master.maxsize(1000,1000) WINDOW_WIDTH = 1000 WINDOW_HEIGHT = 800 self.my_canvas = Canvas(self.master, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg="white") self.my_canvas.pack() self.resetChargePoints = Button(self.master, text="Re-Set", command=self.testButton) self.resetChargePoints.pack(pady=20) # Drawing on the window self.creatGrid() #self.addText() self.drawCircle() # Main circle self.drawChargePoints() # Small red circles for charge points self.drawTestPoint() # Small blue circle for test point # main loop to keep window open. self.master.mainloop() def testButton(self): print("Button clicked") def creatGrid(self): """ Draws the axis lines (fixed location) """ # Create Line (x1, y1, x2, y2) self.my_canvas.create_line(10, 10, 10, 800, fill="black", arrow=FIRST) # Y-Axis self.my_canvas.create_line(10, 800, 900, 800, fill="black", arrow=LAST) # X-Axis x_axisText = Label(self.master, text="x") x_axisText.place(x=900, y=800) y_axisText = Label(self.master, text="y") y_axisText.place(x=15, y=5) def addText(self): """ Adds any needed text to window """ def setCircleCoords(self, point): x1, y1 = 50, 650 x2, y2 = 150, 750 if(point == 'x1'): return x1 if(point == 'y1'): return y1 if(point == 'x2'): return x2 if(point == 'y2'): return y2 def drawCircle(self): """ Draws circle is in a fixed location. # oval (x1, y1, x2, y2) # x1, y1 : Top left of oval # x1, y2 : Bottom right of oval """ self.my_canvas.create_oval( self.setCircleCoords('x1'), self.setCircleCoords('y1'), self.setCircleCoords('x2'), self.setCircleCoords('y2')) def getChargePoints(self, xPos, yPos): """ Gets the charge points from CircleProblem :See CircleProblem: :param xPos: X coordnate of charge point :param yPos: Y coordnate of charge point :return: The location of each charge point """ x = xPos y = yPos def checkChargePoints(xPos,yPos): """ Check to see if the charge points are on the circle, by taking points form setCircleCoords() and comparing them to the points set up already. To check if points are on circle set up loop to go through points to check if they are on the circle or not. Equation for circle: (x-h)^2 + (y-k)^2 = r^2 tkinter makes a square at the top left of the coordinates and constructs a circle inside the square. :return: x,y points: if the points are on the circle print don look good: if points are not on the circle """ check = False x = xPos # x coordinate y = yPos # y coordinate h = 1/2 * x # center x coordinate k = 1/2 * y # center y coordinate r = m.sqrt((x-h)**2 + (y-k)**2) if(x == 0): check = True return check if(checkChargePoints(xPos, yPos) == True): print("Check Pass") return x , y else: print("Check Fail") def drawChargePoints(self): """ Draws the Charge Point at coordinates from getChargePoints Points drawn are small filled ovals ToDo: set points based on getChargePoint() :return: Draws points at the location of the Charge Points """ # points to draw x1,y1 = 100, 100 x2,y2 = x1 + 5 , y1 + 5 # Test points for charge self.my_canvas.create_oval(x1,y1,x2,y2, fill="red") self.my_canvas.create_oval(47, 700, 52, 705, fill="red") # Take x1, y1 (spot on circle) # and add 5 to it for x2,y2. def getTestPoint(self): """ Gets the Test points from the CircleProblem class :return: Test point """ def drawTestPoint(self): """ Draws the test point given coordinates from getTestPoint Points are small ovals :return: Draws small oval for test point. """ self.my_canvas.create_oval(300, 300, 305, 305, fill="blue") display = Drawing() # display whats on the screen (main loop)
0f12223e1f3599189b541cb720a731e0695bcdf0
Birtab18/Verkefni
/verk6/verk6.2.py
99
3.8125
4
s = input("Input a string: ") first_three = (s[0:3]) s = (s[3:]) s = s + first_three print(s)
86ebf80f6b0e59b0247f670926efdd884b9eadfa
anilgeorge04/learn-ds
/datacamp/containers/namedtuple.py
778
3.84375
4
# Import namedtuple from collections from collections import namedtuple # Create the namedtuple: DateDetails DateDetails = namedtuple('DateDetails', ['date', 'stop', 'riders']) # Create the empty list: labeled_entries labeled_entries = [] # Iterate over the entries list for date, stop, riders in entries: # Append a new DateDetails namedtuple instance for each entry to labeled_entries labeled_entries.append(DateDetails(date, stop, riders)) # Print the first 5 items in labeled_entries print(labeled_entries[:5]) # Iterate over the first twenty items in labeled_entries for item in labeled_entries[:20]: # Print each item's stop print(item.stop) # Print each item's date print(item.date) # Print each item's riders print(item.riders)
373ec2563a9df9ac68f46044667f82c6f3c14d8b
macantivbl/Python
/Ejemplos/iterables_diccionarios.py
199
3.84375
4
user = { 'nombre': 'Golem', 'edad': 27, 'puede_nadar': False } for key, value in user.items(): print(key, value) for item in user.values(): print(item) for item in user.keys(): print(item)
4352569de062e47860b58b00eabc74fa9c280513
nurshahjalal/python_exercise
/lambda_map_filter_reduce/lambda.py
549
4.125
4
# A lambda_map_filter_reduce function is a small anonymous function. # A lambda_map_filter_reduce function can take any number of arguments, but can only have one expression. # The expression is evaluated and returned. Lambda functions can be used wherever function objects are required. #regular function def double(x): return x*2 # same thing can be achieved using lambda_map_filter_reduce function val = lambda x: 2 * x add = lambda x, y: x+y max = lambda x, y: x if x> y else y print(val(3)) print(add(3, 7)) print(max(1000, 90000))
f4be2e488fbc8b9d06320c5dd70e9be8e30518d9
nilearn/nilearn
/examples/02_decoding/plot_haxby_glm_decoding.py
5,979
3.84375
4
""" Decoding of a dataset after GLM fit for signal extraction ========================================================= Full step-by-step example of fitting a GLM to perform a decoding experiment. We use the data from one subject of the Haxby dataset. More specifically: 1. Download the Haxby dataset. 2. Extract the information to generate a glm representing the blocks of stimuli. 3. Analyze the decoding performance using a classifier. """ ############################################################################## # Fetch example Haxby dataset # --------------------------- # We download the Haxby dataset # This is a study of visual object category representation # By default 2nd subject will be fetched import numpy as np import pandas as pd from nilearn import datasets haxby_dataset = datasets.fetch_haxby() # repetition has to be known TR = 2.5 ############################################################################## # Load the behavioral data # ------------------------ # Load target information as string and give a numerical identifier to each behavioral = pd.read_csv(haxby_dataset.session_target[0], sep=" ") conditions = behavioral["labels"].values # Record these as an array of sessions sessions = behavioral["chunks"].values unique_sessions = behavioral["chunks"].unique() # fMRI data: a unique file for each session func_filename = haxby_dataset.func[0] ############################################################################## # Build a proper event structure for each session # ----------------------------------------------- events = {} # events will take the form of a dictionary of Dataframes, one per session for session in unique_sessions: # get the condition label per session conditions_session = conditions[sessions == session] # get the number of scans per session, then the corresponding # vector of frame times n_scans = len(conditions_session) frame_times = TR * np.arange(n_scans) # each event last the full TR duration = TR * np.ones(n_scans) # Define the events object events_ = pd.DataFrame( { "onset": frame_times, "trial_type": conditions_session, "duration": duration, } ) # remove the rest condition and insert into the dictionary events[session] = events_[events_.trial_type != "rest"] ############################################################################## # Instantiate and run FirstLevelModel # ----------------------------------- # # We generate a list of z-maps together with their session and condition index z_maps = [] conditions_label = [] session_label = [] # Instantiate the glm from nilearn.glm.first_level import FirstLevelModel glm = FirstLevelModel( t_r=TR, mask_img=haxby_dataset.mask, high_pass=0.008, smoothing_fwhm=4, memory="nilearn_cache", ) ############################################################################## # Run the glm on data from each session # ------------------------------------- events[session].trial_type.unique() from nilearn.image import index_img for session in unique_sessions: # grab the fmri data for that particular session fmri_session = index_img(func_filename, sessions == session) # fit the glm glm.fit(fmri_session, events=events[session]) # set up contrasts: one per condition conditions = events[session].trial_type.unique() for condition_ in conditions: z_maps.append(glm.compute_contrast(condition_)) conditions_label.append(condition_) session_label.append(session) ############################################################################## # Generating a report # ------------------- # Since we have already computed the FirstLevelModel # and have the contrast, we can quickly create a summary report. from nilearn.image import mean_img from nilearn.reporting import make_glm_report mean_img_ = mean_img(func_filename) report = make_glm_report( glm, contrasts=conditions, bg_img=mean_img_, ) report # This report can be viewed in a notebook ############################################################################## # In a jupyter notebook, the report will be automatically inserted, as above. # We have several other ways to access the report: # report.save_as_html('report.html') # report.open_in_browser() ############################################################################## # Build the decoding pipeline # --------------------------- # To define the decoding pipeline we use Decoder object, we choose : # # * a prediction model, here a Support Vector Classifier, with a linear # kernel # # * the mask to use, here a ventral temporal ROI in the visual cortex # # * although it usually helps to decode better, z-maps time series don't # need to be rescaled to a 0 mean, variance of 1 so we use # standardize=False. # # * we use univariate feature selection to reduce the dimension of the # problem keeping only 5% of voxels which are most informative. # # * a cross-validation scheme, here we use LeaveOneGroupOut # cross-validation on the sessions which corresponds to a # leave-one-session-out # # We fit directly this pipeline on the Niimgs outputs of the GLM, with # corresponding conditions labels and session labels # (for the cross validation). from sklearn.model_selection import LeaveOneGroupOut from nilearn.decoding import Decoder decoder = Decoder( estimator="svc", mask=haxby_dataset.mask, standardize=False, screening_percentile=5, cv=LeaveOneGroupOut(), ) decoder.fit(z_maps, conditions_label, groups=session_label) # Return the corresponding mean prediction accuracy compared to chance classification_accuracy = np.mean(list(decoder.cv_scores_.values())) chance_level = 1.0 / len(np.unique(conditions)) print( f"Classification accuracy: {classification_accuracy:.4f} / " f"Chance level: {chance_level}" )
4092b891485ab6ce925c4e39d608da427af9c159
lilyandcy/python3
/leetcode/removeNthFromEnd.py
586
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ cur = head arr = [] while cur != None: arr.append(cur.val) cur = cur.next arr.pop(-n) head = head.next cur = head for i in range(len(arr)): cur.val = arr[i] cur = cur.next return head
76c478bd69b0bf29184502df171c59e51288bc09
DigitalSlideArchive/HistomicsTK
/histomicstk/segmentation/rag_color.py
2,295
3.546875
4
import numpy as np def rag_color(adj_mat): """Generates a coloring of an adjacency graph using the sequential coloring algorithm. Used to bin regions from a label image into a small number of independent groups that can be processed separately with algorithms like multi-label graph cuts or individual active contours. The rationale is to color adjacent objects with distinct colors so that their contours can be co-evolved. Parameters ---------- adj_mat : array_like A binary matrix of size N x N, where N is the number of objects in Label. A value of 'True' at adj_mat(i,j) indicates that objects 'i' and 'j' are neighbors. Does not contain entries for background objects. Returns ------- Colors : array_like A list of colors for the objects encoded in 'adj_mat'. No two objects that are connected in 'adj_mat' will share the same color. See Also -------- histomicstk.segmentation.rag, histomicstk.segmentation.rag_add_layer """ # initialize colors and color count Colors = np.zeros((adj_mat.shape[0], 1), dtype=int) Colors[0] = 1 ColorCount = 1 # iterate over remaining nodes in order, finding legal coloring for i in range(1, adj_mat.shape[0]): # get indices neighbors of node 'i' Neighbors = np.nonzero(adj_mat[i, ])[0].flatten() if Neighbors.size > 0: # get colors of neighbors NeighborColors = Colors[Neighbors] NeighborColors = NeighborColors[np.nonzero(NeighborColors)] # check if neighbors have been labeled if NeighborColors.size > 0: # find lowest legal color of node 'i' Reference = set(range(1, ColorCount + 1)) Diff = Reference.difference(set(NeighborColors)) if len(Diff) == 0: ColorCount += 1 Colors[i] = ColorCount else: Colors[i] = min(Diff) else: # no other neighbors have been labeled yet - set value = 1 Colors[i] = 1 else: # object is an island - no neighbors # set to base color Colors[i] = 1 return Colors.flatten()
01b3414b0422ed14788d7f1b4eea211b6f397c2a
vinay01joshi/python-learning
/PlayGround/DataStructure/arrays.py
129
3.515625
4
from array import array numbers = array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) numbers.append(44) numbers[0] = 1.0 print(numbers)
87b409b429e0201b90cef0e38a1b1017cfe94431
aabhishek-chaurasia-au17/MyCoding_Challenge
/coding-challenges/week15/day05/Q.1.py
1,542
3.578125
4
""" Q-1 ) Gas station (Google interview problem) https://leetcode.com/problems/gas-station/ (5 marks) (Medium) There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique Example 1: Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] Output: 3 Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. """ class Solution: def canCompleteCircuit(self, gas, cost) -> int: if (sum(gas) - sum(cost) < 0): return -1 gas_tank, start_index = 0, 0 for i in range(len(gas)): gas_tank += gas[i] - cost[i] if gas_tank < 0: start_index = i+1 gas_tank = 0 return start_index
5b5ea808baf9b8dd0661370b9afe577969fdc31f
vigneshpr/sample
/single_list.py
2,902
3.765625
4
'''Here I make use of LIST for implementation.Here the address be the index values and the value be the actual data''' import time base_ls=[1,2,3,4,5,6] def dis(): if(len(base_ls)==0): print("Empty Linked_list") proceed() else: print("Display Linked_list") for i in range(len(base_ls)): print("Key-->",i,"Value-->",base_ls[i]) #time.sleep(2) proceed() def inser(): print("---------------------------------------------------------------------------") print("Select Your Option:\n---------------------------------------------------------------------------") print("1.Insert at begin.|\t2.Insert at Last.|\t3.Insert in Between.\n---------------------------------------------------------------------------") sam=int(raw_input("Enter your option:")) if(sam==1): a=input("Enter the Value to insert:") print("Before Insert:",base_ls) base_ls.insert(0,a) print("After Insert:",(base_ls)) proceed() elif(sam==2): a=input("Enter the Value to insert:") print("Before Insert:",base_ls) base_ls.append(a) print("After Insert:",(base_ls)) proceed() elif(sam==3): print(base_ls) b=input("Enter the position to insert:") a=input("Enter the Value to insert:") print("Before Insert:",base_ls) base_ls.insert(b,a) print("After Insert:",(base_ls)) proceed() else: print("Invalid Option") proceed() def rem(): print("---------------------------------------------------------------------------") print("Select Your Option:\n---------------------------------------------------------------------------") print("1.Delete at begin.|\t2.Delete at Last.|\t3.Delete in Between.\n---------------------------------------------------------------------------") sam=int(raw_input("Enter your option:")) if(sam==1): print("Before Insert:",base_ls) base_ls.pop(0) print("After Insert:",(base_ls)) proceed() elif(sam==2): print("Before Delete:",base_ls) base_ls.pop() print("After Delete:",(base_ls)) proceed() elif(sam==3): print(dis()) a=input("Enter the Key_value Value to Delete:") print("Before Delete:",base_ls) base_ls.pop(a) print("After Delete:",base_ls) proceed() else: print("Invalid Option") proceed() def disp(): print("-------------------------Single Linked List--------------------------------") print("Select Your Option:\n---------------------------------------------------------------------------") print("1.Display List.|\t2.Insertion Operation.|\t3.Deletion Operation.\n---------------------------------------------------------------------------") opt=int(input("Enter a Option:")) if(opt==1): dis() elif(opt==2): inser() elif(opt==3): rem() else: print("Invalid Option") proceed() def proceed(): try: st=str(input("Want to Continue (y or n):")) if((st=='y') | (st=='Y')): disp() else: print("\nExiting!!!!!!!!\n") exit() except: proceed() disp()
029c30b9757f8fe26e606746e4bed4e37fe1775e
MickRoche/Data-Processing
/Homework/Scraping/tvscraper.py
3,942
3.828125
4
#!/usr/bin/env python # Name: Mick Roché # Student number: 10739416 """ This script scrapes IMDB and outputs a CSV file with highest rated tv series. """ import csv from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup from urllib.request import urlopen import re TARGET_URL = "http://www.imdb.com/search/title?num_votes=5000,&sort=user_rating,desc&start=1&title_type=tv_series" BACKUP_HTML = 'tvseries.html' OUTPUT_CSV = 'tvseries.csv' def extract_tvseries(dom): """ Extract a list of highest rated TV series from DOM (of IMDB page). Each TV series entry should contain the following fields: - TV Title - Rating - Genres (comma separated if more than one) - Actors/actresses (comma separated if more than one) - Runtime (only a number!) """ # opening the url, offload it to variable Client = urlopen(TARGET_URL) page_html = Client.read() Client.close() # parse the html page_soup = BeautifulSoup(page_html, "html.parser") # get each serie items = page_soup.findAll("div",{"class":"lister-item-content"}) # loop for every item on page tvseries = [] for item in items: # get title title = item.a.text # get rating rating = item.strong.text # get genres genre = item.find("span",{"class":"genre"}).text.strip() # get actors actor_html = item.findAll("a", href=re.compile("name")) actors = [] # iterate over different actors in html for actor in actor_html: actor_names = actor.text actors.append(actor_names) actors = ", ".join(actors) # get runtime runtime = item.find("span",{"class":"runtime"}).text.strip(' min') # append to series tvseries.append((title, rating, genre, actors, runtime)) return tvseries def save_csv(outfile, tvseries): """ Output a CSV file containing highest rated TV-series. """ writer = csv.writer(outfile) writer.writerow(['Title', 'Rating', 'Genre', 'Actors', 'Runtime']) # use extract_tvseries to get all the info extract_tvseries(dom) # iterate over each item and write for title, rating, genre, actors, runtime in tvseries: writer.writerow([title, rating, genre, actors, runtime]) def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None """ try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: print('The following error occurred during HTTP GET request to {0} : {1}'.format(url, str(e))) return None def is_good_response(resp): """ Returns true if the response seems to be HTML, false otherwise """ content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1) if __name__ == "__main__": # get HTML content at target URL html = simple_get(TARGET_URL) # save a copy to disk in the current directory, this serves as an backup # of the original HTML, will be used in grading. with open(BACKUP_HTML, 'wb') as f: f.write(html) # parse the HTML file into a DOM representation dom = BeautifulSoup(html, 'html.parser') # extract the tv series (using the function you implemented) tvseries = extract_tvseries(dom) # write the CSV file to disk (including a header) with open(OUTPUT_CSV, 'w', newline='') as output_file: save_csv(output_file, tvseries)
84c04e89ce8de7303630243259dcb4cb3d16e0b5
LMaunish23/Rock-Paper-Scissor-Lizard-Spock
/rpsls.py
3,365
4.21875
4
#A game on Rock Paper Scissors Lizard Spock (by Sam Kass and Karen Bryla) which was featured #in The Big Bang Theory. Here the game-play is against Sheldon (the characeter from #The Big Bang Theory). Good Luck playing against him! #!/usr/bin/python -tt """Keywords are used instead of whole Name of elements, so that the user does not have to enter the whole name each time. Rules of the game are displayed at the beginning of the game.""" from random import choice def game(): """This is the game function which is the core of this game. Has a dictionary of the keywords for Rock Paper Scissors Lizard Spock, the machine randomly chooses one value from a list of the 5 elements, and compares it with the user's choice. If any of the two players reaches 5 points, ie. by winning 5 times, the game will end. One win = One Point.""" name = input('\n\nHey, whats your name? \n>') n=1 while n == 1: print ('\n(Ro)ck (Sc)issor (Pa)per (Li)zard (Sp)ock') win = 0 lose = 0 while win<3 and lose<3: usr = input('\n>') usr = usr.lower() if usr=='ro' or usr=='li' or usr=='pa' or usr=='sp' or usr=='sc': dic = {'ro':'li','sc':'pa','pa':'ro','li':'sp','sp':'sc','sc':'li','li':'pa','pa':'sp','sp':'ro','ro':'sc'} lst = ['ro','pa','sc','li','sp'] pc = choice(lst) if usr==pc: print ('Its a Tie!') else: if dic[usr] == pc: print ('You WIN with',getname(usr)) print ('Sheldon chose',getname(pc)) win += 1 else: print ('You LOSE with',getname(usr)) print ('Sheldon chose',getname(pc)) lose += 1 print (name,'has points : '+str(win)) print ('Sheldon has points : '+str(lose)) else: print ('Entered something strange! Better be good at signs next time.') if win>lose: print ('\n\n*****',name, 'is the winner! *****\n\n') else: print ('\n\n>>>>> Sheldon Wins!!! <<<<<\n\n') ch = input('\nWant to play again? Press (Y)es to continue, or any other key to exit \n>') if ch=='y' or ch=='Y' or ch=='yes' or ch=='YES': n=1 else: n=0 def getname(a): """This is the getname function which will take one keyword among the 5 as input and accordingly display the Name of that keyword.""" if a=='ro': return 'Rock' elif a=='li': return 'Lizard' elif a=='pa': return 'Paper' elif a=='sp': return 'Spock' elif a=='sc': return 'Scissors' else: return 'Eh, whattay?' def main(): """This is the main function of the game which displays the rules of the game and further calls the game function to start the game.""" print ('Scissors cut Paper') print ('Rock crushes Lizard') print ('Paper covers Rock') print ('Lizard poisons Spock') print ('Spock smashes Scissors') print ('Scissors decapitate lizard') print ('Lizard eats Paper') print ('Paper disproves Spock') print ('Spock vaporizes Rock') print ('Rock breaks Scissors') game() if __name__ == '__main__': main()
fc69197a1680a9678f113fda8f32615ad9d50e64
bharathtintitn/HackerRankProblems
/HackerRankProblems/soduko.py
2,494
3.703125
4
import pdb class Solution(object): def isValidSudoku(self, board): self.board = board self.queue = [] self.getAllIndex() self.numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] print "Final:", self.board return self.gosudoku(0) def getAllIndex(self): for i in xrange(9): for j in xrange(9): if self.board[i][j] <> '.': self.queue.append((i,j)) print "queue:", self.queue, " length:", len(self.queue) def isValidNumber(self, index, number): row, col = index[0], index[1] for i in xrange(9): if (self.board[row][i] == number and i <> col) \ or (self.board[i][col] == number and i <> row): return False r1, r2 = None, None if 0 <= index[0] <= 2: r1, r2 = 0, 3 elif 3 <= index[0] <= 5: r1, r2 = 3, 6 else: r1, r2 = 6, 9 c1, c2 = None, None if 0 <= index[1] <= 2: c1, c2 = 0, 3 elif 3 <= index[1] <= 5: c1, c2 = 3, 6 else: c1, c2 = 6, 9 for i in xrange(r1, r2): for j in xrange(c1, c2): if self.board[i][j] == number and (i <> row and j <> col): return False return True def gosudoku(self, index): if index > len(self.queue)-1: return True pos = self.queue[index] #print "pos:", pos i, j = pos[0], pos[1] num = self.board[i][j] #pdb.set_trace() if self.isValidNumber(pos, num): ret = self.gosudoku(index+1) if ret: return ret return False a = Solution() print a.isValidSudoku([ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ]) print a.isValidSudoku([ ["8","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ])
0bf7565b6aa7c5d64a490da5742b798b3b3b2f9b
vishrutkmr7/DailyPracticeProblemsDIP
/2022/12 December/db12042022.py
816
4.09375
4
""" Given a string, s, that represents a Roman numeral, return its associated integer value. Note: You may assume that each string represents a valid Roman numeral and its value will not exceed one thousand. Ex: Given the following string s... s = "DCLII", return 652. Ex: Given the following string s... s = "VIII", return 8. """ class Solution: def romanToInt(self, s: str) -> int: roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} return sum( roman[s[i]] - 2 * roman[s[i - 1]] if i > 0 and roman[s[i]] > roman[s[i - 1]] else roman[s[i]] for i in range(len(s)) ) # Test Cases if __name__ == "__main__": solution = Solution() print(solution.romanToInt("DCLII")) print(solution.romanToInt("VIII"))
31df1e543fc7506322c31412765b39a9761fc72f
CelsoUliana/Introduction-to-Algorithms
/2/2.1 Insertion Sort/2.1-4.py
531
3.625
4
# Celso Uliana -- Jan 2021 # Linear binary array add python 3 A = [1, 1, 1, 1, 0, 0] # 60 B = [1, 0, 1, 0, 0, 1] # 41 def binaryAdd(A, B): # Initialize n + 1 bit array C = [0 for i in range(len(A) + 1)] carryOver = 0 # Reverse iterate it with carry over for i in reversed(range(len(A) + 1)): j = i - 1 C[i] = A[j] + B[j] + carryOver carryOver = 0 if C[i] > 1: C[i] -= 2 carryOver = 1 C[0] = carryOver return C print(binaryAdd(A, B))
d7e0f1163860935b988ea45cae130300a471dd18
maodunzhe/clean_code
/backtracking/N-Queens.py
914
3.5625
4
''' if wanna change certain character in string: 1st way: test = 'abcd' new = list(test) new[2] = 'Q' ''.join(new) 2rd way: test = 'abc' test = test[:2] + 'Q' + test[3:] ''' class Solution(object): def solveNQueens(self, n): res = [] options = [] for i in range(n): ## string is not mutable in python string = '.' * i + 'Q' + '.' * (n - i - 1) options.append(string) self.solveNQueensHelper(n, res, options, [], range(n)) return res def solveNQueensHelper(self, n, res, options, valueList, leftList): if len(valueList) == n: res.append([options[i] for i in valueList]) else: num = len(valueList) for j in range(len(leftList)): flag = 0 for m in range(len(valueList)): if abs(leftList[j] - valueList[m]) == abs(num - m): flag = 1 if flag == 0: self.solveNQueensHelper(n, res, options, valueList + [leftList[j]], leftList[:j] + leftList[j + 1:])
664586415b303d5dd3daac7cfed1f59e84792499
Judice/iterator_nest
/Fibonacci.py
1,343
3.578125
4
# coding=utf-8 """ 斐波那契数列 """ #for循环生成斐波那契数列 def fibs(n): a, b = 0, 1 for i in range(0,n): f = a a, b =b, a+b print f #递归函数生成斐波那契数列 def fibs(n): if n < 2: return n else: return(fibs(n-1) + fibs(n-2)) def run(items): for i in range(items): print(fibs(i)) #生成一组数列 #或者生成第n个斐波那契数列 def fibs(n): a = [0, 1] if n < 2: return a[n] else: for i in range(2, n+1): a.append(a[i-2]+a[i-1]) return a[n] #生成第n个菲波那切数 #迭代器生成斐波那契数列 class Fibs(): def __init__(self): self.a = 0 self.b = 1 def next(self): f = self.a self.a, self.b = self.b, self.a+self.b return f def __iter__(self): return self #迭代器生成斐波那契数列 class Fab(object): def __init__(self, max): self.max = max self.n, self.a, self.b = 0, 0, 1 def next(self): if self.n < self.max: r = self.b self.a, self.b = self.b, self.a + self.b self.n = self.n + 1 return r raise StopIteration() def __iter__(self): return self
9b78b5c4879e276aafcbfc47cfc9539a6757fcf4
hiroaki-yamamoto/tensorflow-demo
/mnist_keras.py
3,170
3.546875
4
#!/usr/bin/env python # coding=utf-8 """Mnist CNN based on keras' example.""" from keras.datasets import mnist as input_data from keras import backend as K from keras.models import Sequential from keras.layers import ( Dense, Dropout, Activation, Flatten, Convolution2D, MaxPooling2D ) from keras.utils import np_utils nb_classes = 10 # That is the number of integers from 0 to 9 = 10 nb_epoch = 12 # Number of times to learn and refresh the network. # For number of filters # The filter should be larger than the actual image size, and needs to put # multiple filters at different position. # In general, # of filters is power of 2. nb_filters = 64 # Number of Convolution filter i.e. # of neurons? (width, height) = (28, 28) # The size of the image i.e. 28 px x 28 px # For Pool size # poo_size should be defined as coeff. i.e. Pool Layer compress the image by # re-sizing the output. Therefore, (Size of the layer) / (poo_size) is the # result of the pool layer. pool_size = (2, 2) # Pooling co-eff. kernel_size = (3, 3) # The size of the filter. i.e. 3 px x 3 px. batch_size = 128 # Load MNIST data (X_train, y_train), (X_test, y_test) = input_data.load_data() if K.image_dim_ordering() == 'th': # Perhaps, theano handles the data differently. X_train = X_train.reshape(X_train.shape[0], 1, height, width) X_test = X_test.reshape(X_test.shape[0], 1, height, width) input_shape = (1, height, width) else: X_train = X_train.reshape(X_train.shape[0], height, width, 1) X_test = X_test.reshape(X_test.shape[0], height, width, 1) input_shape = (height, width, 1) # Treat the data as float, and standardlize between 0.0 to 1.0. X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) model = Sequential() model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='valid', input_shape=input_shape)) model.add(Activation('relu')) model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1])) # model.add(Activation('relu')) model.add(Dropout(0.25)) model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1])) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=pool_size)) # model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128)) # model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, Y_test)) score = model.evaluate(X_test, Y_test, verbose=0) print('Test score:', score[0]) print('Test accuracy:', score[1]) model.save("mnist_cnn.h5") print('The model data has been saved: mnist_cnn.h5')
4ce5d23ec1bebd5ec3f89ce336d6b9405c8205fd
LoftyCloud/py_games
/snack/snake01.py
1,460
3.765625
4
import tkinter as tk R = 50 C = 50 cell_size = 10 win = tk.Tk() canvas = tk.Canvas(win, width=C * cell_size, height=R * cell_size) snack_list = [(0, 0), (1, 0), (2, 0)] snack_color = "green" food_color = "red" def draw_single_cell(canvas, c, r, color="black"): """ draw black cell with white edge :param canvas: :param c: :param r: cell's location :param color: cell's color, default is black :return: """ x0 = c * cell_size y0 = r * cell_size x1 = x0 + cell_size y1 = y0 + cell_size canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=1) def draw_broad(canvas): """ draw background :param canvas:canvas :return: """ for ri in range(R): for ci in range(C): draw_single_cell(canvas, ci, ri) def draw_snack(canvas, snack_list): """ draw the snack by snack_list :param canvas: :param snack_list: record the every cell's position :return: """ for cell in snack_list: cell_c, cell_r = cell draw_single_cell(canvas, cell_c, cell_r, snack_color) def draw_food(canvas): food = (4, 0) food_c, food_r = food draw_single_cell(canvas, food_c, food_r, food_color) def main(): canvas.pack() # put the canvas into win draw_broad(canvas) draw_snack(canvas, snack_list) draw_food(canvas) win.title("snack") win.mainloop() if __name__ == '__main__': main()
e763b24ccea8962a80ebd5ba41fa72a4b297c7fd
Stepancherro/Algorithm
/two_array_median.py
817
3.75
4
# -*- encoding: utf-8 -*- import math # 中位数索引 def median_index(n): if n % 2: # 奇数情况 return n // 2 else: # 偶数情况 return n // 2 - 1 def two_array_median(X, Y): n = len(X) if n == 1: # 如果数组只有一个元素,则取两者最小的为中位数 return min(X[0], Y[0]) m = median_index(n) # 计算每个数组的中位数索引 if X[m] == Y[m]: # 如果两个中位数相等,那么新的中位数也是该数 return X[m] if X[m] < Y[m]: # 此时整体的中位数应该在X的后半部分或者Y的前半部分 return two_array_median(X[-(m + 1):], Y[: m + 1]) else: return two_array_median(X[: m + 1], Y[-(m + 1):]) A = [1, 2, 3, 4, 5, 6] B = [5, 6, 7, 8, 9, 10] print(two_array_median(A, B))
2a739fd5741ada08166eb9761dc0983c80a16b45
Jeroen-dH/collections
/mm.py
300
3.75
4
# print(random.randint(3, 9)) import random kleuren = ['oranje', 'blauw', 'groen', 'bruin'] global aantal aantal = input("hoeveel m&m's wil je: ") def zakie(aantal): zak = [] for a in range(int(aantal)): zak.append(random.choice(kleuren)) return zak print(sorted(zakie(aantal)))
b87dc73d86d909ff2dde32912fb8d7fa90d3ad3c
tuseto/PythonHomework
/week6/1-List-Functions/list_functions.py
915
3.5
4
def head(arr): return(arr[0]) def last(arr): return(arr[len(arr)-1]) def tail(arr): new_arr = [] for i in range(1,len(arr)): new_arr += [arr[i]] return(new_arr) def equal_lists(arr1,arr2): if len(arr1) == len(arr2): for i in range(0,len(arr1)): if arr1[i] != arr2[i]: return False else: return False return True def count_item(element,arr): counter = 0 for el in arr: if element == el: counter += 1 return (counter) def take(number,arr): new_arr = [] for i in range(0,min(number,len(arr))): new_arr += [arr[i]] return (new_arr) def drop(number,arr): new_arr = [] for i in range(number,len(arr)): new_arr += [arr[i]] return(new_arr) def reverse(arr): rev_arr = [] for i in range(len(arr)-1,-1,-1): rev_arr += [arr[i]] return(rev_arr)
f70a0260743e6483810ec3aa7e02b445285678c2
bouxtehouve/iTarot
/paquet.py
2,107
3.609375
4
# gestion du paquet en terme de regles du jeu (et pas de donne) import random,copy # Cette classe permet de creer un paquet de cartes melangees aleatoirement et de distribuer les cartes aux joueurs. from cartes import carte class paquet: # faire ici la comparaison ?? car la creation des cartes se fait ici def __init__(self): self.liste_cartes=None self.creation_cartes() self.chien=None def creation_cartes(self): couleurs=["excuse","atout","trefle","pique","carreau","coeur"] rangs=["as","2","3","4","5","6","7","8","9","10","valet","cavalier","dame","roi"] liste_cartes=[] for i in couleurs: if i=="atout": for j in xrange(1,22): liste_cartes.append(carte(i,str(j))) else: if i=="excuse": liste_cartes.append(carte(i,"")) else: for j in rangs: liste_cartes.append(carte(i,j)) self.liste_cartes=liste_cartes def distribution_paquet(self,joueurs): #Initialise les mains des joueurs, et le chien. A faire une fois qu'on a les joueurs. distrib=copy.copy(self.liste_cartes) random.shuffle(distrib) # fonction python qui effectue une permutation aleatoire des cartes = melanger les cartes i_chien=random.randint(0,75) self.chien=distrib[i_chien:i_chien+3] # pour plus de simplicite, on met 3 cartes des le debut de la distribution dans le chien distrib=distrib[0:i_chien] + distrib[i_chien+3:78] #le jeu moins le chien est distribue for i in xrange(0,5): joueurs[i].main.extend(distrib[15*i:15*i +15]) joueurs[i].tri_main() ''''p=paquet() def permutations(ensemble): #l'ensemble est une liste d'objects n=len(ensemble) if n<=1: yield ensemble else: for p in permutations(ensemble[1:]): for i in xrange(0,n): yield p[:i]+ensemble[0:1]+p[i:n] lis=list(permutations(p.liste_cartes)) for i in xrange(0,10): print lis[i] #print p.liste_cartes[21] class noeud: def __init__(self): self.children = [] self.parent = None def addChild(self, child) self.children.append(child) child.parent = self '''
8c9df66bf6f6d7cb7125ca18b38d38c59c41c952
fndhnf/gaih-students-repo-example
/Homeworks/HW1.py
701
3.953125
4
#Explain your work ##### nums = list(range(100)) #a=100 dersek evenlist = [] oddlist = [] # odds = [i for i in numbers if i%2!=0] alternatif olabilirdi for x in nums: # bu formatta istendigini dusundugumden, buradan devam ediyorum if (x % 2 == 0) : #2ye kalansız bolunuyorsa cıfttir evenlist.append(x) if (x % 2 != 0) : #else de kullanılabilirdi oddlist.append(x) print(evenlist) print(oddlist) ##### mergedlist2 = [] mergedlist = evenlist + oddlist #listeleri birleştirme aşaması mergedlist2 = [i*2 for i in mergedlist] #herbir indexi 2 ile carpma print(mergedlist2) ###### for j in range (0, len(mergedlist2)): print (j, "th item' data type is:", type(mergedlist2[j]))
6fc368947b70134a612c6fb986d8cf4800d91344
japark/PythonWebScraper
/Basics/basics_for_beginners.py
1,697
3.609375
4
from urllib.request import urlopen from urllib.error import HTTPError, URLError from bs4 import BeautifulSoup ''' *** NOTE *** 1) urlopen 함수 ㄴ GET 요청으로 https://www.example.com 의 HTML 코드 가져오기 2) BeautifulSoup 객체 ㄴ BeautifulSoup 객체에서 특정 태그를 골라내기 3) 예외처리 1 ㄴ 페이지를 찾을 수 없거나 URL 해석에서 에러가 생긴 경우 : HTTPError ㄴ 서버를 찾을 수 없는 경우 : URLError 4) 예외처리 2 ㄴ None 객체에서 속성을 호출하려 할 때 : AttributeError ''' url = 'https://www.example.com' print() ## 1) html = urlopen(url) print(html.read()) print('\n' + '='*100 + '\n') ## 2) html = urlopen(url) bs = BeautifulSoup(html, 'html.parser') # html 대신에 html.read() 도 가능 print(bs.p) # 여러 p 태그 중 첫번째 것을 출력 print('\n' + '='*100 + '\n') ## 3) wrong_url = 'http://www.pythonscraping.com/pages/error.html' # Raises HTTPError # wrong_url = 'http://pythonscrapingthisurldoesnotexist.com' # Raises HTTPError try: html = urlopen(wrong_url) except HTTPError as e: print(e) except URLError as e: print('The server could not be found!') print(e) else: print('It worked!') print('\n' + '='*100 + '\n') ## 4) def getTitle(url): try: html = urlopen(url) except: return None try: bs = BeautifulSoup(html.read(), 'html.parser') title = bs.body.h1 except AttributeError as e: # body 태그가 없거나, 그 밖에 None 객체에서 내부 태그에 접근하려 할 때 print(e) return None return title title = getTitle(url) if title == None: # h1 태그가 없었을 때 print('Title could not be found') else: print(title)
6864cffb99ff8010774fc0d34193798cebcd5a22
candyer/leetcode
/hIndex.py
1,471
4.15625
4
# https://leetcode.com/problems/h-index/description/ # 274. H-Index # Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. # According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, # and the other N - h papers have no more than h citations each." # Example: # Input: citations = [3,0,6,1,5] # Output: 3 # Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had # received 3, 0, 6, 1, 5 citations respectively. # Since the researcher has 3 papers with at least 3 citations each and the remaining # two with no more than 3 citations each, her h-index is 3. # Note: If there are several possible values for h, the maximum one is taken as the h-index. def hIndex(citations): """ :type citations: List[int] :rtype: int """ n = len(citations) citations.sort(reverse=True) if not citations or citations[0] == 0: return 0 for i, c in enumerate(citations): if i >= c: return i return n assert hIndex([3,0,6,1,5]) == 3 assert hIndex([1,2,2,4,5]) == 2 assert hIndex([1,1,5,6]) == 2 assert hIndex([1]) == 1 assert hIndex([200, 300]) == 2 assert hIndex([900, 20, 5, 100]) == 4 assert hIndex([900,900, 900]) == 3 assert hIndex([0, 0, 0, 0]) == 0 assert hIndex([0, 100, 200]) == 2 assert hIndex([]) == 0
44e7abfb1ee7bba5bc0725ea222bc2b3e815902a
AlifsyahRS/Alif-PythonExercises
/dictionary-review/dict_exercise1.py
244
4.09375
4
# Dictionary Exercises Question 1 input_dict = {'hello': 1, 'a': 2, 'world': 'lol'} def removekeys(mydict, keylist): for keyword in keylist: del (mydict[keyword]) return mydict print(removekeys(input_dict, ['hello', 'a']))
d40382f1fabfee8a0dde52a4b3b61d7b4c4d475b
DahrielG/tuitionPreparation
/app/models/model.py
661
3.671875
4
# weeks = (years * 52) + (months * 4) def weeksLeft(gYear, gMonth, cYear, cMonth): years = int(gYear) - int(cYear) months = int(gMonth) - int(cMonth) weeks = (years * 52) + (months * 4) print(weeks) return weeks # weeksLeft() def equation(weeksAmount, tuition): weekly = int(tuition) / int(weeksAmount) weekly = round(weekly, 2) print(weekly) return weekly # print("You need to save " + str(round(weekly, 2)) + " every week.") def neededAid(tuition, weeksleft, contribution): totalContribution = int(weeksleft) * int(contribution) extraMoney = int(tuition) - int(totalContribution) return extraMoney
fe26eb9ae8b9f78920450f84e39182c632970f41
djwen0726/python3-tutorials
/生产者消费者练习1.py
1,265
3.96875
4
import queue import random, threading, time # 生产者类 class Producer(threading.Thread): def __init__(self, name, queue): threading.Thread.__init__(self, name=name) self.data = queue def run(self): for i in range(10): data=random.randint(0,100) print("%s is producing %d to the queue!" % (self.getName(), data)) self.data.put(data) time.sleep(1) print("%s finished!" % self.getName()) # 消费者类 class Consumer(threading.Thread): def __init__(self, name, queue): threading.Thread.__init__(self, name=name) self.data = queue def run(self): for i in range(10): val = self.data.get() print("%s is consuming. %d in the queue is consumed!" % (self.getName(), val)) # time.sleep(random.randrange(10)) print("%s finished!" % self.getName()) #主程序 def main(): global queue queue = queue.Queue() producer = Producer('制造者', queue) consumer = Consumer('消费者', queue) producer.start() consumer.start() producer.join() consumer.join() print('All threads finished!') if __name__ == '__main__': main()
4964769a43a9d98b9b98cc363c1bd187b1587edd
MohammedHassan25/Programming-Foundations-Fundamentals
/chap 05/01_Introduction to functions.py
886
3.953125
4
# ------------------------------------------------------------------------------------- # Function : Block of code packaged together with a name ( ex : print(), input() ) # "def" shortens you many steps and lines # ------------------------------------------------------------------------------------- # for example print("~~~ Mohammed Hassan ~~~") print("My name is Mohammed") print("I am 21 years old") print("I am study in Azhar university") print("~~~ Mohammed Hassan ~~~") print("My name is Mohammed") print("I am 21 years old") print("I am study in Azhar university") print("~~~ Mohammed Hassan ~~~") print("My name is Mohammed") print("I am 21 years old") print("I am study in Azhar university") # better than is def Mohammed(): print("~~~ Mohammed Hassan ~~~") print("My name is Mohammed") print("I am 21 years old") print("I am study in Azhar university") Mohammed() Mohammed() Mohammed()
2883cab45c71d7b3cbcdf254f7b13f0a93302c69
KathrynMorgan/sort
/Python3/Studying/Lesson_1/alphabet_and_numbers.py
982
4.0625
4
#!/usr/bin/env python3 # Make a variable into a multi line string; where does this variable get used? first = ''' Tell me the alphabet! Please please please? What are the first 4? ''' second = ''' But wait, that looks funny!\n\ Can we put them in order?\n\ ''' # We are going to count and play with the alphabet! print(first, '\n c, a, b, d!') # Can we do better? print(second) # Set your base number & echo the value to screen # What happens here when you use the semicolon? # What commentary can you provide on this syntax? c = 1; print('The starting count is:',c) # Now lets keep count and say them in order # Whats the difference between the first, second, and third counter sum syntax? # Do all syntax(es) work? print(c,'= a') c = c + 1 print(c,'= b') c = \ c + 1 print(c,'= c') c = \ c + 1 print(c, '= d') # Remove the "#" from the last line (do not remove the leading space) # Try to run the program, what happens? # Repeat the 4th count! # print(c, '= d')
db1a3143c2cbf6240d2a521430b1cadd693f67cf
frobes/python_learning
/.idea/jichu/names_list.py
103
3.640625
4
#coding=utf-8 names = ['pow','aaab','keh','jack','bob'] for name in names: print name.title()
b055b74ada29a22e192b2c797d717e48c102bac0
cgordoncarroll/dailyProgrammer
/Easy/148/combinationLock.py
750
3.703125
4
#!/usr/bin/python import sys def main(argv): dialSize = int(argv[0]) firstNum = int(argv[1]) secondNum = int(argv[2]) thirdNum = int(argv[3]) totalIncrements = 0 totalIncrements += dialSize*2 #First two full turns totalIncrements += firstNum #Turn to first num #Determine distance for turn 2 secondTurn = (dialSize + firstNum - secondNum) % dialSize if secondTurn == 0: secondTurn = dialSize totalIncrements += secondTurn #Another full rotation totalIncrements += dialSize #Determine distance for turn 3 starting at turn 2 thirdTurn = (thirdNum - secondNum + dialSize) % dialSize if thirdTurn == 0: thirdTurn = dialSize totalIncrements += thirdTurn print totalIncrements if __name__ == "__main__": main(sys.argv[1:])
a63fd46f15494b33e7f4587f2780155ec511c264
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/158_16.py
2,029
4.46875
4
Python | Filter the negative values from given dictionary Given a dictionary, the task is to filter all the negative values from given dictionary. Let’s discuss few methods to do this task. **Method #1: Using dict comprehension** __ __ __ __ __ __ __ # Python code to demonstrate # return the filtered dictionary # on certain criteria from six import iteritems # Initialising dictionary ini_dict = {'a':1, 'b':-2, 'c':-3, 'd':7, 'e':0} # printing initial dictionary print ("initial lists", str(ini_dict)) # filter dictionary such that no value is greater than 0 result = dict((k, v) for k, v in ini_dict.items() if v >= 0) print("resultant dictionary : ", str(result)) --- __ __ **Output:** initial lists {'a': 1, 'c': -3, 'd': 7, 'b': -2, 'e': 0} resultant dictionary : {'a': 1, 'd': 7, 'e': 0} **Method #2: Using lambda and filter** __ __ __ __ __ __ __ # Python code to demonstrate # return the filtered dictionary # on certain criteria from six import iteritems # Initialising dictionary ini_dict = {'a':1, 'b':-2, 'c':-3, 'd':7, 'e':0} # printing initial dictionary print ("initial lists", str(ini_dict)) # filter dictionary such that no value is greater than 0 result = dict(filter(lambda x: x[1] >= 0.0, ini_dict.items())) result = dict(result) print("resultant dictionary : ", str(result)) --- __ __ **Output:** initial lists {'c': -3, 'd': 7, 'e': 0, 'a': 1, 'b': -2} resultant dictionary : {'e': 0, 'a': 1, 'd': 7} Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
e5021fe57391bf5c88313fff80fcf5f8dee7d0aa
golz04/py-cli-basic
/soal3.py
450
3.90625
4
try : x = int(input("Masukkan Angka Pertama :")) y = int(input("Masukkan Angka Kedua :")) if (x == y) : if (x%2 == 0) : print("Hasilnya 0") elif (x%2 == 1) : print("Hasilnya 1") elif (x%2==0 and y%2==1) : hasil = (x*y)+y print("Hasilnya",hasil) elif (x%2==1 and y%2==1) : hasil = x*y print("Hasilnya",hasil) except ValueError : print("Hanya Boleh Angka")
8bb8e72518d7fe554d5412507845719ccaca361c
btrif/Python_dev_repo
/Algorithms/Trees & Search Trees/Binary Search Tree 5.py
4,515
4.125
4
# Created by Bogdan Trif on 15-05-2018 , 5:26 PM. # https://stackoverflow.com/questions/2598437/how-to-implement-a-binary-tree?answertab=votes#tab-top # Here is my simple recursive implementation of binary tree. class Node: def __init__(self, val): self.l = None self.r = None self.v = val class Tree: def __init__(self): self.root = None def getRoot(self): return self.root def add(self, val): if(self.root == None): self.root = Node(val) else: self._add(val, self.root) def _add(self, val, node): if(val < node.v): if(node.l != None): self._add(val, node.l) else: node.l = Node(val) else: if(node.r != None): self._add(val, node.r) else: node.r = Node(val) def find(self, val): if(self.root != None): return self._find(val, self.root) else: return None def _find(self, val, node): if(val == node.v): return node elif(val < node.v and node.l != None): self._find(val, node.l) elif(val > node.v and node.r != None): self._find(val, node.r) def deleteTree(self): # garbage collector will do this for us. self.root = None def printTree(self): if(self.root != None): self._printTree(self.root) def _printTree(self, node): if(node != None): self._printTree(node.l) print (str(node.v) + ' ') self._printTree(node.r) # 3 # 0 4 # 2 8 tree = Tree() tree.add(3) tree.add(4) tree.add(0) tree.add(8) tree.add(2) tree.printTree() print( (tree.find(3)).v) print( tree.find(10)) tree.deleteTree() tree.printTree() #################################### print('\n\n------------------------- METHOD 2 ---------------------------------') # simple binary tree # in this implementation, a node is inserted between an existing node and the root class BinaryTree(): def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self): return self.right def setNodeValue(self,value): self.rootid = value def getNodeValue(self): return self.rootid def insertRight(self,newNode): if self.right == None: self.right = BinaryTree(newNode) else: tree = BinaryTree(newNode) tree.right = self.right self.right = tree def insertLeft(self,newNode): if self.left == None: self.left = BinaryTree(newNode) else: tree = BinaryTree(newNode) tree.left = self.left self.left = tree def printTree(tree): if tree != None: printTree(tree.getLeftChild()) print(tree.getNodeValue()) printTree(tree.getRightChild()) # test tree def testTree(): myTree = BinaryTree("Maud") myTree.insertLeft("Bob") myTree.insertRight("Tony") myTree.insertRight("Steven") printTree(myTree) testTree() #################################### print('\n\n------------------------- METHOD 3 ---------------------------------') # Simple implementation of BST in Python class TreeNode: def __init__(self, value): self.left = None; self.right = None; self.data = value; class Tree: def __init__(self): self.root = None; def addNode(self, node, value): if(node==None): self.root = TreeNode(value); else: if(value<node.data): if(node.left==None): node.left = TreeNode(value) else: self.addNode(node.left, value); else: if(node.right==None): node.right = TreeNode(value) else: self.addNode(node.right, value); def printInorder(self, node): if(node!=None): self.printInorder(node.left) print(node.data) self.printInorder(node.right) def main(): testTree = Tree() testTree.addNode(testTree.root, 200) testTree.addNode(testTree.root, 300) testTree.addNode(testTree.root, 100) testTree.addNode(testTree.root, 30) testTree.printInorder(testTree.root) main()
398929f2a1338cf85a2aa5466c127b236330e9ca
wwylele/chocopy-rs
/chocopy-rs/test/pa2/bad_semantic.py
686
3.65625
4
# Please also refer to other files in student_contributed for more tests x:int = 1 x:int = 2 # global name collision class u(y): # define u before y pass class y(object): z: int = 0 def z(self: y): # member name collision pass def bar(): # missing self pass def foo(self: y, y: int): # shadowing class name pass def baz(self: y, x: x): # x is not a type pass class v(y): def foo(self: v, n: int) -> int: # override with wrong signature return 0 def fooo(self: v, n: int) -> int: if n == 0: return 0 else: print("missing return") y: str = "" # collision with class name
f378ad515abc05ce67ff75a0b024ec26e995bc07
ubercareerprep2021/Uber-Career-Prep-Homework-Gabriel-Silva
/Assignment-3/sorting_algorithms/quick_sort.py
1,074
4.03125
4
def quick_sort(array: list, low: int, high: int): if len(array) == 1: return array if low < high: # index of smaller element partition_index = (low-1) # pivot element as the highest index pivot = array[high] # places smaller than pivot elements to the left and # greater elements to the right for index in range(low, high): # If current element is smaller or equal to pivot if array[index] <= pivot: # increment index of smaller element partition_index = partition_index+1 temp = array[partition_index] array[partition_index] = array[index] array[index] = temp temp = array[partition_index+1] array[partition_index+1] = array[high] array[high] = temp partition_index += 1 # sort elements before and after partition quick_sort(array, low, partition_index-1) quick_sort(array, partition_index+1, high) return array
3840d2a3ad4149dc484ad9ebfeaa4f1fa4b1ae54
jtarlecki/project_euler
/p17.py
1,938
3.53125
4
class NumberToString(object): ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['','','twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] hundred = 'hundred' thousand = 'thousand' def __init__(self, number): self.lim = 1000 self.number = number self.str_list = list(str(number)) self.count = len(self.str_list) self.num_list = [] for s in self.str_list: self.num_list.append(int(s)) def convert(self): if not self.number > self.lim: if self.count == 1: return self.get_ones() if self.count == 2: return self.get_tens() if self.count == 3: return self.get_hundreds() if self.count == 4: return 'onethousand' else: return "please input number less than %d" % self.lim def get_ones(self): return self.ones[self.number] def get_tens(self): t = self.num_list[-2] o = self.num_list[-1] if t == 1: d = self.teens[o] else: d = self.tens[t] + self.ones[o] return d def get_hundreds(self): if self.get_tens() == '': return self.ones[self.num_list[-3]] + self.hundred else: return self.ones[self.num_list[-3]] + self.hundred + 'and' + self.get_tens() lim = 1000 words = [] for i in range(1, lim+1): n = NumberToString(i) words.append(n.convert()) sum_letter_count = 0 c = 1 for word in words: print c, word sum_letter_count += len(word) c+=1 print 'sum_letter_count = ', sum_letter_count
13ad969a12f5844e252d40849b86bf9f79c557f8
jjohn342/GirlsWhoCode
/pseudo.py
206
4.03125
4
ages = [5, 12, 3, 56, 24, 78, 1, 15, 44] # find the sum of list sum = 0 sum = sum(ages) # find the length length = len(ages) average = length / sum # divide length by sum print(average) #print the average
6d8b616ee1879ce062a2e7ec8de149fc4f193939
tacheshun/p1_movie_trailer_website
/entertainment_center.py
993
3.546875
4
import media import fresh_tomatoes #create the objects intantiating the Movie Class. Each object must have the movie title for better reading training_day = media.Movie('Training Day', '2001', 'The story of an undercover police', 'http://upload.wikimedia.org/wikipedia/en/b/b3/Training_Day_Poster.jpg','https://www.youtube.com/watch?v=gKTVQPOH8ZA') matrix = media.Movie('The Matrix', '1999', 'What is the Matrix?', 'http://www.cyber-cinema.com/gallery/MatrixC.jpg', 'https://www.youtube.com/watch?v=m8e-FF8MsqU') avatar = media.Movie('Avatar', '2009', 'On the lush alien world of Pandora live the Na\'vi, beings who appear primitive but are highly evolved.', 'http://th05.deviantart.net/fs71/PRE/f/2010/192/b/e/Avatar_Special_Edition_Poster_by_J_K_K_S.jpg', 'https://www.youtube.com/watch?v=_Tkc5pQp_JE') #create a list storing the favorite movies fav_movies = [training_day, matrix, avatar] #call the open_movies_page from fresh_tomatoes module fresh_tomatoes.open_movies_page(fav_movies)
17b24f580b3f343d3d618ea601f36e4359402d66
qvpiotr/ASD
/Graphs/Bellman-Ford.py
1,190
3.53125
4
#algorytm Bellmana-Forda class vertex: def __init__(self): self.visited = False self.parent = None self.d = float("inf") def neighbour(G,s): neigh = [] for i in range (len(G)): if G[s][i]!=0: neigh.append(i) return neigh def bellman(G,s): verticles = [] for v in range (len(G)): verticles.append(vertex()) verticles[s].d =0 for _ in range (len(G)-1): for u in range (len(G)): for v in neighbour(G,u): if verticles[v].d > verticles[u].d + G[u][v]: verticles[v].d = verticles[u].d + G[u][v] verticles[v].parent = u for u in range(len(G)): for v in neighbour(G,u): if verticles[v].d > verticles[u].d + G[u][v]: print("False") return False return verticles G = [[0,3,0,0,0,0,2,0,0],[3,0,2,1,0,0,0,0,0],[0,2,0,0,5,0,0,0,0],[0,1,0,0,1,7,0,0,0],[0,0,5,1,0,0,0,0,20], [0,0,0,7,0,0,1,1,2],[2,0,0,0,0,1,0,3,0],[0,0,0,0,0,1,3,0,8],[0,0,0,0,20,2,0,7,0]] Gr = [[0,5,0,0,0,0],[0,0,3,0,0,0],[0,0,0,2,0,0],[0,0,0,0,-15,6], [0,1,0,0,0,0],[0,0,0,0,0,0]] bellman(Gr,0)
870ec6a8d13a5a56559a1b5abbec1802d11465bf
tearuka/AoC_2020
/Day09.py
1,055
3.5625
4
#!/usr/bin/env python # coding: utf-8 # read input inp = open("inp/input_09.txt").read().splitlines() inp = [int(line) for line in inp] ### Part 1 def is_sum(data, objective, preamble): counter = 0 for num in data: difference = objective - num if difference not in data: counter += 1 return counter >= preamble def find_number(data, preamble): pos = 0 for number in data[preamble:]: result = is_sum(data[pos : preamble + pos], number, preamble) pos += 1 if result == 1 : return number res1 = find_number(inp, 25) print('Result for part 1: ', res1) # 530627549 ### Part 2 def find_list_sum(data, objective): for pos in range(len(data)): suma = 0 lst = [] while pos < len(data) - 1: suma += data[pos] lst.append(data[pos]) pos = pos + 1 if suma == objective: return min(lst) + max(lst) res2 = find_list_sum(inp, res1) print('Result for part 2: ', res2) # 77730285
65d53a514aecfe0d445e3097fec9a2e32b0f2674
beringresearch/ivis
/ivis/data/generators/triplet_generators.py
8,289
3.5625
4
""" Triplet generators. Functions for creating generators that will yield batches of triplets. Triplets will be created using neighbour matrices, which can either be precomputed or dynamically generated. """ from abc import ABC, abstractmethod from functools import partial import itertools import random import math import numpy as np from tensorflow.keras.utils import Sequence from scipy.sparse import issparse from ..data import get_uint_ctype def generator_from_neighbour_matrix(X, Y, neighbour_matrix, batch_size): if Y is None: return UnsupervisedTripletGenerator(X, neighbour_matrix, batch_size=batch_size) return SupervisedTripletGenerator(X, Y, neighbour_matrix, batch_size=batch_size) class TripletGenerator(Sequence, ABC): def __init__(self, X, neighbour_matrix, batch_size=32): if batch_size > X.shape[0]: raise ValueError('''batch_size value larger than num_rows in dataset (batch_size={}, rows={}). Lower batch_size to a smaller value.'''.format(batch_size, X.shape[0])) self.X = X self.neighbour_matrix = neighbour_matrix self.batch_size = batch_size self.batched_data = hasattr(X, 'get_batch') self.batched_neighbours = hasattr(neighbour_matrix, 'get_batch') self._idx_dtype = get_uint_ctype(self.X.shape[0]) def __len__(self): return int(math.ceil(self.X.shape[0] / float(self.batch_size))) def __getitem__(self, idx): """Gets one batch of triplets""" batch_indices = range(idx * self.batch_size, min((idx + 1) * self.batch_size, self.X.shape[0])) # indices shape: (3, batch_size) triplet_indices = self.get_triplet_indices(batch_indices) label_batch = self.get_labels(batch_indices) # Retrieve actual data using triplet_indices # triplet_batch shape: (3, batch_size, *X.shape[1:]) triplet_batch = self.get_triplet_data(triplet_indices) return self.output_triplets(triplet_batch, label_batch) def get_triplet_indices(self, anchor_indices): """Generates and returns the triplet indices corresponding to the provided indexes. Neighbours are randomly sampled for each row from self.neighbour_matrix and negative samples that are not in the neighbour list are generated randomly.""" neighbour_cands = self.get_all_neighbour_indices(anchor_indices) anchor_indices = np.fromiter(anchor_indices, dtype=self._idx_dtype, count=len(anchor_indices)) try: # Auto ragged array creation deprecated in NumPy 1.19, 2019-11-01, will throw error neighbour_cands = np.asarray(neighbour_cands, dtype=self._idx_dtype) except ValueError: # Handle ragged array with slower, more generic method return self.get_triplet_indices_generic(anchor_indices, neighbour_cands) # Older numpy versions will autocast to dtype=object instead of raise exception # Detect ragged array in this case and handle with generic method if neighbour_cands.ndim < 2: return self.get_triplet_indices_generic(anchor_indices, neighbour_cands) # Non-ragged array - use shape info to randomly select indices all at once neighbour_indices = neighbour_cands[:, np.random.randint(neighbour_cands.shape[1])] negative_indices = self.gen_negative_indices(neighbour_cands) return (anchor_indices, neighbour_indices, negative_indices) def get_all_neighbour_indices(self, anchor_indices): """Retrieves neighbours for the indexes provided from inner neighbour matrix. Uses specialized `get_batch` retrieval method if generator is in batched_neighbours mode. """ if self.batched_neighbours: return self.neighbour_matrix.get_batch(anchor_indices) return [self.neighbour_matrix[idx] for idx in anchor_indices] def gen_negative_indices(self, neighbour_matrix): """Generate random candidate negative indices until the candidate for every row is not present in corresponding row of neighbour_matrix.""" neighbour_matrix = np.asarray(neighbour_matrix) generate_cands = partial(np.random.randint, self.X.shape[0], dtype=self._idx_dtype) cands = generate_cands(size=len(neighbour_matrix)) # Where random cand is present in neighbour row, invalid cand invalid_cands = (cands[:, np.newaxis] == neighbour_matrix).any(axis=1) n_invalid = invalid_cands.sum() while n_invalid > 0: cands[invalid_cands] = generate_cands(size=n_invalid) invalid_cands = (cands[:, np.newaxis] == neighbour_matrix).any(axis=1) n_invalid = invalid_cands.sum() return cands def get_triplet_data(self, triplet_indices): """Maps triplet indices to the actual data in internal data store. Returns a numpy array of shape (3, batch_size, *self.X.shape[1]).""" if self.batched_data: # Flatten triplets, get batch of data, then reshape back into triplets indices = list(itertools.chain.from_iterable(triplet_indices)) # Last batch may be smaller than defined so check real batch size batch_size = int(len(indices) / 3) data = self.X.get_batch(indices) triplet_batch = list(zip(*[iter(data)] * batch_size)) else: if isinstance(self.X, np.ndarray): # Fancy index for speed if data is a numpy array triplet_indices = np.asarray(triplet_indices, dtype=self._idx_dtype) triplet_batch = self.X[triplet_indices] else: triplet_batch = [[self.X[idx] for idx in seq] for seq in triplet_indices] if issparse(self.X): triplet_batch = [[e.toarray()[0] for e in t] for t in triplet_batch] triplet_batch = np.asarray(triplet_batch) return triplet_batch def get_triplet_indices_generic(self, anchor_indices, neighbour_cands=None): """Slower, generic way of generating triplet indices that works on sequences, not just numpy arrays.""" if neighbour_cands is None: neighbour_cands = self.get_all_neighbour_indices(anchor_indices) neighbour_indices = list(map(random.choice, neighbour_cands)) negative_indices = self.gen_negative_indices_generic(neighbour_cands) return (anchor_indices, neighbour_indices, negative_indices) def gen_negative_indices_generic(self, neighbour_map): """Slower, generic way of generating negative indices that works on sequences, not just numpy arrays.""" cands = [random.randrange(0, self.X.shape[0]) for _ in range(len(neighbour_map))] for i in range(len(cands)): while cands[i] in neighbour_map[i]: cands[i] = random.randrange(0, self.X.shape[0]) return cands @abstractmethod def get_labels(self, batch_indices): raise NotImplementedError("Override this method with a concrete implementation") @abstractmethod def output_triplets(self, triplet_batch, label_batch): raise NotImplementedError("Override this method with a concrete implementation") class UnsupervisedTripletGenerator(TripletGenerator): def __init__(self, X, neighbour_matrix, batch_size=32): super().__init__(X, neighbour_matrix, batch_size) self.placeholder_labels = np.empty(batch_size, dtype=np.uint8) def get_labels(self, batch_indices): return self.placeholder_labels[:len(batch_indices)] def output_triplets(self, triplet_batch, label_batch): return tuple([*triplet_batch]), label_batch class SupervisedTripletGenerator(TripletGenerator): def __init__(self, X, Y, neighbour_matrix, batch_size=32): super().__init__(X, neighbour_matrix, batch_size) self.Y = Y def get_labels(self, batch_indices): return self.Y[batch_indices] def output_triplets(self, triplet_batch, label_batch): label_batch = np.asarray(label_batch) return tuple([*triplet_batch]), tuple([label_batch] * 2)
e1b67114daa05030b748cae45b1997f4fca45331
nealstewart/booth
/symbols/drawing.py
619
3.609375
4
"Drawing logic for symbols" from symbols import shapes from symbols import utils def draw_line(ctx, line): first_point = utils.get_center(line[0]) second_point = utils.get_center(line[1]) ctx.move_to(first_point[0], first_point[1]) ctx.line_to(second_point[0], second_point[1]) ctx.close_path() ctx.stroke() def draw_symbol(ctx, symbol): ctx.set_source_rgb(0, 0, 0) for shape in symbol.shapes: shape.draw(ctx) ctx.fill() for container in symbol.containers: container.draw(ctx) ctx.stroke() for line in symbol.lines: draw_line(ctx, line)
1744d184671c0cb3a39a8496c077c0ec7448aca1
jorchard/AutoDiff
/utils.py
3,989
3.609375
4
# utils import numpy as np import matplotlib.pyplot as plt # Abstract class class MyDataset(): def __init__(self): return def __len__(self): raise NotImplementedError def __getitem__(self): raise NotImplementedError # MyDataLoader class MyDataLoader(): def __init__(self, ds, batchsize=1, shuffle=False): ''' dl = MyDataLoader(ds, batchsize=1, shuffle=False) Creates an iterable dataloader object that can be used to feed batches into a neural network. Inputs: ds a MyDataset object batchsize size of the batches shuffle randomize the ordering Then, next(dl) returns the next batch Each batch is a tuple containing (inputs, targets), where: - inputs is a 2D numpy array containing one input per row, and - targets is a 2D numpy array with a target on each row ''' self.index = 0 self.ds = ds self.batchsize = batchsize self.shuffle = shuffle self.n_batches = (len(ds)-1)//self.batchsize + 1 # might include a non-full last batch self.MakeBatches() def Reset(self): self.index = 0 if self.shuffle: self.MakeBatches() def MakeBatches(self): if self.shuffle: self.order = np.randperm(N) else: self.order = list(range(len(self.ds))) self.batches = [] for batchnum in range(self.n_batches): low = batchnum*self.batchsize high = min((batchnum+1)*self.batchsize, len(self.ds)) idxs = self.order[low:high] inputs = [] targets = [] for k in idxs: samp = self.ds.__getitem__(k) inputs.append(samp[0]) targets.append(samp[1]) self.batches.append([np.vstack(inputs), np.vstack(targets)]) def __next__(self): ''' Outputs: dl a list of batches ''' if self.index < self.n_batches: result = self.batches[self.index] self.index += 1 return result raise StopIteration def __iter__(self): return self # SimpleDataset: creates a simple classification dataset, # mapping the row-vectors in A to the row-vectors in B. class SimpleDataset(MyDataset): ''' SimpleDataset ''' def __init__(self, A, B, n=300, noise=0.1): self.samples = [] self.n_classes = len(A) self.input_dim = len(A[0]) for i in range(n): r = np.random.randint(self.n_classes) sample = [A[r]+noise*np.random.randn(*(A[r].shape)), B[r]] self.samples.append(sample) def __getitem__(self, idx): return self.samples[idx] def __len__(self): return len(self.samples) def Inputs(self): x = [] for s in self.samples: x.append(s[0]) return np.stack(x) def Targets(self): t = [] for s in self.samples: t.append(s[1]) return np.stack(t) def InputsOfClass(self, c): x = [] for s in self.samples: if torch.argmax(s[1])==c: x.append(s[0]) return np.stack(x) def ClassMean(self): xmean = [] for c_idx in range(self.n_classes): classmean = np.mean(self.InputsOfClass(c_idx), axis=0) xmean.append(classmean) return np.stack(xmean) def Plot(self, labels=[], idx=(0,1), equal=True): X = self.Inputs() if len(labels)==0: labels = self.Targets() colour_options = ['y', 'r', 'g', 'b', 'k'] cidx = np.argmax(labels, axis=1) colours = [colour_options[k] for k in cidx] plt.scatter(X[:,idx[0]], X[:,idx[1]], color=colours, marker='.') if equal: plt.axis('equal');
59453ab002f092f5b2c3dcd1bbe545260ddcf7ca
gerardomunoz1/gmunoz_repoSoluciones
/LAB 2.1/lab.py
1,748
3.75
4
M = 1000 D = 500 C = 100 L = 50 X = 10 V = 5 I = 1 def arabigo_a_romano (): try: numero_ingresado=int(input("Ingrese un número para su conversión a números Romanos: ")) print ("El número ingresado fue: ", numero_ingresado) while (numero_ingresado > 3999): print ("Número ingresado no válido.") print (" ") numero_ingresado=int(input("Ingrese un número nuevamente: ")) print ("El número ingresado fue: ", numero_ingresado) #print ("El número ingresado en números romanos es: " , numero_ingresado) except: pass def romano_a_arabigo (): try: numero_ingresado2=int(input("Ingrese un número para su conversión a números enteros: ")) print ("El número ingresado fue: ", numero_ingresado2) while (numero_ingresado2 > 3999): print ("Número ingresado no válido.") print (" ") numero_ingresado=int(input("Ingrese un número nuevamente: ")) print ("El número ingresado fue: ", numero_ingresado2) except: pass #print ("El número ingresado en números enteros es: ", numero_ingresado2) print ("--------------------------------------------------------------") print ("==BIENVENIDO AL CONVERSOR DE NÚMEROS==") print (" ") eleccion = int (input ("¿Qué desea convertir: romanos a enteros // enteros a romanos (1 // 2): ")) if (eleccion == 1): print (" ") print ("HA ESCOGIDO CONVERTIR DE N°ROMANOS A N°ENTEROS") print (romano_a_arabigo()) if (eleccion == 2): print (" ") print ("HA ESCOGIDO CONVERTIR DE N°ENTEROS A N°ROMANOS") print (arabigo_a_romano()) else: print ("ERROR, EJECUTE NUEVAMENTE EL PROGRAMA.")
ebefea30edf3a0367779d9a243eed3901f007162
Eric-Wonbin-Sang/CS110Manager
/2020F_hw6_submissions/jaineshita/EshitaJainCH7P2.py
857
4.375
4
# I pledge my Honor that I have # abided by the Stevens Honor System. # Eshita Jain # program determines date validity def main(): isValid = True months_with_31_days = [1, 3, 5, 7, 8, 10, 12] date = input("Enter date (mm/dd/yyy): ") date_list = date.split("/") if len(date_list) != 3: isValid = False else: month, day, year = date_list try: month = int(month) day = int(day) year = int(year) if month > 12 or month < 1 or day > 31 or day < 1 or year < 1: isValid = False elif month not in months_with_31_days and day == 31: isValid = False except: isValid = False if isValid: print("\nThe date", date, "is valid!") else: print("\nThe date", date, "is not valid :(") main()
65b88ff3d4a6b254b46f8dfa86e1c1850974a00d
royhuang813/shiyanlou-python
/challenge-1/calculator.py
724
3.65625
4
#!/usr/bin/env python3 def f(x): b = x - 3500 if b <= 0: print(format(0,'.2f')) elif 0 < b <= 1500: print(format(b * 0.03 - 0, '.2f')) elif 1500 < b <= 4500: print(format(b * 0.1 - 105, '.2f')) elif 4500 < b <= 9000: print(format(b * 0.2 - 555, '.2f')) elif 9000 < b <= 35000: print(format(b * 0.25 - 1005, '.2f')) elif 35000 < b <= 55000: print(format(b * 0.3 - 2755, '.2f')) elif 55000 < b <= 80000: print(format(b * 0.35 - 5505, '.2f')) else: print(format(b * 0.45 - 13505, '.2f')) if __name__ == '__main__': import sys try: salary = int(sys.argv[1]) f(salary) except ValueError: print('Parameter Error')
fd4fba0fe69b0e1195d19b221dcee0a94331e1f6
gcspanda/Python-Crash-Course
/ch05/5-09.py
160
3.8125
4
names = ['admin', 'panda', 'tiger', 'dog', 'cat'] # names = [] if names: for name in names: del name else: print("We need to find some users.")
b7dedd7263d4fe2a1b0ccc918258bd33cf64cd79
jun-young000/grammar-basic
/variale/02_variable1.py
981
3.71875
4
# 변수는 할당해놓고 사용하지 않으면 메모리 공간을 차지하게 됨 # 변수 삭제 명령어 : del # del 변수명 # c_var = 100 # print(c_var) # del c_var # print(c_var) # 문자열 값 저장 # 문자열을 큰따옴표 사용 (작은따옴표도 사용가능) # 여러 종류의 따옴표를 사용시에는 짝을 맞춰야 함 name = "홍길동" std_name = '김철수' pro_name = "이몽룡'교수'" print(name) print(std_name) print(pro_name) address ='서울시 강남구' print(name, address) print(name+"은 " +address+'에 삽니다.') result = name+"은 " +address+'에 삽니다.' print(result) ## 문자와 숫자의 결합(연결) age = 23 print(name + '은 ' + str(age) +'살 입니다') #홍길동은 23살 입니다 print(5 + age) ## 사각형의 면적을 구해서 출력하는 프로그램 # 넓이 : 100 # 높이 : 200 width = 100 height = 200 area = width * height print("면적 : " + str(area)) print("면적 : " , area)
d572b47a3f16e2b55b5efa2f222188c8860d08f2
whyismefly/learn-python
/xiaojiayu/P17-20.py
689
3.75
4
#!/usr/bin/python # encoding:utf-8 a=list() print a b="fwhfjerqwofk'erkfpoerw" b=list(b) print b print len(b) print max(b) b.append(1) print b print min(b) print sorted(b) print list(reversed(sorted(b))) def function1(a,b): "dfwifuoheroigioer" return a+b print function1(3,5) print function1.__doc__#打印方法注释 def function2(*num1): "可变参数,类似形参" print len(num1) print "第一个参数",num1[0],"第二个参数",num1[1] print sum(num1) print num1 print "_"*20 function2(123,312432435,342345) #函数中的局部变量如果与全局变量名字相同在外部调用依然是全局变量,二者只是名字相同,地址不同。
4d245b29fc2d55e368ef053a16342e9aececb3cf
ellelater/Baruch-PreMFE-Python
/level5/5.1/5.1.4.py
745
3.671875
4
import datetime def main(): date = raw_input("Input date (in format %Y-%m-%d):") time = raw_input("Input time (in format %H:%M:%S):") t = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S") delta = raw_input("Input delta time: (in format %H:%M:%S:%f)") sign = 1 if delta[0] == '-': sign = -1 delta = delta[1:] delta_t = datetime.datetime.strptime(delta, "%H:%M:%S:%f") d = datetime.timedelta(hours=delta_t.hour, minutes=delta_t.minute, seconds=delta_t.second, microseconds=delta_t.microsecond) if sign > 0: res_t = t + d else: res_t = t - d print res_t.strftime("%Y-%m-%d %H:%M:%S:%f") if __name__ == '__main__': main()
3e7d856e0e0d07306c8342d7c9ab9adad0cb807e
ChuhanXu/LeetCode
/Amazon OA2/Most frequent word.py
1,362
4.25
4
# Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. # It is guaranteed there is at least one word that isn't banned, and that the answer is unique. # # Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. # The answer is in lowercase. # Input: # paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." # banned = ["hit"] # Output: "ball" # Explanation: # "hit" occurs 3 times, but it is a banned word. # "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. # Note that words in the paragraph are not case sensitive, # that punctuation is ignored (even if adjacent to words, such as "ball,"), # and that "hit" isn't the answer even though it occurs more because it is banned. # python的正则表达式 import collections import re def mostCommonWord( p, banned): ban = set(banned) pattern = re.compile(r'\w+') words = pattern.findall(p.lower()) wordsFrequencyList=collections.Counter(w for w in words if w not in ban) result = wordsFrequencyList.most_common(1)[0][0] return result p="Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] print(mostCommonWord(p, banned))
6d5c8f68a0e25fc1e36d37c6d91d1d9f6b22acfd
AYehia0/codingame
/compete/fastest/shift_index.py
76
3.765625
4
n = int(input()) word = input() print(word[n%len(word):]+word[:n%len(word)])
931bd90faf04a6e094a316b1455538d0c9aab199
S1LV3RJ1NX/SPOJ250
/22_STPAR.py
676
3.59375
4
# http://www.algorithmist.com/index.php/SPOJ_STPAR n = int(input()) while n: side_street = [] # cars = [] curr_car = 1 flag = True cars = [int(x) for x in input().split()] # print(cars) for i in range(n): while len(side_street) != 0 and side_street[-1] == curr_car: curr_car+=1 side_street.pop() if cars[i] == curr_car: curr_car+=1 elif len(side_street) != 0 and side_street[-1] < cars[i]: flag = False break else: side_street.append(cars[i]) if flag: print("yes") else: print("no") n = int(input())
2f50c4cf87e4a04d42d1f78a8c141896931e2930
Kamal-vsi/30days-Python-Bootcamp
/Day17 challenge.py
2,754
3.609375
4
# Python MYSQL # Create a connection for DB and print the version using a python program import mysql.connector db=mysql.connector.connect(host='localhost', user="root", password="Sairam@123") print(db) import sys cur = db.cursor() cur.execute("SELECT VERSION()") data = cur.fetchone() print("DBMS version :", str(data)) # Create a multiple tables & insert data in table dbmt = db.cursor() dbmt.execute("CREATE DATABASE mydatabase12345") dbmt.execute("SHOW DATABASES") for entry in dbmt: print(entry) mydb = mysql.connector.connect( host="localhost", user="root", password="Sairam@123", database="mydatabase12345" ) dbmt = mydb.cursor() dbmt.execute("CREATE TABLE customers (Employee_name VARCHAR(255), Employee_dep VARCHAR(255), Employee_id VARCHAR(255))") dbmt.execute("CREATE TABLE Office(emp_name VARCHAR(255), Employee_id VARCHAR(255), EMP_ADDRESS VARCHAR(255))") dbmt.execute("CREATE TABLE Student(rollno INT(24), STUD_NAME VARCHAR(255), MARK INT(3))") dbmt=mydb.cursor() dbmt.execute("SHOW TABLES") for value in dbmt: print(value) #Create a employee table and read all the employee name in the table using for loop mydb = mysql.connector.connect( host="localhost", user="root", password="Sairam@123", database="mydatabase12345" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE Employee1(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))") sql = "INSERT INTO Employee1(id, name, address) VALUES (%s, %s, %s)" val = ("123", "kamal", "Vandavasi 408") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "Record inserted.") mycursor=mydb.cursor() sql = "INSERT INTO Employee1(id, name, address) VALUES (%s, %s, %s)" val = ("124", "kannan", "Vandavasi 508") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "Record inserted.") sql = "INSERT INTO Employee1(id, name, address) VALUES (%s, %s, %s)" val = ("125", "sriram", "Vandavasi 608") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "Record inserted.") mycursor = mydb.cursor() sql = "INSERT INTO Employee1(id, name, address) VALUES (%s, %s, %s)" val = [ ('1', 'bharathi', 'sanathi street 04'), ('2', 'saroja', 'balu street 05'), ('3', 'pattu', 'anna street 98'), ('4', 'sangavi', 'silicon valley 87'), ('5', 'devi', 'cheety street 56') ] mycursor.executemany(sql, val) mydb.commit() print(mycursor.rowcount, "Was inserted.") mycursor = mydb.cursor() mycursor.execute("SELECT * FROM Employee1") myresult = mycursor.fetchall() for x in myresult: print(x) mycursor = mydb.cursor() mycursor.execute("SELECT name FROM Employee1") myresult = mycursor.fetchall() for x in myresult: print(x)
6952e1592dacf20a159208c85e8a009168aec1eb
iandioch/CPSSD
/ca117/lab1.1/contains_11.py
744
3.84375
4
import sys def count_letters(s): ans = {} for c in s: if c in ans: ans[c] += 1 else: ans[c] = 1 return ans def main(): first_letters = count_letters(sys.argv[1]) second_letters = count_letters(sys.argv[2]) valid = True for c in first_letters: if c not in second_letters: valid = False break if first_letters[c] > second_letters[c]: valid = False break print(valid) # print(count_letters(sys.argv[1])) if __name__ == '__main__': main()
d5e8b43372c1aacb6ab729e2d8f600f2ac571900
bruno-victor32/Curso-de-Python---Mundo-1-Fundamentos
/ex029.py
287
3.796875
4
vel = float(input('Digite a velocidade do veiculo em km/h: ')) if vel > 80: print('Você foi multado devido a está acima do limite de 80 km/h') mul = (vel - 80) * 7 print('A multa vai custar R${:.2f}'.format(mul)) else: print('Você está andando na velocidade correta')
e79ed2a497f7fb675912175f6a431a3635e6643c
Naman0199/Star-Pattern-Game
/tut29exercise.py
350
4
4
print("Pattern Game") n = int(input("enter the number of rows for patterns:\n")) b = bool(int(input("enter 1 for True or 0 for False:\n"))) if b==1: c = 0 while(c<=n): print("*"*c) c = c+1 elif b==0: c=n while(c>0): print("*"*c) c = c-1 else: print("enter valid pattern")
ac6357a9793386a0f6f0a2368d81dc9b779ca3ad
boppreh/2048bot
/bot.py
5,514
3.796875
4
import random class GameOver(Exception): """ Exception raised when the board has no move lefts. """ class Board(object): """ Class for storing, changing and moving the tiles. Methods that change the board return a new changed copy instead. Invalid positions return -1. """ def __init__(self, base_board=None): self.cells = list(base_board.cells) if base_board else [0] * 16 def __str__(self): str_parts = [] for y in range(4): for x in range(4): str_parts.append(str(self[x, y]) + ' ') str_parts.append('\n') return ''.join(str_parts) def __getitem__(self, index): x, y = index if x < 0 or x > 3 or y < 0 or y > 3: return -1 return self.cells[x + 4 * y] def __setitem__(self, index, value): x, y = index self.cells[x + 4 * y] = value def move(self, direction): """ Receives a tuple direction (x, y) and moves all pieces in that direction as much as possible. Similar pieces that collide are merged. Returns the updated board without changing itself. """ dif_x, dif_y = direction # Make sure we move the last tiles first, so they don't block the # previous ones. x_range = range(4) if dif_x < 1 else range(3, -1, -1) y_range = range(4) if dif_y < 1 else range(3, -1, -1) new = Board(self) for x in x_range: for y in y_range: # Ignore empty tiles. if not self[x, y]: continue new_x, new_y = x, y while True: old_x, old_y = new_x, new_y new_x += dif_x new_y += dif_y if new[new_x, new_y] == new[old_x, old_y]: # Same pieces, merge. new[new_x, new_y] *= 2 new[old_x, old_y] = 0 break elif new[new_x, new_y]: # Hit a different tile (or border, which is -1), stop. break else: # Move piece one tile and leave an empty space behind. new[new_x, new_y] = new[old_x, old_y] new[old_x, old_y] = 0 return new def _rand_empty_position(self): """ Returns a random (x, y) that is guaranteed to be empty, or raise GameOver if there isn't one. """ if self.is_full(): raise GameOver() while True: x = random.randint(0, 3) y = random.randint(0, 3) if not self[x, y]: return x, y def _rand_piece(self): """ Returns a random piece 2 or 4, with different odds. """ return random.choice([2] * 9 + [4]) def place_random(self): """ Places a new random piece (2 or 4) in a random empty tile. Returns the updated board without changing itself. """ new = Board(self) new[self._rand_empty_position()] = self._rand_piece() return new def is_full(self): """ Return true if all cells are occupied. """ return all(self.cells) def __eq__(self, other): return self.cells == other.cells class Game(object): """ Class for programatically playing the game. """ KEYMAP = {'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right': (1, 0)} def __init__(self): # Setup board with two random pieces. self.board = Board().place_random().place_random() def play(self, key): """ Plays a movement, where `key` can be 'up', 'down', 'left' or 'right'. Illegal movements are ignored and raises GameOver when the board fills up. """ new = self.board.move(Game.KEYMAP[key]) if new == self.board and not new.is_full(): return self.board = new.place_random() def __str__(self): return '-------\n' + str(self.board) + '-------' def play_human(): """ Allows for a human player to interactively play the game on the console. """ import console def player_logic(board): console.display(str(board)) key = console.get_valid_key(['q', 'up', 'down', 'left', 'right']) if key == 'q': exit() return key return play_bot(player_logic) def play_bot(logic): """ Runs a full playthrough of the game with the given logic, where `logic` is a function that takes the current board state and returns a directional string ('up', 'down', 'left' or 'right'). Returns the score reached (biggest tile value). """ g = Game() try: while True: g.play(logic(g.board)) except GameOver: return max(g.board.cells) def get_bot_max_score(logic, repeats=10): """ Runs a bot logic a number of times, yielding the highest score achieved. """ return max(play_bot(logic) for i in range(repeats)) if __name__ == '__main__': # Uncomment to play yourself. # play_human() # exit() import itertools cycle = itertools.cycle(['left', 'up', 'right', 'up']) # Emit a 'down' once in a while to avoid getting stuck. cycler = lambda board: next(cycle) if random.random() > 0.01 else 'down' print(get_bot_max_score(cycler, 10000))
6750e8ece14262db0c3a6ac5668d510d52f72bff
Tarrasch/Roy_VnTokenizer
/data/clean_dictionary.py
328
3.84375
4
#!/usr/bin/env python3 import fileinput import re word = '' for line_ in fileinput.input(): line = line_.strip() if re.search('##', line): for word_ in line.split(','): word = word_.strip() word = re.sub('##', '', word) word = re.sub(' ', '_', word) print(word)
d8d8a466014b3524cf89111727be5245022099c7
pdez90/COVID-19_US_County-level_Summaries
/model/sir_model.py
2,393
3.71875
4
# Lightly modified from from https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/ # Goal is to learn the beta and gamma parameters from socio-economic facotrs import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt class SIRmodel(): def __init__(self, N=1000, I0=1, R0=1): # Total population, N. self.N = N # Initial number of infected and recovered individuals, I0 and R0. self.I0 = I0 self.R0 = R0 # Everyone else, S0, is susceptible to infection initially. self.S0 = N - I0 - R0 # Contact rate, beta, and mean recovery rate, gamma, (in 1/days). # These should be learned self.beta = 0.2 self.gamma = 1./10 # The SIR model differential equations. def deriv(self, y, t, N, beta, gamma): S, I, R = y dSdt = -beta * S * I / N dIdt = beta * S * I / N - gamma * I dRdt = gamma * I return dSdt, dIdt, dRdt # Learn parameters and update them here def update_param(self, beta, gamma): self.beta = beta self.gamma = gamma def plot(self, t): # Initial conditions vector y0 = self.S0, self.I0, self.R0 # Integrate the SIR equations over the time grid, t. ret = odeint(self.deriv, y0, t, args=(self.N, self.beta, self.gamma)) S, I, R = ret.T # Plot the data on three separate curves for S(t), I(t) and R(t) fig = plt.figure(facecolor='w') ax = fig.add_subplot(111, axisbelow=True) ax.plot(t, S/1000, 'b', alpha=0.5, lw=2, label='Susceptible') ax.plot(t, I/1000, 'r', alpha=0.5, lw=2, label='Infected') ax.plot(t, R/1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity') ax.set_xlabel('Time /days') ax.set_ylabel('Number (1000s)') ax.set_ylim(0,1.2) ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5) for spine in ('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.show() if __name__ == "__main__": # A grid of time points (in days) t = np.linspace(0, 160, 160) model = SIRmodel() model.plot(t)
e01a5f3e3dee7ef4e9a743e69962a9b0fe3b0f61
CrimsonVista/Playground3
/src/playground/common/datastructures/HierarchicalDictionary.py
4,319
4.03125
4
from collections.abc import MutableMapping class HierarchicalKeyHandler(object): """ HierarchicalKeyHandler is an abstract class (interface) with two methods: split and join. Implementing classes should define split and join for data such that split(data) produces a list of parts and join(parts) produce the original data. join(split(data)) = data """ def split(self, key): raise NotImplementedError def join(self, keyParts): raise NotImplementedError class HierarchicalDictionary(MutableMapping): """ HierarchicalDictionary maps hierarcical keys to data, where the key hierarchy is determined by the key handler. The default key handler requires that data supports a 'split' method, e.g., strings. d['x'] = 1 d['x.a'] = 2 """ class DEFAULT_KEY_HANDLER(HierarchicalKeyHandler): def split(self, key): return key.split(".") def join(self, keyParts): return ".".join(keyParts) def __init__(self, splitter=None): self._splitter = splitter if not self._splitter: self._splitter = self.DEFAULT_KEY_HANDLER() self._subDicts = {} self._terminals = {} def lookupByKeyParts(self, keyParts): if len(keyParts) == 1: return self._terminals[keyParts[0]] elif len(keyParts) == 0: raise KeyError else: if keyParts[0] not in self._subDicts: raise KeyError return self._subDicts[keyParts[0]].lookupByKeyParts(keyParts[1:]) def storeByKeyParts(self, keyParts, value): if len(keyParts) == 1: self._terminals[keyParts[0]] = value elif len(keyParts) == 0: raise KeyError else: if keyParts[0] not in self._subDicts: self._subDicts[keyParts[0]] = HierarchicalDictionary(splitter=self._splitter) self._subDicts[keyParts[0]].storeByKeyParts(keyParts[1:], value) def deleteByKeyParts(self, keyParts): if len(keyParts) == 1: del self._terminals[keyParts[0]] elif len(keyParts) == 0: raise KeyError else: self._subDicts[keyParts[0]].deleteByKeyParts(keyParts[1:]) if len(self._subDicts[keyParts[0]]) == 0: del self._subDicts[keyParts[0]] def iterKeys(self, parentKeys=None): for key in self._terminals.keys(): if parentKeys: yield self._splitter.join(parentKeys+[key]) else: yield key for subKey in self._subDicts.keys(): if parentKeys: for hierarchicalKey in self._subDicts[subKey].iterKeys(parentKeys+[subKey]): yield hierarchicalKey else: for hierarchicalKey in self._subDicts[subKey].iterKeys([subKey]): yield hierarchicalKey def __getitem__(self, key): subKeys = self._splitter.split(key) return self.lookupByKeyParts(subKeys) def __setitem__(self, key, value): subKeys = self._splitter.split(key) self.storeByKeyParts(subKeys, value) def __delitem__(self, key): subKeys = self._splitter.split(key) self.deleteByKeyParts(subKeys) def __len__(self): count = len(self._terminals) for subKey in self._subDicts.keys(): count += len(self._subDicts[subKey]) return count def __iter__(self): return self.iterKeys() def basicUnitTest(): hd = HierarchicalDictionary() hd["a"] = 1 hd["a.x"] = 2 hd["a.x.k"] = 3 assert(hd["a"] == 1) assert(hd["a.x"] == 2) assert(hd["a.x.k"] == 3) assert(len(hd) == 3) keys = [] for k in hd: keys.append(k) assert("a" in keys) assert("a.x" in keys) assert("a.x.k" in keys) del hd["a.x"] assert("a" in hd) assert("a.x" not in hd) assert("a.x.k" in hd) if __name__=="__main__": basicUnitTest() print("Basic Unit Test Passed.")
aeb1585762c57281450e6540d70ac68fce955179
ahmetcanbasaran/MU-CSE-Projects
/8.Semester/CSE4094/Project#1/main.py
3,911
3.546875
4
import os import re # To make a node class TrieNode(object): # default constructor def __init__(self, char): self.char = char self.children = [] self.is_end_of_word = False # Is it the last character of the word. self.counter = 1 # How many times this character appeared in the addition process self.file_name = [] self.index = [] # Reading, cleaning and taking words from files def read_files(root): for file_name in os.listdir(os.getcwd() + "/sampleTextFiles"): input_data = open(os.getcwd() + "/sampleTextFiles/" + file_name, 'r').read() words = input_data.split() index = 1 for word in words: length = len(word) word = re.sub(r'[^\w\s]', '', word) # Clean words from punc. add(root, word, file_name, index) index += length + 1 # To add word to the trie def add(root, word, file_name, index): node = root for char in word: found_in_child = False for child in node.children: if child.char == char: child.counter += 1 node = child found_in_child = True break if not found_in_child: new_node = TrieNode(char) node.children.append(new_node) node = new_node node.is_end_of_word = True node.file_name.append(file_name) node.index.append(index) # To check whether a word is in trie def find(root, prefix): case1 = prefix.capitalize() # Capital prefix case2 = prefix.lower() # Lower case prefix case3 = prefix.upper() # Upper case prefix find_prefix(root, case1) find_prefix(root, case2) find_prefix(root, case3) # It goes all path with prefix characters def find_prefix(root, prefix): node = root if not root.children: return for char in prefix: char_not_found = True for child in node.children: if child.char == char: char_not_found = False node = child break if char_not_found: return print_words(node, prefix) # It takes the node which is reached with obtained prefix # Then tries to look at all children and prints they def print_words(root, prefix): node = root if not node.children: print "\n" + prefix + ":" for i in range(len(node.file_name)): print node.file_name[i], node.index[i] return if node.is_end_of_word: print "\n" + prefix + ":" for i in range(len(node.file_name)): print node.file_name[i], node.index[i] for child in node.children: if child.is_end_of_word: print_words(child, (prefix + child.char)) else: print_words(child, (prefix + child.char)) # To search common words in obtained files def common_words(root, file_names, word): node = root if not node.children: return for child in node.children: if child.is_end_of_word and all(elem in child.file_name for elem in file_names): print word + child.char common_words(child, file_names, word + child.char) else: common_words(child, file_names, word + child.char) # Takes desired option of the program and runs it def main(): root = TrieNode('*') read_files(root) query_type = raw_input('Enter 1 to search words with entering a prefix\n' + 'Enter 2 to search common words of desired files\n' + 'What do you want to do? ') if query_type == "1": prefix = raw_input("Enter a prefix: ") find(root, prefix) else: file_names = raw_input("Enter file names to search common words: ") common_words(root, file_names.split(), "") # To run main function if __name__ == '__main__': main()
5d89d29900dc3d230718a42b33e9684b51375f7d
OlehPalka/Second_semester_labs
/labwork10/mark.py
3,820
3.8125
4
""" This module contains class which saves data in array """ import ctypes class AngleADT: """ Class which creates object (array) which saves angles. """ def __init__(self): self.ascii = {'0': 0.0, '1': 22.5, '2': 45.0, '3': 67.5, '4': 90.0, '5': 112.5, '6': 135.0, '7': 157.5, '8': 180.0, '9': 202.5, 'a': 225.0, 'b': 247.5, 'c': 270.0, 'd': 292.5, 'e': 315.0, 'f': 337.5} def word_lenth(self): """ This method counts lenth of the future array """ result = 0 for i in self.message: result += len(hex(ord(i))) - 2 return result def encode_message(self, message): """ This is encoding method. """ self.message = message lenth = self.word_lenth() result = Array(lenth) encoded_mes = "".join([hex(ord(i))[2:] for i in self.message]) for i in range(lenth): if i > 0: if prevoius_char == encoded_mes[i]: angle = 360.0 else: angle = self.ascii[encoded_mes[i]] - \ self.ascii[prevoius_char] result[i] = angle else: result[i] = self.ascii[encoded_mes[i]] prevoius_char = encoded_mes[i] return result def print_array(self, array): """ This is printing method. """ result = list() for i in range(self.word_lenth()): result.append(array[i]) print(result) # Implements the Array ADT using array capabilities of the ctypes module. class Array: """ Creates an array with size elements. """ def __init__(self, size): assert size > 0, "Array size must be > 0" self._size = size # Create the array structure using the ctypes module. py_array_type = ctypes.py_object * size self._elements = py_array_type() # Initialize each element. self.clear(None) # Returns the size of the array. def __len__(self): """ Returns the size of the array. """ return self._size # Gets the contents of the index element. def __getitem__(self, index): """ Gets the contents of the index element. """ assert len(self) > index >= 0, "Array subscript out of range" return self._elements[index] # Puts the value in the array element at index position. def __setitem__(self, index, value): """ Puts the value in the array element at index position. """ assert len(self) > index >= 0, "Array subscript out of range" self._elements[index] = value # Clears the array by setting each element to the given value. def clear(self, value): """ Clears the array by setting each element to the given value. """ for i in range(len(self)): self._elements[i] = value # Returns the array's iterator for traversing the elements. def __iter__(self): """ Returns the array's iterator for traversing the elements. """ return _ArrayIterator(self._elements) # An iterator for the Array ADT. class _ArrayIterator: """ Array iterator """ def __init__(self, the_array): self._array_ref = the_array self._cur_index = 0 def __iter__(self): return self def __next__(self): if self._cur_index < len(self._array_ref): entry = self._array_ref[self._cur_index] self._cur_index += 1 return entry raise StopIteration x = AngleADT() x.encode_message('1 січня') x.print_array(x.encode_message("1 січня"))
9abaff7bf5fbb426965e216d4b4a900b898b21c7
baburajk/python
/practice/listmerge.py
1,810
3.828125
4
#!/usr/local/bin/python3 import argparse class OrderMerge: pass def merge(self,list1,list2): # Make a list to hold both lists mergedlistsize = len(list1) + len(list2) mergedlist = [None] * mergedlistsize current_index_list1 = 0 current_index_list2 = 0 current_index_merged = 0 while current_index_merged < mergedlistsize: #Get value from first list1 and list2 if current_index_list1 < len(list1): first_unmerged_list1 = list1[current_index_list1] if current_index_list2 < len(list2): first_unmerged_list2 = list2[current_index_list2] if first_unmerged_list1 < first_unmerged_list2: mergedlist[current_index_merged] = first_unmerged_list1 current_index_list1 = current_index_list1 + 1 else: mergedlist[current_index_merged] = first_unmerged_list2 current_index_list2 = current_index_list2 + 1 current_index_merged = current_index_merged + 1 return mergedlist #def #OrderMerge def main(): cli = argparse.ArgumentParser() cli.add_argument("--list1",nargs="*",type=int) cli.add_argument("--list2",nargs="*",type=int) args = cli.parse_args() print ("List1", args.list1) print ("List2", args.list2) omerge = OrderMerge() result = omerge.merge(args.list1, args.list2) print ("Result:" , result) if __name__ == "__main__": main()
97e7fe8883606d285eaa22d0820bfe7b7b7e1f3e
weguri/python
/listas_tipos/list/range_list.py
254
4.09375
4
numeros = list(range(1, 8)) print(numeros) intervalo_numeros = list(range(2, 20, 2)) print(intervalo_numeros) # # print("""\nExemplo For e Range""") squares = [] for value in range(12): squares.append(value ** 2) # Exponenciação print(squares)
111e0f374c1bdc8ada830c7bab7a0e9c1a86faff
johncornflake/dailyinterview
/imported-from-gmail/2019-10-12-invert-a-binary-tree.py
1,088
4.25
4
Hi, here's your problem today. This problem was recently asked by Twitter: You are given the root of a binary tree. Invert the binary tree in place. That is, all left children should become right children, and all right children should become left children. Example: a / \ b c / \ / d e f The inverted version of this tree is as follows: a / \ c b \ / \ f e d Here is the function signature: class Node : def __init__ ( self , value ): self . left = None self . right = None self . value = value def preorder ( self ): print self . value , if self . left : self . left . preorder () if self . right : self . right . preorder () def invert ( node ): # Fill this in. root = Node ( 'a' ) root . left = Node ( 'b' ) root . right = Node ( 'c' ) root . left . left = Node ( 'd' ) root . left . right = Node ( 'e' ) root . right . left = Node ( 'f' ) root . preorder () # a b d e c f print "\n" invert ( root ) root . preorder () # a c f b e d
b77e6f30f24f814014afa696862b5bfd97f3c4c2
thormeier-fhnw-repos/sna-holaspirit-to-gephi
/src/gephi/write_csv.py
261
3.65625
4
import csv def write_csv(matrix, file_name): """ Writes a given matrix into a CSV file :param matrix: The matrix to write :return: None """ with open(file_name, "w") as f: writer = csv.writer(f) writer.writerows(matrix)
259362db353b56b8828171a1d9d1d92f4364905d
generalturok/fill_in_the_blanks
/australia_quiz.py
3,308
4
4
'''A Quiz on How Well You know Australian Culture''' #opening sentence to explain what the program is and what it is about print "Play my Australia, fill in the blanks game!"'\n' #Including 3 levels: easy/medium/hard easy_question = '''Australia was founded in __1__ by Captain James Cook. The national emblem of Australia shows 2 animals they are: __2__ and __3__. These animals were chosen because they can not move __4__.\n''' easy_answers = ['1777','kangaroo','emu','back'] medium_question = '''Australia still remains a country in the __1__ of the United Kingdom. Australia has __2__ States and Territories. They are NSW,VIC,SA,WA,NT,ACT,__3__,__4__.\n''' medium_answers = ['commonwealth','8','TAS','QLD'] hard_question = '''Famous Australian athletes and sportspersons include: Cathy __1__, __2__ Ablett, Donald __3__, __4__ Bogut.\n''' hard_answers = ['Freeman','Gary','Bradman','Andrew'] #Using blanks __1__-__4__ is easier to sort then going all the way up to 20. #This was made possible by placing the questions and answers for easy-hard in seperate classes/strings. blanks = ["__1__","__2__","__3__","__4__"] user_input = raw_input("Select a difficulty: easy, medium, hard \n") user_input=user_input.lower() #Sets up the difficulty setting for the user. If the word is not either easy,medium or hard. #The user is forced to re-enter their input. def difficulty(user_input): level_list=["easy","medium","hard"] while user_input not in level_list: user_input = raw_input("Please select one of the 3 options: easy, medium or hard \n") user_input=user_input.lower() if user_input in level_list: user_chances=raw_input("How many 'CHANCES' will you need? \n ") user_chances=int(user_chances) return user_input,user_chances #This function correalates both the answers and the question to the appropriate blanks. #ie: easy questiion to easy answer def question_answer(levelinput): if levelinput == "easy": return easy_answers, easy_question elif levelinput == "medium": return medium_answers,medium_question elif levelinput == "hard": return hard_answers,hard_question level,user_chances = difficulty(user_input) answerlist,question=question_answer(level) #function informs the user if their guesss is true or false and how many chances they have. #There is a else statement which explains when they are wrong and when it is game over def fill_in_the_blank(question, answerlist, blank): print "\nFill in the Blank: "+ question i,guess = 0,0 while (i < len(answerlist)) and (guess < user_chances) : answer = raw_input("What is the missing word/number" + blank[i]+ "? \n") if answer == answerlist[i]: print "Correct! \n" question = question.replace("_"+blank[i]+"_",answerlist[i]) print question i =i + 1 if i == len(answerlist): print "Congratulations! You are a true Australian!! Try at a different level next time ;)" else: print "Try Again \n" guess=guess + 1 if guess == user_chances: print "Too bad , your " + str(user_chances) + " chances are over and unfortunately game is over." fill_in_the_blank(question,answerlist,blanks)
8d1f1516aceaae2eddbe0c4566feceafa5df90ac
jarthurj/ThinkPython
/5-3.py
280
4.0625
4
def check_fermat(a, b, c, n): if a ** n + b ** n == c ** n and n > 2: print("holy smokes fermat was wrong") else: print('NEIN!') if __name__ == '__main__': a = int(input("a?")) b = int(input("b?")) c = int(input("c?")) n = int(input("n?")) check_fermat(a, b, c, n)
eb1245cfd4f95f072a979ccd5776d0dd3730acc4
iveygman/SonnetGen
/wordnode.py
1,602
3.5625
4
class WordNode(object): def __init__(self, word): self.word = word; self.bWords = dict(); self.fWords = dict(); self.nextWord = ''; def addForward(self, fWord): if (fWord not in self.fWords.keys()): self.fWords[fWord] = 1; else: self.fWords[fWord] += 1; def addBackward(self, bWord): if (bWord not in self.bWords.keys()): self.bWords[bWord] = 1; else: self.bWords[bWord] += 1; # computes forward and backward word probabilities based on history def getForwardDistribution(self, salt={}): print "Computing forward distribution for", self.word return self._computeDistribution(self.fWords, salt); def getBackwardDistribution(self, salt={}): print "Computing forward distribution for", self.word return self._computeDistribution(self.bWords, salt); def _computeDistribution(self, dic, salt={}): overall = dict(dic, **salt); total = float(sum(overall.values())) for key, val in overall.items(): overall[key] /= total def getForwardDistributionList(self, salt={}): return self._computeDistributionList(self.fWords,salt) def getBackwardDistributionList(self, salt={}): return self._computeDistributionList(self.bWords,salt) def _computeDistributionList(self, dic, salt={}): overall = dict(dic, **salt) l = [] for key, val in overall.items(): for k in range(0,val): l.append(key) return l
b507e7c6ce6cb44c967a81331a5d3726a2273e09
r9y9/nlp100
/09.py
464
3.953125
4
import numpy as np def f(s): words = s.split(" ") r = [] for word in words: if len(word) < 3: r.append(word) else: subword = [c for c in word[1:-1]] np.random.shuffle(subword) r.append("".join([word[0]] + subword + [word[-1]])) return " ".join(r) s = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ." print(f(s))
3a0caf8b57c8261a6dec76d07a6fadf1ec81fc5f
chizhangucb/Python_Material
/cs61a/lectures/Week1/Lec_Week1_1_Extra.py
1,168
4.53125
5
#===== The Non-Pure Print Function =====# -2 None # a special Python value that represents nothing print(None) print(None, None) print(1, 2, 3) ## 1. Pure function: # Functions have some input (their arguments) and # return some output (the result of applying them). abs(-2) # (1) Pure functions have the property that applying # them has no effects beyond returning a value. # (2) Moreover, a pure function must always return the # same value when called twice with the same arguments. ## 2. Non-pure function: # In addition to returning a value, applying a non-pure # function can generate side effects, which: # make some change to the state of the interpreter or computer # eg. generate additional output beyond the return value print(print(1), print(2)) # The value that print returns is always None print(print(print(1, 2), print(3)), print(print(4), print(5)), print(7)) # A function that does NOT explicitly return a value will return None # But, None is not displayed by the interpreter as the value of an exp def does_not_square(x): x * x does_not_square(4) print(does_not_square(4)) sixteen = does_not_square(4) sixteen sixteen + 4
afa6c9f183f4d9d5c83f9dbf28a63456372eed15
CSPInstructions/HR-1819-Workshop-Analysis-2
/Code/Deeltijd.py
2,696
4.21875
4
# Function that prints the contents of a list with their indexes def printList( list ): # Print a line print("------------") # Create a counter that keeps track of the index counter = 0 # Loop over the items in the list for item in list: # Print the index with it's corresponding value print( str( counter ) + " => " + str( item ) ) # Print another line print("------------") # Function that doubles all the numbers in a list def numbersTimesTwo( numbers ): # Create a new list newList = list() # Loop over the numbers in the list for number in numbers: # Add the doubled number to the new list newList.append( number * 2 ) # Return the new list return newList # Create a lambda function that returns a given number times two lambdaNumberTimesTwo = lambda number: number * 2 # Create the fold function # The fold function combines all the items in a list into a single value def fold( list, startValue, function ): # Create a variable that will store the result result = startValue # Loop over the items in the list for item in list: # Change the result using the provided function result = function( result, item ) # Return the result return result # Create the factorial function def factorial( number ): # Check whether the number has reached the lowest possible boundery if number <= 1: # Return 1 return 1 # Make a recursive call multiplying the current number # with the result of another call to this function return number * factorial( number - 1 ) # Create the fold function in a recursive manner def recursiveFold( function, startValue, *items, startIndex = 0 ): # Check whether we reached the final item in the list if len( items ) <= startIndex: # Return the base value return startValue # Return the execution of the function, with a recursive call and items return function( recursiveFold( function, startValue, *items, startIndex = startIndex + 1), items[startIndex] ) # Test the printList function by providing a list and watching the outcome printList( [9, 8, 7, 6 ] ) # The printList function can also be used for function that return a list printList( numbersTimesTwo( [9, 8, 7, 6 ] ) ) # We start by the normal fold function, we want to add up all the numbers print( fold( [2, 4, 6, 8], 0, lambda result, number: result + number ) ) # Now we use the recursive fold function, we wanna subtract all the numbers print( recursiveFold ( lambda result, number: result - number, 0, 1, 3, 5, 7, 9 ) )