blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
64f767701344bcea45ef4d2507b32b9f2f2bffbb | 0r0loo/D.S-Algo | /Python/doit_da_algo/chap01/print_starts1.py | 303 | 3.78125 | 4 | # *를 n개로 출력하되 w개마다 줄바꿈하기 1
print('*를 출력합니다.')
n = int(input('몇 개를 출력할까요? : '))
w = int(input('몇 개마다 줄바꿈을 할까여? : '))
for i in range(n):
print('*', end='')
if i % w == w - 1:
print()
if n % w:
print()
|
16ac4fcf657be4ad681a4676af25a31d8c346e99 | saviaga/Algorithm-Implementations | /traverse_tree/py/StackTraversal.py | 1,117 | 3.75 | 4 | class StackTraversal:
# Output after stack push
def preorderTraversal(self, root):
stack, cur = [], root
result = []
while cur or stack:
while cur:
stack.append(cur)
result.append(cur.val)
cur = cur.left
cur = stack.pop()
cur = cur.right
return result
# Output after stack pop
def inorderTraversal(self, root):
stack, cur = [], root
result = []
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
result.append(cur.val)
cur = cur.right
return result
# Reverse left right, reverse result
def postorderTraversal(self, root):
stack, cur = [], root
result = []
while cur or stack:
while cur:
stack.append(cur)
result.append(cur.val)
cur = cur.right
cur = stack.pop()
cur = cur.left
result.reverse()
return result
|
8bc9566ce94446146efaff25b262b534a2cc65b1 | MihailBratanov/Kelly-s-py-workbook | /first.py | 1,857 | 3.78125 | 4 | #Url we shall be scraping from
base_url="https://www.lexico.com/en/definition/"
#imports of libraries we will use
from tkinter import *
import requests
import re
from bs4 import BeautifulSoup
#This is a function to remove the html tags from the definition
def cleanup(definition):
regex = "<.*?>"
final_definition = re.sub(regex, '', str(definition))
return final_definition
#main function to lookup definition,creates the window and after typing the word the button press
#sends it over to the createdefinition function where magic happens
def lookup():
defLookUpgui = Toplevel(root)
defLookUpgui.title("Look it up!")
actual_word = StringVar()
wordBox = Entry(defLookUpgui, text='Insert word', textvariable=actual_word).pack()
#here is where magic happens,soup is created and then filtered down to a definition.
def createdefinition():
definition_name = actual_word.get()
#print(type(definition_name))
page = requests.get(base_url + definition_name)
soup = BeautifulSoup(page.content, 'html.parser')
definition_line = soup.find('span', {"class": "ind"})
#creates the window where definitions are displayed
new = cleanup(definition_line)
if new != " ":
definition_gui = Toplevel()
definition_gui.title("Definition:")
definitionText = Label(definition_gui, text=new, height=20)
definitionText.pack()
searchButton = Button(defLookUpgui, text="Look up", command=createdefinition)
searchButton.pack()
#root of the application, the base of all bases, the beginning
root = Tk()
root.title("Kelly's workbook")
label1 = Label(root, text="Welcome to Kelly's workbook")
label1.pack()
lookup_button = Button(root, text="Search definitions", command=lookup)
lookup_button.pack()
#the loop of life
root.mainloop() |
537794df6dc4f0e2de7566ff852e07446a6bdd2d | manishshiwal/guvi | /vowel.py | 163 | 3.796875 | 4 | n=raw_input("enter the letter")
ab=['a','A','e','E','i','O','u','o','I','U']
b=1
for c in ab:
if(n==c):
print("vowel")
b=0
if(b==1):
print("consonant")
|
ce9b9e1faaf31244f2ec3aaa1e9fa1f09201b36f | addherbs/LeetCode | /Medium/39. Combination Sum.py | 1,271 | 3.53125 | 4 | # Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
#
# The same repeated number may be chosen from candidates unlimited number of times.
#
# Note:
#
# All numbers (including target) will be positive integers.
# The solution set must not contain duplicate combinations.
# Example 1:
#
# Input: candidates = [2,3,6,7], target = 7,
# A solution set is:
# [
# [7],
# [2,2,3]
# ]
# Example 2:
#
# Input: candidates = [2,3,5], target = 8,
# A solution set is:
# [
# [2,2,2,2],
# [2,3,3],
# [3,5]
# ]
def cal(nums, target, result_test, current_list, next_index):
# print(target, result_test, current_list, next_index)
if target == 0:
result_test.append(current_list)
print("answer", current_list)
return
if target < 0 or next_index >= len(nums):
return
i = 0
while (target - nums[next_index] * i >= 0):
cal(nums, target - nums[next_index] * i, result_test, current_list + [nums[next_index]] * i, next_index + 1)
i += 1
def call_cal():
result = []
# cal([2, 3, 6, 7], 7, result, [], 0)
cal([2, 3, 5], 8, result, [], 0)
print(result)
call_cal()
|
6aaf1f801baea88a1a028a82477f8def1880df7b | SateehTeppala/Data | /Sorting Algorithams/Bubble Sort.py | 384 | 4.15625 | 4 | '''
Optimized Bubble Sort Algorithm
'''
def BubbleSort(a):
for i in range(len(a)):
for j in range(0,len(a)-i-1):
if a[j] > a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
return a
if __name__ == "__main__":
a = [2,312,21,121,2,454,567,787,453,45,545,3,534,5,34]
data = BubbleSort(a)
print("Array Sorting using Bubble Sort")
print(data) |
d36ec25fe459d3f97ae0d485e94d1e4374be1391 | aucan/LeetCode-problems | /287.FindtheDuplicateNumber.py | 1,430 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 21:23:43 2020
@author: nenad
"""
"""
Problem URL: https://leetcode.com/problems/find-the-duplicate-number/
Problem description:
Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.
"""
# Full explanation: https://leetcode.com/problems/find-the-duplicate-number/solution/
# Time: O(n), space: O(1)
class Solution:
def findDuplicate(self, nums) -> int:
hare = tortoise = 0
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
tortoise = 0
while tortoise != hare:
tortoise = nums[tortoise]
hare = nums[hare]
return tortoise
sol = Solution()
# Test 1
print(sol.findDuplicate([1,3,4,2,2]))
# Test 2
print(sol.findDuplicate([3,1,3,4,2]))
|
ad53896a1b6391ac861c2f43c63352e0696cbd4a | nyuruk/words.py | /words.py | 2,890 | 3.609375 | 4 | # Generate words from simple rules.
import sys
import re
import random
import json
def from_rule(rule, parameters):
"""
Generates a word that matches the specified rules.
"""
if not rule or not parameters:
return None
# Find all parameters that are wrapped in {}
matches = re.finditer('\\{(.*?)\\}', rule)
result = rule
for match in matches:
parameter = match.group(1)
if parameter not in parameters:
continue
possibilities = parameters[parameter]
next_possibility_index = random.randint(0, len(possibilities) - 1)
pick = possibilities[next_possibility_index]
# Remove the braces surrounding the parameter
result = result.replace('{', '')
result = result.replace('}', '')
# Insert the word that was picked
result = result.replace(parameter, pick, 1)
return result
def from_rules(ruleset, max_amount):
"""
Generates up to `max_amount` of words from the rules defined in the file `ruleset`.
It is not guaranteed to reach `max_amount` of words, in case the ruleset does not contain enough unique combinations.
In such a case, all possible combinations will be created.
"""
input = open(ruleset, 'r')
try:
json_data = json.load(input)
except ValueError:
json_data = None
input.close()
if json_data is None:
raise Exception('The ruleset contains invalid JSON data.')
rules = json_data
if 'formats' not in json_data:
raise Exception('The ruleset must contain a rule definition named `formats`.')
results = []
pairings = rules['formats']
parameters = rules['parameters']
if len(pairings) == 0 or len(parameters) == 0:
# Bail out since there's no rules defined.
return results
generated_amount = 0
retries = 0
while generated_amount < max_amount:
# Keep going until we've generated as close to max_amount as possible.
next_rule_index = random.randint(0, len(pairings) - 1)
rule = pairings[next_rule_index]
result = from_rule(rule, parameters)
if result is not None and result in results:
# Duplicate. Retry.
retries += 1
# This could definitely be improved :)
if retries == 100:
break
continue
results.append(result)
generated_amount += 1
return results
def main(argv):
if len(argv) < 2:
raise Exception('The first argument should be a path to a file containing ruleset data in a JSON format.')
rules = argv[1]
amount = 1
if len(argv) > 2:
amount = int(argv[2])
results = from_rules(rules, amount)
print json.dumps(
results,
sort_keys=True,
indent=2)
if __name__ == "__main__":
main(sys.argv)
|
895fd887deeb17e194103f89dad455000eaf0855 | jinglepp/python_cookbook | /03数字日期和时间/03.03数字的格式化输出.py | 2,113 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# 问题
# 需要将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节。
# 解决方案
# 格式化输出单个数字的时候,可以使用内置的 format() 函数,
# 比如:
x = 1234.56789
print(format(x, '0.2f')) # 两位小数
# 1234.57
print(format(x, '>10.1f')) # 右对齐
# 1234.6
print(format(x, '<10.1f')) # 左对齐
# 1234.6
print(format(x, '^10.1f')) # 居中对齐
# 1234.6
print(format(x, ',')) # 千分符
# 1,234.56789
print(format(x, '0,.1f'))
# 1,234.6
# 如果你想使用指数记法,将f改成e或者E(取决于指数输出的大小写形式)。
# 比如:
print(format(x, 'e')) # 1.234568e+03
print(format(x, '0.2E')) # 1.23E+03
# 同时指定宽度和精度的一般形式是 '[<>^]?width[,]?(.digits)?' ,
# 其中 width 和 digits 为整数,
# ?代表可选部分。
# 同样的格式也被用在字符串的 format() 方法中。
# 比如:
print('The value is {:0,.2f}'.format(x))
# The value is 1,234.57
# 讨论
# 数字格式化输出通常是比较简单的。
# 上面演示的技术同时适用于浮点数和 decimal 模块中的 Decimal 数字对象。
# 当指定数字的位数后,结果值会根据 round() 函数同样的规则进行四舍五入后返回。
# 比如:
print(x) # 1234.56789
print(format(x, '0.1f')) # 1234.6
print(format(-x, '0.1f')) # -1234.6
# 包含千位符的格式化跟本地化没有关系。 如果你需要根据地区来显示千位符,你需要自己去调查下 locale 模块中的函数了。
# 你同样也可以使用字符串的 translate() 方法来交换千位符。比如:
swap_separators = {ord('.'): ',', ord(','): '.'}
print(format(x, ',').translate(swap_separators)) # 1.234,56789
# 在很多Python代码中会看到使用%来格式化数字的,比如:
print('%0.2f' % x)
print('%10.1f' % x)
print('%-10.1f' % x)
# 这种格式化方法也是可行的,不过比更加先进的 format() 要差一点。
# 比如,在使用%操作符格式化数字的时候,一些特性(添加千位符)并不能被支持。
|
aabbc9cd21f5cc2a20aa1089610d7bef134ca5cb | AamodPaud3l/python_assignment_dec15 | /eqnsolve.py | 255 | 3.875 | 4 | #Program to solve a y = mx + c having various values of x
x_values = [1, 2.3, 5.6, 7, 78]
def solve_for_y(values):
m = 45
c = 0.5
for x in values:
y = m * x + c
print("For x={0}, y= {1:.2f}".format(x,y))
solve_for_y(x_values)
|
31af92bbb718ddd1060a54d49aee4e81685e92b0 | jgathogo/python_level_1 | /week4/problem8.py | 19,542 | 3.6875 | 4 | import os
import string
import sys
"""
Notes:
- Thumbs up!
- You probably ran out of time but consider using text alignment. It is a godsend for users.
"""
def main():
# 1000 most common English words
common_words = ["be", "and", "of", "a", "in", "to", "have", "too", "it", "I", "that", "for", "you", "he", "with",
"on", "do", "say", "this", "they", "at", "but", "we", "his", "from", "that", "not", "can’t",
"won’t", "by", "she", "or", "as", "what", "go", "their", "can", "who", "get", "if", "would", "her",
"all", "my", "make", "about", "know", "will", "as", "up", "one", "time", "there", "year", "so",
"think", "when", "which", "them", "some", "me", "people", "take", "out", "into", "just", "see",
"him", "your", "come", "could", "now", "than", "like", "other", "how", "then", "its", "our", "two",
"more", "these", "want", "way", "look", "first", "also", "new", "because", "day", "more", "use",
"no", "man", "find", "here", "thing", "give", "many", "well", "only", "those", "tell", "one",
"very", "her", "even", "back", "any", "good", "woman", "through", "us", "life", "child", "there",
"work", "down", "may", "after", "should", "call", "world", "over", "school", "still", "try", "in",
"as", "last", "ask", "need", "too", "feel", "three", "when", "state", "never", "become", "between",
"high", "really", "something", "most", "another", "much", "family", "own", "out", "leave", "put",
"old", "while", "mean", "on", "keep", "student", "why", "let", "great", "same", "big", "group",
"begin", "seem", "country", "help", "talk", "where", "turn", "problem", "every", "start", "hand",
"might", "American", "show", "part", "about", "against", "place", "over", "such", "again", "few",
"case", "most", "week", "company", "where", "system", "each", "right", "program", "hear", "so",
"question", "during", "work", "play", "government", "run", "small", "number", "off", "always",
"move", "like", "night", "live", "Mr.", "point", "believe", "hold", "today", "bring", "happen",
"next", "without", "before", "large", "all", "million", "must", "home", "under", "water", "room",
"write", "mother", "area", "national", "money", "story", "young", "fact", "month", "different",
"lot", "right", "study", "book", "eye", "job", "word", "though", "business", "issue", "side",
"kind", "four", "head", "far", "black", "long", "both", "little", "house", "yes", "after", "since",
"long", "provide", "service", "around", "friend", "important", "father", "sit", "away", "until",
"power", "hour", "game", "often", "yet", "line", "political", "end", "among", "ever", "stand",
"bad", "lose", "however", "member", "pay", "law", "meet", "car", "city", "almost", "include",
"continue", "set", "later", "community", "much", "name", "five", "once", "white", "least",
"president", "learn", "real", "change", "team", "minute", "best", "several", "idea", "kid", "body",
"information", "nothing", "ago", "right", "lead", "social", "understand", "whether", "back",
"watch", "together", "follow", "around", "parent", "only", "stop", "face", "anything", "create",
"public", "already", "speak", "others", "read", "level", "allow", "add", "office", "spend", "door",
"health", "person", "art", "sure", "such", "war", "history", "party", "within", "grow", "result",
"open", "change", "morning", "walk", "reason", "low", "win", "research", "girl", "guy", "early",
"food", "before", "moment", "himself", "air", "teacher", "force", "offer", "enough", "both",
"education", "across", "although", "remember", "foot", "second", "boy", "maybe", "toward", "able",
"age", "off", "policy", "everything", "love", "process", "music", "including", "consider", "appear",
"actually", "buy", "probably", "human", "wait", "serve", "market", "die", "send", "expect", "home",
"sense", "build", "stay", "fall", "oh", "nation", "plan", "cut", "college", "interest", "death",
"course", "someone", "experience", "behind", "reach", "local", "kill", "six", "remain", "effect",
"use", "yeah", "suggest", "class", "control", "raise", "care", "perhaps", "little", "late", "hard",
"field", "else", "pass", "former", "sell", "major", "sometimes", "require", "along", "development",
"themselves", "report", "role", "better", "economic", "effort", "up", "decide", "rate", "strong",
"possible", "heart", "drug", "show", "leader", "light", "voice", "wife", "whole", "police", "mind",
"finally", "pull", "return", "free", "military", "price", "report", "less", "according", "decision",
"explain", "son", "hope", "even", "develop", "view", "relationship", "carry", "town", "road",
"drive", "arm", "true", "federal", "break", "better", "difference", "thank", "receive", "value",
"international", "building", "action", "full", "model", "join", "season", "society", "because",
"tax", "director", "early", "position", "player", "agree", "especially", "record", "pick", "wear",
"paper", "special", "space", "ground", "form", "support", "event", "official", "whose", "matter",
"everyone", "center", "couple", "site", "end", "project", "hit", "base", "activity", "star",
"table", "need", "court", "produce", "eat", "American", "teach", "oil", "half", "situation", "easy",
"cost", "industry", "figure", "face", "street", "image", "itself", "phone", "either", "data",
"cover", "quite", "picture", "clear", "practice", "piece", "land", "recent", "describe", "product",
"doctor", "wall", "patient", "worker", "news", "test", "movie", "certain", "north", "love",
"personal", "open", "support", "simply", "third", "technology", "catch", "step", "baby", "computer",
"type", "attention", "draw", "film", "Republican", "tree", "source", "red", "nearly",
"organization", "choose", "cause", "hair", "look", "point", "century", "evidence", "window",
"difficult", "listen", "soon", "culture", "billion", "chance", "brother", "energy", "period",
"course", "summer", "less", "realize", "hundred", "available", "plant", "likely", "opportunity",
"term", "short", "letter", "condition", "choice", "place", "single", "rule", "daughter",
"administration", "south", "husband", "Congress", "floor", "campaign", "material", "population",
"well", "call", "economy", "medical", "hospital", "church", "close", "thousand", "risk", "current",
"fire", "future", "wrong", "involve", "defense", "anyone", "increase", "security", "bank", "myself",
"certainly", "west", "sport", "board", "seek", "per", "subject", "officer", "private", "rest",
"behavior", "deal", "performance", "fight", "throw", "top", "quickly", "past", "goal", "second",
"bed", "order", "author", "fill", "represent", "focus", "foreign", "drop", "plan", "blood", "upon",
"agency", "push", "nature", "color", "no", "recently", "store", "reduce", "sound", "note", "fine",
"before", "near", "movement", "page", "enter", "share", "than", "common", "poor", "other",
"natural", "race", "concern", "series", "significant", "similar", "hot", "language", "each",
"usually", "response", "dead", "rise", "animal", "factor", "decade", "article", "shoot", "east",
"save", "seven", "artist", "away", "scene", "stock", "career", "despite", "central", "eight",
"thus", "treatment", "beyond", "happy", "exactly", "protect", "approach", "lie", "size", "dog",
"fund", "serious", "occur", "media", "ready", "sign", "thought", "list", "individual", "simple",
"quality", "pressure", "accept", "answer", "hard", "resource", "identify", "left", "meeting",
"determine", "prepare", "disease", "whatever", "success", "argue", "cup", "particularly", "amount",
"ability", "staff", "recognize", "indicate", "character", "growth", "loss", "degree", "wonder",
"attack", "herself", "region", "television", "box", "TV", "training", "pretty", "trade", "deal",
"election", "everybody", "physical", "lay", "general", "feeling", "standard", "bill", "message",
"fail", "outside", "arrive", "analysis", "benefit", "name", "sex", "forward", "lawyer", "present",
"section", "environmental", "glass", "answer", "skill", "sister", "PM", "professor", "operation",
"financial", "crime", "stage", "ok", "compare", "authority", "miss", "design", "sort", "one", "act",
"ten", "knowledge", "gun", "station", "blue", "state", "strategy", "little", "clearly", "discuss",
"indeed", "force", "truth", "song", "example", "democratic", "check", "environment", "leg", "dark",
"public", "various", "rather", "laugh", "guess", "executive", "set", "study", "prove", "hang",
"entire", "rock", "design", "enough", "forget", "since", "claim", "note", "remove", "manager",
"help", "close", "sound", "enjoy", "network", "legal", "religious", "cold", "form", "final", "main",
"science", "green", "memory", "card", "above", "seat", "cell", "establish", "nice", "trial",
"expert", "that", "spring", "firm", "Democrat", "radio", "visit", "management", "care", "avoid",
"imagine", "tonight", "huge", "ball", "no", "close", "finish", "yourself", "talk", "theory",
"impact", "respond", "statement", "maintain", "charge", "popular", "traditional", "onto", "reveal",
"direction", "weapon", "employee", "cultural", "contain", "peace", "head", "control", "base",
"pain", "apply", "play", "measure", "wide", "shake", "fly", "interview", "manage", "chair", "fish",
"particular", "camera", "structure", "politics", "perform", "bit", "weight", "suddenly", "discover",
"candidate", "top", "production", "treat", "trip", "evening", "affect", "inside", "conference",
"unit", "best", "style", "adult", "worry", "range", "mention", "rather", "far", "deep", "front",
"edge", "individual", "specific", "writer", "trouble", "necessary", "throughout", "challenge",
"fear", "shoulder", "institution", "middle", "sea", "dream", "bar", "beautiful", "property",
"instead", "improve", "stuff", "claim"]
# text = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of " \
# "foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it " \
# "was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything " \
# "before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the " \
# "other way—in short, the period was so far like the present period, that some of its noisiest authorities " \
# "insisted on its being received, for good or for evil, in the superlative degree of comparison only. " \
# "There were a king with a large jaw and a queen with a plain face, on the throne of England; there were a " \
# "king with a large jaw and a queen with a fair face, on the throne of France. In both countries it was " \
# "clearer than crystal to the lords of the State preserves of loaves and fishes, that things in general " \
# "were settled for ever. It was the year of Our Lord one thousand seven hundred and seventy-five. Spiritual " \
# "revelations were conceded to England at that favoured period, as at this. Mrs. Southcott had recently " \
# "attained her five-and-twentieth blessed birthday, of whom a prophetic private in the Life Guards had " \
# "heralded the sublime appearance by announcing that arrangements were made for the swallowing up of London " \
# "and Westminster. Even the Cock-lane ghost had been laid only a round dozen of years, after rapping out " \
# "its messages, as the spirits of this very year last past (supernaturally deficient in originality) rapped " \
# "out theirs. Mere messages in the earthly order of events had lately come to the English Crown and People, " \
# "from a congress of British subjects in America: which, strange to relate, have proved more important to " \
# "the human race than any communications yet received through any of the chickens of the Cock-lane brood. " \
# "France, less favoured on the whole as to matters spiritual than her sister of the shield and trident, " \
# "rolled with exceeding smoothness down hill, making paper money and spending it. Under the guidance of her " \
# "Christian pastors, she entertained herself, besides, with such humane achievements as sentencing a youth " \
# "to have his hands cut off, his tongue torn out with pincers, and his body burned alive, because he had not " \
# "kneeled down in the rain to do honour to a dirty procession of monks which passed within his view, at a " \
# "distance of some fifty or sixty yards. It is likely enough that, rooted in the woods of France and Norway, " \
# "there were growing trees, when that sufferer was put to death, already marked by the Woodman, Fate, to " \
# "come down and be sawn into boards, to make a certain movable framework with a sack and a knife in it, " \
# "terrible in history. It is likely enough that in the rough outhouses of some tillers of the heavy lands " \
# "adjacent to Paris, there were sheltered from the weather that very day, rude carts, bespattered with " \
# "rustic mire, snuffed about by pigs, and roosted in by poultry, which the Farmer, Death, had already " \
# "set apart to be his tumbrils of the Revolution. But that Woodman and that Farmer, though they work " \
# "unceasingly, work silently, and no one heard them as they went about with muffled tread: the rather, " \
# "forasmuch as to entertain any suspicion that they were awake, was to be atheistical and traitorous. " \
# "In England, there was scarcely an amount of order and protection to justify much national boasting. " \
# "Daring burglaries by armed men, and highway robberies, took place in the capital itself every night; " \
# "families were publicly cautioned not to go out of town without removing their furniture to upholsterers’ " \
# "warehouses for security; the highwayman in the dark was a City tradesman in the light, and, being " \
# "recognised and challenged by his fellow-tradesman whom he stopped in his character of “the Captain,” " \
# "gallantly shot him through the head and rode away; the mail was waylaid by seven robbers, and the " \
# "guard shot three dead, and then got shot dead himself by the other four, “in consequence of the failure " \
# "of his ammunition:” after which the mail was robbed in peace; that magnificent potentate, the Lord Mayor " \
# "of London, was made to stand and deliver on Turnham Green, by one highwayman, who despoiled the " \
# "illustrious creature in sight of all his retinue; prisoners in London gaols fought battles with their " \
# "turnkeys, and the majesty of the law fired blunderbusses in among them, loaded with rounds of shot and " \
# "ball; thieves snipped off diamond crosses from the necks of noble lords at Court drawing-rooms; " \
# "went into St. Giles’s, to search for contraband goods, and the mob fired on the musketeers, and the " \
# "musketeers fired on the mob, and nobody thought any of these occurrences much out of the common way. " \
# "In the midst of them, the hangman, ever busy and ever worse than useless, was in constant requisition; " \
# "now, stringing up long rows of miscellaneous criminals; now, hanging a housebreaker on Saturday who " \
# "had been taken on Tuesday; now, burning people in the hand at Newgate by the dozen, and now burning " \
# "pamphlets at the door of Westminster Hall; to-day, taking the life of an atrocious murderer, and " \
# "to-morrow of a wretched pilferer who had robbed a farmer’s boy of sixpence. All these things, and a " \
# "thousand like them, came to pass in and close upon the dear old year one thousand seven hundred and " \
# "seventy-five. Environed by them, while the Woodman and the Farmer worked unheeded, those two of the " \
# "jaws, and those other two of the plain and the fair faces, trod with stir enough, and carried their " \
# "divine rights with a high hand. Thus did the year one thousand seven hundred and seventy-five conduct " \
# "their Greatnesses, and myriads of small creatures—the creatures of this chronicle among the rest—along " \
# "the roads that lay before them."
text = input("Paste a paragraph of text copied from any website: ")
# clean text
text_lower = text.lower()
punctuation = string.punctuation + '—'
for char in punctuation:
text_lower = text_lower.replace(char, '')
text_l = text_lower.split(" ")
# find out if word is non-common
# non_common = []
# for word in text_l:
# if word not in common_words:
# if word not in non_common:
# non_common.append(word)
# print(non_common) # print words not in common_words
freq_d = {}
non_common = []
# good!
for word in text_l:
if word in common_words:
if word in freq_d:
freq_d[word] += 1
else:
freq_d[word] = 1
else:
non_common.append(word)
print(f"List of non-common words:\n"
f"{set(non_common)}\n")
print("Relative frequency of common words, in descending order: ")
sorted_keys = sorted(freq_d, key=freq_d.get, reverse=True)
for word in sorted_keys:
number = freq_d[word]
freq = str(round(number / len(text_l) * 100, ndigits=2)) + '%'
print(word, freq, sep=' - ')
return os.EX_OK
if __name__ == "__main__":
sys.exit(main())
|
061714b286b1481edc102b893e83f05ebb88faf8 | giutrec/FablabDoorman | /www/datemanager.py | 498 | 3.734375 | 4 | #!/usr/bin/env python
from sys import argv
from datetime import datetime
format = "%Y-%m-%d %H:%M"
start_time = "16:00"
stop_time = "20:00"
now = datetime.today()
start_date_string = now.strftime("%Y-%m-%d ") + start_time
start_date = datetime.strptime(start_date_string, format)
stop_date_string = now.strftime("%Y-%m-%d ") + stop_time
stop_date = datetime.strptime(stop_date_string, format)
weekday = now.isoweekday()
if weekday <= 5:
if now >= start_date and now <= stop_date:
print 'a'
|
7d01a498c8984d3674a549745126f0e498e4f350 | jgjefersonluis/python-pbp | /secao02-basico/aula22-valormaiormenor/main.py | 458 | 4.03125 | 4 | # Escreva um programa para exibir o maior e menor valor uma vez digitado pelo usuario
a = int(input('Digite o primeiro valor: '))
b = int(input('Digite o segundo valor: '))
c = int(input('Digite o terceiro valor: '))
maior = a
if b > c and b > a:
maior = b
if c > b and c > a:
maior = c
menor = a
if b < c and b < a:
menor = b
if c < b and c < a:
menor = c
print('O menor valor é %d : ' % menor)
print('O maior valor é %d : ' % maior)
|
90fd936722b928db36e7f404309bb0c08dcb35a8 | svenkat19/snap | /benchmark/python/fib-recurs.py | 82 | 3.578125 | 4 | def fib(n):
if n <= 2: return n
return fib(n - 1) + fib(n - 2)
print(fib(35)) |
7451c0b64380a280e6d5943230bf1034e86f3cb2 | biomathcode/Rosalind_solutions | /Strings_and_lists.py | 980 | 3.703125 | 4 | """
Given: A string s of length at most 200 letters and 4 integers a, b, c and d
Return:The slice of this string from indices a through b and c through d (with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our slice.
"""
SampleText = "HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain."
while True:
try:
f1, f2, f3, f4 = [ int(x) for x in input("Enter the four indices: ").split()]
break
except ValueError:
print('Please give four indices!!!! ')
Text= input("please give the text here")
print("this first indices is", f1)
print("the second indices is ", f2)
def Output_function(Text, f1 , f2 , f3, f4):
if Text is not None:
return print(Text[f1:f2 + 1] + " " + Text[f3:f4 + 1])
else:
return print(SampleText[f1:f2 + 1] + " " + SampleText[f3:f4 + 1])
Output_function(Text, f1, f2, f3, f4)
|
98786b98b44e4c24374581dd374350bf992702c3 | hatlonely/leetcode-2018 | /python/119_pascals_triangle_ii.py | 295 | 3.84375 | 4 | #!/usr/bin/env python3
class Solution:
def getRow(self, n):
if n == 0:
return [1]
row = self.getRow(n - 1)
return [1] + [row[i] + row[i+1] for i in range(0, len(row) - 1)] + [1]
if __name__ == '__main__':
print(Solution().getRow(3), [1, 3, 3, 1])
|
c9e7b8d0917bf711109ccb13858b5c88fd4545d5 | yung-pietro/learn-python-the-hard-way | /EXERCISES/ex23.py | 1,532 | 4.1875 | 4 | import sys
script, input_encoding, error = sys.argv
#the argv's that the script requires
def main(language_file, encoding, errors):
#creates function, main, with three inputs, language_file, encoding, and errors. But where do these come from?
line = language_file.readline()
#not sure
if line:
#if statement related to the line variable above. In this case, we are checking the first line to see if it contains anything.
#? How is he testing that this line has something in it?
print_line(line, encoding, errors)
#print_line appears to be a native function. Indeed it is.
return main(language_file, encoding, errors)
# This is calling main, which jumps to the top, creating a loop. The if line statement breaks the loop, when it reaches a blank line.
def print_line(line, encoding, errors):
next_lang = line.strip()
#strip() removes the leading and trailing blank space from the line, assigning it to next_lang. In this case removes the \n
raw_bytes = next_lang.encode(encoding, errors=errors)
#I pass to encode() the encoding I want and how to handle errors.
cooked_string = raw_bytes.decode(encoding, errors=errors)
# This line decodes the raw bytes, passing to decode the encoding I want and how to handle errors. This just basically
# re-assembles (decodes) the raw bytes back into a string
print(raw_bytes, "<===>", cooked_string)
languages = open("languages.txt", encoding="utf-8")
main(languages, input_encoding, error)
|
4049df6753bb05a3656ad534054b54c96af1119c | Barret-ma/leetcode | /567. Permutation in String.py | 1,411 | 3.828125 | 4 | # Given two strings s1 and s2, write a function to return true if s2 contains
# the permutation of s1. In other words, one of the first string's permutations
# is the substring of the second string.
# Example 1:
# Input: s1 = "ab" s2 = "eidbaooo"
# Output: True
# Explanation: s2 contains one permutation of s1 ("ba").
# Example 2:
# Input:s1= "ab" s2 = "eidboaoo"
# Output: False
# Note:
# The input strings only contain lower case letters.
# The length of both given strings is in range [1, 10,000].
from collections import defaultdict, Counter
class Solution(object):
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if not s1 or not s2 or len(s1) > len(s2):
return False
left = 0
right = 0
# hashMap = defaultdict(lambda: 0)
count = 0
hashMap = Counter(s1)
while (right < len(s2)):
hashMap[s2[right]] -= 1
if (hashMap[s2[right]] >= 0):
count += 1
while left < right and hashMap[s2[left]] < 0:
hashMap[s2[left]] += 1
left += 1
if count == len(s1) and right - left + 1 == len(s1):
return True
right += 1
return False
s = Solution()
# s.checkInclusion('ab', 'eidbaooo')
print(s.checkInclusion('abc', 'bbbca')) |
7c1386e726f4867617ac9682657532da2425df07 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/returning_values.py | 1,324 | 4.25 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def area_triangle(base, height):
""" Calculate the area of triange by multipling `base` by `height` """
return base * height / 2
def get_seconds(hours, minutes, seconds):
""" Calculate the `hours` and `minutes` into seconds, then add with
the `seconds` paramater. """
return 3600*hours + 60*minutes + seconds
def convert_seconds(seconds):
""" Convert the duration of time in 'seconds' to the equivalent
number of hours, minutes, and seconds. """
hours = seconds // 3600
minutes = (seconds - hours * 3600) // 60
remaining_seconds = seconds - hours * 3600 - minutes * 60
return hours, minutes, remaining_seconds
def greeting(name):
""" Print out a greeting with provided `name` parameter. """
print("Welcome, " + name)
AREA_A = area_triangle(5, 4)
AREA_B = area_triangle(7, 3)
SUM = AREA_A + AREA_B
print("The sum of both areas is: " + str(SUM))
AMOUNT_A = get_seconds(2, 30, 0)
AMOUNT_B = get_seconds(0, 45, 15)
result = AMOUNT_A + AMOUNT_B
print(result)
HOURS, MINUTES, SECONDS = convert_seconds(5000)
print(HOURS, MINUTES, SECONDS)
# Assigning result of a function call, where the function has no return
# will result in 'None'
RESULT = greeting("Christine")
print(RESULT)
|
5f3fce4dec43a93460b56832074440249eae4b32 | mbuhot/mbuhot-euler-solutions | /python/problem-052.py | 577 | 3.734375 | 4 | #! /usr/bin/env python3
from itertools import count
description = '''
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
'''
def digitStr(i):
return ''.join(sorted(str(i)))
def multiplesShareDigits(i):
ds = digitStr(i)
return all(digitStr(x) == ds for x in [i*2, i*3, i*4, i*5, i*6])
answers = (i for i in count(1) if multiplesShareDigits(i))
print(next(answers))
|
4fd5e020d013ebe4000749cee5b1ece25621c713 | bkyileo/algorithm-practice | /python/Longest Common Prefix.py | 736 | 3.84375 | 4 | __author__ = 'BK'
'''
Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
'''
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return
common=strs[0]
for i in strs:
if len(i)<len(common):
common=i
for i in strs:
for j in xrange(len(common)):
if common[j] != i[j]:
common = common[0:j]
break
return common
solu = Solution()
a=['abcd','abc','abcab','abcde']
print solu.longestCommonPrefix(a) |
f728bda2423de4a317a3609c46f59a6e397b0745 | UniqueDavid/Python | /day6/demo-property.py | 552 | 3.859375 | 4 | #使用@property进行可以设置一个getter函数,即返回一个值
#使用score.setter可以设置相关的值,这里面第一个参数为self,第二个为value
class Student(object):
@property
def name(self):
return self.__name
@property
def score(self):
return self.__score
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError('Score must be an integer!')
if value <0 or value>100:
raise ValueError('Score must between 0~100!')
self.__score=value
s=Student()
s.score=60
print(s.score)
|
50c659616892deecac7a0122bb08a52628386405 | Anishde85/Hacktoberfest21_Algo_Collection | /Python/binary-search.py | 263 | 3.84375 | 4 | def binary_search(arr, n):
st = 0
end = len(arr) - 1
while(st < end):
mid = (st+end)//2
if arr[mid] == n:
return True
elif arr[mid] < n:
end = mid-1
else:
st = mid+1
return False
|
6e93dd515d6e6390ab79034520c0290177b598f1 | adnan15110/DataCompressionWithAdvise | /context_tree/context_tree.py | 2,016 | 3.921875 | 4 |
class TrieNode:
# Trie node class
def __init__(self):
self.children = [] # can be improved by having a dict
self.data = 0
self.count=0
# isEndOfWord is True if node represent the end of the word
self.isEnd = False
class Trie:
# Trie data structure class
def __init__(self):
self.root = self.getNode()
def getNode(self):
# Returns new trie node (initialized to NULLs)
return TrieNode()
def insert(self, key):
pCrawl = self.root
length = len(key)
for ind, char in enumerate(key):
# check if the char already exist in that level or not
child_found=False
for child in pCrawl.children:
if child.data == char:
child_found=True
pCrawl=child
pCrawl.count+=1
break
if not child_found:
new_node = self.getNode()
new_node.data=char
new_node.count=1
pCrawl.children.append(new_node)
pCrawl=pCrawl.children[-1]
pCrawl.isEnd = True
def search(self, key):
pCrawl = self.root
length = len(key)
found=False
for ind, char in enumerate(key):
for child in pCrawl.children:
if child.data==char:
found=True
pCrawl=child
break
if not found:
break
if found:
return pCrawl.count
else:
return 0
class Queue:
def __init__(self):
self.queue = list()
def enqueue(self,data):
self.queue.append(data)
return True
def dequeue(self):
if len(self.queue)>0:
return self.queue.pop(0)
return ("Queue Empty!")
def size(self):
return len(self.queue)
def getQueueData(self):
return ''.join(d for d in self.queue) |
09c1890b291b58e9b585818a888d448f48fb92fc | gqjuly/hipython | /helloword/2020_7_days/nine_class/c8.py | 677 | 3.625 | 4 |
from c9 import Human
"""
继承性:
避免我们定义重复的方法和变量
"""
class Student(Human):
def __init__(self, school, name, age):
self.school = school
# Human.__init__(self,name, age)
super(Student, self).__init__(name, age)
# self.__sorce = 0
def do_homework(self):
super(Student, self).do_homework()
print('english homework')
"""
变量都是可以继承的
"""
# student1 = Student('刘越', 68)
# print(student1.my_sum)
# print(Student.my_sum)
# print(student1.name)
# print(Student.name)
student1 = Student('人民路小学', '刘越', 68)
print(student1.school)
student1.do_homework()
|
6658a8791cec18480fcca1661a942952f52cad72 | st-pauls-school/bio | /2012/q1/python/distinct-prime-factorisation.py | 1,060 | 3.734375 | 4 | def primes(ubound):
rv = [2]
candidates = [x for x in range(3,ubound+1,2)]
candidate = 2
while candidate < ubound**0.5:
candidate = candidates[0]
rv.append(candidate)
# this resizing of the lists is somewhat sub-optimal, considering re-writing, e.g. https://stackoverflow.com/a/3941967
candidates = list(filter(lambda x: x % candidate != 0, candidates))
return rv + candidates
def distinct_primes(value):
rv = []
list_of_primes = primes(value)
while value > 1:
if value % list_of_primes[0] == 0:
rv.append(list_of_primes[0])
value //= list_of_primes[0]
else:
list_of_primes.pop(0)
product = 1
for i in set(rv):
product *= i
return product
print(distinct_primes(100) == 10)
print(distinct_primes(101) == 101)
print(distinct_primes(2) == 2)
print(distinct_primes(1001) == 1001)
print(distinct_primes(371293) == 13)
print(distinct_primes(789774) == 789774)
print(distinct_primes(999883) == 999883)
print(distinct_primes(561125) == 335)
print(distinct_primes(661229) == 4379)
|
c6469d2a545f3249abcc3539f22bd2d7ae1d1af6 | gitPty/windows7 | /windows7/unit16/highs_lows.py | 1,283 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 19:14:04 2019
@author: Administrator
"""
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高气温
filename ='death_valley_2014.csv'
with open (filename) as f:
reader =csv.reader(f)
header_row =next(reader)
dates,highs,lows=[],[],[]
for row in reader:
try:
current_date =datetime.strptime(row[0],"%Y-%m-%d")
high=int(row[1])
low =int(row[3])
except ValueError:
print(current_date,"missing data")
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
#print(highs)
#根据数据绘制图像
fig =plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5)
plt.plot(dates,lows,c='blue',alpha=0.5)
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.3)
#设置图像格式
plt.title("Daily high and low tempratures - 2014-death",fontsize =24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()
plt.ylabel("Temprature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=10)
plt.xlim(dates[0],dates[-1])
plt.show() |
96d86117bb5a578e1ad5f43ae51f4b4b2518a171 | Togas/algorithms | /sorting/insertionSort.py | 292 | 3.984375 | 4 | #sort in place
def insertionSort(array):
for i in range(1, len(array)):
j = i-1
while j >= 0:
if array[i] < array[j]:
array[i], array[j] = array[j], array[i]
j -= 1
i -= 1
else:
break
|
3317d6468880bb73ae91beb4dcba99c0f932f8ae | aming0518/PythonStudy | /替换和空格的消除.py | 262 | 4.3125 | 4 |
mystr="hello 123 hello 123"
print(mystr.replace("123","python"))#替换
print(mystr)
print(mystr.replace("123","python",1))#1,限制次数
print(" ab c ".strip())#前后去掉空格
print(" ab c ".rstrip())#去掉右边空格
print(" ab c ".lstrip())
|
19adc927fecadd9ad39523d8de8cfd702250500f | mindnhand/Learning-Python-5th | /Chapter19.AdvancedFunctionTopics/sumtree.py | 1,622 | 4.3125 | 4 | #!/usr/bin/env python3
#encoding=utf-8
#---------------------------------------------------------
# Usage: python3 sumtree.py
# Description: why recursive function
#---------------------------------------------------------
'''
recursion--or equivalent explicit stack-based algorithms we'll meet
shortly--can be required to traverse arbitrarily shaped structures.
[1, [2, [3, 4], 5], 6, [7, 8]] # Arbitrarily nested sublists
Simple looping statements won't work here because this is not a linear iteration. Nested
looping statements do not suffice either, because the sublists may be nested to arbitrary
depth and in an arbitrary shape--there's no way to know how many nested loops to
code to handle all cases. Instead, the following code accommodates such general nesting
by using recursion to visit sublists along the way:
'''
def sumtree(seq):
tot = 0
for x in seq: # For each item at this level
if not isinstance(x, list):
tot += x # If x is not a list, add numbers directly
else:
tot += sumtree(x) # If x is a list, recur for sumtree function call
return tot
#-------------------------------test----------------------------------
seq_lst = [1, [2, [3, 4], 5], 6, [7, 8]] # Arbitrary nesting structure
sum_res = sumtree(seq_lst) # sum_res is 36
print('The sum result of %s is %s' % (seq_lst, sum_res))
# Pathological cases
print(sumtree([1, [2, [3, [4, [5]]]]])) # Prints 15 (right-heavy)
print(sumtree([[[[[1], 2], 3], 4], 5])) # Prints 15 (left-heavy)
|
57269b576346b40c264a51748cdee321e490db65 | joybakes/HB-Exercise09 | /recursion.py | 1,932 | 4 | 4 | # Multiply all the elements in a list
def multiply_list(l):
total = 1 # Set total to 1
if l == []: # Set the base case, if our list is empty
return 1 # return 1
else: #if our list is not empty
total = l.pop() * multiply_list(l) # total is equal to last number in list * multiply_list(l)
return total
# Return the factorial of n
def factorial(n):
total = 1
if n == 1:
return 1
else:
total = factorial(n-1) * n
return total
# Count the number of elements in the list l
def count_list(l):
total = 0
if l == []:
return 0
else:
l.pop()
total = count_list(l) + 1
return total
# Sum all of the elements in a list
def sum_list(l):
total = 0
if l == []:
return 0
else:
total = l.pop() + sum_list(l)
return total
# Reverse a list without slicing or loops
def reverse(l):
# l.reverse() is what one would do if they were NOT insane. Insane people
# write recursive ridiculousness here:
if len(l) == 1:
return l
temp = l.pop()
return [temp] + reverse(l)
# Fibonacci returns the nth fibonacci number. The nth fibonacci number is
# defined as fib(n) = fib(n-1) + fib(n-2)
def fibonacci(n):
if n <= 3:
return n
return fibonacci(n-2) + fibonacci(n-1)
# Finds the item i in the list l.... RECURSIVELY
def find(l, i):
if len(l) == 1:
return
return i
else
return find(l,i)
# Determines if a string is a palindrome
def palindrome(some_string):
return False
# Given the width and height of a sheet of paper, and the number of times to fold it, return the final dimensions of the sheet as a tuple. Assume that you always fold in half along the longest edge of the sheet.
def fold_paper(width, height, folds):
return (0, 0)
# Count up
# Print all the numbers from 0 to target
def count_up(target, n):
return
|
fb3a79f78c218ceece9e075baaa51b246b7fa92d | manjunatha-kasireddy/python | /python/practice/ifelse/for2.py | 630 | 3.96875 | 4 | ex = ["c-lang", "java", "python", "html", "javascript"]
for x in ex:
print(x)
for x in "java":
print(x)
for x in ex:
print(x)
if x == "python":
break
for x in ex:
if x == "html":
break
print(x)
for x in ex:
if x == "c-lang":
continue
print(x)
for x in range(6):
print(x)
for x in range(2, 6):
print(x)
for x in range(2, 30, 3):
print(x)
for x in range(6):
print(x)
else:
print("Finally finished!")
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
adj = ["red", "big", "tasty"]
for x in adj:
for y in ex:
print(x, y) |
7f876fbd61655d286b2406f1d371e5e439e084b5 | eronekogin/leetcode | /2020/increasing_order_search_tree.py | 696 | 3.75 | 4 | """
https://leetcode.com/problems/increasing-order-search-tree/
"""
from test_helper import TreeNode
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
currNode, stack = root, []
newRoot = currRoot = None
while currNode or stack:
while currNode:
stack.append(currNode)
currNode = currNode.left
currNode = stack.pop()
currNode.left = None
if not newRoot:
newRoot = currRoot = currNode
else:
currRoot.right = currNode
currRoot = currRoot.right
currNode = currNode.right
return newRoot
|
687fb311b55c26b81a942481bdfd6e633dd32986 | nfu13026/FruitGuessingGame | /fruitGuessinggame v0.9.py | 4,127 | 4.21875 | 4 | #fruitGuessinggame
#Nathaniel Fu
#Version 0.9
import time
import sqlite3
import random
def randomFruit(): #This function is connected to a database in order to randomly select a fruit from a database which contains a list of fruit.
with sqlite3.connect("FruitDatabase(GitHub)/fruits.db") as db: #Here is the code that connects my database to randomFruit function.
cursor = db.cursor()
cursor.execute("select FruitName from fruits")
fruitList = cursor.fetchall()
selectFruit = random.choice(fruitList) #A fruit is randomly selected from the database.
result = True
while result == True:
result = jumbleFruit(selectFruit) #Send selectFruit to jumbleFruit function.
selectFruit = random.choice(fruitList) #A fruit is randomly selected from the database.
if result == False:
userOption = input("Please select an option:\n"
"1. Play Again\n"
"2. Quit\n")
while userOption != '1' and userOption != '2':
print ("Invalid entry\n")
userOption = input("Please select an option:\n"
"1. Play Again\n"
"2. Quit\n")
if userOption == '1':
result = True
print ("Good-Bye")
def jumbleFruit(selectFruit): #This function jumbles a string and displays it for the player to guess the jumbled word.
jumbledFruit = str(''.join(selectFruit)) #Change selectFruit variable into string type.
jumbledFruit = list(jumbledFruit) #Then change selectFruit into a list type. This enables random.shuffle module to shuffle the word.
random.shuffle(jumbledFruit) #Word gets shuffled here using random.shuffle module.
print("The jumbled fruit is... ")
print(''.join(jumbledFruit)) #Print jumbledFruit
userGuess = input("Enter your guess: ") #The player is asked to enter a guess.
counter = 4
while counter > 1:
if userGuess == str(''.join(selectFruit)): #If userGuess is the same as selectFruit, print "Good Job."
print("Good Job. Here comes the next fruit.")
return True
elif userGuess != str(''.join(selectFruit)): #Else/if userGuess is not the same as selectFruit, let the player try again.
counter = counter -1
userGuess = input("You have {0} more guesses left. Please guess again: ".format(counter))
if counter == 1:
userGuess = input("You are out of guesses. Make a final guess: ")
if userGuess == str(''.join(selectFruit)):
print("Good job.")
return True
else:
print("Bad luck")
return False
def fruitGuessinggame(): #This function requests for the players name.
print("Welcome to fruit guessing game.\n") #Welcomes the user to fruit guessing game.
print("How To Play: Unscramble the letters to make a word.")
print("NOTE: You have 4 guesses. If you get the first guess wrong a guess is taken off you.\n"
"For every jumbled fruit you will start with 4 guesses.\n"
"If you guess right, you move onto the next jumbled fruit.\n") #Instructions of how to play fruit guessing game.
userName = input("Enter player name: ") #Requests for a name.
while True:
if any(char.isdigit() for char in userName) == True:
userName = input("Enter your name again: ") #Ask for their name again because they might have entered integers.
elif len(userName) > 15 or len(userName) < 3:
userName = input("It's too long or too short. Please try again: ") #Asks for the player's name again because it contains over 15 characters or less than 3 characters.
else:
print("Hello, nice to meet you {0}".format(userName)) #Else, print userName.
break #Break out of while loop
randomFruit() #Go to randomFruit function.
fruitGuessinggame()
|
0f1e6e52b35ccd27212dc7bf1a3566f404fb497b | luffyx25/msc-data-science | /INM430/Week01-part1.py | 2,725 | 3.984375 | 4 | # https://moodle.city.ac.uk/mod/page/view.php?id=1174260
import csv # imports the csv module
import sys # imports the sys module
# total rows
total = 0;
f = open('TB_burden_countries_2014-09-29.csv') # opens the csv file
# Exercises Part-1: Some elementary Python tasks
# 1. Count the number of rows in the csv file you've chosen.
for row in csv.reader(f):
total = total + 1
print("Total rowcount =", total)
# reset
total = 0;
f.seek(0)
errcount = 0
# 2. Pick one of the columns with numeric data and calculate the average value using a loop
for row in csv.reader(f):
total = total + 1
# skip column headers
if(total > 1):
try:
colsum = colsum + float(row[11])
except ValueError:
errcount += 1
# subtract errors
total = total - errcount
# subtract column headers
total = total - 1
# calculate average
colavg = colsum/total
print("Average e_prev_num_lo (column 12) = ", colavg)
print("Errorcount =", errcount)
# 3. Now, repeat step-2 above but this time find the averages for years 1990 and 2011.
# Have you observed any difference?
# reset
total = 0;
f.seek(0)
total1990 = 0
total2011 = 0
colsum1990 = 0;
colsum2011 = 0;
errcount1990 = 0
errcount2011 = 0
for row in csv.reader(f):
total = total + 1
# skip column headers
if(total > 1):
# 1990
if(int(row[5]) == 1990):
try:
total1990 += 1
colsum1990 = colsum1990 + float(row[11])
except ValueError:
errcount1990 += 1
if(int(row[5]) == 2011):
try:
total2011 += 1
colsum2011 = colsum2011 + float(row[11])
except ValueError:
errcount2011 += 1
# subtract errors
total1990 = total1990 - errcount1990
# subtract column headers N/A
# calculate average
colavg1990 = colsum1990/total1990
print("Total rowcount 1990 =", total1990)
print("Average 1990 e_prev_num_lo (column 12) = ", colavg1990)
print("Errorcount 1990 =", errcount1990)
# subtract errors
total2011 = total2011 - errcount2011
# subtract column headers N/A
# calculate average
colavg2011 = colsum2011/total2011
print("Total rowcount 2011 =", total2011)
print("Average 2011 e_prev_num_lo (column 12) = ", colavg2011)
print("Errorcount 2011 =", errcount2011)
"""
OUTPUT
Total rowcount = 4904
Average e_prev_num_lo (column 12) = 567593.7190392482
Errorcount = 11
Total rowcount 1990 = 211
Average 1990 e_prev_num_lo (column 12) = 44379.73417061612
Errorcount 1990 = 1
Total rowcount 2011 = 216
Average 2011 e_prev_num_lo (column 12) = 33320.0524537037
Errorcount 2011 = 1
CONCLUSION: Lower incidence of TB from 1990 to 2011
""" |
b44c973d8ed585904175d4789ca16a361f5a06d7 | ds-ga-1007/assignment9 | /zk388/auxilary_functions.py | 2,576 | 4.03125 | 4 | '''
Created on Dec 3, 2016
@author: Zahra KAdkhodaie
'''
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.text import Text
'''Load the datasets. These datasets must be in the same folder as the code.'''
countries = pd.read_csv('countries.csv')
income = pd.read_excel('indicator gapminder gdp_per_capita_ppp.xlsx ')
'''transform the data set to have years as the rows and countries as the columns,
then show the head of this data set when it is loaded.'''
income_rotated = income.T
income_rotated = income_rotated.drop('gdp pc test')
income_rotated.head()
income_rotated.columns = income['gdp pc test']
print(income_rotated.head())
def visualize_income_year(year):
'''This function graphically displays the distribution of income per person across all countries in the world for
the given year with a bar chart. The bar chart has an slider and can be use in an interactive way. '''
#prepare the data set to be used
income_year = income_rotated.ix[year]
income_year = income_year.dropna()
income_year.sort()
myfigure = plt.figure(figsize=(16, 8))
myaxes = myfigure.add_subplot(1, 1, 1)
myfigure.subplots_adjust(bottom=0.3) #make room for x labels
x_values = range(1, len(income_year)+1 )
myaxes.bar(x_values, income_year.values , width =.5, edgecolor = 'green')
myaxes.set_xticks([x + 0.25 for x in x_values ])
myaxes.set_xticklabels(income_year.index, size = 'small')
plt.xticks(rotation=80)
plt.title('Income per person by country in year ' + str(year))
myfigure.text(.1,.1, 'Use the slider to explore the graph', color= 'red', size='large')
myaxes.set_xlim(1, 30)
Slider_axes = plt.axes([0.15, 0.03, 0.7, 0.03])
myslider = Slider(Slider_axes, 'Slider', 0, len(income_year)-30, valinit = 5)
myslider.valtext.set_visible(False)
def update(val):
myaxes.axis([myslider.val, myslider.val + 30, 0, income_year.max()])
myfigure.canvas.draw_idle()
myslider.on_changed(update)
plt.show()
def merge_by_year(year):
'''merges the countries and income data sets for any given year.
The result is a DataFrame with three columns titled Country, Region, and Income.'''
if year not in income.columns:
return ('No data for this year!')
else:
smallData = income[['gdp pc test' , year]]
smallData.columns = ['Country', 'Income']
mergedData = smallData.merge(right = countries, how = 'inner', on= 'Country')
return mergedData |
1f71d6171e834e059d77958f9f3adecc68e0c139 | MuhammadSaqib-Github/Python | /Assignment 2/Question #3.py | 473 | 3.703125 | 4 | lisT = [1 ,2 ,2 ,2 ,2 ,1 ,3 ,1 ,3 ,3 ,3 ,1 ,5 ,5 ,5 ,0 ]
occurence = 0
length = len(lisT)
for i in range(length):
counter=0
x=i
for j in range(length):
y=j
if (lisT[i]==lisT[j]):
if y-x==0 or y-x==1:
counter=counter+1
x+=1
y+=1
if occurence<counter:
occurence= counter
word = lisT[i]
print("word is " , word , "and occured " , occurence , "times") |
f3382d622452146775228c4068fb5363fe051bc6 | simrit1/asimo | /Chap 20/alice_words.py | 2,218 | 3.671875 | 4 | def text_to_words(the_text):
""" return a list of words with all punctuation removed
and all in lowercase """
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these
"abcdefghijklmnopqrstuvwxyz ")
# Translate the text now.
cleaned_text = the_text.translate(my_substitutions)
wds = cleaned_text.split()
return wds
def get_words_in_book(filename):
""" Read a book from filename, and return a list of words """
f = open(filename, "r")
content = f.read()
f.close()
wds = text_to_words(content)
return wds
book_words = get_words_in_book("AliceInWonderland.txt")
book_words.sort() # Make order at this words list
def make_dic(lis):
""" make dictionary from a list """
dic = {} # Set initial dic
for i in lis:
dic[i] = dic.get(i, 0) + 1
return dic
book_dic = make_dic(book_words)
def write_new_file(filename, dic):
""" Write results from dic into new file """
layout = "{0:<15}{1:>15}"
f = open(filename, "w")
f.write("Word Count\n")
f.write("=======================\n")
for k, v in dic.items():
content = layout.format(k, dic[k])
f.write(content + "\n")
f.close()
write_new_file("alice_words.txt", book_dic)
def analyse_dic(dic): # For testing
""" Statics the dictionary """
longest_wd = None
length = 0
ct = 0
layout = "{0:<10}{1:>10}"
print("Word Count")
print("=======================")
for k, v in dic.items():
ct += 1
if ct < 10: # Because I don't want to print all list
print(layout.format(k, dic[k]))
for k in dic.keys(): # Code block for finding the longest word in "Alice in Wonderland"
if len(k) > length:
length = len(k)
longest_wd = k
print("The longest word in Alice in Wonderland is: ", longest_wd, ". It has", length, "characters.")
analyse_dic(book_dic)
print("The word 'alice' occurred in", book_dic["alice"], "times.")
|
3386638160c393304e239e56634a3e6fa4ece679 | Sm0rter/Challenges | /Prefix Challenge.py | 516 | 3.71875 | 4 | # Variables
going = True
# Functions
def c_p(x, y, z, common):
if len(y) == 0 or len(x) == 0 or len(z) == 0 or x[0] != y[0] or y[0] != z[0] or z[0] != x[0]:
return common
return(c_p(x[1:], z[1:], y[1:], common + x[0]))
# Main Loop
while going == True:
string1 = input("Give me the first word. ")
string2 = input("Give me the second word. ")
string3 = input("Give me the third word. ")
common = ""
common_prefix = c_p(string1, string2, string3, common)
print(common_prefix) |
109e5f6759849f4d475ba9c18deb86cda6318887 | jaquelinepeluzo/Python-Curso-em-Video | /ex016.py | 130 | 4 | 4 | n1 = float(input('Digite um número: '))
print('O número digitado é {}, e sua porção inteira é: {}'.format(n1, int(n1)))
|
1858fd23d76c081809863899b8df4522cb193e7c | ellkrauze/stack_binary_search_tree | /Deck_Python_Errors.py | 1,404 | 3.8125 | 4 | from collections import deque
def main():
d = deque([])
while True:
input_line = input()
console_command = (input_line.split(' '))[0]
if console_command == 'push_front':
number = int(input_line.split(' ')[1])
d.appendleft(number)
print('ok')
if console_command == 'push_back':
number = int(input_line.split(' ')[1])
d.append(number)
print('ok')
if console_command == 'pop_front':
if len(d) != 0:
print(d.popleft())
else:
print('error')
if console_command == 'pop_back':
if len(d) != 0:
print(d.pop())
else:
print('error')
if console_command == 'front':
if len(d) != 0:
print(d[0])
else:
print('error')
if console_command == 'back':
if len(d) != 0:
print(d[-1])
else:
print('error')
if console_command == 'size':
print(len(d))
if console_command == 'clear':
d.clear()
print('ok')
if console_command == 'exit':
print('bye')
break
if __name__ == '__main__':
main() |
7c5f88c58541eee854c87a9cc0e870f18841a1a9 | JackDrogon/CodingEveryday | /code/2021/04/09/python-itertools-groupby.py | 319 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
def sortBy(score):
if score > 80:
return "A"
elif score >= 60:
return "B"
else:
return "C"
scores = [81, 82, 84, 76, 64, 78, 59, 44, 55, 89]
for m, n in itertools.groupby(scores, key=sortBy):
print(m, list(n))
|
7c6bc1e4689efab269a762cadb5e032096608c05 | Javiql/Estructura-de-Datos | /Tarea S1- EjerciciosPáginaWeb/Tarea ejercicio 12.py | 411 | 3.703125 | 4 | #Nombre: Javier Santiago Quiroz Lastre
#Aula: Software A1
#Ejercicio 12:Calcular la suma de los cuadrados de los primeros 100 enteros y escribir el resultado.
class Suma:
def Calcular(self):
i=1
suma=0
x=range(100)
for i in x:
suma=suma+i*i
print("Suma: ",suma)
print("\n")
print("**FIN DE LA EJECUCIÓN**")
suma= Suma()
suma.Calcular() |
3abd1af360dc1be946bad27a4d28a345da510258 | alice19-meet/yl1201718 | /extra/tictactoe | 2,895 | 3.765625 | 4 | class Board():
def __init__(self):
self.board = [[x for x in range(3*n-2, 3*n+1)] for n in range(1, 4)]
self.used_blocks = set()
def __str__(self):
board_output = ""
for row in self.board:
for number in row:
board_output += str(number) + " "
board_output += "\n"
return board_output
def player_move(self, user_play, steps):
def _num_to_coord(num):
"""
1 = (0,0)
...
3 = (0,2)
...
4 = (1,0)
...
9 = (2,0)
"""
if num % 3 == 0:
c = 2
r = num // 3 - 1
else:
c = num % 3 - 1
r = num // 3
return (r,c)
num = int(user_play) # change the user's input to an int
if num in self.used_blocks:
print("You already used this block")
return True
self.used_blocks.add(num) # keep track of the newly used block
# determine whether we need x or o
if steps % 2 == 0: # need x
symbol = "x"
else: # need o
symbol = "o"
(r,c) = _num_to_coord(num)
self.board[r][c] = symbol
return False
def game_state(self):
"""
Returns either "x", "o", "tie"
or None according to who wins
"""
# check for a win by columns, rows, and diagonals
# check the columns
columns = [[self.board[c][r] for c in range(3)] for r in range(3)]
for column in columns:
if column.count(column[0]) == len(column):
return column[0] # return the winning symbol
# check the rows
rows = [[self.board[r][c] for c in range(3)] for r in range(3)]
for row in rows:
if row.count(row[0]) == len(row):
return row[0] # return the winning symbol
# check the diagonals
main = [self.board[n][n] for n in range(3)] # main diagonal
anti = [self.board[n][2-n] for n in range(3)] # antidiagonal
if main.count(main[0]) == len(main) or anti.count(anti[0]) == len(anti):
# return the center element - common to both diagonals
return self.board[1][1]
# check for a tie
if len(self.used_blocks) == 9:
return "tie"
# neither a win nor a tie ==> ongoing
return None
board = Board()
steps = 0
while board.game_state() == None:
print()
print(board)
user_play = input("Enter the number of the square you'd like to choose: ")
user_mistake = board.player_move(user_play, steps)
if not user_mistake:
steps += 1
print(board)
game_state = board.game_state()
if game_state != "tie":
print(game_state + " won!")
else:
print("The game is a tie")
|
a6ae9a6dc166c15ed59fe4e32f2f656255f00d9c | Muriithijoe/Password-Locker | /test.py | 3,149 | 3.578125 | 4 | import pyperclip
import unittest
from locker import User
from credential import Credential
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for user class behaviours
Args:
unittest.TestCase: class that helps in creating test cases
'''
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_user = User("Joe","Instagram","@joe.com","killshot18")
def tearDown(self):
'''
tearDown method that does clean up after each test case has run
'''
User.user_list = []
def test_init(self):
'''
test_init test case to case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.user_name,"Joe")
self.assertEqual(self.new_user.account_name,"Instagram")
self.assertEqual(self.new_user.email,"@joe.com")
self.assertEqual(self.new_user.password,"killshot18")
def test_save_user(self):
'''
test_save_user test case to test if the user object is saved into user list
'''
self.new_user.save_user()
self.assertEqual(len(User.user_list),1)
def test_save_multiple_user(self):
'''
test_save_multiple_user to check if we can save multiple users object to our lists
'''
self.new_user.save_user()
test_user = User("Roman","Facebook","@roman.com","reigns18")
test_user.save_user()
self.assertEqual(len(User.user_list),2)
def test_delete_user(self):
'''
test_delete_contact to test if we can remove a contact from our contact list
'''
self.new_user.save_user()
test_user = User("Roman","Facebook","@roman.com","reigns18")
test_user.save_user()
self.new_user.delete_user()
self.assertEqual(len(User.user_list),1)
def test_find_user_by_account_name(self):
'''
test to check if we can find user by account name and display information
'''
self.new_user.save_user()
test_user = User("Roman","Facebook","@roman.com","reigns18")
test_user.save_user()
found_user = User.find_by_account_name("Facebook")
self.assertEqual(found_user.password,test_user.password)
def test_user_exists(self):
'''
test to check if we can return a boolean if cannot find the contact.
'''
self.new_user.save_user()
test_user = User("Roman","Facebook","@roman.com","reigns18")
test_user.save_user()
user_exists = User.user_exist("Facebook")
self.assertTrue(user_exists)
def test_display_all_users(self):
'''
method that returns a list of all contacts saved
'''
self.assertEqual(Credential.display_users(),Credential.user_list)
def test_copy_email(self):
'''
test to confirm that we are copying email from found user
'''
self.new_user.save_user()
User.copy_email("Instagram")
self.assertEqual(self.new_user.email,pyperclip.paste())
if __name__ == '__main__':
unittest.main() |
63002814329cc2ec351da6089cdaab15b98ffbac | jaykooklee/practicepython | /if.py | 206 | 3.625 | 4 | if True:
print('참입니다.')
if True:
print('참입니다.')
if False:
print('참입니다.')
score = 80
if score > 80:
print('합격입니다.')
else:
print('불합격입니다.')
|
6590806b73eeb82243baf85d9581d33982806275 | wangkai997/leetcode | /2.两数相加.py | 1,290 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode((l1.val+l2.val)%10)
p = head
# add 表示进位
add = (l1.val + l2.val) // 10
while l1.next != None or l2.next != None:
l1 = l1.next if l1.next else ListNode(0)
l2 = l2.next if l2.next else ListNode(0)
value = l1.val + l2.val + add
p.next = ListNode(value % 10)
add = value // 10
p = p.next
if add == 1:
p.next = ListNode(1)
return head
# head = ListNode(l1.val + l2.val)
# cur = head
# while l1.next or l2.next:
# l1 = l1.next if l1.next else ListNode()
# l2 = l2.next if l2.next else ListNode()
# cur.next = ListNode(l1.val + l2.val + cur.val // 10)
# cur.val = cur.val % 10
# cur = cur.next
# if cur.val >= 10:
# cur.next = ListNode(cur.val // 10)
# cur.val = cur.val % 10
# return head
# @lc code=end
|
c2facf5a64c35fba081ea370388df3855554f9bc | Alisson-JP/Programas-Basicos | /Python/Numero dobro e terça parte.py | 308 | 3.984375 | 4 | #Crie um algoritmo que leia um número real e mostre na tela o seu dobro e a sua terça parte.
numero = float(input(f'Por favor, digite um número qualquer: '))
dob = numero * 2
ter = numero / 3
print(f'Você digitou {numero}, o dobro deste valor corresponde a {dob}, já a terça parte é igual a {ter}.')
|
3394f0b8c6ac5dd84796cbe5b9a9506d5fa39ac1 | AllenKd/algorithm_practice | /second_stage/lowest_common_ancestor_in_a_binary_tree.py | 1,138 | 3.828125 | 4 | class Node:
# Constructor to create a new binary node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def find_path(root, target):
if not root:
return False
if root.key == target:
return [root.key]
left = find_path(root.left, target)
right = find_path(root.right, target)
if left:
return [root.key] + left
if right:
return [root.key] + right
return None
def find_lca(root, n1, n2):
p1 = find_path(root, n1)
p2 = find_path(root, n2)
for i in range(min(len(p1), len(p2))):
if p1[i] != p2[i]:
return p1[i-1]
return p1[min(len(p1), len(p2)) - 1]
# description: https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print(find_lca(root, 4, 5))
print(find_lca(root, 4, 6))
print(find_lca(root, 3, 4))
print(find_lca(root, 2, 4))
|
872ae32cf7837edf369ca2cc0988bb21c2ddc846 | AdityaDavalagar/sample | /address.py | 135 | 3.578125 | 4 | address = "1-3-33/221,domalaguda,hyderabad"
temp = ['-','/']
for i in temp:
address = address.replace(i," ")
print address
print temp |
8cb2276934fb11d7e2fbd6c3b5d8f18427484de0 | wellingtonlope/treinamento-programacao | /uri-online-judge/python3/iniciante/1153.py | 136 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def fat(num):
if num == 1:
return 1
return fat(num-1) * num
n = int(input())
print(fat(n))
|
5e13a4066f53c3d50d324229aaa0b06ab20aa1a2 | A01376318/Mision_03 | /Trapecio.py | 745 | 3.625 | 4 | #Autor: Elena R.Tovar, A01376318
#Calcular área y perímetro midiendo base mayor, base menor y altura de trapecio isóceles
import math
#calcula area
def calcArea(ba,bb,h):
a=((ba+bb)/2)*h
return a
#calcula hipotenusa
def hipotenusa(ba,bb,h):
hip= math.sqrt((h**2)+(((ba-bb)/2)**2))
return hip
#calcula perimetro
def calcPerimetro(ba, bb,h):
P=ba+bb+(2*(hipotenusa(ba,bb,h)))
return P
def main():
ba= float(input("Escribe la longitud de la base mayor: "))
bb= float(input("Escribe la longitud de la base menor: "))
h= float(input("Escribe la altura: "))
a= calcArea(ba, bb, h)
P= calcPerimetro(ba,bb,h)
print("Área: %0.2f" %(a))
print("Perímetro: %0.2f" %(P))
main()
|
53a56961bbd744660847e6c553618b52ca689e2c | KarolloS/python-course | /Problem Set 2/p2_3.py | 972 | 3.828125 | 4 | # Monthly interest rate = (Annual interest rate) / 12.0
# Monthly payment lower bound = Balance / 12
# Monthly payment upper bound = (Balance x (1 + Monthly interest rate)12) / 12.0
#
# Write a program that uses these bounds and bisection search to find the smallest monthly payment to the cent
# such that we can pay off the debt within a year. Try it out with large inputs, and notice how fast it is
# (try the same large inputs in your solution to Problem 2 to compare!). Produce the same return value as you did in Problem 2.
balance = 320000
annualInterestRate = 0.2
def rb(b, i, p):
bt = b
for k in range(12):
ub = bt - p
bt = ub + i/12.0*ub
return bt
p = 0
b = balance
eps = 0.01
l = balance/12.0
u = (balance*(1+annualInterestRate/12.0)**12)/12.0
while abs(b) > eps:
p = (u + l) / 2
b = rb(balance, annualInterestRate, p)
if b > eps:
l = p
else:
u = p
print('Lowest Payment: ' + str(round(p, 2))) |
8c8fcdc1b0ff0d40c191d7ba83d1050cb3ecb752 | sdawn29/cloud-training | /for_ex.py | 1,463 | 3.53125 | 4 | s = 'python'
for a in s:
print('a =', a)
b = 'java'
L = [10, 20, 30]
for b in L:
print('b =', b)
print('Now a and b =', a, b)
D = {'A': 10, 'B': 20}
for k in D:
print('k =', k)
line = '-' * 40
print(line)
for k in D.keys():
print('key =', k, 'value =', D[k])
print(line)
for v in D.values():
print('V = ', v)
print(line)
for i in D.items(): # D.items returns a list of tuple
print('i =', i, i[0], i[1])
print(line)
for i, j in D.items():
print(i, j)
print(line)
hosts = ['h1', 'h2', 'h3']
ips = ['ip1', 'ip2']
z = zip(hosts, ips) # has an geteratd function n it
print(z)
print(list(z))
for h, p in zip(hosts, ips):
print(h, p)
print(line)
# for loop like java and c
r1 = range(10)
r2 = range(1, 10)
r3 = range(1, 10, 2)
print(list(r1), list(r2), list(r3), sep='\n')
print(line)
r4 = range(10, 1, -1)
for i in range(2, 10, 2):
print('i =', i)
print(line)
for h in range(0, len(hosts)):
print(hosts[h])
print(line)
for h in range(0, len(hosts), 2):
print(hosts[h])
print(line)
for h in hosts[::2]:
print('h=', h)
print(line)
comp = ['IBM', 'DEL1', 'SAP', "DEL2"]
for c in comp:
if c.startswith('DEL'):
print('found')
break
else:
print('Not Found')
print(line)
for i in comp:
if not i.startswith('DEL'):
continue
if i.startswith('DEL'):
print('Some Logic')
print('last statement of for') |
e171dcc3bb0df770d740074336a213b9830156c0 | EmilianaAP/Movie_match | /Movie_searching.py | 738 | 3.75 | 4 | from imdb import IMDb
def movie_searching(username):
moviesDB = IMDb()
movie_name = input("Enter movie name: ")
movies = moviesDB.search_movie(movie_name)
print('Searching for movies:')
id = movies[0].getID()
movie = moviesDB.get_movie(id)
title = movie['title']
year = movie['year']
rating = movie['rating']
genre = movie['genres']
print('Movie info:')
print(f'{title} - {year}')
print(f'rating: {rating}')
print(f'genre: {genre}')
option = input("Do you want this movie to be added to your matched movies (y/n)? ")
if option == 'y':
file = open("film_data.txt", "a")
print("Film added sucessfully")
file.write(username + ", " + title + "\n") |
b41eda9c8fc780a99da12561f0d9322c216ef98f | TPSGrzegorz/PyCharmStart | /KodolamaczKurs/Prace domowe/OOP_Stringify_Nested.py | 1,239 | 3.734375 | 4 | class Crew:
def __init__(self, members=()):
self.members = list(members)
def __str__(self):
return '\n'.join([str(x) for x in self.members])
class Astronaut:
def __init__(self, name, experience=()):
self.name = name
self.experience = list(experience)
def __str__(self):
if self.experience:
return f'{self.name} veteran of {self.experience}'
else:
return f'{self.name}'
class Mission:
def __init__(self, year, name):
self.year = year
self.name = name
def __repr__(self):
return f'\n\t\t{self.year} : {self.name}'
melissa = Astronaut('Melissa Lewis')
print(f'Commander: \n{melissa}\n')
# Commander:
# Melissa Lewis
mark = Astronaut('Mark Watney', experience=[
Mission(2035, 'Ares 3'),
])
print(f'Space Pirate: \n{mark}\n')
crew = Crew([
Astronaut('Jan Twardowski', experience=[
Mission(1969, 'Apollo 11'),
Mission(2024, 'Artemis 3'),
]),
Astronaut('José Jiménez'),
Astronaut('Mark Watney', experience=[
Mission(2035, 'Ares 3'),
]),
])
print(f'Crew: \n{crew}')
# Crew:
# Jan Twardowski veteran of [
# 1969: Apollo 11,
# 2024: Artemis 3]
# José Jiménez
# Mark Watney veteran of [
# 2035: Ares 3]
|
a4d8e795cef326feed9e6b68adde2d1c48c9c15b | ponpon88/python_lab | /20191202/s6-1.py | 480 | 3.640625 | 4 | def printmsg():
print("副程式", msg)
''' Main func '''
msg = 'Global Variable'
print("主程式", msg)
printmsg()
def printmsg2():
msg2 = "Local Variable"
print("副程式", msg2)
''' Main func '''
msg2 = 'Global Variable'
print("主程式", msg2)
printmsg2()
def printmsg3():
global msg3
msg3 = "Local Variable"
print("副程式", msg3)
''' Main func '''
msg3 = 'Global Variable'
print("主程式", msg3)
printmsg3()
print("主程式", msg3)
|
3bd32cd2107d30ef41241ed246509fcdac4664fb | JhoanRodriguez/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/4-print_hexa.py | 82 | 3.546875 | 4 | #!/usr/bin/python3
for x in range(0, 99):
print("{:d} = 0x{:x}".format(x, x))
|
58234b08fdd28af355e999e81de9ec25af3bc4d5 | choijy1705/AI | /chap04/ex01_MSE.py | 656 | 3.765625 | 4 | # MSE(Mean Squared Error) : 손실함수
import numpy as np
def mean_squared_error(y, p):
return 0.5 * np.sum((y - p)**2)
# 예측 결과 : 2
p = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] # 2일 확률이 60프로 2라고 예측
y = [0,0,1,0,0,0,0,0,0,0] # One-Hot Encoding 방법으로 출력(실제값)
print(mean_squared_error(np.array(y), np.array(p)))
# 0.09750000000000003
# 예측 결과 : 7, 실제값 : 2
p1 = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0]
y = [0,0,1,0,0,0,0,0,0,0]
print(mean_squared_error(np.array(y), np.array(p1))) # 손실함수는 마지막의 예측된값과 실제값을 비교하는 것
# 0.5975 |
5e855b93dffb8f00d63b9012bfe9647542e25154 | sindridan/Python_2018 | /verkefni1.py | 5,024 | 3.6875 | 4 | #liður 1:
#break input into indices where the line breaks
#append into new sortedlist
#sort the list
def cdo(input):
sorts = input.split(" ") #seperates each word in string by spaces and lists them
sorts.sort()
newstr = " ".join(sorts) #create a unified string and form a space between every word
return newstr
cdo('in theory there is no difference between theory and practice')
#liður 2:
def duplicates(s):
dup = []
found = {} #used for comparing seen duplicate elements
for x in s:
if x not in found:
found[x] = True #if the element hasn't been seen before in input list
else:
if found[x] == True: #after comparison, if element has been seen in found, add it to the duplicate list
dup.append(x)
return list(set(dup)) #cleans out duplicates from the list
duplicates([1337, 42, 5318008, 1337, 5318008, 5885522])
duplicates([1337, 1337, 42, 42, 42, 5318008, 1337, 5318008, 5885522, 42])
#liður 3:
def flatten(lis):
sortLis = list(sorted(lis))
m = {}
for index, value in enumerate(sortLis): #create enumerated list [(0,4), (1,6), (2,8)]
m[value] = index #map the indexes to the values
returnList = []
for value in lis:
returnList.append(m[value]) #use the map to access the index associated with the value and add it to the returning list
return returnList
flatten([984, 523, 653, 503, 557, 170, 336, 552, 511, 768, 184, 565, 564, 133, 277, 966, 37, 427, 351, 62, 500, 131, 160, 12, 304, 972, 725, 14, 46, 346, 820, 671, 24, 726, 300],)
#liður 4:
def rm_duplicates(lis):
s = set(lis) #removes duplicates because of set
newList = list(s) #convert back to list
return sorted(newList)
rm_duplicates([18, 7, 1, 15, 15, 1, 19])
#liður 5:
#zip indexes 1 to n-1 for L
def scramble(original, keys):
indices = list(range(0, len(original))) #create index list
originalMatched = list(zip(original, indices)) #no sorting, map original to indexes 0 to n-1
newList = []
for x in keys: #iterate through keys, comparing them with originalmatched to find match, then append in keys order
for y in originalMatched:
if x == y[1]: #if index in originalmatched matches the key, append value to newlist
newList.append(y[0])
return newList
scramble([100, 42, 4, 1337], [1,3,2,0])
#liður 6:
import math
def excel_index(s):
chars = []
for x in s:
charval = ord(x) - 64 #find ascii val, take away 64 to get A = 1
chars.append(charval)
totalVal = 0
i = 0
for i in range(len(chars)):
exp = math.pow(26, len(chars) - (i+1)) #get the correct power for the amount of chars in input, if AA, then power is 26^1 because we've exceeded the complete first list, else 26^0 if only single char in input
totalVal = (totalVal + exp * chars[i])
return int(totalVal) #comes originally out as a float
excel_index('CA')
excel_index('AA')
excel_index('LOL')
#liður 8:
import re #regex
def birthdays(s):
s = s.split('\n') #splits the input on newlines
birthdays = []
for x in s:
birthdays.append(x[0:4]) #list containing first four letters, indicating birthdays
finalList = []
for day in duplicates(birthdays): #reusing duplicates function, filters out kennitalas with same birthdate: only checking where there is more than one same birthdate
kt = tuple(filter(lambda x : day == x[:4] , s)) #tuples together those with the same birthdate (first four digits) as the 'day' variable.
finalList.append(kt)
return finalList
birthdays('''0212862149
0407792319
0212849289
1112792819
0407992939
0212970299''')
import re
def process_ls(s):
lines = s.splitlines() #removes newlines from the input
l = []
for line in lines:
l.append(list(re.split(r'\s{2,}', line))) #regex split, only splits where there is more than 2 whitespaces between words
retList = []
for j in range(len(l[0])): #starts at first list index
for i in range(len(l)):
if(len(l[0]) > len(l[i]) and j == len(l[0]) - 1): #to avoid index out of bounds
return retList
retList.append(l[i][j]) #2d array iterate, appending in a vertical order
return retList
process_ls("""ac pid.pid console-kit-daemon.pid lock pm-utils sdp upstart-socket-bridge.pid
acpid.socket crond.pid mdm.pid postgresql sendsigs.omit.d upstart-udev-bridge.pid
apache2 crond.reboot mdm_socket pppconfig shm user
apache2.pid cups motd resolvconf udev utmp
avahi-daemon dbus mount rsyslogd.pid udisks wicd
console dhclient.pid network samba udisks2 wpa_supplicant
ConsoleKit initramfs plymouth screen upstart-file-bridge.pid""",)
|
dd069a546b04f836997cc82d6a345e4edd62485b | mukesh-jogi/python_repo | /Sem-6/Threading/multithread-lock.py | 1,016 | 3.5625 | 4 | import threading
from time import sleep
class C1(threading.Thread):
def __init__(self,threadname): # Overriding Thread class(baseclass) __init__ method
threading.Thread.__init__(self)
self.threadname = threadname
def run(self): # Overriding Thread class(baseclass) run method
isacquired = 0
print("Acquiring Lock : ",self.threadname)
isacquired = threadlock.acquire()
if(isacquired==0):
print("Thread Blocked: ",self.threadname)
else:
print("Lock Acquired : ",self.threadname)
for i in range(5):
print("Thread: ",self.threadname)
sleep(1)
print("Releasing Lock : ",self.threadname)
threadlock.release()
print("Lock Released : ",self.threadname)
threadlock = threading.Lock()
obj1 = C1("Thread1")
obj2 = C1("Thread2")
obj3 = C1("Thread3")
obj4 = C1("Thread4")
obj3.start()
obj4.start()
obj1.start()
obj2.start()
obj1.join()
obj2.join()
obj3.join()
obj4.join()
print("Bye") |
cd0ff3bc7246086f771b5f07ebbd8219990def13 | siarhiejkresik/Epam-2019-Python-Homework | /final_task/pycalc/calculator/precedence.py | 2,355 | 3.515625 | 4 | """
The operator precedence.
"""
from enum import IntEnum
class Precedence(IntEnum):
"""
The operator precedence according to the operator precedence in Python.
https://docs.python.org/3/reference/expressions.html#operator-precedence
"""
DEFAULT = 0
# Lambda expression
LAMBDA = 10 # lambda
# Conditional expression
CONDITIONAL_EXPRESSION = 20 # if – else
# Boolean OR
BOOLEAN_OR = 30 # or
# Boolean AND
BOOLEAN_AND = 40 # and
# Boolean NOT
BOOLEAN_NOT = 50 # not x
# Comparisons, including membership tests and identity tests
COMPARISONS = 60 # <, <= , > , >= , != , ==
MEMBERSHIP_TESTS = 60 # in, not in
IDENTITY_TESTS = 60 # is, is not
# Bitwise XOR
BITWISE_XOR = 70 # ^
# Bitwise OR
BITWISE_OR = 80 # |
# Bitwise AND
BITWISE_AND = 90 # &
# Shifts
SHIFTS = 100 # <<, >>
# Addition and subtraction
ADDITION = 110 # +
SUBTRACTION = 110 # -
# Multiplication, matrix multiplication, division, floor division, remainder
MULTIPLICATION = 120 # *
MATRIX_MULTIPLICATION = 120 # @
DIVISION = 120 # /
FLOOR_DIVISION = 120 # //
REMAINDER = 120 # %
# Positive, negative, bitwise NOT
POSITIVE = 130 # +x
NEGATIVE = 130 # -x
BITWISE_NOT = 130 # ~x
# Exponentiation
EXPONENTIATION = 140 # ^
# EXPONENTIATION = 140 # **
# Await expression
AWAIT = 150 # await x
# Subscription, slicing, call, attribute reference
SUBSCRIPTION = 160 # x[index],
SLICING = 160 # x[index:index],
CALL = 160 # x(arguments...),
ATTRIBUTE_REFERENCE = 160 # x.attribute
# Binding or tuple display, list display, dictionary display, set display
BINDING = 170
TUPLE = 170 # (expressions...),
LIST = 170 # [expressions...],
DICTIONARY = 170 # {key: value...},
SET = 170 # {expressions...}
|
b10961fb09b913e29bc502ab39b3d20fbfb2bd78 | pptech-ds/PPTech-Recommender-System-1 | /main.py | 12,578 | 3.671875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('dark')
# To understand recommender system I followed the tutorial from "https://stackabuse.com/creating-a-simple-recommender-system-in-python-using-pandas"
# Database used for this tuto comming from "https://grouplens.org/datasets/movielens/"
# For this project I will use the small one to ease data processing "http://files.grouplens.org/datasets/movielens/ml-latest-small.zip"
# 1- Reading data containing movie ratings
ratings_data = pd.read_csv("ratings_small.csv")
print('--- Reading data containing movie ratings ---')
print(ratings_data.head())
print('----------------------\n\n')
# --- Reading data containing movie ratings ---
# userId movieId rating timestamp
# 0 1 1 4.0 964982703
# 1 1 3 4.0 964981247
# 2 1 6 4.0 964982224
# 3 1 47 5.0 964983815
# 4 1 50 5.0 964982931
# ----------------------
# 2- Reading data containing movie titles and genres
movie_names = pd.read_csv("movies_small.csv")
print('--- Reading data containing movie titles and genres ---')
print(movie_names.head())
print('----------------------\n\n')
# --- Reading data containing movie titles and genres ---
# movieId title genres
# 0 1 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
# 1 2 Jumanji (1995) Adventure|Children|Fantasy
# 2 3 Grumpier Old Men (1995) Comedy|Romance
# 3 4 Waiting to Exhale (1995) Comedy|Drama|Romance
# 4 5 Father of the Bride Part II (1995) Comedy
# ----------------------
# 3- Merging both dataset into one dataframe using "movieId" column as reference
movie_data = pd.merge(ratings_data, movie_names, on='movieId')
print('--- Merged data ---')
print(movie_data.head())
print('----------------------\n\n')
# --- Merged data ---
# userId movieId rating timestamp title genres
# 0 1 1 4.0 964982703 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
# 1 5 1 4.0 847434962 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
# 2 7 1 4.5 1106635946 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
# 3 15 1 2.5 1510577970 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
# 4 17 1 4.5 1305696483 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
# ----------------------
# 4- Grouping merged data by movie "title" and calculating the mean for "rating" for each movie title
movie_data.groupby('title')['rating'].mean().head()
print('--- Grouped by title and mean ---')
print(movie_data.groupby('title')['rating'].mean().head())
print('----------------------\n\n')
# --- Grouped by title and mean ---
# title
# '71 (2014) 4.0
# 'Hellboy': The Seeds of Creation (2004) 4.0
# 'Round Midnight (1986) 3.5
# 'Salem's Lot (2004) 5.0
# 'Til There Was You (1997) 4.0
# Name: rating, dtype: float64
# ----------------------
# 5- Sorting previous data highest to lowest mean for each movie
movie_data.groupby('title')['rating'].mean().sort_values(ascending=False).head()
print('--- Sorting previous data highest to lowest mean for each movie ---')
print(movie_data.groupby('title')['rating'].mean().sort_values(ascending=False).head())
print('----------------------\n\n')
# --- Sorting previous data highest to lowest mean for each movie ---
# title
# Karlson Returns (1970) 5.0
# Winter in Prostokvashino (1984) 5.0
# My Love (2006) 5.0
# Sorority House Massacre II (1990) 5.0
# Winnie the Pooh and the Day of Concern (1972) 5.0
# Name: rating, dtype: float64
# ----------------------
# 6- Counting number of ratings for each movie and sorting it highest to lowest
movie_data.groupby('title')['rating'].count().sort_values(ascending=False).head()
print('--- Counting number of ratings for each movie and sorting it highest to lowest ---')
print(movie_data.groupby('title')['rating'].count().sort_values(ascending=False).head())
print('----------------------\n\n')
# --- Counting number of ratings for each movie and sorting it highest to lowest ---
# title
# Forrest Gump (1994) 329
# Shawshank Redemption, The (1994) 317
# Pulp Fiction (1994) 307
# Silence of the Lambs, The (1991) 279
# Matrix, The (1999) 278
# Name: rating, dtype: int64
# ----------------------
# 7.1- Getting mean for each movie
ratings_mean_count = pd.DataFrame(movie_data.groupby('title')['rating'].mean())
# 7.2- Adding new column "rating_counts" to get number of user who added a rating for each movie
ratings_mean_count['rating_counts'] = pd.DataFrame(movie_data.groupby('title')['rating'].count())
print('--- ratings_mean_count.head() ---')
print(ratings_mean_count.head())
print('----------------------\n\n')
# --- ratings_mean_count.head() ---
# rating rating_counts
# title
# '71 (2014) 4.0 1
# 'Hellboy': The Seeds of Creation (2004) 4.0 1
# 'Round Midnight (1986) 3.5 2
# 'Salem's Lot (2004) 5.0 1
# 'Til There Was You (1997) 4.0 2
# ----------------------
# 8- Plotting histogram for the number of ratings represented by the "rating_counts" column
plt.figure(figsize=(8,6))
plt.rcParams['patch.force_edgecolor'] = True
ratings_mean_count['rating_counts'].hist(bins=50)
plt.savefig('plots/histogram_nb_ratings_by_rating_counts.png')
# See figure "plots/histogram_nb_ratings_by_rating_counts.png"
# 9- Plotting histogram for average ratings
plt.figure(figsize=(8,6))
plt.rcParams['patch.force_edgecolor'] = True
ratings_mean_count['rating'].hist(bins=50)
plt.savefig('plots/histogram_avg_ratings.png')
# See figure "plots/histogram_avg_ratings.png"
# 10- Plotting average ratings against the number of ratings
plt.figure(figsize=(8,6))
plt.rcParams['patch.force_edgecolor'] = True
sns.jointplot(x='rating', y='rating_counts', data=ratings_mean_count, alpha=0.4)
plt.savefig('plots/seaborn_avg_ratings_vs_nb_ratings.png')
# See figure "plots/seaborn_avg_ratings_vs_nb_ratings.png"
# 11- Finding Similarities Between Movies: we will have rating by user for each movie
user_movie_rating = movie_data.pivot_table(index='userId', columns='title', values='rating')
print('--- user_movie_rating.head() ---')
print(user_movie_rating.head())
print('----------------------\n\n')
# --- user_movie_rating.head() ---
# title '71 (2014) 'Hellboy': The Seeds of Creation (2004) 'Round Midnight (1986) 'Salem's Lot (2004) ... xXx (2002) xXx: State of the Union (2005) ¡Three Amigos! (1986) À nous la liberté (Freedom for Us) (1931)
# userId ...
# 1 NaN NaN NaN NaN ... NaN NaN 4.0
# NaN
# 2 NaN NaN NaN NaN ... NaN NaN NaN
# NaN
# 3 NaN NaN NaN NaN ... NaN NaN NaN
# NaN
# 4 NaN NaN NaN NaN ... NaN NaN NaN
# NaN
# 5 NaN NaN NaN NaN ... NaN NaN NaN
# NaN
# [5 rows x 9719 columns]
# ----------------------
# 12- Finding the user ratings for "Forrest Gump (1994)"
forrest_gump_ratings = user_movie_rating['Forrest Gump (1994)']
print('--- forrest_gump_ratings.head() ---')
print(forrest_gump_ratings.head())
print('----------------------\n\n')
# --- forrest_gump_ratings.head() ---
# userId
# 1 4.0
# 2 NaN
# 3 NaN
# 4 NaN
# 5 NaN
# Name: Forrest Gump (1994), dtype: float64
# ----------------------
# 13.1- Finding all movies having similarities with "Forrest Gump (1994)"
movies_like_forest_gump = user_movie_rating.corrwith(forrest_gump_ratings)
# 13.2- Adding new column "Correlation" with correlation score
corr_forrest_gump = pd.DataFrame(movies_like_forest_gump, columns=['Correlation'])
# 13.3 Dropping all NA in dataframe
corr_forrest_gump.dropna(inplace=True)
print('--- corr_forrest_gump.head() ---')
print(corr_forrest_gump.head())
print('----------------------\n\n')
# --- corr_forrest_gump.head() ---
# Correlation
# title
# 'burbs, The (1989) 0.197712
# (500) Days of Summer (2009) 0.234095
# *batteries not included (1987) 0.892710
# ...And Justice for All (1979) 0.928571
# 10 Cent Pistol (2015) -1.000000
# ----------------------
# 14- Sorting previous dataset
corr_forrest_gump.sort_values('Correlation', ascending=False).head(10)
print('--- corr_forrest_gump.sort_values(Correlation, ascending=False).head(10) ---')
print(corr_forrest_gump.sort_values('Correlation', ascending=False).head(10))
print('----------------------\n\n')
# --- corr_forrest_gump.sort_values(Correlation, ascending=False).head(10) ---
# Correlation
# title
# Lost & Found (1999) 1.0
# Century of the Self, The (2002) 1.0
# The 5th Wave (2016) 1.0
# Play Time (a.k.a. Playtime) (1967) 1.0
# Memories (Memorîzu) (1995) 1.0
# Playing God (1997) 1.0
# Killers (2010) 1.0
# Girl Walks Home Alone at Night, A (2014) 1.0
# Tampopo (1985) 1.0
# Cercle Rouge, Le (Red Circle, The) (1970) 1.0
# ----------------------
# 15- Joining previous dataset with rating counts
corr_forrest_gump = corr_forrest_gump.join(ratings_mean_count['rating_counts'])
corr_forrest_gump.head()
print('--- corr_forrest_gump.head() ---')
print(corr_forrest_gump.head())
print('----------------------\n\n')
# --- corr_forrest_gump.head() ---
# Correlation rating_counts
# title
# 'burbs, The (1989) 0.197712 17
# (500) Days of Summer (2009) 0.234095 42
# *batteries not included (1987) 0.892710 7
# ...And Justice for All (1979) 0.928571 3
# 10 Cent Pistol (2015) -1.000000 2
# ----------------------
# 16- Sorting previous dataframe to get most relevant movies to less ones with limiting rating_counts at 50
corr_forrest_gump[corr_forrest_gump ['rating_counts']>50].sort_values('Correlation', ascending=False).head()
print('--- corr_forrest_gump[corr_forrest_gump [rating_counts]>50].sort_values(Correlation, ascending=False).head() ---')
print(corr_forrest_gump[corr_forrest_gump ['rating_counts']>50].sort_values('Correlation', ascending=False).head())
print('----------------------\n\n')
# --- corr_forrest_gump[corr_forrest_gump [rating_counts]>50].sort_values(Correlation, ascending=False).head() ---
# Correlation rating_counts
# title
# Forrest Gump (1994) 1.000000 329
# Mr. Holland's Opus (1995) 0.652144 80
# Pocahontas (1995) 0.550118 68
# Grumpier Old Men (1995) 0.534682 52
# Caddyshack (1980) 0.520328 52
# ----------------------
|
78a3070b719c5521e36d241e9ad26ccb33817cfc | nlpclass-2018-II/python-and-nltk-intro-exercise-muhammadhsn23 | /number6.py | 263 | 3.890625 | 4 | import nltk
# nltk.download('punkt')
sentence = 'I am going to take the NLP class next semester'
tokens = nltk.word_tokenize(sentence)
i=0
for words in tokens: #iterate through all splitted words
print(len(words)) #print the number of characters in the words |
d64d339ab2800064a7882951c68885b4211d4de0 | cwmaguire/genetic_algorithms_book | /escape.py | 834 | 3.703125 | 4 | import turtle
def escaped(position):
x = int(position[0])
y = int(position[1])
return x < -35 or x > 35 or y < -35 or y > 35
def draw_bag():
turtle.shape('turtle')
turtle.pen(pencolor='brown', pensize=5)
turtle.penup()
turtle.goto(-35, 35)
turtle.pendown()
turtle.right(90)
turtle.forward(70)
turtle.left(90)
turtle.forward(70)
turtle.left(90)
turtle.forward(70)
def draw_line():
angle = 0
step = 5
# t = turtle.Turtle()
while not escaped(turtle.position()):
turtle.left(angle)
turtle.forward(step)
print('Escaped!')
if __name__ == '__main__':
print('starting')
turtle.setworldcoordinates(-70., -70., 70., 70.)
draw_bag()
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
draw_line()
turtle.mainloop()
|
5a22bfda22239f3394726c7a3db7c855abfa1827 | 10GGGGGGGGGG/colouring_graphs | /colouring_graphs.py | 3,329 | 3.609375 | 4 | import networkx as nx
import matplotlib.pyplot as plt
# Python program for solution of M Coloring
# problem using backtracking
class Graph():
nodes = []
edges = []
matrix = []
colors = []
colorDB = ['red','aqua','lawngreen','yellow','pink','orange','gray','salmon','cornflowerblue','fuchsia','c']
def __init__(self, nodes):
self.nodes = nodes
self.colors = [None] * len(self.nodes)
def colorearGrafo(self, m):
if self.colorearRecursivo(m, 0) == None:
print("No hay solución para ese número máximo de colores.")
return False
# Print the solution
print("Existe solución para ese número máximo de colores. \nLa asignación es la siguiente:")
for i in range(len(self.nodes)):
print('vértice ',self.nodes[i],': (',self.colors[i]+1,')',self.colorDB[self.colors[i]])
return True
def colorearRecursivo(self, m, v):
if v == len(self.nodes):
return True
for c in range(m):
if self.checkValido(v, c):
self.colors[v] = c
if self.colorearRecursivo(m, v + 1):
return True
self.colors[v] = None
def checkValido(self, v, c):
for i in range(len(self.nodes)):
if self.matrix[v][i] == 1 and self.colors[i] == c:
return False
return True
def loadEdges(self, edgesMatrix):
self.matrix = edgesMatrix
for row in range(len(self.nodes)):
for col in range(len(self.nodes)):
if edgesMatrix[row][col]==1:
self.edges.append((self.nodes[row],self.nodes[col]))
print(self.edges)
def dibujarGrafo(self):
G = nx.Graph()
labels = {}
for n in self.nodes:
labels[n] = n
G.add_nodes_from(self.nodes)
G.add_edges_from(self.edges)
pos = nx.circular_layout(G)
for i in range(len(self.nodes)):
nx.draw_networkx_nodes(G, pos,
nodelist=[self.nodes[i]],
node_color=self.colorDB[self.colors[i]],
node_size=500,
alpha=0.7)
nx.draw_networkx_labels(G, pos, labels, font_size=18)
nx.draw_networkx_edges(G, pos,
edgelist=G.edges,
width=1.5, alpha=1, edge_color='black')
plt.show()
#'''
g = Graph(['a','b','c','d','e','f','g'])
g.loadEdges([ #a b c d e f g
[1, 0, 1, 0, 1, 0, 1],# a
[0, 1, 1, 1, 1, 0, 1],# b
[1, 1, 1, 1, 1, 1, 1],# c
[0, 1, 1, 1, 0, 1, 1],# d
[1, 1, 1, 0, 1, 1, 1],# e
[0, 0, 1, 1, 1, 1, 1],# f
[1, 1, 1, 1, 1, 1, 1] # g
])
m = 7
g.colorearGrafo(m)
g.dibujarGrafo()
'''
g = Graph(['a','b','c','d'])
g.loadEdges([
#a b c d
[1, 1, 1, 1],# a
[1, 1, 1, 1],# b
[1, 1, 1, 1],# c
[1, 1, 1, 1] # d
])
m = 4
g.colorearGrafo(m)
g.dibujarGrafo()
'''
|
40f51f018d8be8f7ecd3db8307d702172e5e89a2 | colons/euler | /common.py | 977 | 3.796875 | 4 | alphabet = 'abcdefghijklmnopqrstuvwxyz'
def factors(n):
d = 1
fs = set()
sqrt = int(n**0.5)
while d <= sqrt:
if n % d == 0:
f = n/d
fs.add(d)
fs.add(f)
d += 1
return fs
def is_prime(number):
if number == 1 or number < 0:
return False
for divisor in xrange(2, int(number**.5)+1):
if number % divisor == 0:
return False
return True
def factorial(n):
f = 1
while n > 0:
f *= n
n -= 1
return f
def is_palindrome(word):
rev = ''
for l in word:
rev = l+rev
if rev == word:
return True
else:
return False
def is_pandigital_string(string, numerals='123456789'):
if len(string) != 9:
return False
for numeral in numerals:
if numeral not in string:
return False
return True
def is_pandigital(number):
return is_pandigital_string(str(number))
|
5d6b386581014f5298f04084c7aff1de5fc9ecde | dAIsySHEng1/CCC-Senior-Python-Solutions | /2011/S1.py | 240 | 3.640625 | 4 | N = int(input())
count_t=0
count_s=0
for i in range(N):
l = input()
count_s+= l.count('s')+l.count('S')
count_t+= l.count('t')+l.count('T')
if count_s>count_t or count_s==count_t:
print('French')
else:
print('English')
|
299b6edb7758a4ab05596d2eeb7d4bf03bf17c0a | DDUDDI/mycode1 | /0515/member.py | 216 | 3.734375 | 4 | class Member:
def __init__(self, num, name, phone):
self.num = num
self.name = name
self.phone = phone
def info(self):
print('\t', self.num, '\t', self.name, '\t', self.phone) |
dff53a57170b4d59dab8100387c5b3c75d9d3037 | Durga944/loop | /loop_str.py | 62 | 3.6875 | 4 | str="durga"
a=0
while(a<len(str)):
print(str[a])
a=a+1 |
cf504822c44fcd06e39dcdd522c4f7b837b3783d | sankeerth/Algorithms | /String/python/leetcode/valid_palindrome_iii.py | 1,224 | 3.9375 | 4 | """
1216. Valid Palindrome III
Given a string s and an integer k, return true if s is a k-palindrome.
A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.
Example 1:
Input: s = "abcdeca", k = 2
Output: true
Explanation: Remove 'b' and 'e' characters.
Example 2:
Input: s = "abbababa", k = 1
Output: true
Constraints:
1 <= s.length <= 1000
s consists of only lowercase English letters.
1 <= k <= s.length
"""
class Solution:
def isValidPalindrome(self, s: str, k: int) -> bool:
memo = {}
def isValid(i, j, count):
if (i,j,count) in memo:
return memo[(i,j,count)]
while i <= j:
if s[i] != s[j]:
if count < k:
if isValid(i+1, j, count+1) or isValid(i, j-1, count+1):
return True
break
i += 1
j -= 1
res = True if i > j else False
memo[(i,j,count)] = res
return res
return isValid(0, len(s)-1, 0)
sol = Solution()
print(sol.isValidPalindrome("abcdeca", 2))
print(sol.isValidPalindrome("abbababa", 1))
|
c8d9a1670ea13fd076506f85844d3b756e20993d | yjkim0083/3min_keras | /02_ANN/ann_regression.py | 1,672 | 3.546875 | 4 | # 회귀 ANN 모델
from keras import layers, models
class ANN(models.Model):
def __init__(self, Nin, Nh, Nout):
# Prepare network layers and activation functions
hidden = layers.Dense(Nh)
output = layers.Dense(Nout)
relu = layers.Activation("relu")
# Connect network elements
x = layers.Input(shape=(Nin,))
h = relu(hidden(x))
y = output(h)
super().__init__(x,y)
self.compile(loss="mse", optimizer="sgd")
# 학습과 평가용 데이터 불러오기
from keras import datasets
from sklearn import preprocessing
def Data_func():
(X_train, y_train), (X_test, y_test) = datasets.boston_housing.load_data()
scaler = preprocessing.MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
return (X_train, y_train), (X_test, y_test)
# 회귀 ANN 학습 결과 그래프 구현
import matplotlib.pyplot as plt
from kerasapp.skeras import plot_loss
# 회귀 ANN 학습 및 성능 분석
def main():
Nin = 13
Nh = 5
Nout = 1
model = ANN(Nin, Nh, Nout)
(X_train, Y_train), (X_test, Y_test) = Data_func()
history = model.fit(X_train,
Y_train,
epochs=200,
batch_size=100,
validation_split=0.2,
verbose=2)
performance_test = model.evaluate(X_test,
Y_test,
batch_size=100)
print("\nTest Loss => {:.2f}".format(performance_test))
plot_loss(history)
plt.show()
if __name__ == "__main__":
main()
|
dc6a2550f33c59ad7aa31cc5e4369510fc9d1ab0 | shashank977/Leetcode-Algo | /max_ascending_subarr.py | 251 | 3.828125 | 4 | def maxAscendingSum(nums):
if not nums:
return 0
sum = maxSum = nums[0]
for i in range(1,len(nums)):
if nums[i]>nums[i-1]:
sum+=nums[i]
maxSum = max(maxSum, sum)
else:
sum = nums[i]
return maxSum
print(maxAscendingSum([100,10,1])) |
172860b768863338b0bdd06d35442ef47fa507c6 | smkamranqadri/python-excercises | /excercise-7.py | 189 | 3.890625 | 4 | # Question 7 (Chapter 8):
# Please generate a random float where the value is between 10 and 100 using Python math module.
# Hints:Use random.random() to generate a random float in [0,1]. |
576e69ea02f4a0b6810e9f3c7933928a4d2473ed | Covax84/Coursera-Python-Basics | /quadratic_equation.py | 429 | 3.734375 | 4 | # квадратное уравнение: ax² + bx + c
# дискриминант: D = b² - 4ac
# вывести корни в порядке возрастания
a = float(input())
b = float(input())
c = float(input())
d = b**2 - (4 * a * c)
if d > 0:
x = (-b - d ** 0.5) / (2 * a)
y = (-b + d ** 0.5) / (2 * a)
if x < y:
print(x, y)
else:
print(y, x)
elif d == 0:
print(-(b / (2 * a)))
|
1c98c2d9acb50ea6448a401592b60df27c5caf25 | kashyrskyy/web-dev-tutorial | /triangle class.py | 1,065 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
import math
class Triangle():
def __init__(self, a, b, c):
self.side1 = a
self.side2 = b
self.side3 = c
def perimeter(self):
return self.side1 + self.side2 + self.side3
def area(self):
return 1/4(sqrt(-self.side1^4 + 2*(self.side1*self.side2)^2-self.side2^4+2*(self.side2*self.side3)^2-self.side3^4))
def scale(self, scale_factor):
return Triangle(scale_factor*self.side1, scale_factor*self.side2, scale_factor*self.side3)
def is_valid(self):
if self.side1 + self.side2 > self.side3 and self.side2+self.side3>self.side1 and self.side3+self.side1>self.side2:
return True
else:
return False
def is_right(self):
if self.side1^2 == self.side2^2 + self.side3^2:
return True
else:
False
test_triangle = Triangle(3,4,5)
test_triangle.perimeter()
test_triangle.area()
test_triangle.scale(3)
test_triangle.is_valid()
# In[ ]:
|
96cb9a7fbff2fca911b7d8721a98732cfa4dbfd4 | bl00p1ng/Python-Intermedio | /list_and_dicts.py | 618 | 3.796875 | 4 | def run():
my_list = [1, 'hello', True, 4.5]
my_dict = {"firstname": "Andrés", "lastname": "López"}
super_list = [
{"firstname": "Andrés", "lastname": "López"},
{"firstname": "Tony", "lastname": "Stark"},
{"firstname": "Peter", "lastname": "Parker"},
{"firstname": "Hana", "lastname": "Uzaki"},
]
super_dict = {
"natural_nums": [1, 2, 3, 4, 5],
"integer_nums": [-1, -2, 0, 1, 2],
"floating_nums": [1.1, 4.5, 6.43]
}
for key, value in super_dict.items():
print(f'{key} - {value}')
if __name__ == '__main__':
run()
|
d6a7c68bd23074d006187b3facfd070e30cec55c | lucyluoxi90/LearningPython | /hello.py | 4,713 | 4.21875 | 4 | print("Hello World")
the_world_is_flat = 1
if the_world_is_flat:
print "Be careful not to fall off!"
#3.1.1
print 2+2
print 50-5*6
(50-5.0*6)/4
8/5.0
17/3 #int / int ->int
17/3.0 #int / float -> float
17//3.0 # explicit floor division discards the fractional part
17%3 # the % operator returns the remainder of the division
5*3+2 # result * divisor + remainder
5**2 # 5 squared
2**7 # 2 to the power of 7
width = 20
height = 5*9
width*height
n # try to access an undefined variable
tax=12.4/100
price= 100.50
price*tax
price+_
round(_,2)
#3.1.2
'spam eggs' #single quotes
print 'doesn\'t' # use \' to escape the single quote
print "doesn't" #use double quotes instead
print '"Yes," he said.'
print "\"Yes,\" he said."
print '"Isn\'t," she said.'
s = 'First lin.\nSecond line.' # \n means newline
print s
print 'C:\some\name' #this prints new line after \n
print r'C:\some\name' #this prints \ as special character with r in front
print """\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""" # use tirple quotes for multiple lines of string. End of line are authomatically included in the string, to prevent that add \
print 3* 'un' + 'ium'
'py''thon' #returns 'python', quotes next to each other are concatenated
prefix='py'
prefix 'thon' #doesn't return a string
prefix + 'thon' #+ could combine variable and literal
#long string
text= ('Put several strings within parentheses'
'to have them joined together.')
text #returns the strings above together using parentheses
#indices of a string
word= 'python'
word[0] #first character
word[5] #character in position 5
word[-1] #last character or first character from the right
word[-2] #second-last character, 0 = -0
#slicing
word[0:2] #characters form postion 0 to 2 (2 is excluded)
word[:2]+word[2:] #returns 'python', :2 includes everything before 2 and 2: includes 2 and everything after 2
word [-2:] #same result as word [4:]
word[42] #error because it's bigger than index
word[3:42] #returns 'hon'
word[42:] #returns ''
word[0] ='j' #error, python string cannot be changed
'j'+word[1:] #returns 'Jython' - new string created
s= 'helloworld'
len(s) #returns length of the string
#3.1.3 Unicode strings
u'Hello World !' #returns u'Hello World !'
u'Hello\u0020World !' #returns u'Hello World !'. \0020 represents space(which is the ordinal value (in numbers) of a byte)
ur'Hello\u0020World !' #returns u'Hello World !', use 'ur' to have Python use the Raw-Unicode-Escape encoding
ur'Hello\\u0020World !' #returns u'Hello\\\\u0020World !', uneven number of \\\
u"abc"#returns u'abc'
str(u"abc") #returns 'abc'
u"äöü" #special characters, returns u'\xe4\xf6\xfc' which is the sequence of bytes
str(u"äöü") #error
u"äöü".encode('utf-8') #convert Unicode string into 8-bit string which is a dialect of unicode
unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')# returns u'\xe4\xf6\xfc', convert back to bytes (unicode string)
3.1.4
squares=[1,4,9,16,25] #define a list
squares #returns [1, 4, 9, 16, 25]
#indexing
squares[0] #all sequence type like strings, lists are indexed and sliced. Returns 1
squares[-1] #returns 25
squares[-2] #returns 16
squares[:] #[1, 4, 9, 16, 25] slice operations return a new list containing the request. A new shallow copy of the lst.
squares + [36, 49, 64, 81, 100] #concatenation returns [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#Mutable! unlike strings
cubes = [1, 8, 27, 65, 125] # something's wrong here
4 ** 3 # returns 64 for the cube of 4, not 65!
cubes[3] = 64 # replace the wrong value
cubes #returns [1, 8, 27, 64, 125]
#append: add new items to the end of the list
cubes.append(216) # add the cube of 6 to the END OF THE LIST
cubes.append(7 ** 3) # and the cube of 7
cubes #returns [1, 8, 27, 64, 125, 216, 343]
letters=['a', 'b', 'c', 'd'] #define letters list
letters #returns ['a', 'b', 'c', 'd']
letters[0:3]=['L', 'L', 'L'] #slicing and replace with L
letters #returns ['L', 'L', 'L', 'd']
letters[0:3]=[] #removed the Ls
letters #returns ['d']
letters[:]=[] #clear the lists by replacing with empty list
letters #returns []
letters= ['a', 'b', 'c', 'd']
len(letters) # find the length of the list
#nest lists
a= ['l', 'u', 'c', 'y']
b=[23,24]
x=[a,b]
x #returns [['l', 'u', 'c', 'y'], [23, 24]]
x[0] #returns ['l', 'u', 'c', 'y']
x[1][1] #returns postion 1 of the nested list at position 1
3.2
#fibonacci series
a,b=0,1
while b<10: #any negatives are true, 0 is false. condition could be list or a string
print b
a, b = b, a+b
#returns:
1
1
2
3
5
8
#<,>,==,<=,>=,!= (not equal)
#use + to print
|
7a1fdb1c91a87980d9162885a03430f8403fd3f9 | Yue-Du/Leetcode | /33.py | 1,144 | 3.578125 | 4 | from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums)==0:
return -1
left=0
right=len(nums)-1
med=(left+right)//2
while left+1 < right:
if nums[med] > nums[right]:
left=med
med=(left+right)//2
elif nums[med]<nums[right]:
right=med
med=(left+right)//2
if nums[left]<nums[right]:
zz=right
else:
zz=left
if target==nums[zz]:
return zz
elif target<nums[0]:
left=zz
right=len(nums)-1
else:
left=0
right=zz
med=(left+right)//2
while left+1 < right:
if nums[med]<target:
left=med
med=(left+right)//2
else:
right=med
med=(left+right)//2
if nums[left]==target:
return left
elif nums[right]==target:
return right
else:
return -1
New = Solution()
New.search([1,3,5],5) |
5323f6abf6d0a793a622cfea5de075f2c3c309f4 | deshdeepakPandey/Assignment1 | /PrimeNumbers.py | 179 | 3.75 | 4 | Number=int(input("Enter Number: "))
for j in range(2,Number+1):
k=0
for i in range(2,j/2+1):
if(j%i==0):
k=k+1
if(k<=0):
print(j),
|
7e5d96030e051f76c183d7cd19c28d5e49ea7033 | nikkiwojo/TDD-Project | /test_ordering.py | 716 | 3.890625 | 4 |
# Writing a unit test (basic example)
# First - need to import unittest package
# Second - need to import class/functions from original code
# Second - set up a class that will define a bunch of functions to test original code
# Notice parameter for the class is unittest.TestCase
# See example below for what to put in each function
# To run the unit test, in the terminal type python3 -m unittest test_ordering
import unittest
from ordering import order
class testing_stuff(unittest.TestCase):
def test_order(self):
given = [5,3,2,1,8,14]
expected = [1,2,3,5,8,14]
actual = order(given)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main() |
925ec04191841fd4c63bf0301ae6d732c870e3be | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/Overflow/_Learning/problems/problem_07_dictionary.py | 510 | 3.78125 | 4 | # DICTIONARY
#
# Write a function named "my_filter" that takes a dictionary as a parameter.
# Return another dictionary that consists of the key/value pairs from the
# argument where the value has a length less than or equal to 3. Use any
# construct that want to implement "my_filter".
#
# Test data follows.
# WRITE YOUR CODE HERE
# TEST DATA
print(my_filter({1: ".", 2: "..", 5: "....."})) # > {1: ".", 2: ".."}
print(my_filter({})) # > {}
print(my_filter({1: ".....", 2: "....", 5: ""})) # > {5: ""}
|
a7a284ebe3d3a9484994d50ef7487bd6844e3961 | rishabhranawat/challenge | /leetcode/abbreviation.py | 1,065 | 3.609375 | 4 | class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
:type dictionary: List[str]
"""
self.abbrs = {}
for each in dictionary:
ab = self.getAbbreviation(each)
if(ab in self.abbrs):
self.abbrs[ab].add(each)
else:
self.abbrs[ab] = set()
self.abbrs[ab].add(each)
def getAbbreviation(self, word):
if(len(word) == 0): return None
return word[0]+str(len(word[:-1]))+word[-1]
def isUnique(self, word):
"""
:type word: str
:rtype: bool
"""
ab = self.getAbbreviation(word)
if(ab not in self.abbrs):
return True
elif(len(self.abbrs[ab]) > 1):
return False
elif(len(self.abbrs[ab]) == 1 and word not in self.abbrs[ab]):
return False
return True
# Your ValidWordAbbr object will be instantiated and called as such:
obj = ValidWordAbbr(["a", "a"])
print(obj.isUnique("a")) |
86dd91ed439e368d155397eb44453f0e621f5d19 | naveenselvan/hackerranksolutions | /sWAP cASE.py | 245 | 3.78125 | 4 | def swap_case(s):
c=[]
e=''
for i in s:
c.append(i)
for j in c:
if(j.isupper()==True):
e+=j.lower()
else:
e+=j.upper()
return e
|
5415daf4ab0d250304964de3065412c4871390f8 | sanyapalmero/Advent-of-code-2018 | /Day2/main.py | 1,277 | 3.90625 | 4 | def find_checksum(list_id): #solution of part 1
temp = []
res1 = 0
res2 = 0
for line in list_id:
two_count = 0
three_count = 0
for letter in line:
temp.append(letter)
for letter in temp:
if temp.count(letter) == 2:
two_count = 1
if temp.count(letter) == 3:
three_count = 1
res1 += two_count
res2 += three_count
temp.clear()
return res1 * res2
def find_common_letters(list_id): #solution of part 2
for line1 in list_id:
for line2 in list_id:
diff_letter_count = 0
for i in range(len(line1)):
if line1[i] != line2[i]:
diff_letter_count += 1
if diff_letter_count == 1:
return line1, line2 #find 2 lines that differ by 1 letter
def main():
list_id = []
file = open("list.txt")
for line in file:
list_id.append(str(line))
print(find_checksum(list_id))
line1, line2 = find_common_letters(list_id)
res = "res: "
for letter1, letter2 in zip(line1, line2):
if letter1 == letter2:
res += letter1 #remove extra letter
print(res)
if __name__ == '__main__':
main()
|
26b4192e8075364bae32c3ff6e3958b668ae1d42 | DonCastillo/learning-python | /0061_set_challenge.py | 169 | 3.515625 | 4 |
while True:
text = input("Enter a text here: ")
if text.casefold() == "quit":
break
else:
print(sorted(set(text).difference(set("aeiou")))) |
578e302c56d7408a4b4c0324c6510b459bc6c721 | rafaelperazzo/programacao-web | /moodledata/vpl_data/69/usersdata/168/36267/submittedfiles/jogo.py | 736 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import math
cv=int(input('Digite o número de vitórias do Cormengo: '))
ce=int(input('Digite o número de empate do Cormengo: '))
cs=int(input('Digite o número de saldo de gols do Cormengo: '))
fv=int(input('Digite o número de vitórias do Flaminthians: '))
fe=int(input('Digite o número de empate do Flaminthians: '))
fs=int(input('Digite o número de saldo de gols do Flaminthians: '))
if (cv>fv):
print('C')
elif (cv<fv):
print('F')
else:
print('=')
if (ce>fe):
print('C')
elif (ce<fe):
print('F')
else:
print('=')
if (cs>fs):
print('C')
elif (cs<fs):
print('F')
else:
print('=')
|
b9cd36a78a7ef15e6e254e79b49a309e125acfcc | aretisravani/python6 | /arm.py | 107 | 3.53125 | 4 | a=int(raw_input())
b=a%10
c=a/10
d=c%10
e=c/10
x=b**3+d**3+e**3
if(x==a):
print("yes")
else:
print("no")
|
ad3fea33f8163877572f7ec99a8f80cbbbfb31ec | erjan/coding_exercises | /maximum_matrix_sum.py | 1,637 | 3.984375 | 4 | '''
You are given an n x n integer matrix. You can do the following operation any number of times:
Choose any two adjacent elements of matrix and multiply each of them by -1.
Two elements are considered adjacent if and only if they share a border.
Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.
'''
class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
# count -'s
count = 0
for row in matrix:
for col_num in row:
if col_num < 0:
count += 1
tot_sum = sum([sum([abs(x) for x in row])
for row in matrix])
if count % 2 == 0:
return tot_sum
else:
min_val = min([min([abs(x) for x in row])
for row in matrix])
return tot_sum - 2 * min_val
--------------------------------------------------------------------------
class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
count_neg = 0
total = 0
m = math.inf
for i in range(n):
for j in range(n):
total += abs(matrix[i][j])
m=min(m,abs(matrix[i][j]))
if matrix[i][j] < 0:
count_neg +=1
if count_neg %2 == 0: #even neg nums
return total
elif count_neg %2 == 1:
return total - 2*m
|
8d01098dc7941f59dc39ba84a3529327911039cb | emanuelgustavo/pythonscripts | /Introdução a Ciencia da Computação com Python - PII/w5_busca_binária/w5_Ex2_bubble_sort.py | 459 | 3.921875 | 4 | def bubble_sort(lista):
fim = len(lista)
first = True
for i in range(fim-1, 0, -1):
if first:
#print(lista)
first = False
for j in range(i):
a = lista[j]
b = lista[j+1]
if a > b:
lista[j] = b
lista[j+1] = a
print(lista)
return lista
'''
def test():
bubble_sort([5, 1, 3, 4, 2, 0])
test()
''' |
197123c26689787a9bb58d86e283513db68580e4 | rajathans/cp | /CodeChef/hs08test.py | 174 | 3.796875 | 4 | x,y = raw_input().split()
x = int(x)
y = float(y)
if ((x % 5) == 0):
if((y-x-0.5)>0):
print("%0.2f"%(y-x-0.5))
else:
print("%0.2f"%y)
else:
print("%0.2f"%y) |
3705242fe7cad024a763f6c429fc3ba67163a886 | rikoodb/agregador_de_editais | /projeto_parser_inovacao/spiders/testes/testes_db_usuario.py | 1,208 | 3.53125 | 4 | import os
import unittest
import sqlite3
from usuario.usuario import lista_usuarios
class test_db_usuario(unittest.TestCase):
def setUp(self):
self.conn = sqlite3.connect("mydatabase.db")
self.cursor = self.conn.cursor()
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS usuario
(
id_usuario INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(100) NOT NULL,
email VARCHAR(80) NOT NULL
)
""")
self.conn.commit()
self.cursor.execute("""
INSERT INTO
usuario(nome, email)
VALUES
(
'joao','joao@hotmail.com'
)
""")
self.conn.commit()
def tearDown(self):
os.remove("mydatabase.db")
self.conn.close()
def teste_lista_usuarios(self):
"""
testando a funcao lista_usuarios
"""
resultado_bd = lista_usuarios(self.conn, self.cursor)
self.assertEqual(len(resultado_bd), 1)
resultado_esperado = [(1, 'joao', 'joao@hotmail.com')]
self.assertEqual(resultado_bd, resultado_esperado)
|
950e0385dee010fc04faca4e3e15ecbeca7019de | bhaveshpatelquantiphi/python | /day 3/calc.py | 2,155 | 3.90625 | 4 | import logging
import datetime
# now = datetime.datetime.now()
logging.basicConfig(filename='example.log',level=logging.DEBUG)
# logging.debug('This message should go to the log file')
# logging.info('So should this')
def add(x,y):
"""
add (x(float), y(float))
Return (float) :addition of first and second number """
return x+y
def sub(x,y):
"""
sub (x(float), y(float))
Return (float) :Subtraction of first and second number """
return x-y
def mul(x,y):
"""
mul (x(float), y(float))
Return (float) :Multiple of first and second number """
return x*y
def div(x,y):
"""
div(first number(float), second number(float))
Return (float) :Division of first and second number
"""
try:
return x/y
except ZeroDivisionError,e:
logging.
0.0("Can't divide by zero"+"\t"+str(x)+" "+str(y)+"\t"+str(datetime.datetime.now()))
print "Can't divide by zero"
def mod(x,y):
"""
Mod(first number(float), second number(float))
Return (float) :Modulus of first and second number
"""
if y==0: # If denominator is zero
# logging.warning('Can\'t divide by zero',x,y)
return "Can't divide by 0"
if y<0: # If denominator is Negative
# logging.warning('Can\'t be negative',x,y)
return "Can't be negative"
return x%int(y)
def input():
"""
Input()
Common function to take number inputs a,b
"""
print "Enter first numbers :",
global a
try:
a = float(raw_input())
except ValueError,e:
print e
print "Enter second numbers :",
global b
try:
b = float(raw_input())
except ValueError,e:
print ValueError,e
flag = True
while (flag) :
input()
print "Enter your operation :\n + : Plus, - : Minus, * : Multiple, / : Divide, % : Mod, e : Exit\n",
p = raw_input()
# Compare the input operation and call the operation
if(p=='+'):
print add(a,b)
elif(p=='-'):
print sub(a,b)
elif(p=='*'):
print mul(a,b)
elif(p=='/'):
print div(a,b)
elif(p=='%'):
print mod(a,b)
elif(p=='e'):
flag = False;
else:
print "Try again !" |
3c638aa8de7f0a0c6b8c2c25e54ec3fd4c279d9a | RajatPrakash/Python_Journey | /matplot_lib_oops.py | 459 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
figure = plt.figure(figsize=(10, 10)) # creating a simple figure
axes = figure.add_axes([0, 0, 1, 1])
x = np.linspace(0, 10, 100)
y = np.tan(x)
axes.plot(x, y, 'r--', label= 'Red Sine Wave #01')
axes.set_xlabel('Time')
axes.set_ylabel('Sine wave')
axes.set_title('My third plot')
axes.legend()
axes.set_ylim([-1, 1]) # set x and y limits
axes.set_xlim([0, 10])
axes.grid()
plt.plot(x, y)
plt.show() |
0050ea4f21566b9cc4317cc0e818fc0ba4dd1939 | conniechen19870216/WorkNotes | /Ubuntu4Me/codes/python/calc1.py | 525 | 3.5625 | 4 | #!/usr/bin/python
#coding:utf-8
from __future__ import division
x = int(raw_input("please input x: "));
y = int(raw_input("please input y: "));
def jia(x, y):
return x+y
def jian(x, y):
return x-y
def cheng(x, y):
return x*y
def chu(x, y):
return x/y
def calc(x, o, y):
if o == '+':
return jia(x, y)
elif o == '-':
return jian(x, y)
elif o == '*':
return cheng(x, y)
elif o == '/':
return chu(x, y)
else:
pass
print calc(x, '+', y)
print calc(x, '-', y)
print calc(x, '*', y)
print calc(x, '/', y)
|
b5457cb06b80bdb700244192651108498099b7ce | stephanieeechang/PythonGameProg | /PyCharmProj/Codingame/Defibrillators.py | 835 | 3.5625 | 4 | '''
Q2 final project
Codingame - Easy Level - Defibrillators
'''
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
defibList = []
smallestD = 99999999
lon = input()
lon = float(lon.replace(',','.'))*math.pi/180
lat = input()
lat = float(lat.replace(',','.'))*math.pi/180
n = int(input())
for i in range(n):
defib = input()
dSplit = defib.split(';')
dSplit[4] = float(dSplit[4].replace(',','.'))*math.pi/180
dSplit[5] = float(dSplit[5].replace(',','.'))*math.pi/180
x = (dSplit[4]-lon)*math.cos((lat+dSplit[5])/2)
y = dSplit[5]-lat
d = math.sqrt(x**2 + y**2)*6371
if d < smallestD:
smallestD = d
name = dSplit[1]
# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
print(name)
|
675d86bb8c0c5dcbdbe80b66a4291e64fc3e3cc1 | bvsslgayathri-8679/pythonlab | /1_2.py | 65 | 3.703125 | 4 | n=int(input())
if n>=0:print("positive")
else:print("negative") |
69cd770f18c2af8d4ab1fbbf1be95fe8aacdb80c | codegician/Python-Scripts | /inheritance.py | 927 | 3.875 | 4 | class Parent():
def __init__(self, last_name, eye_color):
print("Parent Constructor Called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last Name - "+self.last_name)
print("Eye Color - "+self.eye_color)
class Child(Parent):
def __init__(self, last_name, eye_color,number_of_toys):
print("Child Constructor Called")
Parent.__init__(self, last_name, eye_color)
self.number_of_toys = number_of_toys
def show_info(self):
print("Last Name - "+self.last_name)
print("Eye Color - "+self.eye_color)
print("Number of Toys - "+str(self.number_of_toys))
xen_dark = Parent("Dark", "black")
#xen_dark.show_info()
#print(xen_dark.last_name)
atlas_dark = Child("Dark", "black", 1)
atlas_dark.show_info()
#print(atlas_dark.last_name)
#print(atlas_dark.number_of_toys)
|
b2d205e7a7c6f7dd492b65eee3eed9ef78e0f82f | MarionMcG/python-fundamentals | /Lecture notes and demos/1review.py | 1,617 | 4.3125 | 4 | #Demos and notes from Week 1 of Python Fundamentals
#Reviewing the basics
#Is it Tuesday?? (Review of IF Statements)
import datetime
print()
print("Is it Tuesday???")
today = datetime.datetime.today()
dayofweek = today.weekday()
print ('Today = ',today)
print ('Day of Week =', dayofweek)
#If the day of the week equals 1, then its Tuesday as datetime
#sets days as number 0 - 6 , with Monday been the first day = 0
if dayofweek == 1:
print("It's Tuesday!")
elif dayofweek == 0:
print("It's not Tuesday....")
print("Luckily it will be Tuesday Tomorrow!")
else:
print("Sorry, it's not Tueday")
print()
#Highest common factor (Review of WHILE Loops)
print('Highest Common Factor')
a = 50
b = 20
while b > 0:
#Set a = temp value that can be overwritten using this format.
#IN PYTHON: a, b are the old values on the LHS and they are overwritten by new values.
#On the RHS new values, are b and a modulo b
a, b = b, a%b
print(a, 'is the HCF of 20 and 50')
print()
#Listing the first 10 square numbers (Review of FOR Loops)
#Used to iterate through a list, so you always need to begin with a list!
print("The first 11 Square numbers")
for i in range(11):
#range (10) is same as list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f"{i:2} {i*i:4}")
print()
#Highest Common Factor ..again(Review of FUNCTIONS)
def hcf (a, b):
""" Returns the Highest Common Factor of a, b
"""
if a<b:
a, b = b, a
while b > 0:
a, b = b, a % b
return a
print ("The HCF of 20 and 50 is", hcf (20, 50))
print("The HCF of 143 and 22 is", hcf (143, 22))
print() |
6b886f6ad60a72be720a57d5f257f931d4914ead | theshadman/CPSC231_Stuff | /T14and15/Tutorial_14.py | 1,222 | 3.75 | 4 | #from tkinter import*
import tkinter as tk
import time
'''
animation = Tk()
canvas = Canvas(animation, width=500, height=500)
canvas.pack()
canvas.create_line(50,50,150,150)
while True:
for x in range(50):
canvas.move(1,5,0)
animation.update()
time.sleep(0.05)
for x in range(50):
canvas.move(1,-5,0)
animation.update()
time.sleep(0.05)
'''
global switch
switch = 1
win = tk.Tk()
win.title("Python GUI")
win.geometry("500x500")
win.resizable(False, False)
label = tk.Label(win, text="A Label")
label.grid(column=0, row=0)
#buttons
def clicked_01():
switch = int(input("? "))
button_1.configure(text="I have been clicked")
if switch%2==0:
label.configure(foreground = 'red')
label.configure(text="a red line")
else:
label.configure(foreground = 'blue')
label.configure(text="a blue line")
switch+=1
def clicked_02():
label.configure(text='Hello '+name.get())
#textBox
name = tk.StringVar()
textBox_1 = tk.Entry(win, width=12, textvariable=name)
textBox_1.grid(column=0,row=1)
button_1 = tk.Button(win, text="I dare you, I double dare you.",command=clicked_01)
button_1.grid(column=1, row=0)
while int(input("? "))%2==0:
clicked_01()
win.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.