blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
f730d0117e713937c0b7ec55bf76563f083fdbcb
danluu/dump
/dasgupta/rosalind/3sum.py
1,072
3.671875
4
import collections # Create a set of inverse of all numbers in xs. # For every pair of numbers, check to see if the pair sums to inverse of any number. def solve(xs): candidates = collections.defaultdict(list) for i in range(len(xs)): candidates[-xs[i]].append(i) for i in range(len(xs)): for j in range(len(xs)): if i != j and (xs[i] + xs[j]) in candidates: return "{} {} {}".format(i+1, j+1, candidates[xs[i]+xs[j]][0]+1) return -1 # with open('rosalind_3sum.txt') as f: with open('/Users/danluu/Downloads/rosalind_3sum.txt') as f: num_lines_s, num_entries_per_line_s = f.readline().strip().split(' ') num_lines = int(num_lines_s) num_entries_per_line = int(num_entries_per_line_s) for line in f: num_lines -= 1 numbers = [int(x) for x in line.strip().split(' ')] assert(len(numbers) == num_entries_per_line) print(solve(numbers)) assert(num_lines == 0)
7810702f1445f2920b22ff168d9d71d065a502ab
mir-pucrs/norm-detect
/rlist.py
350
3.78125
4
class rlist(list): """ A resizeable list that allows elements to be inserted in arbitrary positions""" def __init__(self, default): self._default = default def __setitem__(self, key, value): if key >= len(self): self += [self._default] * (key - len(self) + 1) super(rlist, self).__setitem__(key, value)
dc3b73dbd6de39c321d992355879bcfdeeafec45
wilsonify/euler
/src/euler_python_package/euler_python/easiest/p006.py
854
3.625
4
def problem006(): """ s = N(N + 1) / 2. s2 = N(N + 1)(2N + 1) / 6. Hence s^2 - s2 = (N^4 / 4) + (N^3 / 6) - (N^2 / 4) - (N / 6). The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ number = 100 s = sum(i for i in range(1, number + 1)) s2 = sum(i ** 2 for i in range(1, number + 1)) return s ** 2 - s2 if __name__ == "__main__": print(problem006())
324e624d99ea53e99b055289a46ae586553fc439
mik-79-ekb/Python_start
/Lesson_2/HW_2.5.py
201
3.6875
4
""" Task 2.5 """ list = [7, 5, 3, 3, 2] rating = int(input("Введите новый рейтинг: ")) ind= 0 for x in list: if rating <= x: ind += 1 list.insert(ind, rating) print(list)
67a38e0e53c833a52b2fc1f20914813e8edc6e0d
joalcava/College-projects
/8 Puzzle/Solver.py
2,042
3.71875
4
## Important note: ## I have taken inspiration from this code: ## https://gist.github.com/thiagopnts/8015876 from Queue import PriorityQueue class State(object): def __init__(board, weight, level, back_state): self.board = board self.weight = weight self.level = level self.back_state = back_state class Solver(object): def __init__(self, board): self.queue = PriorityQueue() self.state = State(board, board.manhattan(), 0) self.queue.put(self.state) self.opened = [] self.close = [] def moves(self): level = 0 while (not self.queue.empty()): current = self.queue.get() if current[2].isSolvable() and not self.is_in_closed(current[2]): if current[2].isGoal(): print 'encontre la solucion' return self.print_list(current[3]) else: self.close.append(current[2]) current[2].neighbors() level += 1 for i in current[2].neighborhood: back_states = list(current[3]) back_states.append(current[2]) state = ( i.manhattan(), level, i, back_states) if not self.is_in_opened(i): self.opened.append(i) self.queue.put(state) else: continue return 'No tiene solucion' def print_list(self, _list): for i in _list: print i print str(len(_list)) return 0 def is_in_opened(self, board): for i in self.opened: if board == i: return True return False def is_in_closed(self, board): for i in self.close: if board == i: return True return False
c9c81e4a9898ff667056c695b5e5ded93b966277
TaiPham25/PhamPhuTai---Fundamentals---C4E16
/Session02/Homework/number.py
110
4
4
from math import factorial n = int(input("Enter number:")) n = factorial(n) print('Factorial of number: ' ,n)
e4e2c4dfa5e75c5e03ac462e570c95c5de6d94ed
ismailraju/capcha-crack
/pythonlearning.py
349
3.53125
4
p = [29, 58, 66, 71, 87] print p[0::2] print "raju "*10 name="ismail hossain raju" print 'k' in name print 'n' in name print [20]*10 family=["dad","mom","sis"] print 'sis' in family print 'bro' in family print len(family) print max(p) print list('ismail hossain raju') p[2]=44444 print p del p[2] print p p[1:1]=[2,2,2,2] print p p.append(2000) print p
6308c6d14708d3b58e376692fdbdd935b35a0254
1YaoDaDa/OCEAN
/让繁琐工作简单化/GongBaLei.py
924
4.28125
4
# this program says hello and ask for my name print('Hello world') print('What is your name?') # ask for their name myname = input() # the return from input is 'str'. print('It is good to meet you,' + myname) print('The length of your name is:') print(len(myname)) # the return from len() is int. print('What is your age?') myage = input() print('You will be ' + str(int(myage) + 1) + ' in a year.') # '+' only work for int and int, or str and str, not for others. # str() convert ('') into str forcibly. print('What is your goal for studying pyton?') mygoal = input() print('Your goal is to reducing work time!') print('GonBaLei!') print('How much do you exercise?') myextime = input() print('Ok!' + ' Do you study python today?') print('Yes' + ' or ' + 'No') myanswer = input() if myanswer == 'Yes': print('Congratulations!' + ' See you tommorow.') else: print('The key to success is adhering to your target.')
d49bc7397194aaf8b264e08c532e4863ffea4404
ChandraSiva11/sony-presamplecode
/tasks/final_tasks/recursion/12.power_of_no.py
283
4.28125
4
# Python Program to Find the Power of a Number Using Recursion def power(base, expo): if expo == 0: return 1 else: return base * power(base, expo - 1) def main(): base_no = 5 exp_no = 2 res = power(base_no, exp_no) print("Result", res) if __name__ == '__main__': main()
b5e5f1bf89e333886bd029f4d41eca806520cfd1
Ryan-Swanson/py_sorts
/main.py
1,692
4.28125
4
# This file contains selection, insert, bubble, merge, and # quick sorts, and a function to generate a random list of # size quantity with numbers ranging from 0 to quantity from random import seed from random import randint # Random list generator, with arg quantity def random_list(quantity: int) -> int: seed() rand_list = [] for item in range(0, quantity): rand_list.append(randint(0, quantity*2)) return rand_list # Selection Sort def selection_sort(sort_me): length = len(sort_me) for item in range(length): min_index = item for index in range(item+1, length): if sort_me[index] < sort_me[min_index]: min_index = index sort_me[item], sort_me[min_index] = sort_me[min_index], sort_me[item] # Insertion Sort def insertion_sort(sort_me, length): if length <= 1: return insertion_sort(sort_me,length-1) last = sort_me[length-1] j = length - 2 while (j >= 0 and sort_me[j]>last): sort_me[j+1] = sort_me[j] j -= 1 sort_me[j+1] = last # Bubble Sort def bubble_sort(sort_me): for item in sort_me: for index in range(len(sort_me)-1): if sort_me[index] > sort_me[index+1]: sort_me[index], sort_me[index+1] =sort_me[index+1], sort_me[index] test_list = random_list(20) print("Original list: \n", test_list) selection_sort(test_list) print("Selection Sort: \n", test_list) test_list = random_list(25) print("Original list(insertion sort): \n", test_list) insertion_sort(test_list,len(test_list)) print("Insertion sort: \n", test_list) test_list = random_list(20) print("Original list(Bubble sort): \n", test_list) bubble_sort(test_list) print("Bubble sort: \n", test_list)
ef0a54a287c7bf79a385a42a3c741f8edc3cde85
f1uk3r/Daily-Programmer
/Problem-5/dp5-password-protection.py
716
3.59375
4
def locked(): found = 0 username = input("Enter your username: ") user = open('username.txt', 'r') userlist = user.read().split("\n") user.close() for line in userlist: if username in line: found = 1; num = userlist.index(line) break if found == 0: print("You are not what we are looking for.") locked() else: checkPass(username, num) def checkPass(username, num): print("Welcome " + username + ", ") password = input("Enter your Password: ") pass1 = open('password.txt', 'r') passlist1 = pass1.read().split("\n") pass1.close() if password == passlist1[num]: print("You are a candidate for human sacrifice.") else: print("Enter the right password") checkPass() locked()
bd990afe03d68f88360af872ce0505c7c4d4da0d
PhillipDHK/Recommender
/RecommenderEngine.py
3,114
3.734375
4
''' @author: Phillip Kang ''' def averages(items, ratings): ''' This function calculates the average ratings for items. A two-tuple is returned, where the first element is a string and the second element is a float. ''' lst1 = [0 for x in range(len(items))] lst2 = [0 for x in range(len(items))] for k, v in ratings.items(): for value in range(len(v)): lst1[value] += v[value] if v[value] != 0: lst2[value] += 1 lst3 = [] for i in range(len(lst1)): if lst2[i] == 0: lst3.append(float(0)) else: lst3.append(lst1[i]/lst2[i]) ret = [] for i in range(len(items)): ret.append(tuple((items[i], lst3[i]))) ret = sorted(ret) return sorted(ret, key = lambda x: x[1], reverse = True) def similarities(name, ratings): ''' This function calculates how similar the rater called name is to all other raters. A two-tuple is returned, where the first element is a string and the second element is an integer. ''' lst1 = [] d = {} for k, v in ratings.items(): if k == name: lst1.append(v) if k != name: d[k] = v count = 0 for k, v in d.items(): for i in range(len(v)): count += v[i] * lst1[0][i] d[k] = count count = 0 d_list = d.items() ret = list(d_list) ret = sorted(ret) return sorted(ret, key = lambda x: x[1], reverse = True) def recommendations(name, items, ratings, numUsers): ''' This function calculates the weighted average ratings and makes recommendations based on the parameters and weighted average. A two-tuple is returned, where the first element is a string and the second element is a float. ''' similar = similarities(name, ratings) similar = similar[:numUsers] d = {} for k, v in ratings.items(): weight = 0 for i in similar: if k == i[0]: weight = i[1] new_ratings = [weight * x for x in v] d[k] = new_ratings return averages(items, d) if __name__ == '__main__': items = ["DivinityCafe", "FarmStead", "IlForno", "LoopPizzaGrill", "McDonalds", "PandaExpress", "Tandoor", "TheCommons", "TheSkillet"] ratings = {"Sarah Lee": [3, 3, 3, 3, 0, -3, 5, 0, -3], "Melanie": [5, 0, 3, 0, 1, 3, 3, 3, 1], "J J": [0, 1, 0, -1, 1, 1, 3, 0, 1], "Sly one": [5, 0, 1, 3, 0, 0, 3, 3, 3], "Sung-Hoon": [0, -1, -1, 5, 1, 3, -3, 1, -3], "Nana Grace": [5, 0, 3, -5, -1, 0, 1, 3, 0], "Harry": [5, 3, 0, -1, -3, -5, 0, 5, 1], "Wei": [1, 1, 0, 3, -1, 0, 5, 3, 0]} # print(averages(items, ratings)) # print(similarities('Harry', ratings)) print(recommendations('Harry', items, ratings, 2))
37156bcd0902c19e217ab17bf06ded3e6c44c9f6
poojagmahajan/Data_Analysis
/Data Analytics/Statistics/Probability_ mass_function.py
599
3.578125
4
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import binom from PIL import Image # Number of experiments n = 10 # Probability of success p = 0.5 # Array of probable outcomes of number of heads x = range(0,11) # Get probabilities prob = binom.pmf(x, n, p) # Set properties of the plot fig, binom_plot = plt.subplots(figsize=(10,8)) binom_plot.set_xlabel("Number of Heads",fontsize=16) binom_plot.set_ylabel("Probability",fontsize=16) binom_plot.vlines(x, 0, prob, colors='r', lw=5, alpha=0.5) # Plot the graph binom_plot.plot(x, prob, 'ro') plt.show()
59f293e2097b25927d32027dcbdea7213df2ee88
cfowles27293/leetcode
/venv/remove_duplicates.py
1,300
3.5
4
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) > 1: nums = self.mark(nums) i = 0 while(i < len(nums)-1): if not nums[i] == None: i += 1 else: j = i + 1 while nums[j] == None: if j < len(nums)-1: j += 1 else: print(nums) return self.count(nums) temp = nums[j] nums[j] = nums[i] nums[i] = temp print(nums) return self.count(nums) def mark(self,nums): for i in range(len(nums)-1): j = i + 1 while nums[i] == nums[j]: nums[j] = None if j + 1 < len(nums): j += 1 else: break return nums def count(self, nums): end = 0 for num in nums: if num != None: end += 1 return end if __name__ == "__main__": nums = [1,2] s= Solution() print(s.removeDuplicates(nums))
aa739b8bc9a5dad8702f297282bab26a4dab5bd3
guancongyi/LeetCode_py
/75-SortColors.py
548
3.71875
4
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ begin, i, end = 0, 0, len(nums)-1 while i <= end: if nums[i] == 0: nums[begin], nums[i] = nums[i], nums[begin] i+=1 begin+=1 elif nums[i] == 2: nums[end], nums[i] = nums[i], nums[end] end-=1 else: i+=1 print(nums)
10e9ca52f911c5c2e2756e6c92809c4f5a4c9aef
Deepakat43/luminartechnolab
/fuctinaprgrmming/filtering.py
799
3.59375
4
st=[7,8,10,4,3,2] print(list(filter(lambda num:num%2==0,st))) print(list(filter(lambda num:num>5,st))) empyees=[ {"eid":1000,"name":"ajay","salary":25000,"designation":"developer"}, {"eid":1001,"name":"vijay","salary":22000,"designation":"developer"}, {"eid":1002,"name":"arun","salary":26000,"designation":"qa"}, {"eid":1003,"name":"varun","salary":27000,"designation":"ba"}, {"eid":1004,"name":"ram","salary":20000,"designation":"nrkt"}, ] # print(list(filter(lambda emp:emp["designation"]=="developer",empyees))) # # #fr getting only names # devp=list(filter(lambda emp:emp["designation"]=="developer",empyees)) # print(list(map(lambda emp:emp["name"],devp))) print(list(map(lambda emp:emp["name"],list(filter(lambda emp:emp["designation"]=="developer",empyees)))))
8695641c9006fda911e301c4b9e9f2e102db3b74
jarzab3/smart_city_mdx
/test/boards/asip_writer.py
840
3.78125
4
__author__ = 'Gianluca Barbon' # this library allows to make this class an abstract class # from abc import ABCMeta, abstractmethod # notice that in java this is an interface, but python as no interfaces! # python 2.7 version # class AsipWriter(object): # __metaclass__=ABCMeta # # @abstractmethod # def write(self, val): # pass # python 3 version # class AsipWriter (metaclass=ABCMeta): # # @abstractmethod # def write(self, val): # pass # this version actually is not an abstract class, but we need to implement it in this way in order to be compatible # with both python versions, without the use of external libraries (for compatibility) class AsipWriter: #method that will be overridden in child classes def write(self, val): raise NotImplementedError( "Should have implemented this" )
cf1172cb46306713289f5bbd80ccc5442ee601c9
young-geng/leet_code
/problems/264_ugly-number-ii/main.py
767
3.609375
4
# https://leetcode.com/problems/ugly-number-ii/ import heapq class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ def addToHeap(heap, dictionary, key): if key in dictionary: dictionary[key] += 1 else: dictionary[key] = 1 heapq.heappush(heap, key) if n == 1: return 1 heap = [1] seen = {1:1} for i in xrange(1, n): root = heapq.heappop(heap) u2 = root*2 u3 = root*3 u5 = root*5 addToHeap(heap, seen, u2) addToHeap(heap, seen, u3) addToHeap(heap, seen, u5) return heapq.heappop(heap)
e691ff915526366092201cae24ea76e3e86ec3f5
simtb/coding-puzzles
/daily_coding_challenges/challenges/stack.py
1,608
4.21875
4
""" This problem was asked by Amazon. Implement a stack that has the following methods: push(val), which pushes an element onto the stack pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null. max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null. Each method should run in constant time. """ class Stack: def __init__(self): self.stack: list = [] self.__max_values: list = [] @property def is_empty(self) -> bool: return not bool(self.stack) def push(self, val: int) -> None: if self.is_empty and not self.__max_values: self.__max_values.append(val) elif not self.is_empty and self.__max_values and val >= self.__max_values[-1]: self.__max_values.append(val) else: pass self.stack.append(val) def pop(self) -> int: if self.is_empty and not self.__max_values: return None value: int = self.stack.pop() if value == self.__max_values[-1]: self.__max_values.pop() return value def max(self) -> int: if self.is_empty and not self.__max_values: return None else: return self.__max_values[-1] def __contains__(self, test_value: int) -> bool: for value in self.stack: if test_value == value: return True return False
781f0f5cd62ea98d3969845747aec35e02304b72
Punchyou/DS_from_Scratch
/probability.py
4,494
3.734375
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 2 20:47:42 2019 @author: maria_p """ """Conditionl Probabilities.""" """A family with two unknown children.""" from random import choice, seed, random from math import sqrt, exp, pi, erf from matplotlib import pyplot as plt from collections import Counter def random_kid(): return choice(["boy", "girl"]) both_girls = 0 older_girl = 0 either_girl = 0 seed(5) # seed() returns a different sequence of values for _ in range(10000): younger = random_kid() older = random_kid() if older == "girl": older_girl += 1 if older == "girl" and younger == "girl": both_girls += 1 if older == "girl" or younger == "girl": either_girl += 1 #print("P(both | older): ", both_girls / older_girl) #print("P(both | either: ", both_girls / either_girl) """The density function""" def uniform_pdf(x): return 1 if x >= 0 and x <1 else 0 """The cumulative distribution function""" def uniform_cfd(x): """returns the probbility that a uniform random vroable is <= x""" if x<0: return 0 elif x < 1: return x else: return 1 """The normal pdfs""" def normal_pdf(x, mu = 0, sigma = 1): sqrt_two_pi = sqrt(2 * pi) return (exp(-(x - mu) ** 2 / 2 / sigma ** 2) / (sqrt_two_pi * sigma)) xs = [x / 10.0 for x in range(-50, 50)] plt.plot(xs, [normal_pdf(x, sigma=1) for x in xs], '-', label = 'mu=0, sigma=1') #standart norma distribution plt.plot(xs, [normal_pdf(x, sigma=2) for x in xs], '--', label = 'mu=0, sigma=2') plt.plot(xs, [normal_pdf(x, sigma=0.5) for x in xs], ':', label = 'mu=0, sigma=0.5') plt.plot(xs, [normal_pdf(x, mu = -1) for x in xs], '-.', label = 'mu=-1, sigma=1') plt.legend() plt.title("Various Normal pdfs") #plt.show() """The norms cdfs""" def normal_cdf(x, mu=0, sigma=1): return (1 + erf((x - mu) / sqrt(2) / sigma)) / 2 #using the erf, error function plt.plot(xs, [normal_cdf(x, sigma=1) for x in xs], '-', label = 'mu=0, sigma=1') #standart norma distribution plt.plot(xs, [normal_cdf(x, sigma=2) for x in xs], '--', label = 'mu=0, sigma=2') plt.plot(xs, [normal_cdf(x, sigma=0.5) for x in xs], ':', label = 'mu=0, sigma=0.5') plt.plot(xs, [normal_cdf(x, mu = -1) for x in xs], '-.', label = 'mu=-1, sigma=1') plt.legend(loc = 4) #bottom right plt.title("Various Normal cdfs") #plt.show() """Invert normal_cdf to find the values corresponding to specific probabiity. This function repeatedly bisects intervals until it narrows in on a Z tht's close enough to the desired probability.""" def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=0.00001): """find approximate inverse using binary search.""" #if not standard, compute standard nd rescale if mu !=0 or sigma !=1: return mu + sigma * inverse_normal_cdf(p, tolerance=tolerance) low_z = -10.0 #normal_cdf(-10) is close to 0 hi_z = 10.0 #norml_cfd(10) is close to 1 while hi_z - low_z > tolerance: mid_z = (low_z + hi_z) / 2 #the midpoint mid_p = normal_cdf(mid_z) #and the cdf's value there if mid_p < p: #midpoint still too low, search above it low_z = mid_z elif mid_p > p: #midpoint still to high hi_z = mid_z else: break return mid_z """The central limit theorem - For large n sampe of samples, the distribution of means for the samples of samples is approximatelly normal.""" """A Bernouli variable is the sum of n independent bernouli random variables, each of which equals 1 with probability p and 0 with probability 1 - p.""" def bernouli_trial(p): return 1 if random() < p else 0 def binomial(n, p): return sum(bernouli_trial(p) for _ in range(n)) """Ploting the binomial and normal distributions.""" def make_hist(p, n, num_points): data = [binomial(n, p) for _ in range(num_points)] #use a bar chrt to show the actual binomial samples histogram = Counter(data) plt.bar([x - 0.4 for x in histogram.keys()], [v / num_points for v in histogram.values()], 0.8, color='0.75') mu = p * n sigma = sqrt(n * p * ( 1 - p)) #use a line to show the normal approximation xs = range(min(data), max(data) + 1) ys = [normal_cdf(i + 0.5, mu, sigma) - normal_cdf(i - 0.5, mu, sigma) for i in xs] plt.plot(xs, ys) plt.title("Binomial Distribution vs. Normal Approximation") #plt.show() #make_hist(0.75, 100, 10000)
d2533a610909fda15c97d699e042c1decff76852
dongxiexiyin/leetcode
/191-number-of-1-bits/number-of-1-bits.py
3,336
4.03125
4
# -*- coding:utf-8 -*- # Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). # # Example 1: # # # Input: 11 # Output: 3 # Explanation: Integer 11 has binary representation 00000000000000000000000000001011 # # # Example 2: # # # Input: 128 # Output: 1 # Explanation: Integer 128 has binary representation 00000000000000000000000010000000 # # class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ #自己写的,方法1,转换成字符串,数1的个数 ''' return bin(n).count('1') ''' #方法二,不断向右位移,如果末位等于1,count + 1 ''' count = 0 if n == 0: return count for _ in range(32): count += (n & 1) n >>= 1 return count ''' #看了汉明重量的维基百科,利用树状相加是最好的解决办法。 ''' m1 = 0x55555555 m2 = 0x33333333 m4 = 0x0f0f0f0f m8 = 0x00ff00ff m16 = 0x0000ffff h01 = 0x01010101 ''' #最原始的写法如下,这也是树状相加的基本思路,但是效率比较低,用到的计算次数比较多 ''' n = (n & m1) + ((n >> 1) & m1) n = (n & m2) + ((n >> 2) & m2) n = (n & m4) + ((n >> 4) & m4) n = (n & m8) + ((n >> 8) & m8) n = (n & m16) + ((n >> 16) & m16) return n ''' #改进版的算法,计算次数有所减少 ''' n -= (n >> 1) & m1 #put count of each 2 bits into those 2 bits n = (n & m2) + ((n >> 2) & m2) #put count of each 4 bits into those 4 bits n = (n + (n >> 4)) & m4 #put count of each 8 bits into those 8 bits n += n >> 8 #put count of each 16 bits into their lowest 8 bits n += n >> 16 #put count of each 32 bits into their lowest 8 bits return n & 0xff ''' #终极版的算法,计算次数最少,效果最好,但是好像有错。。。 ''' n -= (n >> 1) & m1 #put count of each 2 bits into those 2 bits n = (n & m2) + ((n >> 2) & m2) #put count of each 4 bits into those 4 bits n = (n + (n >> 4)) & m4 #put count of each 8 bits into those 8 bits return (n * h01) >> 24 #returns left 8 bits of n + (n<<8) + (n<<16) + (n<<24) + ... ''' #如果已知大多数位是0的话,还有更快的算法。这些更快的算法是基于这样一种事实即n与n - 1相与得到的最低位永远是0,例如n = 01000100010000,n - 1 = 01000100001111,n & (n - 1) = 01000100000000。减1操作将最右边的符号从0变到1,从1变到0,与操作将会移除最右端的1。如果最初n有N个1,那么经过N次这样的迭代运算,n将减到0。下面的算法就是根据这个原理实现的。 ''' count = 0 while n > 0: n &= n - 1 count += 1 return count ''' #如果已知大多数位是1的话,也许可以把n &= n - 1的条件改成n |= n + 1? count = 0 while n < 0xffffffff: n |= n + 1 count += 1 return 32 - count
6c1d9eb2de2831820fe6d39d4ef8b1c353ed62d0
Kavinchandar/Programming-Data-Structures-and-Algorithms-using-Python-NPTEL-2021
/everthing python/best_gcd.py
136
3.59375
4
n, m = map(int, input().split()) def gcd(n, m): if m == 0: return n return gcd(m, n % m) print(gcd(n, m))
0abbd7ac43014d8715f55fc340eeb17f45f8ba03
Matheus-HX-Alves/Python
/PrimeirosExercicios/pontos.py
330
4
4
import math x1 = float(input("Digite um número para x1: ")) y1 = float(input("Digite um número para y1: ")) x2 = float(input("Digite um número para x2: ")) y2 = float(input("Digite um número para y2: ")) DistanciaAB = math.sqrt((x1 - x2)**2 + (y1 - y2)**2) if DistanciaAB >= 10: print ("longe") else: print("perto")
afd705a045fbc69534f8e58bf950385975e95ca0
nicopenaredondo/python-adventure
/if_else_with_looping.py
381
3.9375
4
number = 23 flag = True while flag: guess = int(raw_input('Enter an Integer : ')) if guess == number: print 'Your guess is right' flag = False elif guess < number: print 'A lil bit higher' else: print 'wtf' else: print 'The while loop is done' #lol print 'Done!'
89e01ef76d51bad24795cdd994233725a8f8ea01
mpettersson/PythonReview
/questions/list_and_recursion/has_two_sum.py
3,546
3.84375
4
""" HAS TWO SUM Write a function that accepts a (unsorted) list l and an integer total t, then returns True if there exists two elements in the list with the sum t, False otherwise. Example: Input = [11, 2, -2, 7, 4, 1], 6 Output = True """ import copy # Questions you should ask the interviewer (if not explicitly stated): # - What time/space complexity are you looking for? # - Can the list be modified? # - Are the numbers in the list unique? # - Can there be duplicates in the k elements? # APPROACH: Naive/Brute Force # # Loop over every pair, if a pair sum to t and are not the same value, return True, False otherwise. # # Time Complexity: O(n**2), where n is the number of elements in the list. # Space Complexity: O(1). def has_two_sum_via_bf(l, t): if l is not None and t is not None: for i in range(len(l)): for j in range(i+1, len(l)): if l[i] + l[j] == t and i != j: return True # return i, j # Alternatively, the indices of the first found set could be returned. return False # APPROACH: (Time Optimized) Via Dict # # This approach uses a dictionary for O(1) lookup times. # # Time Complexity: O(n), where n is the number of elements in the list. # Space Complexity: O(n), where n is the number of elements in the list. def has_two_sum_via_dict(l, t): if l is not None and isinstance(t, int): d = {} # Value: Index for i, n in enumerate(l): diff = t - n if diff in d: return True # return i, d[diff] # Alternatively, the indices of the first found set could be returned. d[n] = i return False # APPROACH: (Space Optimized) Two Pointer/Invariant (Invariant: A Condition That Remains True During Execution) # # In this case the invariant is: "the sublist (l[lo:hi+1]), holds the solution, if it exits". This approach uses two # pointers pointing at the lowest and highest values in a sorted list. The two pointers incrementally converge until # either two values with the desired sum are found (True is returned) or the lower pointers index is no longer less than # the higher pointers index (False is returned). # # Time Complexity: O(n * log(n)), where n is the number of elements in the list. # Space Complexity: O(1) (if allowed to modify the list, O(n) otherwise). def has_two_sum_via_pointer(l, t): if l is not None and t is not None: l.sort() # O(n * log(n)) if len(l) > 1: lo = 0 hi = len(l)-1 while lo < hi: if l[lo] + l[hi] == t: return True elif l[lo] + l[hi] < t: lo += 1 else: hi -= 1 return False args = [([13, 0, 14, -2, -1, 7, 9, 5, 3, 6], 6), ([2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2], 2), ([0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8], 0), ([-2, 1, 2, 4, 8, 11], 6), ([3], 6), ([2, 4], 6), ([2, 2], 4), ([2], 4), ([6], 6), ([-2, -1, 0, 3, 5, 6, 7, 9, 13, 14], 6), ([], 6), ([-2, 1, 2, 4, 7, 11], None), (None, 6), (None, None)] fns = [has_two_sum_via_bf, has_two_sum_via_dict, has_two_sum_via_pointer] for l, n in args: for fn in fns: print(f"{fn.__name__}({l}, {n}): {fn(copy.copy(l), n)}") print()
519bd77377c6c62dab12e447d530827c3375595a
sa-i/20200414py3interm
/type_hints.py
561
3.703125
4
#!/usr/bin/env python import typing as T Numeric = T.Union[int, float] # T.Any T.Iterable T.List[type] T.Tuple[Type] # def name(...) -> return_type: def c2f(celsius: Numeric) -> float: fahrenheit = ((9 * celsius) / 5) + 32 return fahrenheit f = c2f(37.1) print(f) f = c2f(37) print(f) # type hinting vs type checking # type hinting? YES # type checking? NO def get_powers(n: int) -> T.Iterable: return n, n ** 2, n ** 3 x = get_powers(5) print(x) def doit(num_list: T.Iterable[Numeric]) -> T.List[float]: return [10] doit([5])
1f4b6f39aeeab66c37f1a6639452fcb92847bcd2
ahddredlover/python_book
/codes/chapter-04/eg_4-04.py
247
3.71875
4
def copy(seq): return [copy(o) if type(o) is list else o for o in seq] if __name__ == "__main__": lst = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10, 11]]]]] lst_new = copy(lst) lst_new[2][2][2][2][2] = 0 print(lst) print(lst_new)
f87dcb6aafd839dbd8076475d3e3b28e66c7ae1a
HermanLin/CSUY1134
/homework/hw06/hl3213_hw6_q1.py
739
3.828125
4
from DoublyLinkedList import DoublyLinkedList class LinkedQueue: def __init__(self): self.data = DoublyLinkedList() self.num_elem = 0 def __len__(self): return self.num_elem def is_empty(self): return self.num_elem == 0 def enqueue(self, e): self.data.add_last(e) def dequeue(self): return self.data.delete_first() def first(self): if self.is_empty(): raise Exception("Queue is empty") return self.data.header.next.data def main(): lq = LinkedQueue() for x in range(10): lq.enqueue(x) print(lq.data) for x in range(10): dq = lq.dequeue() print(dq) print(lq.data, len(lq)) #main()
5a36885f6d7dbea39a376e7e212b65539dd9bbc2
Piotrek1697/Python2020
/Sprawdzian1/Piotr_Janus_236677_S1_zad1.py
1,244
4.03125
4
import sys def main(args): input_nums = args if len(input_nums) == 1: # When input is like: 3,4,5 input_nums = args[0].split(",") if len(input_nums) != 3: sys.exit("Input must have 3 elements. Input numbers must be like: a0 q n, or a0,q,n\n" "First number (a0) - First number of series\n" "Second number (r) - difference\n" "Third number (n) - Number of displaying elements of series") try: input_nums = to_int(input_nums) except: sys.exit("Some input arguments are not integers. Please put integer numbers") print("Series: ", get_math_series(input_nums[0], input_nums[1], input_nums[2])) def get_math_series(a0, r, n): """Getting arithmetic series Parameters ---------- a0 : int First number of series r : int difference n : int Number of displaying elements of series Returns ------- list List of arithmetic series with length = n """ series = [a0] for i in range(0, n - 1): series.append(series[i] + r) return series def to_int(list): return [int(number) for number in list] if __name__ == '__main__': main(sys.argv[1:])
90e22effbef119cca902eee27011ed8825ac2ea6
AdamZhouSE/pythonHomework
/Code/CodeRecords/2951/60768/316571.py
1,851
3.546875
4
str1 = input() str2 = input() int2 = int(str2, 3) tempInt2 = 0 ZERO_ONE = [0, 1] ONE_TWO = [1, 2] ZERO_TWO = [0, 2] for i in range(0, len(str2)): tempStr2 = str2 if str2[i] == '0': for j in ONE_TWO: tempStr2 = str2[0:i] + str(j) + str2[i + 1:len(str2)] tempInt2 = int(tempStr2, 3) for m in range(len(str1)): tempStr1 = str1 if tempStr1[m] == '1': tempStr1 = str1[0: m] + '0' + str1[m + 1: len(str1)] else: tempStr1 = str1[0: m] + '1' + str1[m + 1: len(str1)] tempInt1 = int(tempStr1, 2) if tempInt2 == tempInt1: print(tempInt1, end="") elif str2[i] == '1': for j in ZERO_TWO: tempStr2 = str2[0:i] + str(j) + str2[i + 1:len(str2)] tempInt2 = int(tempStr2, 3) for m in range(0, len(str1)): tempStr1 = str1 if tempStr1[m] == '1': tempStr1 = str1[0: m] + '0' + str1[m + 1: len(str1)] else: tempStr1 = str1[0: m] + '1' + str1[m + 1: len(str1)] tempInt1 = int(tempStr1, 2) if tempInt2 == tempInt1: print(tempInt1, end="") else: for j in ZERO_ONE: tempStr2 = str2[0:i] + str(j) + str2[i + 1:len(str2)] tempInt2 = int(tempStr2, 3) for m in range(0, len(str1)): tempStr1 = str1 if tempStr1[m] == '1': tempStr1 = str1[0: m] + '0' + str1[m + 1: len(str1)] else: tempStr1 = str1[0: m] + '1' + str1[m + 1: len(str1)] tempInt1 = int(tempStr1, 2) if tempInt2 == tempInt1: print(tempInt1, end="")
6f65cf51f534a095ce834ef1925ff219090121c9
r3dback/cisco-bb
/bblevel1_hands_on_exercise.py
1,323
4.5
4
# Python 3.6.5 # By: Francisco Rojo, 30/7/2018 # Cisco BB Level 1 _assignment # # How to run on Python3 # > python3 hands_on_exercise.py import math import random # Expected Output #pi is a with a value of 3.141592653589793 #i is greater than 50 #The fruit is orange #12 x 96 = 1152 #48 x 17 = 816 #196523 x 87323 = 17160977929 # TODO: Write a print statement that displays both the type and value of `pi` print ("pi is a ",type(math.pi),"with a value of ",math.pi) # TODO: Write a conditional to print out if `i` is less than or greater than 50 i = random.randint(0,500) if int(i) < 50: print (i," is less than 50") elif int(i) > 50: print (i," is greater than 50") # TODO: Write a conditional that prints the color of the picked fruit select_fruit = random.choice(['orange', 'strawberry', 'bannana']) fruit = { 'orange':'Orange','strawberry':'Red','bannana':'Yellow'} print ("The Fruit is ",fruit.get(select_fruit)) # TODO: Write a function that multiplies two numbers and returns the result def _multiply (n1,n2): result = int(n1) * int (n2) return(result) # TODO: Now call the function a few times to calculate the following answers n1=12 n2=96 print (n1," x ",n2," = ",_multiply(n1,n2)) n1=48 n2=17 print (n1," x ",n2," = ",_multiply(n1,n2)) n1=196523 n2=87323 print (n1," x ",n2," = ",_multiply(n1,n2))
15b3b3e68c0e13ccabfa5cc43bc4ee862061b023
MitCandy/PythonNotes
/Basics/strings.py
807
4.15625
4
# SimpleString print("Get Good") # Backslash for using quotation inside quotation print("Get\"Good") # Can be assigned on variable and execute name = "Roy" print(name) # Concenateable w/without variable name1 = "Burnett" print("Your name is " + name1) # String w function word = "klen" print(word.upper()) # Capitalize those words word1 = "KLEN" print(word1.lower()) # vice versa word2 = "I love you" print(len(word2)) # measure the length of characters ( counted from zero, spaces included ) # Show only individual characters myname = "Doppel" print(myname[0]) # Prints D print(myname[4]) # Prints e # Another function for counting index some_word = "Hent Have" # ( ͡° ͜ʖ ͡°) Author weeb lmao print(some_word.index("H")) # Prints 0 and btw case sensitive print(some_word.index("a")) # Prints 6
d1ef410e33f6a459899f37748e2bde3216aa0178
Guillaume-Maille/Python-Challenges
/Booksort/Task 4.py
446
3.515625
4
def add_info(): column = input("Add new info:") with open('Books.txt') as c: c1 = c.readlines() with open('NewBooks.txt', "w+") as f: lines = f.read().splitlines() for line in f: if line == lines[1]: f.write(c1[1] + column) else: for x in c1: new_info = input("Enter new info:") f.write(x + new_info)
3eeec65fe9160c25e1e0c1a41a200a4af2ec8ab8
aifulislam/Python_Demo_Forth_Part
/lesson6.py
2,258
3.96875
4
# 24/12/2020------- # Tamim Shahriar Subeen------- # String()---------------- s = "hello" print(len(s)) print(s) l = len(s) print(l) s = '' print(s) print(len(s)) s = "Dimik's" print(s) s = "Dimik\s" print(s) country = "Bangladesh" print(country[4]) for c in country: print(c) c = ["A", "b", "c"] print(c) print(c[1]) country2 = "Bangl" + "adesh" print(country2) x = "50" + "5" print(x) country3 = "Bangldesh" print(country.find("Ban")) print(country.find("ang")) print(country.find("Bangla")) print(country.find("Bengla")) print(country3.find("desh")) country4 = "North Korea" new_country4 = country4.replace("North", "South") print(country4) print(new_country4) text = "this is a test. this is another test. this is final test." new_text = text.replace("this", "This") print(text) print(new_text) text2 = "hello" text2 = text2.replace("hello", "Hello") print(text2) text3 = " this is a string. " print(text3) t1 = text3.lstrip() print(t1) t2 = text3.rstrip() print(t2) t3 = text3.strip() print(t3) text4 = " this is a sentence. " new_text4 = text4.rstrip() print(new_text4) print(text4) s1 = "Arif" s_up = s1.upper() print(s_up) s_lw = s1.lower() print(s_lw) s_cap = s1.capitalize() print(s_cap) str = "I am a programmer" words = str.split() print(words) for word in words: print(word) str2 = "This is" str2 = str2.count("is") print(str2) s2 = "Arif" po = s2.startswith("Ari") print(po) po = s2.startswith("ari") print(po) po = s2.endswith("if") print(po) po = s2.endswith("f") print(po) name = "Mr. Arif Billah" if name.startswith("Mr."): print("Dear Sir") str3 = "a quick brown for jumps over the lazy dog" for c in "abcdefghijklmnopqrstuvwxyz": print(c, str3.count(c)) import turtle name = turtle.textinput("name", "what is your name?") name = name.lower() if name.startswith("mr"): print("Hello Sir, how are you?") elif name.startswith("mrs") or name.startswith("miss") or name.startswith("ms"): print("Hello Madam, how are you?") else: name = name.capitalize() str = "Hi " + name + "!How are you?" print(str) turtle.exitonclick() # ------------End------------- #
d9332223290be1827ddf975b480a460289c58671
col-a-guo/tftRolldownCost
/tftGoldCost.py
3,048
3.671875
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 06:59:58 2020 @author: r2d2go """ import random import math import matplotlib.pyplot as plt def run(winrate, startstreak, startgold): gold = startgold lostGold = 0 winstreak = startstreak for i in range (10): winvar = random.uniform(0,1) if winvar < winrate: gold += 1 if winvar > 0: winstreak += 1 else: winstreak = 1 else: if winvar < 0: winstreak -= 1 else: winstreak = -1 if gold > 50: return lostGold else: lostGold += 5-math.floor(gold/10) if winstreak > 4: gold += 3 elif winstreak < -4: gold += 3 elif winstreak > 3: gold += 2 elif winstreak < -3: gold += 2 elif winstreak > 1: gold += 1 elif winstreak < -1: gold += 1 gold += math.floor(gold/10)+5 def averageRun(winrate, startstreak, startgold, runs): totalLostGold = 0.0 for i in range (runs): totalLostGold += run(winrate, startstreak, startgold) return(totalLostGold/runs) runList = [] runs = 1000 for i in range(50): runList.append([]) startgold = i for j in range(3): startstreak = -4 + 4*j winrate = .1+.4*j runList[i].append(averageRun(winrate, startstreak, startgold, runs)) xList = [] for i in range(26): xList.append(2*i) x = range(len(runList)) y = runList plt.xlabel("Ending Gold") plt.ylabel("Gold Lost") plt.title("Rolldown Total Costs") for i in range(len(y[0])): plt.plot(x,[pt[i] for pt in y],label = "starting streak = " + str(-4+4*i) + " wins, winrate = " + str((1+4*i)/10)) plt.legend() plt.show() bigList = [['Start Gold', '10% WR', '50% WR', '90% WR']] for i in range(52): bigList.append([i]) for mCostRun in range(3): marginalCostList = [] for i in range(len(runList)-2): marginalCostList.append([runList[i][mCostRun]-runList[i+2][mCostRun]]) marginalCostList.append([runList[48][mCostRun]]) marginalCostList.append([runList[49][mCostRun]]) marginalCostList = [[0],[0]]+marginalCostList x = range(len(marginalCostList)) y = marginalCostList plt.xlabel("Starting Gold") plt.ylabel("Cost of Rolling Once") plt.title("Rolldown Individual Roll Costs") plt.xticks(ticks=xList) for i in range(len(y[0])): plt.bar(x,[pt[i] for pt in y],label = "starting streak = " + str(-4+4*mCostRun) + ", winrate = " + str((1+4*mCostRun)/10)) plt.legend() plt.show() for i in range(len(marginalCostList)): bigList[i+1] = bigList[i+1]+[round(marginalCostList[i][0],4)] plt.title('Cost of Rolling Once', pad = 650) plt.table(bigList, loc='top') plt.show()
32a2f0ca4e0cad5fdf551fea957321884b93192d
Ace-0/MovieAnalysis
/data/cleanup_metadata.py
1,847
3.84375
4
import pandas as pd def isValidRow(row): if ((row['adult'] != 'TRUE' and row['adult'] != 'FALSE') or (not str(row['budget']).isdigit()) or (not str(row['id']).isdigit()) or (not isFloat(str(row['popularity']))) or (not str(row['revenue']).isdigit()) or (not str(row['runtime']).isdigit()) or (not isFloat(str(row['vote_average']))) or (not str(row['vote_count']).isdigit()) ): return False else: return True def isFloat(value): try: float(value) return True except ValueError: return False def cleanCsvFile(inputFile, outputFile): # Read csv file data = pd.read_csv(inputFile, encoding = "ISO-8859-1") # Keep only the necessary columns data = data[['adult', 'budget', 'id', 'imdb_id', 'original_language', 'original_title', 'popularity', 'release_date', 'revenue', 'runtime', 'status', 'title', 'vote_average', 'vote_count']] print(data.head()) invalidRows = [] idSet = set() # Iterate each row to remove invalid rows for index, row in data.iterrows(): if (isValidRow(row)): # if the row is valid, check the id movieId = int(str(row['id'])) if (not (movieId in idSet)): idSet.add(movieId) else: # if the id is duplicate, drop it later invalidRows.append(index) else: # if the row is invalid, drop it later invalidRows.append(index) print('Number of invalid rows: ' + str(len(invalidRows))) data.drop(invalidRows, inplace=True) data.to_csv(outputFile, sep=',', encoding='utf-8', index=False) def main(): cleanCsvFile('movielens.csv', 'movielens_cleaned.csv') if __name__== "__main__": main()
090bec83f4f7e7b78c520e5fe201141e329e3a3a
karolinaWu/leetcode-lintcode
/leetcode/Python3/28.ImplementstrStr().py
293
3.578125
4
#https://leetcode.com/problems/implement-strstr/ class Solution: def strStr(self, haystack: str, needle: str) -> int: l1 = len(haystack) l2 = len(needle) for i in range(l1-l2+1): if haystack[i:i+l2] == needle: return i return -1
117cd8ab9eb27b8421af8fe1c42d008ce2128835
BlutigerHammer/calculating-area-from-given-data
/areaModule.py
1,053
4
4
# -*- coding: utf-8-*- ''' Functions for calculating the training ground area: - use the Gauss formula - the input is a list of lists like: [[x, y], [x, y], ...] - x and y - are coordinates of the polygon corners in 2D - there are 2 functions: - area () - based on python language lists - araenp () - uses numpy arrays ''' import numpy as np # --------------------------------------------------------------------- def area(coordinates): """ Describe what the function does and what arguments it accepts """ #calculates the area using python lists return round(ssum,2) # --------------------------------------------------------------------- def areanp(coordinates): """ Describe what the function does and what arguments it accepts """ # calculates the area using arrays of the numpy module # shifting arrays y1 = np.roll(y,1) # yi - 1 y2 = np.roll(y,-1) # yi + 1 # you have boards ready !!! # create a formula return ..... # ---------------------------------------------------------------------
f987cf49aed143934468f83a559a96548dcd46eb
borjas93/mi_primer_programa
/contar_palabras.py
1,097
4.1875
4
""" Este ejercicio trata sobre contar las palabras que aparecen en una cadena. Para este cometido, vamos a definir una funcion muy basica que detecte las palabras de cualquier texto. """ def detectar_palabras(cadena): lista_palabras = [] palabra = '' for item in cadena: if item != ' ' and item != ',' and item != '.': palabra += item else: lista_palabras.append(palabra) palabra = '' print(lista_palabras) return lista_palabras def cont_palabras(lista): apariciones_palabra = dict() for item in lista: if item not in apariciones_palabra: indice = 0 apariciones = 0 while indice < len(lista): if item == lista[indice]: apariciones += 1 indice += 1 apariciones_palabra[item] = 'aparece {} vez/veces'.format(apariciones) print (apariciones_palabra) return cadena_usuario = 'hola hola moco moco nate borja hola moco' lista_usuario = detectar_palabras(cadena_usuario) cont_palabras(lista_usuario)
a961c2a190ce46bfd04b2bece113b8a3acdad180
concpetosfundamentalesprogramacionaa19/ejercicios-clases5-020519-SantiagoDGarcia
/miproyecto/run4.py
1,374
3.90625
4
"""" file: run3.py autor: @SantiagoDGarcia Deseamos obtener el costo de una carrera universitaria. El valor Promedio de cada ciclo es de 1200$ El valor Promedio del seguro educativo es 100$ c/u ciclo, si la edad es menor igual a 20, caso contrariario sera de 150$ Si el estudiante tiene una modalidad a distancia el numero de ciclos a seguir es 10, contrario seran 8 ciclos obtener el costo de la carrera de un estudiante EJM: modalidad: Distancia edad = 18 13000 modadlidad: Presencial <> edad = 22 """ # Se establece las variables principales valor_ciclo = 1200 modalidad = input ("Ingrese la modalidad del estudiante: Presencial, Distancia \n") edad = int (input ("Ingrese la edad del estudiante: \n")) ciclos = int seguro = int # Se establece la condicion anidada de la modalidad para determinar la cantidad de ciclos if (modalidad == "Distancia" or modalidad == "distancia"): ciclos = 10 else: ciclos = 8 # Se establece el costo a pagar de la cantidad de ciclos por el valor de cada uno cant_ciclo = ciclos*valor_ciclo # Se establece el costo total de todos los ciclos # Se establece la condicion anidad acerca de su seguro, referente a su edad if (edad <= 20): seguro = 100*ciclos else: seguro = 150*ciclos # Se establece la variable final de las sumas costo_f = cant_ciclo + seguro print("El costo Total de la carrera es: ", costo_f)
1b948b6559b736b5aaf9e06217bd65d0ac2b70a8
saharma/PythonExercises
/Exercises/mathProgram.py
499
4.1875
4
num1 = float(input('Enter the first number: ')) num2 = float(input('Enter the second number: ')) print('{} plus {} equals {}'.format(num1, num2, num1 + num2)) print('{} minus {} equals {}'.format(num1, num2, num1 - num2)) print('{} multiplied by {} equals {}'.format(num1, num2, num1 * num2)) print('{} divided by {} equals {}'.format(num1, num2, num1 / num2)) print('{} modulo {} equals {}'.format(num1, num2, num1 % num2)) print('{} to the power of {} equals {}'.format(num1, num2, num1 ** num2))
5d253ceaa59174917050cb5845acb99ba444c199
jacqueline-homan/python2.7_tutorials
/py2.7tutorial.py
1,002
4.28125
4
# This Python tutorial uses Python 2.7 #printing out the Fibonacci sequence vertically a, b = 0, 1 while b < 10: print b a, b = b, a+b # printing out the Fibonacci sequence horizontally a, b = 0, 1 while b < 10: print b, a, b = b, a+b #printing out from user input, dialogue w/ user myName = raw_input("What is your name?") print "OK, you said your name is:", (myName) user_response = raw_input("Is this correct - Y or N ?") print "You answered:",(user_response) # defining a function for a Py web app def main(): print "hello ya nerd!" if __name__ == "__main__": main() print "Yup" main() # declaring and intializing a variable f = 0; print f #re-declaring a variable f = "do rei me" print f #converting to a string to avoid TypeError print "do rei me" + str(123) # local variable def some_function(): f = "blah blah blah" print f some_function() print f #global variable def some_function(): global f f = "blah blah blah" print f some_function() print f del f print f
b529e8cf1d25bd63d76af4c00113f4ae5411c4dc
kimdaebeom/Machine_Learning_spartacodingclub
/linear_regression/kaggle_linear_regression_ex2.py
1,079
3.5
4
#여러 X값을 이용하여 매출 예측하기 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import Adam, SGD import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split df = pd.read_csv('advertising.csv') x_data = np.array(df[['TV', 'Newspaper', 'Radio']], dtype=np.float32) y_data = np.array(df['Sales'], dtype=np.float32) x_data = x_data.reshape((-1, 3)) y_data = y_data.reshape((-1, 1)) print(x_data.shape) print(y_data.shape) x_train, x_val, y_train, y_val = train_test_split(x_data, y_data, test_size=0.2, random_state=2021) print(x_train.shape, x_val.shape) print(y_train.shape, y_val.shape) model = Sequential([ Dense(1) ]) model.compile(loss='mean_squared_error', optimizer=Adam(lr=0.1)) model.fit( x_train, y_train, validation_data=(x_val, y_val), # 검증 데이터를 넣어주면 한 epoch이 끝날때마다 자동으로 검증 epochs=100 # epochs 복수형으로 쓰기! )
a5406120605cdc850d0d97d2ac3ccb4202dd14c0
zHigor33/ListasDeExerciciosPython202
/Estrutura de Decisão/L2E28.py
1,418
3.921875
4
print(" Até 5 Kg Acima de 5 Kg") print("File Duplo R$ 4,90 por Kg R$ 5,80 por Kg") print("Alcatra R$ 5,90 por Kg R$ 6,80 por Kg") print("Picanha R$ 6,90 por Kg R$ 7,80 por Kg") typeOfMeat = str(input("Informe o tipo de carne (file/alcatra/picanha): ")) quantityInKilos = float(input("Informe o peso em quilos: ")) cardTabajara = str(input("Vai pagar com o cartão Tabajara (s/n): ")) if typeOfMeat == "file": if quantityInKilos <= 5: total = quantityInKilos * 4.9 elif quantityInKilos > 5: total = quantityInKilos * 5.8 elif typeOfMeat == "alcatra": if quantityInKilos <= 5: total = quantityInKilos * 5.9 elif quantityInKilos > 5: total = quantityInKilos * 6.8 elif typeOfMeat == "picanha": if quantityInKilos <= 5: total = quantityInKilos * 6.9 elif quantityInKilos > 5: total = quantityInKilos * 7.8 else: print("Carne não existente!") if cardTabajara == "s": totalWithDiscount = total * 0.95 print("\n Nota Fiscal: ") print("Tipo de carne: "+str(typeOfMeat)) print("Quantidade (Kg): "+str(quantityInKilos)) print("Preço total: "+str(total)) print("Tipo de pagamento: Cartão Tabajara") print("Valor a pagar (com desconto): "+str(totalWithDiscount))
aae24dd1e494d3f828a4c8ece342bea95e02978e
samdejong86/AboutMe
/SamFacts.py
1,864
3.765625
4
#import some libraries import sys from random import randint #open the file containing my qualifications with open("Sam_deJong.dat") as f: Facts = f.readlines() #clear whitespace and remove empty entries Facts = [x.strip() for x in Facts] Facts = [s for s in Facts if len(s) != 0] print "I am the highly qualified, well rounded candidate that you're looking for!" numFacts="" #loop until a positive number is entered while not numFacts.isdigit(): #get user input numFacts = raw_input("Enter a number to see a few of my qualities:") #if not a number, print a message if not numFacts.isdigit(): print "Not a number!" #print a message if no facts requested if int(numFacts) == 0: print "Ok, lets talk in person instead! Call me at 250-888-5720 to set up an interview!" quit() #if there's more facts requested than the file contains, print all the facts, tooMany=False if int(numFacts) > len(Facts): numFacts = len(Facts) tooMany=True print "I am:" #print randomly selected facts randomNums = list() while len(randomNums) < int(numFacts): rNum = randint(0, len(Facts)-1) #make sure there's no doubles if rNum not in randomNums: randomNums.extend([rNum]) thisFact = Facts[rNum] #do some formatting (add A or An in front of the fact) precurser = "\tA " if thisFact[0] in ('a', 'e', 'i', 'o', 'u'): #at 'An' if the fact starts with a vowel precurser="\tAn " if thisFact[0] == 'Y': #special case precurser = "\t" if thisFact[:3] == "The": #special case precurser = "\t" print precurser+thisFact #if more facts are requested than the file contains, print info for getting more if tooMany: print "To hear more, call me at 250-888-5720"
7a1d69d6a7b8d9b665ff82ee962905188513f9fd
nishantkakar/ctci-6th-ed
/Chapter 8/8.4 Power Set.py
246
3.78125
4
def power_set(arr): """ :type arr: list :rtype: list """ subsets = [[]] for i in arr: for j in range(len(subsets)): subsets.append(subsets[j] + [i]) return subsets x = [1, 2, 3] print power_set(x)
ddabf0201c2e282a1ed422d4de95c8303fc00ad2
extragornax/AdventOfCode
/2020/Day 04/code.py
3,248
3.5
4
import re def checkHex(s): for ch in s: if ((ch < '0' or ch > '9') and (ch < 'a' or ch > 'f')): return False return True def two(): file = open("input.txt") data = [] tmpVal = {} for i in file: i = i.rstrip() if len(i) == 0: if len(tmpVal) > 0: data.append(tmpVal) tmpVal = {} continue # print(i) spl = i.split() for item in spl: key = item.split(':')[0] val = item.split(':')[1] tmpVal[key] = val if len(tmpVal) > 0: data.append(tmpVal) tmpVal = {} goodPassword = 0 regex = re.compile("^(?P<numbers>\d*)(?P<letters>\w*)$") for i in data: if "byr" in i and len(i['byr']) == 4 and i['byr'].isnumeric() and int(i['byr']) >= 1920 and int(i['byr']) <= 2002: if "iyr" in i and len(i['iyr']) == 4 and i['iyr'].isnumeric() and int(i['iyr']) >= 2010 and int(i['iyr']) <= 2020: if "eyr" in i and len(i['eyr']) == 4 and i['eyr'].isnumeric() and int(i['eyr']) >= 2020 and int(i['eyr']) <= 2030: if "hgt" in i: (height, cmOrIn) = regex.search(i['hgt']).groups() if cmOrIn == "cm": if int(height) < 150 or int(height) > 193: continue elif cmOrIn == "in": if int(height) < 59 or int(height) > 76: continue else: continue if "hcl" in i and len(i['hcl']) == 7 and i['hcl'][0] == '#' and checkHex(i['hcl'][1:]): if "ecl" in i: test = i['ecl'] if test != "amb" and test != "blu" and test != "brn" and test != "gry" and test != "grn" and test != "hzl" and test != "oth": continue if "pid" in i: if i['pid'].isnumeric() == False or len(i['pid']) != 9: continue goodPassword += 1 print(goodPassword) def one(): file = open("input.txt") data = [] tmpVal = {} for i in file: i = i.rstrip() if len(i) == 0: if len(tmpVal) > 0: data.append(tmpVal) tmpVal = {} continue # print(i) spl = i.split() for item in spl: key = item.split(':')[0] val = item.split(':')[1] tmpVal[key] = val if len(tmpVal) > 0: data.append(tmpVal) tmpVal = {} goodPassword = 0 for i in data: if "byr" in i: if "iyr" in i: if "eyr" in i: if "hgt" in i: if "hcl" in i: if "ecl" in i: if "pid" in i: goodPassword += 1 print(goodPassword) print("one") one() print("two") two()
f0b239c9cf52128330b3a7e5a0fc1f22754b7e61
dtingg/Fall2018-PY210A
/students/student_framllat/session04/dict_set_solution_rft.py
3,796
4.65625
5
#!/usr/bin/env python """ dict/set lab solutions: MODIFIED Chris' version. """ # Create a dictionary containing "name", "city", and "cake" for # "Santa" from "NorthPole" who likes "Lemon". gen_d = {"name": "Santa", "city": "NorthPole", "cake": "Lemon"} # Display the dictionary. print("\nGeneric printing of dictionary {}".format(gen_d)) print() # or something fancier, like: print ("{name} is from {city}, and likes {cake} cake.".format(name=gen_d['name'], city=gen_d['city'], cake=gen_d['cake'])) # But if that seems like unnecceasry typing -- it is: # we'll learn the **d form is session05: print("\tUsing the ** form") print("{name} is from {city}, and likes {cake} cake.\n".format(**gen_d)) # Delete the entry for "cake". # Display the dictionary. print("Deleting the cake entry.....") del gen_d["cake"] print(gen_d) # Add an entry for "fruit" with "Mango" and display the dictionary. print("Now let's add in a fruit to the dictionary") gen_d['fruit'] = 'Mango' print(gen_d) # Display the dictionary keys. print("\n\tHere are the keys:", gen_d.keys()) # Display the dictionary values. print("\n\tHere are the values:", gen_d.values()) # Display whether or not "cake" is a key in the dictionary (i.e. False) (now). print("\nIs the word cake in the dict? And the answer is: ", ('cake' in gen_d)) # Display whether or not "Mango" is a value in the dictionary. print("Is the word Mango in the dictionary? The answer is: ", ('Mango' in gen_d.values()),"\n") # Using the dict constructor and zip, build a dictionary of numbers # from zero to fifteen and the hexadecimal equivalent (string is fine). # did you find the hex() function?" nums = range(16) hexes = [] for num in nums: hexes.append(hex(num)) print("Built list of hexified numbers *** \n", hexes) print("Then we package together the decimal:hex pairing ***") hex_dict = dict(zip(nums, hexes)) print(hex_dict,"\n") # Using the dictionary from item 1: Make a dictionary using the same keys # but with the number of 't's in each value. print("Using the Santa Dictionary", gen_d.items()) a_dict = {} for key, val in gen_d.items(): a_dict[key] = val.count('t') print("This dictionary is derived from Santa dictionary using count of letter t for values", a_dict, "\n") # replacing the values in the original dict: for key, val in gen_d.items(): gen_d[key] = val.count('t') print("Replace in orig dict: ","\t" ,gen_d) # Or the direct way -- update() is very handy! gen_d.update(a_dict) print("Or the update method:","\t", gen_d) # Create sets s2, s3 and s4 that contain numbers from zero through # twenty, divisible 2, 3 and 4. # Display the sets. s2 = set() s3 = set() s4 = set() for i in range(21): if not i % 2: s2.add(i) if not i % 3: s3.add(i) if not i % 4: s4.add(i) print("\nSet Two using modulo 2:",s2) print("Set Three using modulo 3:",s3) print("Set Four using modulo 4:",s4) # Display if s3 is a subset of s2 (False) print("Is s3 a subset of s2? Answer: ", s3.issubset(s2)) # and if s4 is a subset of s2 (True). print("Is s4 a subset of s2? Answer: ", s4.issubset(s2)) # Create a set with the letters in 'Python' and add 'i' to the set. s = set('Python') s.add('i') print("Now we have another letter",s) # maybe: s = set('Python'.lower()) # that wasn't specified... s.add('i') # Create a frozenset with the letters in 'marathon' fs = frozenset('marathon') # display the union and intersection of the two sets. print("union:", s.union(fs)) print("intersection:", s.intersection(fs)) # note that order doesn't matter for these: print("union:", fs.union(s)) print("intersection:", fs.intersection(s))
ab0daa62bc5438d654933e181091bce661304b63
nhichan/hachaubaonhi-fundamental-c4e16
/session2/bài học/conditional_statement.py
252
4.0625
4
yob = int(input('what is your birthyear: ')) age =2018-yob print('your age: ',age) if age<10: print('baby') elif age<=18: print('teenager') elif age==24: print('adult') else: #else k bao h co dieu kien print('not baby') print ('bye')
00588c4434b526f928bbbfa4b7df4523d09be184
CorbinMayes/Artificial_Intelligence_19W
/Mazeworld/astar_search.py
3,624
3.578125
4
#Corbin Mayes 1/17/19 #Talked with Hunter Gallant from SearchSolution import SearchSolution from heapq import heappush, heappop class AstarNode: # each search node except the root has a parent node # and all search nodes wrap a state object def __init__(self, state, heuristic, parent=None, transition_cost=0): #classify the instance variables self.state = state self.heuristic = heuristic self.parent = parent self.transition_cost = transition_cost def priority(self): # calculate the priority of the node return (self.heuristic + self.transition_cost) # comparison operator, # needed for heappush and heappop to work with AstarNodes: def __lt__(self, other): return self.priority() < other.priority() # take the current node, and follow its parents back # as far as possible. Grab the states from the nodes, # and reverse the resulting list of states. def backchain(node): result = [] current = node while current: result.append(current.state) current = current.parent result.reverse() return result def astar_search(search_problem, heuristic_fn): #get the start start node and add it to the heap start_node = AstarNode(search_problem.start_state, heuristic_fn(search_problem.start_state)) pqueue = [] heappush(pqueue, start_node) #create the solution solution = SearchSolution(search_problem, "Astar with heuristic " + heuristic_fn.__name__) visited_cost = {} if type(start_node.state) is list: visited_cost[start_node.state] = 0 elif type(start_node.state) is set: visited_cost[frozenset(start_node.state)] = 0 elif type(start_node.state) is tuple: visited_cost[start_node.state] = 0 explored = set() while pqueue: #get the next node on the heap node = heappop(pqueue) if type(node.state) is list or type(node.state) is tuple: explored.add(node.state) elif type(node) is set: explored.add(frozenset(node.state)) #test if its the goal if search_problem.goal_test(node.state): solution.path = backchain(node) solution.nodes_visited = len(explored) if type(node) is list or type(node) is tuple: solution.cost = visited_cost[node.state] elif type(node) is set: solution.cost = visited_cost[frozenset(node.state)] return solution #get the children of the node for child in search_problem.get_successors(node.state): child_node = AstarNode(child, heuristic_fn(child), node, len(backchain(node))+1) if type(child_node.state) is list or type(child_node.state) is tuple: visited_cost[child_node.state] = child_node.transition_cost elif type(child_node.state) is set: visited_cost[frozenset(child_node.state)] = child_node.transition_cost #add the child to the heap if not seen if child_node not in backchain(node): if child_node not in pqueue and child_node.state not in explored: heappush(pqueue, child_node) #if child is already in heap then test for the priority to get the best solution elif child_node in pqueue: equal_node = pqueue[child_node] if child_node.priority() < equal_node.priority(): del pqueue[equal_node] heappush(pqueue, child_node) solution.path = [] return solution
8b6fe886b0f4c468548d64d2cd0a83177908f1fb
GafasAV/SomeTestTasks
/fizzBuzz.py
314
4
4
def fizzBuzz(n): if n % 3 == 0 and n % 5 == 0: return "FizzBuzz" elif n % 3 == 0: return "Fizz" elif n % 5 == 0: return "Buzz" else: return str(n) if __name__ == "__main__": count = int(input("Input numbers count :")) result = "" print(result.join(fizzBuzz(n) for n in range(1, count+1)))
9b91921e15327d7620c920f81f4e41f845138fcb
atasoya/MultipleChoiceExamMaker
/main.py
754
3.625
4
Questions = [] Options = [] abc = "abcdefgh" QuestionNumber = input("Enter The Question Number : ") OptionNumber = input("Enter The Option Number : ") for i in range(int(QuestionNumber)) : Question = input("Enter the question : ") Questions.append(Question) for x in range(int(OptionNumber)) : Option = input("Enter the option : ") Options.append(Option) for i in range(int(QuestionNumber)) : TitleOfQuestion = str(i+1) + "- " + Questions[i] + ("\n" * 2 ) examfile = open("exam.txt","a") examfile.write(TitleOfQuestion) for x in range(int(OptionNumber)) : examfile.write(abc[x] + ") " + Options[x] + "\n") examfile.write("\n") examfile.close()
4d508ee34b197f6acfa24ae8a56d1debd17ab321
Pitt-Pauly/ML-Hadoop-practice
/Unixversion.py
2,254
3.5625
4
## # Pierre Pauly # s0836497 # level 10 # # Further Documentation in ReadMe.txt ## import re class SimpleCaps: """ Simple word capitalizing script using Naive Bayes. (Unix version) """ ## # init # # params: filename, path to training set (txt file). # ## def __init__(self, filename = ''): self.freqs = {} self.wordbag = [] # default file if (filename == ''): filename = './small.txt' with open(filename,'r') as f: word_list = f.read() #assumption: space delimited sentences word_list = re.split(" *",word_list) self.createFeatures(word_list) ## # Task 1. # Use the following set of features: # the word itself, # the last two letters, # the last three letters, # the first two letters, # the first three letters. # # value (val): 1 if feature is present # 0 otherwise # # label: 1 if word is capitalized (first letter is upper case), # 0 otherwise # # freqDict: dictionary (map) containing the frequencies of the words appearing of the form: # key: (feature, label) # value: number of occurances ## def createFeatures(self,words): val = 1 for word in words: label = word[0].islower() if (len(word)>=3): features = [(word,val), (word[-2:], val), (word[-3:],val), (word[0:1],val), (word[0:2],val)] else: if (len(word)==2): features = [(word,val), (word[-2:], val), (word[0:1],val), (word[0:2],val)] else: features = [(word,val)] self.wordbag.append((features,label)) # and count the frequencies for f,v in features: if (self.freqs.__contains__((f,label))): self.freqs[(f,label)] +=1 else: self.freqs[(f,label)] = 1 print (self.wordbag, self.freqs)
ef8f091c8ca2b9037789604defc264cb4d792199
padfoot18/AISearchStrategies
/uninformed_search.py
1,605
3.515625
4
""" dfs ids for map exploration """ import ids_search import dfs_search import generate_state_space_tree class Node: def __init__(self, city_name, parent, id, level): self.city_name = city_name self.level = level self.parent = parent self.child = [] self.id = id # id can be used for printing sequence of nodes visited. For eg n1 will # have id 1, n2 will have id 2 def __repr__(self): # return str(self.id)+self.city_name child_names = [x.city_name for x in self.child] return "City Name: {}, Parent: {}, Child: {}".format(self.city_name, self.parent, child_names) def __str__(self): return str(self.id)+'-'+self.city_name def append_child(self, children): for child in children: self.child.append(child) n1 = Node('Arad', None, 1, 1) n2 = Node('Sibiu', n1, 2, 2) n3 = Node('Timisoara', n1, 3, 2) n4 = Node('Zerind', n1, 4, 2) n5 = Node('Oradia', n2, 5, 3) n6 = Node('Rimmicu Vilcea', n2, 6, 3) n7 = Node('Fagaras', n2, 7, 3) n8 = Node('Lugoj', n3, 8, 3) n9 = Node('Craiova', n6, 9, 4) n10 = Node('Pitesti', n6, 10, 4) n11 = Node('Bucharest', n7, 11, 4) n12 = Node('Mehadia', n8, 12, 4) n1.append_child([n2, n3, n4]) n2.append_child([n5, n6, n7]) n3.append_child([n8]) n6.append_child([n9, n10]) n7.append_child([n11]) n8.append_child([n12]) generate_state_space_tree.generate_tree(n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12) print("\nIDS") if not ids_search.ids(n1, 'Bucharest', 4): print('Goal state not found') print("\nDFS") dfs_search.dfs_main(n1, 'Bucharest')
f52ce286f5b780344c17d6b6a7c31aa8f9fcdc72
geofreym21/Analyze_game_Pandas_Lib_Jupyter
/Heroes_of_Pymoli_Assign4.py
4,569
3.65625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Depedencies and Setup import pandas as pd import numpy as np # In[2]: # File to Load file_to_load = "..\Assignment\purchase_data.csv" # Read Purchasing File and store into Pandas data frame purchase_data = pd.read_csv(file_to_load) purchase_data.head() # In[3]: # Assign the unique players unique_players = purchase_data["SN"].unique # Display the unique players unique_players # In[4]: # count the number of unique players number_of_unique_players = len(purchase_data["SN"].unique()) number_of_unique_players # In[5]: # create a data frame in order to show the total players total_df = pd.DataFrame({"Total Players": [number_of_unique_players]}) total_df["Total Players"] = total_df["Total Players"].map("{:<}".format) total_df # In[6]: # compute number of unique items, average price, number of purchases and total revenue # number of unique items unique_items = len(purchase_data["Item ID"].unique()) # number of purchases num_of_purchases = len(purchase_data) # average price ave_price = purchase_data["Price"].mean() #total revenue total_revenue = sum(purchase_data["Price"]) # In[7]: # Data Frame for purchasing analysis information purchasing_df = pd.DataFrame({"Number of Unique Items":[unique_items], "Average Price":[ave_price], "Number of Purchases":[num_of_purchases],"Total Revenue":[total_revenue]}) purchasing_df["Number of Unique Items"] = purchasing_df["Number of Unique Items"].map("{:<}".format) purchasing_df["Average Price"] = purchasing_df["Average Price"].map("${:<.2f}".format) purchasing_df["Number of Purchases"] = purchasing_df["Number of Purchases"].map("{:<}".format) purchasing_df["Total Revenue"] = purchasing_df["Total Revenue"].map("${:<,.2f}".format) purchasing_df # In[20]: # Gender Demographics # Drop the duplicates in column SN gender_group = purchase_data.drop_duplicates('SN') gender_count = gender_group["Gender"].value_counts #gender_count() # In[9]: # gender count to data frame gender_df = pd.DataFrame(gender_count()) #gender_df # In[10]: # get the percentage per gender and add to the gender Count # rename the column Gender to Total Count gender_perct = gender_df["Gender"]/number_of_unique_players gender_df["Percent of Players"] = gender_perct gender_df_renamed = gender_df.rename(columns={"Gender": "Total Count"}) gender_df_renamed.head() # In[11]: # Purchasing Analysis (Gender) pur_count_df = purchase_data[["Purchase ID", "Gender"]] pur_count = pur_count_df["Gender"].value_counts() #pur_count # In[12]: # Create a data frame for the Analysis pur_gender = pd.DataFrame(pur_count) #pur_gender # In[13]: # Get data that is grouped by Gender group_gender_df = purchase_data.groupby(["Gender"]) # get the average purchase per gender and add to the data frame ave_pur_gender = group_gender_df["Price"].mean() pur_gender["Average Purchase Price"] = ave_pur_gender # get the total purchase value and add to the data frame tot_pur_gender = group_gender_df["Price"].sum() pur_gender["Total Purchase Value"] = tot_pur_gender # rename the column pur_gender_renamed = pur_gender.rename(columns={"Gender": "Total Count"}) pur_gender_renamed #avg_tot_person = #pur_gender # In[14]: # Get data taht is group per person # group_per_person = purchase_data.groupby(["SN","Gender"]) # ave_tot_person = group_per_person["Price"].mean() # ave_tot_person_df = pd.DataFrame(ave_tot_person) # ave_tot_group_df = ave_tot_person_df.groupby(["Gender"]) # average_per_person = ave_tot_group_df["Price"].mean() # average_per_person # add to the data frame that is group by gender #group_gender_df["Pur Person"] = ave_tot_person # In[15]: print(purchase_data["Age"].max()) print(purchase_data["Age"].min()) # In[16]: # Create bins bins = [0, 10, 15, 20, 25, 30, 35, 40, 45] # names for the bins bin_names = ["<10", "10-14","15-19","20-24","25-29","30-34","35-39","40+"] #purchase_data["Total Count"] = pd.cut(purchase_data["Age"], bins, labels=bin_names) #purchase_data pd.cut(gender_group["Age"], bins, labels=bin_names).head() # In[17]: # Place the data series into a new column inside of the DataFrame gender_group["Total Count"] = pd.cut(gender_group["Age"], bins, labels=bin_names) gender_group.head() # In[18]: # Create a GroupBy object based upon "View Group" purchase_data_group = gender_group.groupby("Total Count") # Find how many rows fall into each bin print(purchase_data_group["SN"].count()) # Get the average of each column within the GroupBy object purchase_data_group[["Price"]].count() # In[ ]:
a9a03c032d2d69f2b444a683c75965955bb7cd37
hathu0610/nguyenhathu-fundamental-c4e13
/Session02/HW/Ex3c1.py
105
3.53125
4
for j in range(1,10): for i in range(1, 10): k = j*i print(k, end="\t") print()
18cd75fabeb057eaabe94cfc47505f05cb39d76f
nyp-sit/python
/practical6/RetailPrice.py
267
4.15625
4
wholesaleCost = float(input("Enter the wholesale cost of product: $")) while wholesaleCost > 0: retailPrice = wholesaleCost * 1.25 print("The retail price is $%.2f" % (retailPrice)) wholesaleCost = float(input("Enter the wholesale cost of product: $"))
56d9788891128abfa6bc54647e14e0823dc59da9
JosepAnSabate/Python_geology
/exercisis_a.py
686
3.8125
4
#ex1 b = ["h","o","l","a"] c = [] for bs in b: c.append(bs.upper()) print(c) #ex2 e=9 f = 1/2*(2/(e-3))+e**3 g = 1/2*(2/e-3)+e**3 print(f) print(g) #ex 3 diccionari={'Monday':2,'Tuessay':5, 'Wednesday':8,'Thursday':0, 'Friday': 4,'Saturday':0, 'Sunday':0} print(dir({})) #visualize the methods and attributes of any Python object print(sum(diccionari.values())) for x in diccionari.values(): print(x) sum = 0 for x in diccionari.values(): sum = sum + x print(sum) #ex4 tupla=(7,1,2,5,8,6,100,25) for p in tupla: if p%2 == 0: print(p,"es parell") else: print(p,"es imparell") ...
26ae68a0affd0b7a7ae1a8327d55c7ae1b8b5d2e
linhnvfpt/homework
/python/practice_python/exer15.py
425
4.40625
4
# Write a program (using functions!) that asks the user for a long string # containing multiple words. Print back to the user the same string, # except with the words in backwards order. def reverseWordOrder(helptext = "Input a string: "): string = input(helptext) result = string.split(" ") result.reverse() string_reverse = " ".join(result) return string_reverse print(reverseWordOrder())
22386ecc2d932d409217d70bcf8fabff92089c65
Erick-Paguay/perick885
/grupotech.py
942
3.75
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 16 19:27:04 2020 @author: Erick Paguay """ if __name__ == '__main__': inicial = int() final = int() impresiones = int() blanconegro = str() costoblanconegro = float() costocolor = float() costoimpresion = float() costoblanconegro = 0.06 costocolor = 0.12 print("Contador inicial: ") inicial = int(input()) print("Contador final: ") final = int(input()) print("Ingrese 1 si fue impresion blanco y negro y 2 si fue a color: ") blanconegro = input() if not (blanconegro=="1" or blanconegro=="2"): print("Tipo de impresion incorrecto") else: if final<inicial: print("El valor final es mayor que el inicial") else: impresiones = final-inicial if blanconegro=="1": costoimpresion = impresiones*costoblanconegro else: costoimpresion = impresiones*costocolor print("Impresiones: ",impresiones) print("Costo: ",costoimpresion)
860a246796d2f09b7998653bb7e23ada4535de1e
Mercrist/CodeWars-Submissions
/4 kyu/frequentWords.py
783
4.125
4
from collections import Counter #supports convenient and rapid tallies import re def top_3_words(text): counts = Counter(re.findall("'?[a-z][a-z']*", text.lower())) #an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values return [w for w, words in counts.most_common(3)] print(top_3_words("""In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income."""))
de33d7c3058259442d127f5ff8efaca700c97a88
amanji/quartet_phylogeny_algorithm
/phylogeny.py
885
3.6875
4
class Phylogeny: def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self): return self.right def getNodeValue(self): return self.rootid def insertRight(self,newNode): if self.right == None: self.right = Phylogeny(newNode) else: tree = Phylogeny(newNode) tree.right = self.right self.right = tree def insertLeft(self,newNode): if self.left == None: self.left = Phylogeny(newNode) else: tree = Phylogeny(newNode) self.left = tree tree.left = self.left def printTree(self): if self != None: print(self.getNodeValue()) printTree(self.getLeftChild()) printTree(self.getRightChild())
05cd00d13d8ad80ff5e4b16f6da7899b83449a3e
junyang10734/leetcode-python
/1736.py
635
3.640625
4
# 1736. Latest Time by Replacing Hidden Digits # String class Solution: def maximumTime(self, time: str) -> str: res = '' for i,t in enumerate(time): if t == '?': if i == 0: res += '2' elif i == 1: res += '3' if res[0] == '2' else '9' elif i == 3: res += '5' elif i == 4: res += '9' else: res += t if res[0] == '2' and res[1] > '3': res = '1' + res[1:] return res
d1e5fa48f12e02be231ecc71bbbbd199935de902
ramamca90/cyient_assessment
/ps_model_test.py
4,044
3.640625
4
# -*- coding: utf-8 -*- """ Created on Fri May 28 09:02:51 2021 @author: gonzalez """ """ Exercise: Create a class to contol a power supply (PS) and provide a main function that shows the usage The PS has 4 outputs each of then can be set to a given level (range from 0 to 15 V or to 48 V). The state of the supply can be also control between ON:1 and OFF:1. To test the exercise, a model of the comunication with the instrument is provided, see bellow. The commands to interact with the instrument are listed in the model """ """ Power supply iterface model for testing """ from ps_driver import PSDriver class PS_model(): PS_OUTPUT1_LEVEL = 0 PS_OUTPUT1_STATE = 0 PS_OUTPUT2_LEVEL = 0 PS_OUTPUT2_STATE = 0 PS_OUTPUT3_LEVEL = 0 PS_OUTPUT3_STATE = 0 PS_OUTPUT4_LEVEL = 0 PS_OUTPUT4_STATE = 0 def send_cmd(self, commad_string): response = "" cmd = commad_string.split(" ")[0] if (cmd == "output1:state?"): response = str(self.PS_OUTPUT1_STATE) elif (cmd == "output2:state?"): response = str(self.PS_OUTPUT2_STATE) elif (cmd == "output3:state?"): response = str(self.PS_OUTPUT3_STATE) elif (cmd == "output4:state?"): response = str(self.PS_OUTPUT4_STATE) elif (cmd == "output1:voltage_level?"): response = str(float(self.PS_OUTPUT1_LEVEL)) elif (cmd == "output2:voltage_level?"): response = str(float(self.PS_OUTPUT2_LEVEL)) elif (cmd == "output3:voltage_level?"): response = str(float(self.PS_OUTPUT3_LEVEL)) elif (cmd == "output4:voltage_level?"): response = str(float(self.PS_OUTPUT4_LEVEL)) elif (cmd == "output1:state"): value = int(commad_string.split(" ")[1]) self.PS_OUTPUT1_STATE = value elif (cmd == "output2:state"): value = int(commad_string.split(" ")[1]) self.PS_OUTPUT2_STATE = value elif (cmd == "output3:state"): value = int(commad_string.split(" ")[1]) self.PS_OUTPUT3_STATE = value elif (cmd == "output4:state"): value = int(commad_string.split(" ")[1]) self.PS_OUTPUT4_STATE = value elif (cmd == "output1:voltage_level"): value = float(commad_string.split(" ")[1]) self.PS_OUTPUT1_LEVEL = value elif (cmd == "output2:voltage_level"): value = float(commad_string.split(" ")[1]) self.PS_OUTPUT2_LEVEL = value elif (cmd == "output3:voltage_state"): value = float(commad_string.split(" ")[1]) self.PS_OUTPUT3_LEVEL = value elif (cmd == "output4:voltage_state"): value = float(commad_string.split(" ")[1]) self.PS_OUTPUT4_LEVEL = value elif (cmd == "output1:curr_limit"): value = float(commad_string.split(" ")[1]) self.PS_OUTPUT1_CURR_LIMIT = value else: raise("Command is not allowed") return response """ Here the class """ class PS_driver(): pass """ Here the main """ def main(): # example how to use the model ps = PS_model() response = ps.send_cmd("output2:voltage_level?") print(response) response = ps.send_cmd("output2:voltage_level 1.2") response = ps.send_cmd("output2:voltage_level?") print(response) response = ps.send_cmd("output2:state?") print(response) response = ps.send_cmd("output2:state 1") response = ps.send_cmd("output2:state?") print(response) response = ps.send_cmd("output1:curr_limit 3.2") print(response) psd = PSDriver(ps) print(psd.ps_output2_state) print(psd.ps_output1_level) if __name__ == '__main__': main()
93a0ddcc04d1c582162d00f46d47ff2285bc4472
mrgrier/AnagramExercise
/anagram.py
461
3.609375
4
import math import os import random import re import sys from collections import Counter def substringAnagrams(s): count = 0 substrings = [] l = len(s) i = 0 while i < l: j = i + 1 while j <= len(s): sub = s[i:j] for x in substrings: if(areAnagrams(sub, x)): count = count + 1 substrings.append(sub) j = j + 1 i = i + 1 return count def areAnagrams(s1, s2): return Counter(s1) == Counter(s2)
995c725152123ff6cc5144c50c58cdd8fbc6ed96
akmalmuhammed/Skools_Kool
/Chapter_08/exercise1.py
467
4
4
__author__ = 'matt' """ Write a function that takes a string as an argument and displays the letters backward, one per line. """ def backward(z): """ Take a string and display letters backwards """ index = 1 while index < len(z): letter = z[-index] print letter index = index + 1 print z[0] # Is there a better way? Seems hackish to have this at end. if __name__ == '__main__': print backward('sometexthereyeah')
be2351ded3ab698e678235cbedae0a7a3ddbb2c2
JavierPerezGithub/Python
/src/interfazGrafica/Ventana7.py
481
3.640625
4
''' Created on 14/2/2018 @author: 5725 ''' from Tkinter import * ventana1 = Tk() ventana1.title("Posicionamiento") etiqueta1 = Label(ventana1, text="Posicionamiento diferente 1").place(x=10, y=10) etiqueta2 = Label(ventana1, text="Posicionamiento diferente 2").place(x=200, y=10) etiqueta3 = Label(ventana1, text="Posicionamiento diferente 3").place(x=10, y=50) etiqueta4 = Label(ventana1, text="Posicionamiento diferente 4").place(x=200, y=50) ventana1.mainloop()
44747a9628824589ab9794b80abb904684b0267c
sujitkc/evaluate
/demo/submissions/rn010/Q2.py
544
3.890625
4
def increment(x): return x+1 def decrement(x): return x-1 def add(x, y): for i in range(x): y = increment(y) return y def subtract(x, y): for i in range(x): y = decrement(y) return y def multiply(x, y): copy = 0 for i in range(x): copy = add(copy, y) return copy def division(x, y): copy = x for i in range(y): copy = subtract(copy, y) return copy def exponent(x, y): copy = x for i in range(x): copy = multiply(x, copy) return copy
46299e100af88c059c8023f65c7821071c5515fe
924235317/leetcode
/73_set_matrix_zeroes.py
905
3.734375
4
def setZeroes(matrix: list) -> None: row, col = len(matrix), len(matrix[0]) row_flag = False col_flag = False for i in range(row): if matrix[i][0] == 0: row_flag = True break for i in range(col): if matrix[0][i] == 0: col_flag = True break for h in range(1, row): for w in range(1, col): if matrix[h][w] == 0: matrix[0][w] = 0 matrix[h][0] = 0 for h in range(1, row): for w in range(1, col): if matrix[0][w] == 0 or matrix[h][0] == 0: matrix[h][w] = 0 if row_flag: for i in range(row): matrix[i][0] = 0 if col_flag: for i in range(col): matrix[0][i] = 0 if __name__ == "__main__": matrix =[[0,1,2,0],[3,4,5,2],[1,3,1,5]] setZeroes(matrix) print(matrix)
f89535ab720b85c106695d238bd1d881b80d9586
AntoineCanda/A2DI
/tp1-canda/exo1.py
6,245
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 15 15:51:27 2017 @author: canda """ import numpy as np import matplotlib.pyplot as mpl import random import time from sklearn import datasets # Question 1 : chargement des donnees data = datasets.load_iris() # Question 2 : Obtenir informations sur le dataset : 150 exemples, 3 classes , dimension = 4 et type(d) est numeric. print(data['DESCR']) # Question 3 : Fonction qui permet de diviser le dataset en 2 dataset d'apprentissage et de teste avec la proportion n dans le dataset d'apprentissage. Les exemples sont divisés en 3 blocs de 50 exemples représentant à chaque fois une classe. Pour avoir de l'aléatoire, on les divise en 3 datasets de 50 que l'on mélange aléatoirement avec une fonction shuffle. Ensuite on récupère les n premiers exemples correspondants au pourcentage souhaité pour l'ensemble d'apprentissage et le reste pour l'ensemble de test. On a donc un partage aléatoire et équivalent des exemples dans les deux sets. # Parametre : data les donnees a diviser, n un entier compris entre [0;100] representant la part de l'ensemble initiale dans l'ensemble d'apprentissage def diviser_data_set(data, n) : # Nbre de donnee que l'on met dans l'ensemble d'apprentissage nb = int((50*n)/100) dataApp = [] targetApp = [] dataTest = [] targetTest = [] dataTemp = {} for i in range(0,3): dataTemp['data'] = data['data'][i*50:i*50+50] dataTemp['target'] = data['target'][i*50:i*50+50] random.shuffle(dataTemp['data']) dataApp.extend(dataTemp['data'][0:nb]) targetApp.extend(dataTemp['target'][0:nb]) dataTest.extend(dataTemp['data'][nb:50]) targetTest.extend(dataTemp['target'][nb:50]) app={'data':dataApp,'target':targetApp} test={'data':dataTest,'target':targetTest} return app,test # Question 4 : Pour la fonction kppv on commence par définir une fonction calculant la distance euclidienne entre deux points en tenant compte de chaque attribut pour la calculer. Ensuite on va trier la liste des distances (après copie) et ensuite on va chercher les indices dans la liste des distances non triés pour avoir les k premieres distances et on va chercher la classe associee. On calcule ensuite l'histogramme des distributions de classe obtenus pour les k plus proche voisins et on selectionne la classe la plus presente. # Remarque : En cas de distance équale on a pas les indices suivant le premier : on peut donc se retrouver avec une erreur. En revanche en utilisant les fonctions argsort pour calculer l'ordre de chaque distance et ensuite where pour trouver les k premieres valeurs on a difficilement plus de 75% de bonne classification. On a generalement une classe qui n'apparait quasiment pas (la 1) alors que en procedant ainsi on obtient plus de 90% de bonne classification selon k. def distance(x,y): res = 0 for i in range(0,len(x)): res += ((y[i] - x[i])**2) return (res**(1/2)) # Parametre : data l'ensemble de donnee utilisee, x l'instance que l'on considere et k le nombre de voisins que l'on considere. def kppv(data,x,k): dist = [] for i in range(0,len(data['data'])): res = distance(x,data['data'][i]) dist.append(res) dist_triee = list(dist) dist_triee.sort() pos = [] for i in range(0,len(dist)): idx = dist.index(dist_triee[i]) pos.append(idx) classe = [] for i in range(0,k): classe.append(data['target'][pos[i]]) b = np.bincount(classe) c = np.argmax(b) return c # Question 5 : On calcule le taux en faisant nombre de bonne classification sur nombre totale de classification. def taux_classification(dataApp,dataTest,k): cpt = 0 for i in range(0,len(dataTest['data'])): classe = kppv(dataApp,dataTest['data'][i],k) if classe == dataTest['target'][i]: cpt = cpt+1 res = cpt / len(dataTest['data']) return res * 100 # Question 6 : On fait varier k de 1 à 100 en tenant compte du fait du nombre d'exemples dans l'ensemble d'apprentissage. # Généralement pour des k entre 5 et 10 on a des taux très intéressants. Il arrive qu'avec k très faible (< 3) on ait parfois 100% de bonne classification mais attention vu le tres faible nombre de voisins considere il peut s'agir juste d'une coincidence. def classifier_var_k(l): taux = [] dataApp,dataTest = diviser_data_set(data,l) n = min(len(dataApp['data'])+1,101) for i in range(1,n): val = taux_classification(dataApp,dataTest,i) taux.append(val) for i, elt in enumerate(taux): print("Pour k = {} le taux de classification vaut {}.".format(i+1, elt)) x = [] for i in range(1,n): x.append(i) mpl.plot(x,taux) mpl.axis([1,n,0,100]) mpl.xlabel('Nombre de voisins considérés') mpl.ylabel('Pourcentage de bonnes classifications') mpl.show() return taux # Question 7 : On remarque qu'on a un pic aux alentours de 55%/60% dans le temps d'execution ce qui peut être interprete comme suit : c'est entre les proportions entre les dataset les plus proches qu'on est le plus penalise (a l'instar du fait que plus deux valeurs sont proche et plus leur produit est improtant (5*5 > 1*9)). # Apres le temps mis pour classifier n'est pas non plus tres eleves, il peut donc avoir un certain intérêt. def my_range(start, end, step): while start <= end: yield start start += step def classifier_var_dataApp(): t = [] for i in my_range(20,95,5): t0 = 0 t1 = 0 tm = 0 for j in range(0,100): t0 = time.time() dataApp,dataTest = diviser_data_set(data,i) taux_classification(dataApp,dataTest,15) t1 = time.time() tm = tm +(t1-t0) t.append(tm/15) x = [] for i in my_range(20,95,5): x.append(i) mpl.plot(x,t) mpl.axis([20,95,0,max(t)]) mpl.xlabel('Pourcentage du dataset dans le dataset d\'apprentissage') mpl.ylabel('Temps moyen pour un calcul de taux') mpl.show()
b08f42f9e9ef5866d39d9b45a32e2a8102dd1768
leizhi90/python
/base_python/day19_thread/work.py
2,411
3.96875
4
# -*- coding:utf-8 -*- # @Author : LZ # @Time : 2018/4/13 18:38 import threading # 当创建一个线程时,该线程是前台线程还是后台线程? #strat启动后变成前台程序,执行完毕销毁后变成后天程序 # 编写两个线程,对同一个全局变量增加若干次(次数多一点),会出现什么情况。 num = 0 def f_mult(): global num for i in range(1000000): num += 1 # t1 = threading.Thread(target=f_mult) # t2 = threading.Thread(target=f_mult) # t1.start() # t2.start() # t1.join() # t2.join() # print(num) # 两个线程,使用同一个函数作为target,然后在函数定义一个局部变量,两个线程分别对该变量自增若干次,会出现什么情况。 def f_2(): n = 0 for i in range(10000000): n += 1 print(n) # t1 = threading.Thread(target=f_2) # t2 = threading.Thread(target=f_2) # t1.start() # t2.start() # 编写买家与卖家交易的程序,一个钱锁,一个货锁,并造成死锁。 class Goods(): """ 商品类 """ def __init__(self,name,num,price): self.name = name self.num = num self.price = price class Seller(): def __init__(self,goods,g_lock): self.goods = goods self.g_lock = g_lock def seller_good(self,n,buyer): g_lock.acquire() buyer.m_lock.acquire() self.goods.num -= n buyer.money -= self.goods.price * n g_lock.release() buyer.m_lock.release() def __call__(self, *args, **kwargs): print(self.goods.name,self.goods.num) class Buyer(): def __init__(self,money,m_lock): #threading.Thread.__init__(self) self.money = money self.m_lock = m_lock def buy_goods(self,n,seller): self.m_lock.acquire() seller.g_lock.acquire() seller.goods.num -= n self.money -= seller.goods.price * n seller.g_lock.release() self.m_lock.release() def __call__(self, *args, **kwargs): print(self.money) g_lock = threading.RLock() m_lock = threading.RLock() goods = Goods('Wake me up at nine thirty',10,100) seller =Seller(goods,g_lock) buyer = Buyer(1000,m_lock) s = threading.Thread(target=seller.seller_good,args=(6,buyer)) b = threading.Thread(target=buyer.buy_goods,args=(6,seller)) s.start() #b.start() #s.join() #b.join() print(seller.goods.num) print(buyer.money)
cfd2f2cd9e4f750b3393d8d26e3ca763f8ecc1cb
ceeoinnovations/SPIKE_AI_Puppy
/Lesson_4/Lesson4Main-ReLearn_Example.py
1,762
3.640625
4
# Last modified: July 8th '21 # Main Code for Lesson 4: AI Fetch Examples #(Reinforcement Learning with Linear Model Example Code) import hub, utime sensor = hub.port.A.device ### <----- REPLACE WITH YOUR SPIKE'S HUB PORT number_of_examples = 3 # Setup reinforcement learning class, takes 2 ports for motor as parameters # Make sure these ports match your motor ports # Correct the directions to make your puppy move forward: # 1 = counterclockwise, -1 = clockwise puppy_re_learn = Fetch_ReLearn(direction1=1, direction2=1) # Update and correct the model during training for i in range(number_of_examples): puppy_re_learn.reinforcement_learning() # Final update of model puppy_re_learn.generate_linear_model(puppy_re_learn.distances, puppy_re_learn.times) # For the final trial, you can choose whether to manually #enter a distance for the puppy to run, or you can choose to #use the ultrasonic sensor to read a target distance. If #you want to use a manual input distance, let the following #line of code run. If you wish to use the ultrasonic #sensor, "comment out" the following line by putting a #"#" in front of it. puppy_re_learn.prediction_entry() utime.sleep(0.5) # Run predictions and move for ultrasonic sensor readings print('CENTER button:','predict','RIGHT button:','exit') while True: utime.sleep(0.1) if hub.button.right.is_pressed(): break elif hub.button.center.is_pressed(): # Drive forward the sensor reading distance dist = sensor.get()[0] print("Measurement: ", dist) utime.sleep(2) time = puppy_re_learn.prediction(dist) print("Drove ", dist, "cm in ", time, " sec") utime.sleep(1)
e5f4d5e4800ecd10547974cdd330043f67b1c218
prtk07/Programming
/Python/akumar-99_checkparallellines.py
418
4.21875
4
############################ ### FACTORS OF A NUMBER ### ############################ print("Line is ax+by=c") a1 = int(input("Enter a1: ")) b1 = int(input("Enter b1: ")) c1 = int(input("Enter c1: ")) a2 = int(input("Enter a2: ")) b2 = int(input("Enter b2: ")) c2 = int(input("Enter c2: ")) if(a1/a1 == b1/b2): print("Lines are parallel") else: print("Lines are not parallel") # This is contributed by Ashish Kumar.
b18bc6f214f45a43de30dacf715987cdf8782c73
luogao/python-learning
/py_slice.py
1,071
3.640625
4
#### Slice 切片 L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] print(L[0:3]) # ['Michael', 'Sarah', 'Tracy'] newL = L[1:2] print(newL) # ['Sarah'] reverseL = L[-2:] print(reverseL) # ['Bob', 'Jack'] L1 = list(range(100)) print(L1[:10]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(len(L1[-10:])) # 10 print() print(L1[::5]) # [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] print(L1[:10:2]) # [0, 2, 4, 6, 8] # copyL1 = L1[:] # print(copyL1) T = (0, 1, 2, 3, 4, 5) print(T[:3]) S = 'ABCDEFG' print(S[0:-1]) # TASK def trim(s): if (s[:1] == ' '): return trim(s[1:]) if (s[-1:] == ' '): return trim(s[:-1]) return s # 测试: if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')
1ceee07f6f1818b79158ee7a05644a59755966b9
dakbill/Lab_Python_05
/Lab05.py
2,319
3.90625
4
def do(thing): return str(thing) + str(1) do(5) #do(5) will have a string value of 51 ########################################################## def do(one, two=5): return one+two do(5) #do(5) will have an integer value of 10 def do(a,b): a=5 b=5 return a*b inp = 8 do(inp,5) print inp #do(inp,5) will evaluate to 25 but inp will print 8 ########################################################## def try_to_change_list_contents(the_list): the_list.append('four') outer_list = ['one', 'two', 'three'] try_to_change_list_contents(outer_list) print outer_list #4 will be appended to the list ########################################################### def do(a, f): return a*f(a) def inp(a): return a*2 print do(6,inp) #The output is 72 ########################################################### def factorial(num): out=1 for i in range(num,0,-1): out*=i return out num=input("Enter num to calculate its factorial:") print str(num)+" factorial is "+str(factorial(num)) #factorial ########################################################### def fibonacci(num): out=[] p1=0 p2=1 for i in range(1,num+1): if (i < 2): numout=i; else: numout=p2 + p1 p1=p2 p2=numout out.append(numout) return out num=input('Enter num of fibo sequence you want:') print fibonacci(num) #fibonacci ############################################################## def prime(n): if(n==2): return True else: div_count=0 for i in (1,n+1): if((n%i)==0): div_count+=1 if(div_count==2): return True else: return False num=input('Enter num to test:') out=prime(num) if(out): print 'Prime num' else: print 'Not prime' #Prime ############################################################## def isPalindrome(string): out=string[::-1] print out if(out==string): return True else: return False ans=isPalindrome('able was I ere I saw elba') print ans #isSubstring ############################################################## def isSubstring(baby_string,mother_string): return baby_string in mother_string
fa58ea34e18454038d020f9e97680a2671a89b56
FreedomPeace/python
/basicKnowledge/05ForWhile.py
581
3.8125
4
names = ['lily', 'lucy', 'jake'] for name in names: print(name) # 求1+2+...+10的和 --range(10) total = 0 for x in range(11): total += x # print(total) print('1-10的和total为:' + str(total)) nums = [1, 3, 5] totals = sum(nums) print(totals) totals = sum(list(range(101))) print("100以内的和为:" + str(totals)) totals = 0 x = 99 while x > 0: totals = totals + x x -= 2 print("100以内奇数和为:" + str(totals)) totals = 0 i = 2 while i < 101: totals = totals + i i = i + 2 print("100以内偶数和为:" + str(totals))
8e86aa7b66427627a30fc69deac7ec07b1cee435
VineetPrasadVerma/GeeksForGeeks
/SudoPlacementCourse/DistinctPalindromeSubstring.py
404
3.5625
4
test_cases = int(input()) for _ in range(test_cases): arr_list = input() size = len(arr_list) palindrome_list = [] for i in range(size): for j in range(i+1, size+1): temp = arr_list[i:j] reverse_temp = temp[::-1] if temp == reverse_temp: palindrome_list.append(temp) count = list(set(palindrome_list)) print(len(count))
1e062b08bf8b22908c4882d1a36debed7cd2e2d5
aigerimzh/BFDjango
/Week1/CodingBat/count_evens .py
135
3.59375
4
def count_evens(nums): cnt = 0 for x in range (len(nums)): if nums[x]%2 == 0: cnt = cnt+ 1 return cnt
8da65219f2253b8fef4879e47ca3c81db8d3e64a
avsuv/python_level_1
/5/5.py
277
3.546875
4
with open('5.txt', 'w') as file: nums = input('Введите числа через пробел: ') file.write(nums) numbers = [] with open('5.txt', 'r') as file: numbers = file.read().strip().split() summ = 0 for num in numbers: summ += int(num) print(summ)
161517b7795f2291deae1d75e09b3ad3b0383a28
1sma3l/Practice_Python
/conversor.py
758
3.75
4
def conversor(tipo_peso, valor_dollar): pesos = input("¿Cuantos pesos " + tipo_peso + " tienes?: ") pesos = float(pesos) dolares = pesos / valor_dollar dolares = round(dolares, 2) #Redondeamos la cantidad a 2 decimales dolares = str(dolares) print("Tienes $" + dolares + " dolares") menu = """ Bienvenido al conversor de monedaa ✔ 1 - Pesos colombianos 2 - Pesos argentinos 3 - Pesos mexicanos Elige una opción: """ opcion = int(input(menu)) #Dentro de la variable opcion guardo el numero que se valla a teclear if opcion == 1: conversor('colombianos', 3875) elif opcion == 2: conversor('cargentinos', 65) elif opcion == 3: conversor('mexicanos', 24) else: print('Ingresa una opción correcta por favor')
75cd40870a247b735d08bd29bdf3d9b08104f794
cl3e8/tuple-meetup-web-scraping-workshop
/01_requests/02_requests_json_eg.py
1,002
3.859375
4
import requests import pprint """ Requests Library JSON Example: Using the requests library, you can view contents in other formats as well. One very popular data format for the web is JSON (JavaScript Object Notation). With the Requests library, you can easily read in JSON data to a dictionary. Pro tip! Many times you don't even need web scraping. Numerous websites provide the information you may be looking for through the use of APIs. (https://www.json.org/) (https://2.python-requests.org/en/master/) """ # Try replacing this URL with different ones and see what you get! # # https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson # https://xkcd.com/353/info.0.json # # Pro tip: try replacing "black-mirror" with other episodes r = requests.get('http://api.tvmaze.com/singlesearch/shows?q=black-mirror&embed=episodes') print('JSON:') # We use the `pprint` library to make the object easier to read pprint.pprint(r.json()) # What happens when we output r.text?
70fe9c848d3928509702fc35c16f31ddd6224b56
chunxi-alpc/gcx_pacman
/search/search.py
6,211
3.84375
4
# coding=UTF-8 # search.py """ In search.py, you will implement generic search algorithms which are called by Pacman agents (in searchAgents.py). """ import util class SearchProblem: """ This class outlines the structure of a search problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class). You do not need to change anything in this class, ever. """ def getStartState(self): """ Returns the start state for the search problem. """ util.raiseNotDefined() def isGoalState(self, state): """ state: Search state Returns True if and only if the state is a valid goal state. """ util.raiseNotDefined() def getSuccessors(self, state): """ state: Search state For a given state, this should return a list of triples, (successor, action, stepCost), where 'successor' is a successor to the current state, 'action' is the action required to get there, and 'stepCost' is the incremental cost of expanding to that successor. """ util.raiseNotDefined() def getCostOfActions(self, actions): """ actions: A list of actions to take This method returns the total cost of a particular sequence of actions. The sequence must be composed of legal moves. """ util.raiseNotDefined() def tinyMazeSearch(problem): """ Returns a sequence of moves that solves tinyMaze. For any other maze, the sequence of moves will be incorrect, so only use this for tinyMaze """ from game import Directions s = Directions.SOUTH w = Directions.WEST return [s,s,w,s,w,w,s,w] def depthFirstSearch(problem): #初始状态 s = problem.getStartState() #标记已经搜索过的状态集合exstates exstates = [] #用栈实现dfs states = util.Stack() states.push((s, [])) #循环终止条件:遍历完毕/目标测试成功 while not states.isEmpty() and not problem.isGoalState(s): state, actions = states.pop() exstates.append(state) successor = problem.getSuccessors(state) for node in successor: coordinates = node[0] direction = node[1] #判断状态是否重复 if not coordinates in exstates: states.push((coordinates, actions + [direction])) #把最后搜索的状态赋值到s,以便目标测试 s = coordinates #返回动作序列 return actions + [direction] util.raiseNotDefined() def breadthFirstSearch(problem): #初始状态 s = problem.getStartState() #标记已经搜索过的状态集合exstates exstates = [] #用队列queue实现bfs states = util.Queue() states.push((s, [])) while not states.isEmpty(): state, action = states.pop() #目标测试 if problem.isGoalState(state): return action #检查重复 if state not in exstates: successor = problem.getSuccessors(state) exstates.append(state) #把后继节点加入队列 for node in successor: coordinates = node[0] direction = node[1] if coordinates not in exstates: states.push((coordinates, action + [direction])) #返回动作序列 return action util.raiseNotDefined() def uniformCostSearch(problem): #初始状态 start = problem.getStartState() #标记已经搜索过的状态集合exstates exstates = [] #用优先队列PriorityQueue实现ucs states = util.PriorityQueue() states.push((start, []) ,0) while not states.isEmpty(): state, actions = states.pop() #目标测试 if problem.isGoalState(state): return actions #检查重复 if state not in exstates: #扩展 successors = problem.getSuccessors(state) for node in successors: coordinate = node[0] direction = node[1] if coordinate not in exstates: newActions = actions + [direction] #ucs比bfs的区别在于getCostOfActions决定节点扩展的优先级 states.push((coordinate, actions + [direction]), problem.getCostOfActions(newActions)) exstates.append(state) return actions util.raiseNotDefined() def nullHeuristic(state, problem=None): """ A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial. 启发式函数有两个输入变量:搜索问题的状态 (主参数), 和问题本身(相关参考信息) """ return 0 def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost f(n) and heuristic g(n) first." start = problem.getStartState() exstates = [] # 使用优先队列,每次扩展都是选择当前代价最小的方向 states = util.PriorityQueue() states.push((start, []), nullHeuristic(start, problem)) nCost = 0 while not states.isEmpty(): state, actions = states.pop() #目标测试 if problem.isGoalState(state): return actions #检查重复 if state not in exstates: #扩展 successors = problem.getSuccessors(state) for node in successors: coordinate = node[0] direction = node[1] if coordinate not in exstates: newActions = actions + [direction] #计算动作代价和启发式函数值得和 newCost = problem.getCostOfActions(newActions) + heuristic(coordinate, problem) states.push((coordinate, actions + [direction]), newCost) exstates.append(state) #返回动作序列 return actions util.raiseNotDefined() # Abbreviations bfs = breadthFirstSearch dfs = depthFirstSearch astar = aStarSearch ucs = uniformCostSearch
8d1928bd1266185c8a096f6000d631c1966ada98
kazlik0310/python
/vsearch.py
498
3.921875
4
def search_for_vowels(phrase:str) -> set: """Возвращает булево значение в зависимости от присутствия любых гласных.""" vowels = set('aeiou') return vowels.intersection(set(phrase)) def search_for_letters(phrase:set, letters:str='aeiou') -> set: """Находит множество букв из 'letters', найденных в указанном слове""" return set(letters).intersection(set(phrase))
dd5694a39ecd17df831beea627b0af08a61e3c45
figkim/TC2
/leetcode/2020/easy/00020_valid_parentheses/valid_paren_WY.py
635
3.5
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ pars = {"(":")","[":"]","{":"}"} stack = list() for i,par in enumerate(s): if par in pars.keys(): stack.append(par) elif (par in pars.values()) and (i > 0): if stack == []: return False elif pars.get(stack[-1]) == par: stack.pop() else: return False else: return False return stack == []
ad162c0963c0a3f13970dfebc690993de4998941
charles161/python
/Factorial.py
332
3.78125
4
tc = input("Enter the number of test cases: ") a=[] for i in range(tc): a.append(input("Enter the input of "+str(i+1)+ " test case: ")) def factorial( n ): if n==0: return 1 else: return n*factorial(n-1) for na in a: if na<0: print("Invalid") else: print(str(factorial(na)))
cc61fe596b967bf852083b37cc3c0521eccc672c
harsilspatel/toy-robot-simulator
/RobotSimulator.py
2,661
4.03125
4
from enum import Enum class Direction(Enum): """Enum to representation robot direction.""" NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 class RobotSimulator: def __init__(self, table_width=5, table_length=5): assert table_width > 0, "Table width should be a positive integer" assert table_length > 0, "Table length should be a positive integer" self.table_width = table_width self.table_length = table_length self.robot_x = None self.robot_y = None self.robot_direction = None self._is_valid_command = False def __eq__(self, other): # assuming we only have one robot. return isinstance(other, RobotSimulator) and \ all([getattr(self, attr) == getattr(other, attr) for attr in vars(self)]) def is_valid_position(self, new_x, new_y): """To validate if the new robot position is on the tabletop""" return 0 <= new_x < self.table_width and 0 <= new_y < self.table_length def place(self, x, y, direction): """Function to validate the new position and place the robot""" if self.is_valid_position(x, y): self.robot_x = x self.robot_y = y self.robot_direction = direction self._is_valid_command = True def move(self, step=1): """Function to validate the move the robot""" if not self._is_valid_command: return new_x, new_y = self.robot_x, self.robot_y if self.robot_direction == Direction.EAST: new_x += step elif self.robot_direction == Direction.WEST: new_x -= step elif self.robot_direction == Direction.NORTH: new_y += step else: new_y -= step if self.is_valid_position(new_x, new_y): self.robot_x, self.robot_y = new_x, new_y def report(self): """Function to report the robot's position and direction""" if self._is_valid_command: return '{},{},{}'.format(self.robot_x, self.robot_y, self.robot_direction.name) def parse_command(self, line): """Function to parse each line of command.""" params = line.strip().split() command = params[0] if command == 'PLACE': try: x, y, dir = params[1].split(',') self.place(int(x), int(y), Direction[dir.upper()]) except: pass elif command == 'MOVE': self.move() elif command == 'REPORT': output = self.report() if output: print(output) elif command == 'LEFT': if self._is_valid_command: self.robot_direction = Direction((self.robot_direction.value - 1) % 4) elif command == 'RIGHT': if self._is_valid_command: self.robot_direction = Direction((self.robot_direction.value + 1) % 4) else: pass def process_input(self, input): """Function to process multi-line commands""" for command in input.strip().split('\n'): self.parse_command(command)
d9d274f086dc030610709f4ea954694dde402ca0
mikhail-rozov/GB_Python-main-course-1
/Lesson 4/L4_task6.py
1,880
4
4
# Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. # Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, # что создаваемый цикл не должен быть бесконечным. Необходимо предусмотреть условие его завершения. # Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл. # Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено. from itertools import count, cycle try: start_number = int(input('Введите число, с которого начнём генерацию чисел: ')) end_number = int(input('Введите число, которым закончим генерацию чисел: ')) the_list = [2, 15, 32, 53, 123, 140] for number in count(start_number): if number > end_number: break else: print(number) times = int(input('Сколько раз хотите повторить вывод элементов последовательности? ')) counter = 1 for number in cycle(the_list): if counter > times: break else: counter += 1 print(number) except ValueError: print('Вводить нужно числа!')
b4d70cbeb75cc6a23c9bd6be7d461be3fdb34398
pri-nitta/firstProject
/CAP8/Funcoes.py
900
4.125
4
def perguntar(): return input("O que deseja realizar?\n" + "1 - Inserir usuário\n" + "2 - Pesquisar usuário\n" + "3 - Excluir usuário\n" + "4 - Listar usuário: ").upper() # não precisa do retorno, pq é a memória def inserir(dicionario): dicionario[input("Digite o login: ").upper()] = [input("Digite o nome: ").upper(), input("Digite a última data de acesso: "), input("Última estação acessada: ").upper()] def pesquisar(dicionario): nome = input("Digite o login que deseja buscar: ").upper() print(dicionario.get(nome)) def excluir(dicionario): nome = input("Digite o login que deseja excluir: ").upper() print(f"Usuario, {nome} removido com sucesso!") dicionario.remove("nome")
2330266af33295d1b4cb7982871a7416de9aeb5a
alexandrepoulin/ProjectEulerInPython
/problems/problem 123.py
350
3.515625
4
print("Starting") import useful MAX = 10**6 primes = useful.primesTo(MAX) answer = 0 for i in range(0,len(primes)): if i%2 == 1: continue val = 2*(i+1)*primes[i]% primes[i]**2 if val > 10**10: print(val) print(primes[i]) answer = i+1 break print(answer) input("Done")
e2ca225aa70ff3285d27cc80e348a0437adce91f
scottwat86/Automate_Boring_Stuff_
/ch12_excel/PP21_Excel_to_text.py
965
4.0625
4
#! python3 # PP21_Excel_to_text.py # Write a program that performs the tasks of the previous program in reverse order: # The program should open a spreadsheet and write the cells of column A into one text file, the # cells of column B into another text file, and so on. # By Scott Watson # Import modules import sys import openpyxl as xl from openpyxl.utils import get_column_letter # Command line argument verification if len(sys.argv) < 2: print('Usage: python3 PP21_Excel_to_text.py <excel_1> .. .<excel_n>') sys.exit(-1) print(sys.argv[1]) wb = xl.load_workbook(sys.argv[1]) sheet = wb.active for column in range(1, sheet.max_column + 1): file_name = 'Column_' + get_column_letter(column) + '_.txt' with open(file_name, 'a') as file: for row in range(1, sheet.max_row + 1): cell = sheet[get_column_letter(column)+str(row)].value if cell == None: continue file.write(str(cell) + ',')
dede04bdde1c57dfdbe02c70e174b51a35293763
Kite-free/crop
/findfile.py
652
3.859375
4
#输入要查找的文件名 查找当前文件夹下该文件的相对目录: import os path = os.path.abspath('.') target_str = input('请输入要搜索的文件名关键字:') for root, dirs, files in os.walk(path): for file in files: if target_str in file: print(os.path.join(root.replace(os.getcwd(),'.'), file)) # print(os.path.join(root, file)) # os.walk # root 所指的是当前正在遍历的这个文件夹的本身的地址 # dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录) # files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
c540ad3261997b1ab47a068c8fc60647560a3581
hiepxanh/C4E4
/MaiHuong/Session 02 - assignment 02.py
777
4.09375
4
from turtle import * # Exercise 1 ## Check variables type: type () a = 3 b = 3.05 c = "Hello" print(type(a)) print(type(b)) print(type(c)) ## 3 examples of invalid name ##3consoi = 13 ##soi@ = "hello" ##max(i) = 21 # Exercise 2: calculates areas of the circle r = 10 # r : radius areas = r**2*3.14 print(" Areas = ", areas) # Exercise 3: convert Celsius​(0C) into Fahrenheit​(0F) C = 10 F = C*1.8 + 32 print(str.format("Temperature: {0} (C) = {1} (F)", C, F)) # Exercise 4: bacterias B = 2 for i in range (5): total = B*(2**(i//2)) print("After ", i, " minutes we would have ", total, " bacterias") # Exercise 5: fibonacci a = 0 b = 1 for i in range(0, 5): a,b = b, a+b print(str.format("Month {0} : {1} pair(s) of rabbits", i, b))
76d04841a0467417cbccb1d504688cd5d01328be
patel-deepak506/Codechef
/NAV_DEEPAK P/NAVHW_049.py
272
3.90625
4
''' NAVHW_049: Draw a flowchart to print the following sequence. * * * * * * * * * * * * * * * ''' n=int(input()) # a=1 # while a<=n: # b=a # while b<+n: # print("*",end=" ") # b+=1 # k=1 # while k for i in range(1,n+1): print(" "*(n-i),"*"*i)
6af0a3f24064ee2a4e54242755746cc1217f3023
tamyrds/Exercicios-Python
/Mundo_2_Python/estrutura_while/desafio_70.py
680
3.953125
4
maior = totH = totM = 0 print('=-' * 20) print("CADASTRE UMA PESSOA") print('=-' * 20) while True: idade = int(input("Idade:")) sexo = str(input("Sexo: ")).upper() if idade >= 18: maior +=1 if sexo == 'M': totH += 1 if idade < 20 and sexo == 'F': totM +=1 tipo = ' ' while tipo not in 'SN': tipo = str(input("Quer continuar? [S/N]")).upper() if tipo == 'N': break print(f"Total de pessoas com mais de 18 anos: {maior}") print(f'Ao todo temos {totH} homens cadastrados') print(f'E temos {totM} mulheres com menos de 20 anos') print('=-' * 20)
dbf7c9d3fad35cb132fa3bb9377f815cff5e323e
djlim98/Algorithm
/programmers/Stack&Queue/4.py
598
3.59375
4
#https://programmers.co.kr/learn/courses/30/lessons/42587 def solution(priorities, location): answer = 0 count=0 while priorities: candinate=priorities.pop(0) location-=1 flag=True for i in priorities: if candinate<i: flag=False break if not flag: priorities.append(candinate) if location==-1: location+=len(priorities) else: count+=1 if location==-1: answer=count break return answer
d2932c43a90a05dbf2dbc75595428eba8c8eae60
Piyush-Ranjan-Mishra/python
/Machine Learning & AI/knn.py
2,159
3.578125
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd path = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" # assign column names to the dataset as follows − headernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class'] dataset = pd.read_csv(path, names=headernames) dataset.head() # slno. sepal-length sepal-width petal-length petal-width Class # 0 5.1 3.5 1.4 0.2 Iris-setosa # 1 4.9 3.0 1.4 0.2 Iris-setosa # 2 4.7 3.2 1.3 0.2 Iris-setosa # 3 4.6 3.1 1.5 0.2 Iris-setosa # 4 5.0 3.6 1.4 0.2 Iris-setosa # Data Preprocessing X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Training and testing set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40) # data scaling from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) # train the model from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=8) classifier.fit(X_train, y_train) # Predictions y_pred = classifier.predict(X_test) # print the results from sklearn.metrics import classification_report, confusion_matrix, accuracy_score result = confusion_matrix(y_test, y_pred) print("Confusion Matrix:") print(result) result1 = classification_report(y_test, y_pred) print("Classification Report:",) print (result1) result2 = accuracy_score(y_test,y_pred) print("Accuracy:",result2) # Output # Confusion Matrix: # [[21 0 0] # [ 0 16 0] # [ 0 7 16]] # Classification Report: # precision recall f1-score support # Iris-setosa 1.00 1.00 1.00 21 # Iris-versicolor 0.70 1.00 0.82 16 # Iris-virginica 1.00 0.70 0.82 23 # micro avg 0.88 0.88 0.88 60 # macro avg 0.90 0.90 0.88 60 # weighted avg 0.92 0.88 0.88 60 # Accuracy: 0.8833333333333333
1e38e9f2ac4ccce19efe1ffb1b8f1bb36b7245ad
nandadao/Python_note
/note/download_note/first_month/day09/exercise02.py
241
3.71875
4
""" 定义函数,判断二维数字列表中是否存在某个数字 输入:二维列表、11 输出:True/False """ map = [ [2, 0, 2, 0], [2, 4, 0, 2], [0, 0, 2, 0], [2, 4, 4, 2], ] print(2 in map)# False X
97812f10c889bcd5c750604abaf26038754d514d
ggrecco/python
/basico/zumbis/velocidadeExcedida.py
235
3.890625
4
velocidade = int(input("Velocidade do carro: ")) if velocidade > 110: multa = (velocidade - 110) * 5 print("Você foi mulado em R$ {}".format(multa)) else: print("Parabéns você está dentro do limite de velocidade!")
81a676e978976b43ced27e7a5b839445adf0c18b
dado3212/ProjectEuler
/euler_22.py
820
3.609375
4
# Problem 22 # Answer: 871198282 ''' Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 x 53 = 49714. What is the total of all the name scores in the file? ''' def score(name): s = 0 for i in name: s += (ord(i)-64) return s with open('names.txt','r') as f: names = sorted(map(lambda x: x[1:-1],f.readline().split(","))) total = 0 for index, name in enumerate(names): total += score(name) * (index+1) print total
f260c08d786305c4791e7b203443827a46f3bb8e
sourabbanka22/Competitive-Programming-Foundation
/Dynamic Programming/knapsackProblem.py
839
3.515625
4
def knapsackProblem(items, capacity): memo = [[0 for _ in range(capacity+1)] for _ in range(len(items)+1)] for row in range(1, len(items)+1): for col in range(capacity+1): currentWeight = items[row-1][1] currentValue = items[row-1][0] if currentWeight<=col: memo[row][col] = max(memo[row-1][col-currentWeight]+currentValue, memo[row-1][col]) else: memo[row][col] = memo[row-1][col] itemIndices = [] row = len(items) col = capacity while col>0 and row>0: top = memo[row][col] == memo[row-1][col] if not top: itemIndices.append(row-1) col -= items[row-1][1] row-=1 return [memo[-1][-1], itemIndices[::-1]] print(knapsackProblem([[1, 2], [4, 3], [5, 6], [6, 7]], 10))