blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5fb7f49ac5f9cfc8d798dd3d3a1584b8bb9a7dc4
Jpeck219/nyc-mhtn-ds-060319-lectures
/Mod_1/rolling-stones/functions1.py
7,955
3.921875
4
import csv from collections import Counter import json with open('data.csv') as f: # we are using DictReader because we want our information to be in dictionary format. rolling_stones_list = list(csv.DictReader(f)) #print(rolling_stones_list[:4]) #Find by name - Takes in a string that represents the name of an album. Should #return a dictionary with the correct album, or return None. def find_name(name, search_list): for item in search_list: if 'album' in item: if name == item['album']: return item elif 'name' in item: if name == item['name']: return item return None #Find by rank - Takes in a number that represents the rank in the list of top #albums and returns the album with that rank. If there is no album with that #rank, it returns None. def find_rank(rank, search_list): for item in search_list: if 'rank' in item: if str(rank) == item['rank']: return item elif 'number' in item: if str(rank) == item['number']: return item return None #print(find_album_rank('501')) #Find by year - Takes in a number for the year in which an album was released #and returns a list of albums that were released in that year. #If there are no albums released in the given year, it returns an empty list. def find_year(year, search_list): in_that_year = [] for item in search_list: if str(year) == item['year']: in_that_year.append(item) return in_that_year # print(len(find_album_year('1976'))) # print(find_album_year('2012')) #Find by years - Takes in a start year and end year. Returns a list of all # albums that were released on or between the start and end years. #If no albums are found for those years, then an empty list is returned. def find_year_range(start,end,search_list): in_range_years = [] for item in search_list: if int(item['year']) >= int(start) and int(item['year']) <= int(end): in_range_years.append(item) return in_range_years #print(find_album_year_range(1953,1957)) #Find by ranks - Takes in a start rank and end rank. Returns a list of albums #that are ranked between the start and end ranks. If no albums are found for #those ranks, then an empty list is returned. def find_rank_range(start,end,search_list): in_range_ranks = [] for item in search_list: if 'rank' in item: if int(item['rank']) >= int(start) and int(item['rank']) <= int(end): in_range_ranks.append(item) elif 'number' in item: if int(item['number']) >= int(start) and int(item['number']) <= int(end): in_range_ranks.append(item) return in_range_ranks #print(find_album_rank_range(499,700)) #All titles - Returns a list of titles for each album. def all_titles(search_list): titles_list = [] if 'name' in search_list[0]: for item in search_list: titles_list.append(item['name']) elif 'album' in search_list[0]: for item in search_list: titles_list.append(item['album']) return titles_list #All artists - Returns a list of artist names for each album. def all_artists(search_list): artist_list = [] for item in search_list: artist_list.append(item['artist']) return artist_list #Artists with the most albums - Returns the artist with the highest amount of #albums on the list of top albums # def artist_most_albums(): # occurence_count = Counter(all_album_artists()) # print(occurence_count) # print() # print(occurence_count.most_common(1)) # print() # print(occurence_count.most_common(1)[0]) # print() # print(occurence_count.most_common(1)[0][0]) # return def artist_most_popular(search_list): occurence_count = Counter(all_artists(search_list)) return occurence_count.most_common(1)[0][0] #Most popular word - Returns the word used most in amongst all album titles # def most_pop_word(search_list): # title_string = " ".join(all_titles(search_list)).lower() # title_string = title_string.replace('!', '') # title_string = title_string.replace('?', '') # title_string = title_string.replace('(', '') # title_string = title_string.replace(')', '') # title_string = title_string.replace('"', '') # title_string = title_string.replace(',', '') # title_string = title_string.replace(':', '') # title_string = title_string.replace('/', '') # title_string = title_string.replace('-', '') # #print(title_string) # wc = Counter(title_string.split()) # #print(wc) # return wc.most_common(1)[0][0] def most_pop_word(search_list): all_words = [] if 'album' in search_list[0]: for item in search_list: all_words += item['album'].split() elif 'name' in search_list[0]: for item in search_list: all_words += item['name'].split() return Counter([word.lower() for word in all_words]).most_common(1)[0][0] #Histogram of albums by decade - Returns a histogram with each decade pointing #to the number of albums released during that decade. # def hist_albums_per_decade #Histogram by genre - Returns a histogram with each genre pointing to the #number of albums that are categorized as being in that genre # def hist_genre # open the text file in read text_file = open('top-500-songs.txt', 'r') # read each line of the text file # here is where you can print out the lines to your terminal and get an idea # for how you might think about re-formatting the data lines = text_file.readlines() #print(lines) #take read text file and sort into list of dictionaries #1) loop through list for each element (in this case each song). #2) split each element into individual list (for each element) #3) make each element a dictionary with keys #4) add each dictionary to list of dictionaries def list_of_dict_songs(lines): song_dict_list = [] for line in lines: split_song = line.split('\t') song_dict = { 'rank' : split_song[0], 'name' : split_song[1], 'artist' : split_song[2], 'year' : split_song[3].replace('\n', '')} song_dict_list.append(song_dict) return song_dict_list #print(list_of_dict_songs(lines)) #print(find_rank(30, rolling_stones_list)) #print(find_rank(31, list_of_dict_songs(lines))) # print(find_year(1957, rolling_stones_list)) # print(find_year(1990, list_of_dict_songs(lines))) # print(find_year_range(1953,1957,rolling_stones_list)) # print() # print(find_year_range(1989,1991,list_of_dict_songs(lines))) # print(find_rank_range(20,23,rolling_stones_list)) # print() # print(find_rank_range(100,104,list_of_dict_songs(lines))) # print(all_titles(rolling_stones_list)) # print() # print(all_titles(list_of_dict_songs(lines))) # print(all_artists(rolling_stones_list)) # print() # print(all_artists(list_of_dict_songs(lines))) file = open('track_data.json', 'r') json_data = json.load(file) print(json_data) # albumWithMostTopSongs - returns the name of the artist and album that has that # most songs featured on the top 500 songs list # # albumsWithTopSongs - returns a list with the name of only the albums that have #tracks featured on the list of top 500 songs # # songsThatAreOnTopAlbums - returns a list with the name of only the songs #featured on the list of top albums # # top10AlbumsByTopSongs - returns a histogram with the 10 albums that have the # most songs that appear in the top songs list. The album names should point to #the number of songs that appear on the top 500 songs list. # # topOverallArtist - Artist featured with the most songs and albums on the two #lists. This means that if Brittany Spears had 3 of her albums featured on the #top albums listed and 10 of her songs featured on the top songs, she would have # a total of 13. The artist with the highest aggregate score would be the top #overall artist.
600dcfd8d809520bfbe2af0ca94293411206eac9
bishkou/leet-code
/Arrays 101/moveZero.py
439
3.765625
4
from typing import List def moveZeroes(nums: List[int]) -> None: j = 0 i = 0 while i < len(nums): while j < len(nums) and nums[j] != 0: j += 1 if i > j and i != 0: nums[j] = nums[i] nums[i] = 0 i += 1 else: i += 1 if __name__ == '__main__': nums = [1, 0, 1, 0, 3, 12] moveZeroes(nums) # print(moveZeroes(nums)) print(nums)
7fac4084c82ea280dea4afa3bbce686dd6df84a7
yusun-hci/LeetCodeDaily
/43_Multiply_Strings_20180613.py
1,383
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 13 01:58:42 2018 @author: lifanhong The length of both num1 and num2 is < 110. —— what's the point of this? test case: when output = "0" 3141592653589793238462643383279502884197169399375105820974944592 2718281828459045235360287471352662497757247093699959574966967627 """ class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ result = [0] * (len(num1) + len(num2) + 2) output = "" for i in range(len(num1)): for j in range(len(num2)): temp = int(num1[-1-i]) * int(num2[-1-j]) result[-1-i-j] += temp % 10 if temp >= 10: result[-2-i-j] += temp // 10 for k in range(len(result)): if result[-1-k] >= 10: result[-2-k] += result[-1-k] // 10 result[-1-k] = result[-1-k] % 10 #print(result) for digit in result: if digit != 0 or output != "" : output += str(digit) if output == "": output = "0" return output print(Solution().multiply("3141592653589793238462643383279502884197169399375105820974944592","2718281828459045235360287471352662497757247093699959574966967627"))
b6af5b818a08f0e9da96acb7bfca724c3495e11b
xiongfeihtp/NLP-embedding
/ChineseWordSegment/sentence_manager/sentence_embedding.py
4,809
3.703125
4
''' Embedding a sentence into a vector. By the approach of described in 'A SIMPLE BUT TOUGH-TO-BEAT BASELINE FOR SEN- TENCE EMBEDDINGS', Sanjeev Arora, et al. But with some modification / addition. If there are some words not exists in the vocabulary, give it a random value with uniform distribution in space D^w Author: Minquan Date: 2017-06-20 ''' import jieba import numpy as np import pickle import os from sentence_manager.pca import get_pca import logging from utlis.redis_manager import get_word_vector from utlis.redis_manager import get_word_count_frequency cache = {} def get_sentence_words_vector(sentence): """ :param A sentence. word1word2word3..word_n :return: vectors of those words. [vector1, vector2, ... vector_n] """ words = list(jieba.cut(sentence)) test_word = '测试' test_vector = get_word_vector(test_word) assert test_vector is not None vectors = map(get_word_vector, words) try: vectors, words = zip(*([(v, w) for v, w in zip(vectors, words) if v is not None])) except ValueError: return [], [] return vectors, words def get_vector_dimension(vectors): """ Get the right dimension of one vector array. :param vectors: [V1, V2, .. None, VN], we need to know what's the dimension of 'None' :return: the dimension of not None vector. """ for vec in vectors: if vec is not None: vec = np.array(vec) dimension = vec.shape[0] break else: dimension = None return dimension def change_none_vector_to_real_value(vectors): """ There are several words not exist in vocabulary, and those word's vector will become None, In this process, we change those None Value to Real Value. Based on the Word2Vec methods, we could change those to a uniform distribution or Gaussian distribution based on the train methods. :param vectors: [V1, V2, V3, ..None, . VN] :return: [V1, V2, V3, .. V_i, .. VN] """ vector_length = get_vector_dimension(vectors) if vector_length is not None: new_vectors = [vec if vec is not None else get_random_vector(vector_length) for vec in vectors] else: new_vectors = None return new_vectors def get_random_vector(vector_size): vocabulary_size = 1000 # min_interval = -0.5 # max_interval = 0.5 random_vec = np.random.normal(0, 0.5, size=vector_size) return random_vec def get_sentence_embedding(sentence): vectors, words = get_sentence_words_vector(sentence) a = 1.e-3 three_times_frequency = 3.8e-08 ## if one word not occured in hudong wiki, we assume it have weighted_vectors = [] for word, v in zip(words, vectors): frequency = get_word_count_frequency(word) or three_times_frequency if v is None or frequency is None: continue else: weight = a / (a + frequency) weighted_vector = weight * v weighted_vectors.append(weighted_vector) length = len(words) #two sentence embedding expression final_vector = np.sum(weighted_vectors, axis=0) / length # if length > 1: # principle_component = get_pca(vectors)[0] # dot = np.dot(principle_component, np.transpose(principle_component)) # final_vector = final_vector - dot * final_vector return final_vector def test_long_sentence(): sentence = """【环球网报道 记者 朱佩】英国首相特蕾莎∙梅日前称,由于曼彻斯特恐袭案,该国恐怖威胁级别从“严重”提高至“危急”。这意味着可能派遣军队保障安全。据俄新社5月24日报道,伦敦警察厅反恐部门负责人马克•罗利表示,希望恐怖威胁级别不会太长时间维持在最高级别。 罗利在回答恐怖威胁“危急”水平制度要维持多久的问题时说道:“我不想预测未来,但如果你看看我们的历史,这样一个威胁级别是非常不寻常和罕见的措施。它从未维持很久,我们也希望这样。但在这样一个高风险期我们将竭尽所能,军队将帮助我们。” 当地时间5月22日晚,自杀式恐怖分子在曼彻斯特竞技场音乐厅内实施了爆炸。爆炸造成22人死亡,59人受伤。伤亡者中有许多儿童。至少有8人失踪,恐怖组织“伊斯兰国”声称对爆炸负责。""" # # logging.basicConfig(level=logging.DEBUG) sentence_vec = get_sentence_embedding(sentence) assert sentence_vec is not None print(sentence_vec.shape) print(sentence_vec) print('test done!') def test_special_case(): sentence = '昨天' sentence_vec = get_sentence_embedding(sentence) return sentence_vec if __name__ == '__main__': test_special_case()
8e485f833c51fa1d0f2919072fb0025503c0eb9d
renedekluis/HBO-ICT_python_2B
/Week5/Opdracht1/main.py
1,010
3.890625
4
import sys sys.path.append("../") from BFS import * def is_connected(G): """ This function checks if graph is fully connected. Parameters ---------- G: graph Dictionary of graph connections. Returns: -------- is_connected : Boolean returns if the graph is fully connected or not. Example: -------- >>> G = {v[0]:[v[1],v[2]], v[1]:[v[0],v[2],v[3]], v[2]:[v[0],v[1],v[3]], v[3]:[v[7]], v[7]:[v[3]]} >>> False """ BFS(G,v[0]) for i in G: if i.distance == INFINITY: return False return True v = [Vertex(i) for i in range(8)] G = {v[0]:[v[4],v[5]], v[1]:[v[4],v[5],v[6]], v[2]:[v[4],v[5],v[6]], v[3]:[v[7]], v[4]:[v[0],v[1],v[5]], v[5]:[v[0],v[1],v[2],v[4]], v[6]:[v[1],v[2]], v[7]:[v[3]]} print(is_connected(G)) v = [Vertex(i) for i in range(8)] G = {v[0]:[v[4],v[5]], v[1]:[v[4],v[5],v[6]], v[2]:[v[4],v[5],v[6]], v[4]:[v[0],v[1],v[5]], v[5]:[v[0],v[1],v[2],v[4]], v[6]:[v[1],v[2]]} print(is_connected(G))
7d866e70906280b49b0707860ca6b406e799fb5e
liuminghao0830/leetcode
/609_Find_Duplicate_File_in_System.py
755
3.625
4
import collections class Solution(object): def findDuplicate(self, paths): """ :type paths: List[str] :rtype: List[List[str]] """ # Time complexity: O(m * n), m: len(paths), n: files in each paths # Space complexity: O(m * n) group = collections.defaultdict(list) for p in paths: files = p.split() for f in files[1:]: cont = f.split('(') group[cont[-1]].append(files[0] + '/' + cont[0]) return [x for x in list(group.values()) if len(x) > 1] solution = Solution() input1 = ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"] print(solution.findDuplicate(input1))
f743236c17a169f9636f8fc561c8277d01e60b57
cmcahoon01/SpaceRogue
/ships/projectile.py
1,326
3.53125
4
from ships import ship, projectile import pygame from math import sin, cos, atan2, pi, degrees, sqrt class Projectile(ship.Ship): def __init__(self, angle, allied, control): super().__init__(control) self.hitbox_radius = 3 self.angle = angle self.speed = 30 self.life_time = 50 self.allied = allied self.damage = 10 def draw(self, window, x, y): color = (0, 0, 255) if self.allied else (255, 0, 0) pygame.draw.circle(window, color, (x, y), self.hitbox_radius) def move(self): self.life_time -= 1 if self.life_time > 0: closest, distance_sqr = self.find_closest(list(self.container.contained_near().keys())) if closest is None or sqrt(distance_sqr) > self.hitbox_radius + closest.hitbox_radius: self.forward() else: if self.allied and (closest in self.ships.ally_ships or closest in self.ships.ally_projectiles): self.forward() return if not self.allied and (closest in self.ships.enemy_ships or closest in self.ships.enemy_projectiles): self.forward() return self.die() closest.hit(self) else: self.die()
50d5688036eb9886bfda2247a497693d84d64223
TeyMeiQun/DPL5211Tri2110
/lab5.4.py
506
3.734375
4
#student id:1201200152 #STUDENT NAME:TEY MEI QUN def rectangle(width,length): r_area=width*length return r_area def traingle(width,length): t_area=(width*length)/2 return t_area def main(): width=float(input("Enter width:")) length=float(input("Enter length:")) rarea=rectangle(width,length) tarea=traingle(width,length) print("Rectangle area : {:.2f}".format(rarea)) print("Triangle area : {:.2f}".format(tarea)) i=0 while(i<2): main() i+=1
d24063a833f26fca5b39341b4acc731339f702c4
gsrr/leetcode
/hackerrank/week_of_code_34/test_same_occurrence.py
993
3.609375
4
#!/bin/python import sys import collections import itertools import json def findsubsets(S,m): return set(itertools.combinations(S, m)) def same_occurrence(q, dic): cnt = 0 for s in dic.keys(): ss = json.loads(s) if ss.get(str(q[0]),0) == ss.get(str(q[1]),0): cnt += dic[s] return cnt def find_all_sarr(arr): dic = collections.defaultdict(int) cnt = 0 for i in xrange(1, len(arr) + 1): for j in xrange(0, len(arr) - i + 1): s = collections.Counter(arr[j : j + i]) if len(s.keys()) > 0: dic[json.dumps(s)] += 1 return dic if __name__ == "__main__": n, q = raw_input().strip().split(' ') n, q = [int(n), int(q)] arr = map(int, raw_input().strip().split(' ')) dic = find_all_sarr(arr) for a0 in xrange(q): x, y = raw_input().strip().split(' ') x, y = [int(x), int(y)] print same_occurrence((x,y), dic) # Write Your Code Here
b944f0d728a7d8d854a955798670d1777f050940
Codebeastdave/GUI-Calculator-project
/scratch_1.py
1,792
3.5625
4
# class Calc: def __init__(self, x, y, operator): self.minus = "-" self.plus = "+" self.x = x self.y = y self.operator = operator def add(self): assert self.operator == self.plus results = str(self.x) + self.operator + str(self.y) return "{0} = {1}\n".format(results, eval(results)) def subtract(self): assert self.operator == self.minus results = str(self.x) + self.operator + str(self.y) return "{0} = {1}\n".format(results, eval(results)) class ProcessCalc: def __init__(self): self.filename = input("filename: ") self.calculations = int(input("number of calculations: ")) self.__input_x = "" self.__input_y = "" self.__operator = "" def store(self): x = open(r"C:\Users\DAVID\.PyCharmCE2019.1\config\scratches\{0}".format(self.filename), "w") x.close() x = open(r"C:\Users\DAVID\.PyCharmCE2019.1\config\scratches\{0}".format(self.filename), "r") if x.read(): x.close() x = open(r"C:\Users\DAVID\.PyCharmCE2019.1\config\scratches\{0}".format(self.filename), "a") else: x.close() x = open(r"C:\Users\DAVID\.PyCharmCE2019.1\config\scratches\{0}".format(self.filename), "w") for loop in range(self.calculations): self.__input_x = input("x: ") self.__input_y = input("Y: ") self.__operator = input("operator") if self.__operator == "+": x.write(Calc(self.__input_x, self.__input_y, self.__operator).add()) else: x.write(Calc(self.__input_x, self.__input_y, self.__operator).subtract()) x.close() ProcessCalc().store()
4fb7bf8ff0068a78e5cdef5749544eeba8488908
HunterProgram22/Football_game_project
/Football_game_project/firstdown.py
1,094
3.53125
4
# coding: utf-8 class team(object): # Class with attribute of a team on a yardline def __init__(self, yardline = 20): self.yardline = yardline def yardchange(self, yardchange): self.yardline = self.yardline + yardchange def printyard(self): print(self.yardline) class series(team): # a series is an subclass of team to handle 4 downs to gain 10 yards def __init__(self, down = 1, yardstogo = 10): team.__init__(self) self.down = down self.yardstogo = yardstogo self.printdown() def printdown(self): print("It is %d down and %d yards to go on the %d yardline." % (self.down, self.yardstogo, self.yardline)) print("-" * 30) def downchange(self, yards = 0): if yards >= self.yardstogo: self.down = 1 self.yardstogo = 10 self.yardchange(yards) else: if self.down >= 4: gameover() self.down = self.down + 1 self.yardstogo = self.yardstogo - yards self.yardchange(yards) self.printdown() def getyardline(self): return self.yardline def gameover(): print("Turnover on downs. You lose!") exit(0)
b5e28408c67fc71edc6933233f8d3497af93c85b
kgremban/leetcode
/0066-plus-one.py
635
3.546875
4
from typing import List class Solution: def plusOne(self, digits: List[int]) -> List[int]: if digits[-1] < 9: digits[-1] += 1 return digits index = len(digits) - 1 while index >= 0: if digits[index] == 9: digits[index] = 0 index -= 1 else: digits[index] += 1 return digits return [1] + digits def main(): sol = Solution() input1 = [1, 2, 3] input2 = [4, 3, 2, 1] input3 = [1, 9, 9, 9] print(sol.plusOne(input3)) if __name__ == "__main__": main()
ec1aef56d737bbe43b2dfd4041bdf49234d209e9
nihal223/Python-Playground
/CTCI/Chapter4/01-route-between-nodes.py
1,121
3.8125
4
import unittest from collections import defaultdict class Graph(): def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph def add_edge(self, u, v): self.graph[u].append(v) def is_reachable(self, s, d): q = [] visited = [False]*self.V q.append(s) visited[s] = True while q: print(q) x = q.pop(0) if x == d: return True for y in self.graph[x]: if visited[y] == False: visited[y] = True q.append(y) return False class Test(unittest.TestCase): def test_find_route(self): g = Graph(4) g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) u = 1 v = 3 self.assertEqual(g.is_reachable(u, v), True) u = 3 v = 1 self.assertEqual(g.is_reachable(u, v), False) if __name__ == "__main__": unittest.main()
058c05d8d570e68aa48a662ff7dbe77e5831c1f7
iamreebika/Python
/Datatypes19.py
175
3.875
4
def smallest_num_in_list( list ): min = list[ 0 ] for a in list: if a < min: min = a return min print(smallest_num_in_list([12, -10, -8, 90]))
55b9acd501a97cf73865fe063f6f293c25f9c88e
salman079/python
/helloworld/test.py
691
3.671875
4
# class Point (): # def __init__(self,x=0,y=0): # self.x=x # self.y=y # def __sub__(self,other): # x=self.x+other.x # y=self.y+other.y # return Point(x,y) # p1 = Point(3,4) # p2 = Point(1,2) # result = p1-p2 # print(result.x,result.y) # class Parent (): # def __init__(self): # self.x=1 # def change(self): # self.x=10 # class Child(Parent): # def change(self): # self.x=self.x+1 # return self.x # def main(): # obj=Child() # print(obj.change()) # main() # n = 4 # n % 2 #print("hellln"+2+"s") with open("greet1.txt", "w") as f: f.write("Hello, world!!!!!!!!!!!!kkkk!!!!") a = 1/0
94f4324e61ccbecb98243a0758c862745f330aec
adnanzaidi/Image-Classification
/More_than_two_Classes/CNN_Classification_Multi_Class.py
3,404
3.671875
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 1 11:13:51 2018 @author: pranavjain This program predicts the type of flower from an image. """ # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # Initialising the CNN classifier = Sequential() # Convolution # make 32 feature detectors with a size of 3x3 # choose the input-image's format to be 64x64 with 3 channels classifier.add(Conv2D(32, (3, 3), input_shape=(128, 128, 3), activation="relu")) # Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Conv2D(32, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Flattening classifier.add(Flatten()) # Full connection classifier.add(Dense(activation="relu", units=128)) # make sure the units is equal to the number of classes classifier.add(Dense(activation="softmax", units=10)) # Compiling the CNN classifier.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy']) # use ImageDataGenerator to preprocess the data from keras.preprocessing.image import ImageDataGenerator # augment the data that we have train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) # prepare training data training_data = train_datagen.flow_from_directory('dataset/training_set', target_size = (128, 128), batch_size = 32, class_mode = 'categorical') # prepare test data test_data = test_datagen.flow_from_directory('dataset/test_set', target_size = (128, 128), batch_size = 32, class_mode = 'categorical') # finally start computation classifier.fit_generator(training_data, steps_per_epoch = (8000 / 32), epochs = 25, validation_data = test_data, validation_steps = 2000) # to make predictions import numpy as np from keras.preprocessing import image test_image = image.load_img('test.png', target_size = (128, 128)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) result = classifier.predict(test_image) # training_data.class_indices if result[0][0] == 1: prediction = 'aquilegia' elif result[0][1] == 1: prediction = 'bellflower' elif result[0][2] == 1: prediction = 'calendula' elif result[0][3] == 1: prediction = 'goldquelle' elif result[0][4] == 1: prediction = 'iris' elif result[0][5] == 1: prediction = 'leucanthemum' elif result[0][6] == 1: prediction = 'phlox' elif result[0][7] == 1: prediction = 'rose' elif result[0][8] == 1: prediction = 'rudbeckia_laciniata' elif result[0][9] == 1: prediction = 'viola' print(prediction)
c3d15173a7b98b1b05b87de66cd077fe525e2787
cloveses/myhouse
/mysimple/q4.py
877
3.9375
4
class Person: def __init__(self, name, age, vocation, salary): self.name = name self.age = age self.vocation = vocation self.salary = salary def introduce(self): print('name:', self.name) print('age:', self.age) print('vocation:', self.vocation) def income(self): print("{}'s income: {}".format(self.name, self.salary)) def tax(self): print("{}'s tax: {}".format(self.name, self.salary * 0.2)) def __add__(self, person): print("total salary:", self.salary + person.salary) self.salary += person.salary return self def __call__(self): self.introduce() if __name__ == '__main__': pa = Person('John', 32, 'teacher', 3460) pb = Person('Mary', 30, 'worker', 3580) pa.introduce() pa.income() pa.tax() pa() pc = pa + pb
9c9e87b5267682e91a27a9c8ef5e0d0b045f94f8
kwangminini/Algorhitm
/BAEKJOON/1927Solution.py
540
3.609375
4
""" 문제 제목 : 최소 힙 문제 난이도 : 하 문제 유형 : 힙, 자료구조 최소 힙의 기본적인 기능을 구현 heapq 라이브러리를 이용하면 간단히 힙 구현 가능 배열로 하니 시간초과 -> 최소 힙 """ import heapq n=int(input()) heap=[] result=[] for _ in range(n): data = int(input()) if data == 0: if heap: result.append(heapq.heappop(heap)) else: result.append(0) else: heapq.heappush(heap,data) for data in result: print(data)
6b389b6f90bde59b27becfae1a69eb94e92d90c9
afonso-21902703/pw-ficha3
/pw-python-03-main/exercicio_1/analisa_ficheiro/acessorio.py
539
3.703125
4
def pede_nome()->"String": while True: teclado = input('Insira o nome do ficheiro: ') try: open(teclado) for n in teclado: if n =='.': tecladosplit = teclado.split('.') if tecladosplit[1] == 'txt': return tecladosplit[0] exit() except IOError: print('não existe') def gera_nome(): nome_txt = pede_nome() return(nome_txt + '.json') pede_nome()
2c258cabcf17d8cc9ce3c9b896b8dc9d5dfd79ef
StefanDimitrovDimitrov/Python_Fundamentals
/Python_Fundamentals/Fundamentals level/13.Exaam prep/05_exam.py
640
3.859375
4
guest_singer_price = int(input()) command = "" cover = 0 total_guest = 0 is_restauran_is_full = False while not is_restauran_is_full: command = input() if command == "The restaurant is full": is_restaurant_is_fill = True break else: num_guest = int(command) total_guest += num_guest if num_guest < 5: cover += num_guest * 100 else: cover += num_guest * 70 if cover >= guest_singer_price: print(f"You have {total_guest} guests and {cover - guest_singer_price} leva left.") else: print(f"You have {total_guest} guests and {cover} leva income, but no singer.")
a44dbfdfeff0b83a98b784ae9b5a4671bbda19ba
JakeNTech/GCSE-Python-Code
/Input/Welcome.py
101
3.828125
4
name = input("What is your name, please? ").title() print("Hello", name ,"welcome to the doctors!!")
ee8af45c88422cbce4b651fa6aa1cb20c114fcc2
swapnil-sat/webwing-code
/ManthanBore/Flow Control/Iterative Statement/using_for.py
826
4.0625
4
# l=[1,2,3,4,5] # print(l) # for i in l : # print(i) # l=[1,2,3,4,5] # print(l) # for i in l : # if i % 2 == 0 : # print(i,"is even number") # for i in range (1,10,1): # print(i) # for x in range (1,10,2) : # print(x) # for i in range (20,0,-1) : # print(i) # for x in range (20,0,-3) : # print(x) # l=[1,2,3,4,5,6,7] # print(l) # for i in l [:3] : # print(i) # for i in l [1:3] : # print(i) # for i in l [2:3] : # print(i) # for i in l [2:] : # print(i) # for i in l [:: -1] : # print(i) # for i in l [:: -3] : # print(i) # s="welcome webwing" # for x in s: # print(x) # x=["Have","A","Nice","Day"] # for i in x: # print(i) # Nested in for loop:- # x=["Have","A","Nice","Day"] # for word in x: # for character in word: # print(character)
fc22320009d7508bf73cfb624f78bc0f4a008513
AbhinavTC/My-python-programs
/add and multipy numbers.py
378
4.125
4
# function to add two numbers def add_numbers(num1, num2): return num1 + num2 # function to multiply two numbers def multiply_numbers(num1, num2): return num1 * num2 number1 = 5 number2 = 30 sum_result = add_numbers(number1, number2) print("Sum is", sum_result) product_result = multiply_numbers(number1, number2) print("Product is", product_result)
81d37b3bbaaefe8e1c67b2b0b278abbac4db5847
Preetpalkaur3701/python-programmes
/primeinterval.py
386
3.90625
4
lower = input("first number") upper= input("secong number") check=False print ("prime numbersbetween",lower, "and",upper, "are:") for num in range(lower, upper+1): if num > 1: for i in range(2,num): if (num % i) == 0: check=True if check == False: print num check=False """ if num > 1: for i in range(2,num): if (num % i) == 0: break else: print (num) """
3f435e4878ea28ef2aeb00730ba57034c8511839
hejazizo/stackoverflow-bot
/send_email.py
1,128
3.671875
4
"""The first step is to create an SMTP object, each object is used for connection with one server.""" import smtplib from validate_email import validate_email import emoji def send_mail(receiver, randnum): is_valid = validate_email(receiver) if not is_valid: return "Invalid email address" elif is_valid: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() flag = server.verify(receiver) print(flag) #Next, log in to the server passwd = 'ap_project' sender = "aptelegrambot@gmail.com" server.login(sender, passwd) #Send the mail email_content = """Welcome to AUT Advanced Programming Forum!\nYour login code: {}""".format(randnum) msg = "\r\n".join([ "From: {0}".format(sender), "To: {0}".format(receiver), "Subject: {0}".format('Advanced Programming Course BOT Login'), "", email_content ]) server.sendmail(sender, receiver, msg) return emoji.emojize(':key: Enter the confirmation code sent to:\n:e-mail: ') + receiver
5a8729215c8f23ba1de3b3935dce950df42aaf63
chuzhinoves/DevOps_Python_HW3
/3.py
292
4
4
""" Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. """ def my_func(a, b, c): return sum([a, b, c]) - min([a,b,c])
32041aaefd77c794dbdaee692f199ce82ccb3a71
manjumugali/Python_Programs
/ObjectOrientedPrograms/Inventory.py
986
3.75
4
""" ****************************************************************************** * Purpose: Reading JSON File * * @author: Manjunath Mugali * @version: 3.7 * @since: 27-01-2019 * ****************************************************************************** """ import json from OOPS_Utility.Test_Oops_Utility import InventoryDetails class Inventory: try: with open("Inventory.json", "r") as file: # open Json file json_file = file.read() # read json file file.close() # close file items = json.loads(json_file) # convert json object to python object u = InventoryDetails() # creating object of InventoryDetails class u.inventoryDetails(items) # invoking inventoryDetails class function except FileNotFoundError: print("File not Found") if __name__ == "__main__": Inventory()
4499a7dc3f8ff6bf7a769ef1134293b24be3c26a
rv-nataraj/myprograms
/prog16.py
122
4
4
n=input("Enter a value : ") n=int(n) sum=0 for x in range(1,n,1): sum=sum+x print("Sum of first ",n," numbers is ",sum)
55db07ef1eae861e716bde77d0c564237dfd8e5d
flaviogpacheco/python-520
/aula1_3.py
419
3.9375
4
#!/usr/bin/python3 # ==, !=, <, <=, >, >= # Se o numero resultado da soma for maior 100 # Escrever: "Que numero grandão..." # Caso contrário: "Que numero pequeno..." n1 = int(input('Digite o primeiro número: ')) n2 = int(input('Digite o segundo número: ')) n3 = n1 + n2 print(n3) if n3 > 100: print('Que número grandão...') elif n3 == 50: print('...') else: print('Que número pequeno...')
092731e968adb8cda2fa5ffb12e4b8acc4295f40
sinegami301194/Python-HSE
/6 week/mergeLists.py
488
3.78125
4
import random A = list(map(int, input().split())) B = list(map(int, input().split())) def quicksort(nums): if len(nums) <= 1: return nums else: q = random.choice(nums) l_nums = [n for n in nums if n < q] e_nums = [q] * nums.count(q) b_nums = [n for n in nums if n > q] return quicksort(l_nums) + e_nums + quicksort(b_nums) def merge(A, B): C = A + B return C C = merge(A, B) B = quicksort(C) print(*B, end='')
33402df1245439cecdcee3555d575ba4e21cfe19
sichkar-valentyn/Working_with_files_in_Python
/Files_in_Python.py
5,364
3.984375
4
# File: Files_in_Python.py # Description: Examples on how to work with files in Python # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 Valentyn N Sichkar # github.com/sichkar-valentyn # # Reference to: # [1] Valentyn N Sichkar. Examples on how to work with files in Python // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Working_with_files_in_Python (date of access: XX.XX.XXXX) # Possible modes to open file with: # r (read) - open for reading (by default) # w (write) - open to write, all information in the file will be deleted # a (append) - open to write, writing will be done at the end # b (binary) - open in a binary mode # t (text) - open in the text mode (by default) # r+ - open for reading and writing # w+ - open for reading and writing, all information will be deleted # Opening file for reading f = open('test.txt', 'r') # Reading first 5 symbols from the file x = f.read(5) print(x) # Reading file till the end y = f.read() print(y) # Showing the y as the representation of line type print(repr(y)) # Method to split the information from the file to the different lines y = y.splitlines() print(y) # Closing the file f.close() # Opening file for reading f = open('test.txt', 'r') # Reading just one line from the file z = f.readline() z = z.rstrip() # Deleting the right symbol to move for the next line print(repr(z)) # Reading the second line z = f.readline().strip() # Another way how to delete symbol to move for the next line print(repr(z)) # Closing the file f.close() # Opening file for reading f = open('test.txt', 'r') # Reading lines one by one using loop for line in f: line = line.rstrip() print(repr(line)) # When everything is read already from the file # The last try will give the empty string x = f.read() print(repr(x)) # Closing the file f.close() # Opening file for writing # If the file doesn't exist, it will be created f = open('test_w.txt', 'w') # Writing the line into the file f.write('Hello!\n') # We use here the \n to move to the next line f.write('World!\n\n') # Another way to write lines in the file in separate rows lines = ['Line1', 'Line2', 'Line3'] content = '\n'.join(lines) # We use .join and say that symbol \n has to be places between lines f.write(content) # Closing the file f.close() # Opening file for appending # If the file doesn't exist, it will be created f = open('test_a.txt', 'a') f.write('Hello!\n') # Each time we will run this code it will append new info in the file # Closing the file f.close() # Another and recommended way to open file and close it automatically with open('test.txt') as f: for line in f: line = line.rstrip() print(line) # Here file will be already closed # It is possible to open several files at the same time with open('test.txt') as f, open('test_copy.txt', 'w') as w: for line in f: w.write(line) # Copying all info from file f to w # Implementing the task # there is a file with some amount of lines # It is needed to create the copy of this file but with opposite order of the lines in it with open('test.txt') as f, open('test_copy.txt', 'w') as w: lst = [] # Reading all the lines and putting them into the list for line in f: lst += [line.rstrip()] # Reordering the elements of the list in reverse direction lst = lst[::-1] # Joining all the elements from the list with the symbol \n content = '\n'.join(lst) # Writing the information into the copy file w.write(content) # Using os and os.path while working with files import os import os.path # Showing all files and directories in the current folder print(os.listdir()) # Getting the current directory print(os.getcwd()) # Changing the current directory os.chdir('tensorflow') print(os.getcwd()) # Changing back the directory in one level upper os.chdir('..') print(os.getcwd()) # Showing the files in the specific directory print(os.listdir('tensorflow')) # Checking if the file exists print(os.path.exists('test.txt')) print(os.path.exists('tensorflow')) # Checking if the path is the file print(os.path.isfile('test.txt')) print(os.path.isfile('tensorflow')) # Checking if the file is the directory print(os.path.isdir('test.txt')) print(os.path.isdir('tensorflow')) # Getting the absolute path to the file print(os.path.abspath('test.txt')) # Using os.walk for going through all directories and files in them from thr current directory for current_dir, dirs, files in os.walk('.'): # Fullstop here means the current directory print(current_dir, dirs, files) # Using shutil for copying the files and directories import shutil # Copying the file shutil.copy('test.txt', 'test_test.txt') # Copying the directory #shutil.copytree('tensorflow', 'tensorflow_copy') # Implementing the task # Reading the directory and all sub-directories # And showing only that directories which contain the .py files # Also, sorting the results in lexicographical order lst = [] for current_dir, dirs, files in os.walk('main'): # You can use your own directory or any other for x in files: if '.py' in x: lst += [current_dir] break # Sorting the resulted list lst.sort() # Preparing data for writing content = '\n'.join(lst) # Writing in the file f = open('results.txt', 'w') f.write(content) f.close()
c015680a51cbe0d087fb805a62a12365c797a8c8
larryworm1127/tic-tac-toe-python
/ttt_game/ttt_computer.py
1,575
3.765625
4
""" Mini-max Tic-Tac-Toe Player """ from typing import Tuple from .ttt_board import * # Scoring values SCORES = {PLAYERX: 1, DRAW: 0, PLAYERO: -1} def get_move(board: TTTBoard, player: int) -> Tuple[int, int]: """Make a move on the board. Returns a tuple with two elements. The first element is the score of the given board and the second element is the desired move as a tuple, (row, col). """ return alpha_beta_pruning_move(board, player, -2, 2)[1] def alpha_beta_pruning_move(board: TTTBoard, player: int, alpha: int, beta: int) -> Tuple[int, Tuple[int, int]]: """A helper function for mm_move to find the best move. Returns the score and best move for the current state of the board. """ # initialize local variables other_player = switch_player(player) best_move = (-1, -1) best_score = -2 # base case if board.check_win() is not None: return SCORES[board.check_win()], best_move # recursive case for move in board.get_empty_squares(): trial = board.clone() trial.move(move[0], move[1], player) score = alpha_beta_pruning_move(trial, other_player, -beta, -max(alpha, best_score))[0] alpha = score * SCORES[player] if alpha == 1: return score, move elif alpha > best_score: best_score = alpha best_move = move if best_score >= beta: break return best_score * SCORES[player], best_move
285915d6bbfc1abace271907ca5e79581e09f8d9
dimmxx/codecademy
/FileIO_WithAs.py
176
3.59375
4
with open("text.txt", "w") as textfile: textfile.write("Success!") with open("text.txt", "w") as my_file: if not my_file.closed: my_file.close() my_file.write("OK")
0f969719b70c5aed7ca258b0475bd363209f3174
Aasthaengg/IBMdataset
/Python_codes/p03796/s491879310.py
237
3.6875
4
#-*-coding:utf-8-*- import sys input=sys.stdin.readline def main(): n = int(input()) mod = 10**9+7 power=1 for i in range(1,n+1): power*=i power%=mod print(power) if __name__=="__main__": main()
3f19872efe0ba6446572452c7aab7f33ee8d4d37
gabastil/reports
/pyExperiments/get_pass.py
545
3.53125
4
from Tkinter import * def getpwd(): password='' root=Tk() pwdbox=Entry(root, show='*') def onpwdentry(evt): password=pwdbox.get() root.destroy() def onokclick(): password=pwdbox.get() root.destroy() Label(root, text='Password').pack(side='top') pwdbox.pack(side='top') pwdbox.bind('<Return>', onpwdentry) Button(root, command=onokclick, text='OK').pack(side='top') root.mainloop() return password if __name__ == "__main__": pwd = getpwd() print(pwd)
ad50aaf1365bea9d1a4f2eb42bd51b29d7dcbdf9
bboyle34/PythonBeginnerProgramming
/ch6-examples/UsefulTurtleFunctions.py
1,961
4.34375
4
import turtle # Draw a line from (x1, y1) to (x2, y2) def drawLine(x1, y1, x2, y2): turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) # Write a text at the specified location (x, y) def writeText(s, x, y): turtle.penup() # Pull the pen up turtle.goto(x, y) turtle.pendown() # Pull the pen down turtle.write(s) # Write a string # Draw a point at the specified location (x, y) def drawPoint(x, y): turtle.penup() # Pull the pen up turtle.goto(x, y) turtle.pendown() # Pull the pen down turtle.begin_fill() # Begin to fill color in a shape turtle.circle(3) turtle.end_fill() # Fill the shape # Draw a circle at centered at (x, y) with the specified radius def drawCircle(x, y, radius): turtle.penup() # Pull the pen up turtle.goto(x, y - radius) turtle.pendown() # Pull the pen down turtle.circle(radius) # Draw a rectangle at (x, y) with the specified width and height def drawRectangle(x, y, width, height): turtle.penup() # Pull the pen up turtle.goto(x + width / 2, y + height / 2) turtle.pendown() # Pull the pen down turtle.right(90) turtle.forward(height) turtle.right(90) turtle.forward(width) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.forward(width) def menu(): print("Your options: \n(l)ine \n(t)ext - \n(p)oint - \n(c)ircle - \n(r)ectangle") choice = input("Choose one of the following: ") main() def main(): menu() if choice[0].upper() == "L": drawLine() elif choice[0].upper() == "T": writeText() elif choice[0].upper() == "P": drawPoint() elif choice[0].upper() == "C": drawCircle() elif choice[0].upper() == "R": drawRectangle() else: print("Please enter a valid option.") menu() main()
16fa481e0b0870cb188c2037f33998716719c2a7
Akagi201/learning-python
/misc/list.py
230
4.5625
5
#!/usr/bin/env python # Python 3: List comprehensions fruits = ['Banana', 'Apple', 'Lime'] loud_fruits = [fruit.upper() for fruit in fruits] print(loud_fruits) # List and the enumerate function print(list(enumerate(fruits)))
9facb78e4df94052f0cf7bc3ac339194193d70c8
Streamline27/TSI-Python-LabWorks
/LabTasks/Task4.py
644
4.1875
4
__author__ = 'Vladislav' # Some types in python are mutable some are not. # this is the only way to change variable inside function. def mutable_pow(a): a[0] **= 2 print "Inside mut_pow "+ str(a[0]) # In this way variable wont be mutated # but will be returned. # This is a nice way to go! def function_pow(a): a **= 2 print "Inside function_pow " + str(a) return a**2 # Entering data i = input("Enter number: ") # Demo of call by value function_pow(i) print "After by value: "+str(i) # Demo of only way to mutate passed int mutable_list = [i] mutable_pow(mutable_list) print "After by list: "+ str(mutable_list[0])
ee3b8fd6e99cedaeb2e322bbb7b94ca8e2cfda34
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_4.py
907
4.40625
4
#!/usr/bin/env python3 """Write a DoBreakfast function that takes five arguments: meat, eggs, potatos, toast, and beverage. The default meat is bacon, eggs are over easy, potatos is hash browns, toast is white, and beverage is coffee. The function prints: Here is your bacon and scrambled eggs with home fries and rye toast. Can I bring you more milk? Call it at least 3 different times, scrambling the arguments. """ def DoBreakfast(meat="bacon", eggs="over easy", potatos="hash browns", toast="white", beverage="coffee"): print ("Here is your %s and %s eggs with %s and %s toast." % ( meat, eggs, potatos, toast)) print ("Can I bring you more %s?" % beverage) def main(): DoBreakfast() DoBreakfast("ham", "basted", "cottage cheese", "cinnamon", "orange juice") DoBreakfast("sausage", beverage="chai", toast="wheat") main()
d88c8949572368324be28df108c36d3482e17da2
zheyuanKelvin/leetcode_template
/binary_search.py
485
4.03125
4
#binary search: ''' Points: update start as mid + 1 return start at the end f(mid): three sum questions, 'sum == target' g(mid): usually 'nums[mid] > target' ''' def binary_search(start, end): while start < end: mid = start + (end - start) // 2 if f(mid): #optional return mid if g(mid): end = mid # new range, [start, mid) else: start = mid + 1 # new range [mid+1, end) return start # or not found
503376e36f2b23c9bda0a60c15746a38192c0afe
gulci-poz/lpthw
/ex1.py
6,468
4.09375
4
# -*- coding: utf-8 -*- # linia z kodowaniem musi być pierwsza, nawet przed import import math print "Hello World!" print "Hello Again" print "I like typing this." print "This is fun." print "Yay! Printing." print "I'd much rather you 'not'." print 'I "said" do not touch this.' print u"Sebastian Gulczyński" print u"ęóąśłżźćń" # dodatkowo trzeba użyć u przed stringiem, który będzie zawierał znak z Unicode # nie ma komentarzy wieloliniowych print "addition ", 2 + 2 print "subtraction ", 4 - 3 # trzeba używać liczb w zapisie float print "division ", 2.0 / 4.4 # dzielenie obcina część ułamkową print "division integer ", 7 / 4 print "multiplication ", 4 * 5 print "modulus ", 21 % 6 print "less than ", 3 < 4 print "greater than ", 3 > 4 print "less-than-equal ", 5 <= 6 print "greater-than-equal ", 5 >= 6 print "a few operators ", 2 + 3 > 6 * 7 # PEMDAS - Parentheses, Exponents, Multiplication, Division, Addition, Subtraction - kolejność działań w Pythonie cars = 100.0 # ilość z kierowcami czy bez? space_in_a_car = 4.0 drivers = 31.0 passengers = 90.0 cars_not_driven = cars - drivers cars_driven = drivers # liczymy bez odejmowania kierowców carpool_capacity = cars_driven * space_in_a_car # liczymy bez odejmowania kierowców average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car." my_name = u"Sebastian Gulczyński" # w ten sposób unikamy automatycznych spacji w print # działa podsawienie zmiennej, również z Unicode print "Hi %s!" % my_name my_age = 31 my_height = 190 my_weight = 81 my_eyes = "blue" my_teeth = "yellow" my_hair = "blond" my_height_inches = my_height / 2.54 # avoirdupois system, system wag - 1 funt to 16 uncji my_weight_pounds = 81 / 0.45359237 # dla podania kilku wartości używamy nawiasu print "He's got %s eyes and %s hair." % (my_eyes, my_hair) # używamy %d dla int, można używać działań w cześci formatowania print "If I add %d, %d and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight) print "My height in inches is %f." % my_height_inches print "My weight in pounds is %f." % my_weight_pounds # %e i %E dają zapis wykładniczy (lowercase, uppercase) # istnieje też %g i %G # forma alternatywna wymusza zapis dziesiętny # normalna forma również daje zapis dziesiętny, mimo braku części dziesiętnej # precyzja wynosi domyślnie 6 cyfr sample_float = 5 print "Sample float e %f." % sample_float print "Sample float E %F." % sample_float # %r konwertuje każdy obiekt Pythona za pomocą repr() # %r niby do debuggowania (r - representation) # %s konwertuje każdy obiekt Pythona za pomocą str() # repr() zwraca string z reprezentacją obiektu do wydruku, tę samą wartość zwracają konwersje # można przedefiniować dla danego obiektu __repr()__ # str() zwraca string "nicely printable", nie zawsze usiłuje zwrócić string akceptowalny przez eval() # dzięki %r możemy uzyskać w stringu wszystkie cyfry części dziesiętnej print "My weight in pounds (r) is %r." % my_weight_pounds # %f ma domyślnie precyzję 6, %s "ładnie formatuje" do 8 cyfr, zaokrąglając przy tym, %r daje nam wszystkie cyfry (na pewno precyzja jest różna dla różnych liczb, które przetestowałem) print "My weight in pounds (s) is %s." % my_weight_pounds print "Round pi", round(3.14) print "Round number", round(3.99) print "Math pi f %f" % math.pi print "Math pi s %s" % math.pi print "Math pi r %r" % math.pi hipy = "hi from py" hiphp = "hi from php" # %r dla stringa daje single quote print "gulci says %r" % hipy # %s nie daje single quote print "gulci also says %s" % hiphp # możemy dodać single quote print "gulci also says '%s'" % hiphp # formatowanie można zapisać pod stringiem # escape znaku % robimy %% hilarious = False joke_evaluation = "Superdowcip! %r" joke_evaluation_format = "Superdowcip 5%%! %r" % hilarious print joke_evaluation % hilarious print joke_evaluation_format # bez formatowania dostajemy każdy znak jako element stringa print joke_evaluation left = "leftist" right = "rightous" # konkatenacja, bez spacji print left + right # drukowanie znaku daną ilość razy print "=" * 30 end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # przecinek sprawia, że zostajemy na tej samej linii print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 + end12 formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % ("one", "two", "three", "four") print formatter % (True, False, False, True) print formatter % (formatter, formatter, formatter, formatter) # string zawierający ' jest wypisywany w "" # tab nie ma znaczenia print formatter % ( "I had this thing.", "That you could type up right", "But it didn't sing.", "So I said goodnight." ) # %s poprawnie wyświetla znaku unicode print "%s" % u"Sebastian Gulczyński" # dodając u do stringa, mówimy, że mamy tam jakiś znak unicode # ale cały ten string zostaje "przekazany" do %r, dlatego mamy wypisane \u0144 # %r interesują literały print "%r" % "Sebastian Gulczyński" print "%r" % u"Sebastian Gulczyński" days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print "Here are the days: ", days print "Here are the months: ", months print u"""(pierwsza pusta linia) możemy wydrukować dowloną ilość linii (ostatnia pusta linia)""" # \n nie działa na %r, dostajemy literały print "linia%r" % "\nnowa linia" print "double quote escape \"" print "single quote escape \'" print "\ttab escape" print "backslash escape \\" # dzwonek ASCII # print "\a" print '''(triple single begin) "bla bla bla" (triple single end)''' print "-" * 73 print "|%s\t|%d\t|%d\t|%d\t|%s\t|%s\t|%s\t|" % (my_name, my_age, my_weight, my_height, my_eyes, my_teeth, my_hair) print "-" * 73 print "single quote r %r" % "\'" print "double quote r %r" % "\"" print "single quote s %s" % "\'" print "double quote s %s" % "\"" # alternatywnie ["/", "-", "|", "\\", "|"] # taby mają znaczenie while True: for i in ["|", "/", "-", "\\", "|", "/", "-", "\\"]: # bez przecinka będzie nowa linia print "%s\r" % i,
83ea96f0e8792231d2532175a4b553e32b8b6f1c
ChicksMix/programing
/unit 7/hickshouse.py
1,796
3.984375
4
import turtle def main(): t=turtle.Turtle() t.hideturtle() roof(t) house(t) door(t) windows(t) def roof(t): t.pencolor("black") t.pensize(2) t.fillcolor("brown") t.up t.begin_fill() t.goto(-100,0) t.down() t.goto(100,0) t.goto(0,150) t.goto(-100,0) t.end_fill() t.up() #Roof is a triangle with black outline and brown fill. The base of the triangle has a width of 200 pixels and the height is 150 pixels return t def house(t): t.pencolor("black") t.pensize(2) t.fillcolor("red") t.up t.begin_fill() t.goto(-80,0) t.down() t.goto(80,0) t.goto(80,-200) t.goto(-80,-200) t.goto(-80,0) t.end_fill() t.up() #House is a black outlined red filled rectangle that has a height of 200 pixels and a width of 160 pixels. return t def door(t): t.pencolor("black") t.pensize(2) t.fillcolor("blue") t.up t.begin_fill() t.goto(25,-200) t.down() t.goto(25,-125) t.goto(-25,-125) t.goto(-25,-200) t.goto(25,-200) t.end_fill() t.up() #Door is a black outlined blue filled rectangle with a width of 50 pixels and height of 75 pixels return t def windows(t): t.pencolor("black") t.pensize(2) t.fillcolor("white") t.up t.begin_fill() t.goto(30,-30) t.down() t.goto(70,-30) t.goto(70,-70) t.goto(30,-70) t.goto(30,-30) t.end_fill() t.up() t.pencolor("black") t.pensize(2) t.fillcolor("white") t.up t.begin_fill() t.goto(-30,-30) t.down() t.goto(-70,-30) t.goto(-70,-70) t.goto(-30,-70) t.goto(-30,-30) t.end_fill() t.up() #Windows are black outline white filled squares with a width of 50 pixels. return t main()
22e8fee1b519831e83455f6505c1d90a1fa37a6d
vikasbaghel1001/Hactoberfest2021_projects
/python project/Binary_search.py
424
3.765625
4
def search(a:list,element,x,y): mid=y+1//2 if(a[mid]==element): return mid elif(element>a[mid]): return search(a,element,mid+1,y) elif(element<a[mid]): return search(a,element,0,mid-1) else: return "not found" import random L1=[x for x in range(1,90)] element=random.randint(1,90) print(element) print(search(L1,element,0,len(L1)))
769b8ad326294ddf17b174be872d2a2885bdd24e
mohnoor94/ProblemsSolving
/src/main/python/staircase.py
3,075
4.03125
4
def number_of_ways(n): """ *** 'Amazon' interview question *** Staircase problem with allowed steps of only 1 or 2 at a time. Problem statement and more details: https://youtu.be/5o-kdjv7FD0 """ if n == 0 or n == 1: return 1 result = s1 = s2 = 1 for i in range(2, n + 1): result = s1 + s2 s1 = s2 s2 = result return result def number_of_ways_general(n, steps): """ *** 'Amazon' interview question *** Staircase problem with allowed steps given in a set. Problem statement and more details: https://youtu.be/5o-kdjv7FD0 """ if n == 0: return 1 nums = [0] * (n + 1) nums[0] = 1 for i in range(1, n + 1): total = 0 for j in steps: if i - j >= 0: total += nums[i - j] nums[i] = total return nums[n] if __name__ == '__main__': print(0, "==>", number_of_ways(0)) print(1, "==>", number_of_ways(1)) print(2, "==>", number_of_ways(2)) print(3, "==>", number_of_ways(3)) print(4, "==>", number_of_ways(4)) print(5, "==>", number_of_ways(5)) print(6, "==>", number_of_ways(6)) print(7, "==>", number_of_ways(7)) print("********************") print(0, ",", {1, 2}, "==>", number_of_ways_general(0, {1, 2})) print(1, ",", {1, 2}, "==>", number_of_ways_general(1, {1, 2})) print(2, ",", {1, 2}, "==>", number_of_ways_general(2, {1, 2})) print(3, ",", {1, 2}, "==>", number_of_ways_general(3, {1, 2})) print(4, ",", {1, 2}, "==>", number_of_ways_general(4, {1, 2})) print(5, ",", {1, 2}, "==>", number_of_ways_general(5, {1, 2})) print(6, ",", {1, 2}, "==>", number_of_ways_general(6, {1, 2})) print(7, ",", {1, 2}, "==>", number_of_ways_general(7, {1, 2})) print("********************") print(0, ",", {1, 2, 5}, "==>", number_of_ways_general(0, {1, 2, 5})) print(1, ",", {1, 2, 5}, "==>", number_of_ways_general(1, {1, 2, 5})) print(2, ",", {1, 2, 5}, "==>", number_of_ways_general(2, {1, 2, 5})) print(3, ",", {1, 2, 5}, "==>", number_of_ways_general(3, {1, 2, 5})) print(4, ",", {1, 2, 5}, "==>", number_of_ways_general(4, {1, 2, 5})) print(5, ",", {1, 2, 5}, "==>", number_of_ways_general(5, {1, 2, 5})) print(6, ",", {1, 2, 5}, "==>", number_of_ways_general(6, {1, 2, 5})) print(7, ",", {1, 2, 5}, "==>", number_of_ways_general(7, {1, 2, 5})) print("********************") print(0, ",", {1, 3, 5}, "==>", number_of_ways_general(0, {1, 3, 5})) print(1, ",", {1, 3, 5}, "==>", number_of_ways_general(1, {1, 3, 5})) print(2, ",", {1, 3, 5}, "==>", number_of_ways_general(2, {1, 3, 5})) print(3, ",", {1, 3, 5}, "==>", number_of_ways_general(3, {1, 3, 5})) print(4, ",", {1, 3, 5}, "==>", number_of_ways_general(4, {1, 3, 5})) print(5, ",", {1, 3, 5}, "==>", number_of_ways_general(5, {1, 3, 5})) print(6, ",", {1, 3, 5}, "==>", number_of_ways_general(6, {1, 3, 5})) print(7, ",", {1, 3, 5}, "==>", number_of_ways_general(7, {1, 3, 5})) print("********************")
59a574c8ed8c2475affcde251e4417aad71eada6
akraturi/sem6
/nft/percept.py
1,550
3.53125
4
import math import time def activation_function(x): if x >= 0: return 1 else: return 0 def sigmoidal_activation_function(x): return 1/(1+math.exp(-x)) w1 = -0.1 w2 = 0.1 bias = 0.3 learning_rate = 0.1 patterns = [] gate = int(input("Press 1 for AND\n Press 2:NAND\n Press 3:OR:")) switcher = { 1:"and_inp", 2:"nand_inp", 3:"or_inp" } inp_file = switcher.get(gate,-1) if inp_file == -1: print("Invalid Choice.. Existing") exit() with open(inp_file,"r") as inp: for line in inp: x1,x2,t = list(map(int,line.split())) patterns.append((x1,x2,t)) count=0 iteration = 0 while True: iteration = iteration+1 print("FOR ITERATION#"+str(iteration)) for pattern in patterns: a,b,t = pattern yin = round(a*w1+b*w2+bias,2) yout = activation_function(yin) # yout = sigmoidal_activation_function(yin) error = (t - yout) if error != 0: w1 = (w1 + round(learning_rate*error*a,2)) w2 = (w2 + round(learning_rate*error*b,2)) bias = (bias + round(learning_rate*error,2)) else: count = count+1 print("Pattern "+str(pattern)) print("Yinp:"+str(yin)) print("w1:"+str(w1)+" w2:"+str(w2)+" b:"+str(bias)) time.sleep(2) if count == len(patterns): break else: count = 0 print("Final weights are") print("w1:"+str(w1)+" w2:"+str(w2)+" b:"+str(bias))
0fc094f5a94ee3477608557169596f5018f3fd6f
Kristyli2009/MatrixMultiplication
/codes/RegInputFromFile.py
3,268
4.125
4
#!/usr/bin/env python3 import time import csv def input_data(): """ A function to read data from a file and store them in a list and return it""" numbers = [] data_file = input("Please enter the file name with extension: ") with open(data_file) as file: for line in file: numbers.append(line.strip().split()) return numbers def convert_str_to_int(numbers, matrix_a, matrix_b, size): """A function to convert the data of string into the data of integer, then split into two matrices""" for i in range(size): for j in range(size): matrix_a[i][j] = int(numbers[i + 1][j]) matrix_b[i][j] = int(numbers[size + i + 1][j]) def multiply_two_matrices(matrix_a, matrix_b, size, m_times, a_times): """A function to multiply two matrices and store the result into another list, and calculate the number of multiplication operation and addition operation""" matrix_c = [[0 for i in range(size)] for j in range(size)] for i in range(size): for j in range(size): total = matrix_a[i][0] * matrix_b[0][j] m_times = m_times + 1 for k in range(1, size): total = total + matrix_a[i][k] * matrix_b[k][j] m_times = m_times + 1 a_times = a_times + 1 matrix_c[i][j] = total return matrix_c, m_times, a_times def output_data_into_file(matrix_c, m_times, a_times, r_time): """ A function to output the data into a file""" with open("RegularOutput.txt", "a") as outfile: outfile.write("The size of matrix is " + str(matrix_size) + ".\n\n") for i in matrix_c: for j in i: outfile.write(str(j) + " ") outfile.write("\n") outfile.write("The number of multiplication operation is " + str(m_times) + ".\n") outfile.write("The number of addition operations is " + str(a_times) + ".\n") outfile.write("The total number of operations is " + str(m_times + a_times) + ".\n\n") outfile.write("The running time is " + str(r_time) + ".\n\n") outfile.write("*" * 200 + "\n\n") def out_data_to_csv_file(size, m_times, a_times, r_time): """ A function to output the data about the number of multiplication operations and addition operations and running time""" with open('RegularOutput.csv', 'a') as file: the_writer = csv.writer(file) the_writer.writerow([size, m_times, a_times, m_times + a_times, r_time]) if __name__ == '__main__': data = input_data() matrix_size = int(data[0][0]) matrix_A = [[0 for i in range(matrix_size)] for j in range(matrix_size)] matrix_B = [[0 for i in range(matrix_size)] for j in range(matrix_size)] convert_str_to_int(data, matrix_A, matrix_B, matrix_size) M_times = 0 A_times = 0 start = time.time() matrix_C, M_times, A_times = multiply_two_matrices(matrix_A, matrix_B, matrix_size, M_times, A_times) end = time.time() running_time = end - start output_data_into_file(matrix_C, M_times, A_times, running_time) out_data_to_csv_file(matrix_size, M_times, A_times, running_time) print("Please check the output file: RegularOutput.txt or RegularOutput.csv for the result!")
08010dc7047c15c6c0fe43803392c27fc312cbbf
kpratapaneni/Masters_Classwork
/AI_480/hw7/agents.py
2,333
4.15625
4
from abc import abstractmethod class Agent(object): def __init__(self, name): self.name = name def __str__(self): return "Agent_" + self.name @abstractmethod def will_buy(self, value, price, prob): """Given a value, price, and prob of Junk, return True if you want to buy it; False otherwise. Override this method.""" class HalfProbAgent(Agent): """Buys if the prob < 0.5 no matter what the value or price is""" def will_buy(self, value, price, prob): return (prob < 0.5) class RatioAgent(Agent): """Buys if the ratio of the price to value is below a specified threshold""" def __init__(self, name, max_p_v_ratio): super(RatioAgent, self).__init__(name) self.max_p_v_ratio = max_p_v_ratio def will_buy(self, value, price, prob): return (price/value <= self.max_p_v_ratio) class BuyAllAgent(Agent): """Simply buys all products""" def will_buy(self, value, price, prob): return True class StudentAgent(Agent): """The Student Agent""" def __init__(self, name): super(StudentAgent, self).__init__(name) self.count = 0 self.expected_avg_profit = None def meu(self, value, price, prob, is_junk, shall_buy): # junk false and buying if is_junk == False and shall_buy == True: return value # junk true and buy elif is_junk == True and shall_buy == True: return -(value+price) # junk true and buy elif is_junk == True and shall_buy == False: return price elif is_junk == False and shall_buy == False: return -value def will_buy(self, value, price, prob): # value - selling price # price - cost price # profit = sp - cp (i.e. value-price) # CHANGE THIS. IMPLEMENT THE BODY OF THIS METHOD not_junk_prob = 1 - prob buying_prob = (prob * self.meu(value, price, prob, True, True)) + (not_junk_prob * self.meu(value, price, prob, False, True)) not_buying_prob = (prob * self.meu(value, price, prob, True, False)) + (not_junk_prob * self.meu(value, price, prob, False, False)) if(buying_prob > not_buying_prob): return True else: return False
9a42b1a4a7a2eaa90fcad2ef6c5d14c066b1a121
kristaps/aoc2020
/day09.py
1,634
3.921875
4
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import List from itertools import combinations def check_number(n: int, latest: List[int]): # Reduce combination count by eliminating numbers that are # too large to sum up to n with any of the other numbers max_valid = n - min(latest) latest = [i for i in latest if i <= max_valid] return any( (n1 + n2 == n for n1, n2 in combinations(latest, 2)) ) def find_mismatch(numbers, preamble_length=25): latest, numbers = numbers[:preamble_length], numbers[preamble_length:] for n in numbers: if not check_number(n, latest): return n latest.append(n) latest.pop(0) def find_weakness(numbers, mismatch): for i in range(0, len(numbers)): range_sum = 0 for j in range(i, len(numbers)): range_sum += numbers[j] if range_sum == mismatch: matching_range = numbers[i:j] return min(matching_range) + max(matching_range) if range_sum > mismatch: break def solve(): arg_parser = ArgumentParser() arg_parser.add_argument('--preamble-length', default=25, type=int) arg_parser.add_argument('input_file') args = arg_parser.parse_args() with open(args.input_file, 'r') as input_file: numbers = [int(l) for l in input_file.read().splitlines()] mismatch = find_mismatch(numbers, args.preamble_length) weakness = find_weakness(numbers, mismatch) print("MISMATCH:", mismatch) print("WEAKNESS:", weakness) if __name__ == '__main__': solve()
531f18c778cadb16a132cd6cd778446fe0d1196b
Hibatallah98124/emoji
/emoji.py
490
3.625
4
import turtle lion=turtle.Turtle() lion.up() lion.goto(0,-100) lion.down() lion.begin_fill() lion.fillcolor("yellow") lion.circle(100) lion.end_fill() lion.up() lion.goto(-67,-40) lion.setheading(-60) lion.width(5) lion.down() lion.circle(80,120) lion.fillcolor("black") for i in range(-35,105,70): lion.up() lion.goto(i,35) lion.setheading(0) lion.down() lion.begin_fill() lion.circle(10) lion.end_fill() lion.hideturtle()
387736725b1aeb39c7eb1ec6dc3dc3671f6a65e1
ornelasf1/python_interpreter2
/hw4/hw4_testcase4.py
138
3.625
4
a = 5 b = 3 c = 2 if a>3: print("1 conditiion satified") else: print("nothing satisfied") else: print("nothing satisfied 2")
f78f453bb1377dcd960c2738449f179ab4bb3365
WeaselE/Small-Programs
/Infinite Divide By Two.py
215
3.5
4
from decimal import * from time import sleep def divide_by_two(nl): num = nl / 2 return num getcontext().prec = 100 n = Decimal(1.0) while n != 0: n = divide_by_two(n) print(n) # sleep(0.025)
f75d1f107990ba8eccd6f1593dfef5c1b459b67d
bnconti/Exercises-Primer-Python
/ch4/24_Bernoulli_trials.py
1,040
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Exercise 4.24: Compute probabilities with the binomial distribution # Author: Bruno N. Conti """ SAMPLE RUN: Probability of getting 2 heads when flipping a coin 5 times: 31.25% Probability of getting 4 ones in a row when throwing a die 4 times: 0.08% Probability of breaking your ski 1 time in 5 competitions: 4.10% """ from math import factorial as f def binomial(x, n, p): """ :param x: ammount of successes that we want (x <= n) :param n: amount of tests :param p: probability of success of each test :return: probability of success (x times) """ return f(n) / (f(x)*(f(n-x))) * p**x * (1-p)**(n-x) if __name__ == '__main__': print("Probability of getting 2 heads when flipping a coin 5 times: {:.2%}".format(binomial(2, 5, 0.5))) print("Probability of getting 4 ones in a row when throwing a die 4 times: {:.2%}".format(binomial(4, 4, 1/6))) print("Probability of breaking your ski 1 time in 5 competitions: {:.2%}".format(1 - binomial(0, 5, 1/120)))
2a1e4ada9aaf7b254530a78425a428cab7d7ed9a
TheScouser/algorithms
/arrays/6_string_compression.py
485
3.75
4
def compress(string): compressed = [] current_char = string[0] count = 0 for i in range(len(string)): if current_char != string[i]: compressed.append(current_char+str(count)) count = 0 current_char = string[i] count += 1 elif i == len(string) - 1: count+=1 compressed.append(current_char+str(count)) else: count += 1 compressed = "".join(compressed) if len(string) < len(compressed): return string return compressed print compress("aabcccccaaa")
e251aca45100a6f3ab8825581eeaca755657d085
jakobend/adventofcode
/day4/__main__.py
523
3.890625
4
""" Runs doctests and then calculates the answer to the puzzle. """ import sys import os import doctest from . import is_simple_passphrase, is_anagram_passphrase with open(os.path.join(os.path.dirname(__file__), "input.txt"), "rU") as f: PASSHPHRASES = [ line.strip().split(" ") for line in f ] doctest.testmod(sys.modules[__package__]) print("Part 1:", sum(is_simple_passphrase(phrase) for phrase in PASSHPHRASES)) print("Part 2:", sum(is_anagram_passphrase(phrase) for phrase in PASSHPHRASES))
80558d10df9675497d9bf179edd5670252ca2fa4
QuantumMagician/Python_Challenge
/Day04/day04.functions.py
827
4.125
4
# built-in function lists """float(), type(), int(), input(), """ # def doesn't invoke automatically x = 10 print('Aloha') def name(): print("I'm a quantummagician, and I love math.") print('OK') x = x+4 print(x) # parameter is a variable in the function def hello(word): #word=parameter if word == 'ed': #'ed'=argument print('Omg') elif word == 'es': print('I see') else: print('no worry') hello('ed') hello('es') hello('xx') # multiple parameters and arguments def add(a,b): plus = a + b return plus # won't do anything x = add(10,20) print(x) # compute gross salary def gross(h,r): sal = h * r return sal hrs = input("Enter Hours:") rate = input("Enter Rate:") h = float(hrs) r = float(rate) if h > 40: print((h-40)*r*0.5 + (h*r)) else: print(h*r)
6ecd881844e228170499941b56ea62da32718cab
Goular/PythonModule
/05廖雪峰Python教程/04.高级特性/02迭代.py
114
3.609375
4
for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y) for i,value in enumerate(['A','B','C']): print(i,value)
5fa47e9c73a151e96277a306b6d4f1606e09338a
AJCaceres/Python-is-easy
/Homework_5.py
186
4.0625
4
for numbers in range(1,100): if (numbers%3 == 0) & (numbers%5==0): print("FizzBuzz") elif numbers%3 == 0: print("Fizz") elif numbers%5 == 0: print("Buzz") else: print(numbers)
54c83d4135e991d246fd0767f85ee4f6c0fd543e
CrzRabbit/Python
/leetcode/0645_E_错误的集合.py
1,194
3.5625
4
''' 集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。 给定一个数组 nums 代表了集合 S 发生错误后的结果。 请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。 示例 1: 输入:nums = [1,2,2,4] 输出:[2,3] 示例 2: 输入:nums = [1,1] 输出:[1,2] 提示: 2 <= nums.length <= 104 1 <= nums[i] <= 104 ''' from typing import List from leetcode.tools.time import printTime class Solution: @printTime() def findErrorNums(self, nums: List[int]) -> List[int]: self.len = len(nums) mem = [0 for i in range(self.len + 1)] xor = 0 twice = None for i in range(self.len): xor ^= nums[i] mem[nums[i]] += 1 if mem[nums[i]] == 2: twice = nums[i] for i in range(self.len): xor ^= (i + 1) return [twice, xor ^ twice] nums = [1, 2, 2, 4] Solution().findErrorNums(nums)
660725efc46a30ba612bb05271872ea165265142
virgax7/ProjectEuler
/src/questions-21-40/q30.py
705
3.75
4
# Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: # # 1634 = 14 + 64 + 34 + 44 # 8208 = 84 + 24 + 04 + 84 # 9474 = 94 + 44 + 74 + 44 # As 1 = 14 is not a sum it is not included. # # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. # limit = 0 import itertools import numpy as np for i in itertools.count(): limit = i digit_len = len(str(i)) if i > sum(np.array([9] * digit_len) ** 5): break ans = 0 for i in range(2, 354295): if sum(np.array(list(map(int, list(str(i))))) ** 5) == i: ans += i print(ans)
9e116279884fc61ebe0d86019e84b49c89599ba3
igotaname6/roguelike_game
/hot_cold.py
2,321
4.1875
4
import random import time def user_input(n): correct_number = None while correct_number is None: try: number = int(input("Its your {} attempt,type a three-digit number: ".format(n))) if number > 999 or number < 100: raise ValueError correct_number = number except ValueError: print("This is no number or it don't have 3 digits") return list(str(correct_number)) def create_number(): while True: random_number = list(str(random.randint(100, 999))) if random_number[0] == random_number[1] \ or random_number[1] == random_number[2] \ or random_number[2] == random_number[0]: pass else: break return random_number def set_difficulty(): while True: user_choise = input("Choose difficulty level") if user_choise in ["5", "10", "15"]: break return int(user_choise) # print("""I am thinking of a 3-digit number. Try to guess what it is. # # Here are some clues: # # When I say: That means: # # Cold No digit is correct. # # Warm One digit is correct but in the wrong position. # # Hot One digit is correct and in the right position. # # I have thought up a number. You have 10 guesses to get it.) """) def game(): number_to_guess_original = create_number() print(number_to_guess_original) n = 1 start = time.time() difficulty = 30 while n <= difficulty: cold_check = 0 number_to_guess = number_to_guess_original[:] user_guess = user_input(n) if user_guess == number_to_guess: print("You won!") end = time.time() print("{:.3}".format(end-start)) return "win" else: i = 0 while i < len(number_to_guess): if number_to_guess[i] == user_guess[i]: print("Hot") number_to_guess.pop(i) user_guess.pop(i) else: i += 1 for digit in user_guess: if digit in number_to_guess: print("warm") else: cold_check += 1 if cold_check == 3: print("Cold") n += 1
dd334fe884f7617c70978550a6879d2be2fbba8b
wobuxiangtong/algorithm
/basics/sort/quick_sort.py
898
3.796875
4
#趣图 #https://idea-instructions.com/quick-sort/ def quick_sort_1(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort_1(left) + middle + quick_sort_1(right) print(quick_sort_1([3,6,8,10,1,2,1])) def quick_sort_2(array, l, r): if l < r: q = partition(array, l, r) quick_sort_2(array, l, q - 1) quick_sort_2(array, q + 1, r) def partition(array, l, r): x = array[r] i = l for j in range(l, r): if array[j] <= x: array[i], array[j] = array[j], array[i] i += 1 array[i], array[r] = array[r], array[i] return i a = [3,6,8,10,1,2,1,2,3,4,64,3,5,2,55,3] quick_sort_2(a,0,15) print(a)
6d4e7d1ca8d3d46685c9719180aca8fca60d7586
phucodes/lc101-git
/vigenere.py
1,027
3.671875
4
from helpers import alphabet_position, rotate_character def encription_key(text, rot): counter = 0 enc_key_phrase = "" enc_key_list = [] counter = ((len(text)//len(rot))+1) enc_key_phrase += rot * counter enc_key_list = list(enc_key_phrase) return enc_key_list def encrypt(text, rot): encryp_key = (encription_key(text, rot)) encr_list = list(encryp_key) final_message = [] hold_key = "" key_val = 0 for char in text: if char.isalpha(): hold_key = encr_list[key_val] encr_let = alphabet_position(hold_key) final_message.append(rotate_character(char, encr_let)) key_val = int(key_val) + 1 else: final_message.append(char) key_val = key_val return "".join(final_message) def main(): text = input("Enter a message for cypher: ") rot = input("Cypher key (must not be nonalpha): ") print(encrypt(text, rot)) if __name__ == '__main__': main()
ad196e72f7132a36df0916d1bbcc91fb89de940c
Raj-Bisen/python
/SumofFactors.py
739
4.09375
4
# Accept number from user and return addition of its factors # input : 6 # output : 1 + 2 + 3 = 6 def AdditionFactors(no): iCnt = 1 iSum = 0 for i in range(1,int(no/2)+1): # no1 = 6 if no % iCnt == 0: iSum = iSum + iCnt iCnt = iCnt +1 return iSum #while(iCnt <= no/2): #if((no % iCnt) == 0): #iSum = iSum + iCnt #iCnt = iCnt + 1 #return iSum def main(): print("Enter the number") value1 = int(input()) print("*****************************") ret = AdditionFactors(value1) print("Addition of factors is : ",ret) print("*****************************") if __name__=="__main__": main()
136d4734f6ce4421381dafd02a080ba2770fe212
tkhura5/FlightsDelay_StatisticalModels
/Scripts/Models/Model_Time_Series.py
625
3.5625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY,YEARLY import datetime from datetime import * #Reading the dataframe df = pd.DataFrame() df=pd.read_csv('flights.csv',low_memory=False) df['DEPARTURE_DELAY'] = df['DEPARTURE_DELAY'].apply(pd.to_numeric) group = pd.DataFrame() group = df.groupby(['DATE']).mean() df=df['DATE'].unique() print df #visually analysing time series using scatter plot df['DATE'].unique().to_csv('date.csv',index=False) x=df['DEPARTURE_TIME'] y=df['DEPARTURE_DELAY'] plt.scatter(x,y) plt.show()
6ec6cbb8822930d8a97246919869e9599fbcf811
krohak/Project_Euler
/LeetCode/Medium/Set Matrix Zeroes/revise/1.py
1,342
3.578125
4
def set_matrix_zeroes(arr): m = len(arr) n = len(arr[0]) print(m, n) row_zero = 0 col_zero = 0 i = 0 while i<m: if arr[i][0] == 0: col_zero = 1 i+=1 j = 0 while j<n: if arr[0][j] == 0: row_zero = 1 j+=1 # print(row_zero, col_zero) i = 1 # print(i, j) while i<m: j = 1 while j<n: # print(i, j, arr[i][j]) if arr[i][j] == 0: arr[i][0] = 0 arr[0][j] = 0 j+=1 i+=1 # print(i, j, arr) i, j = 1, 1 # make rows zero while i<m: if arr[i][0] == 0: arr[i] = [0]*n i+=1 # make col zero while j<n: if arr[0][j] == 0: k = 0 while k<m: arr[k][j] = 0 k+=1 j+=1 if col_zero: k = 0 while k<m: arr[k][0] = 0 k+=1 if row_zero: arr[0] = [0]*n return arr arr = [ [1,1,1,1], [1,0,0,1], [1,0,1,1], [1,1,1,1] ] arr = [ [1,1,1], [1,0,1], [1,1,1] ] arr = [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] arr = [ [1,2,3,4], [5,0,5,2], [8,9,2,0], [5,7,2,1] ] sol = set_matrix_zeroes(arr) print(sol)
dae23fdb2cbcd508a0daab4c28aad6331075e421
partho-maple/coding-interview-gym
/leetcode.com/python/334_Increasing_Triplet_Subsequence.py
1,263
3.859375
4
# Solution 1: Two pointer technique class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ firstNum, secondNum = float('inf'), float('inf') for num in nums: if num <= firstNum: firstNum = num elif num <= secondNum: secondNum = num else: return True return False # Solution 2: generic solution that checks for K increasing numbers in an array. So the triplet solution is just K=3. class Solution: def increasingTriplet(self, nums): return self.increasingKlet(nums, 3) def increasingKlet(self, nums, k): ''' Approach: start with k-1 very large values, as soon as we find a number bigger than all k-1, return true. Time: O(n*k) Space: O(k) this is the generic solution for this problem ''' small_arr = [float('inf') for _ in range(k)] for num in nums: for i in range(k-1): if num <= small_arr[i]: small_arr[i] = num break if num > small_arr[-1]: return True return False
f6c14f0c94dabce371433e8f01adc168551d86b6
aztlanleuc/stile-interview-project-task
/Devon McKenzie Project Team Task.py
4,529
4.53125
5
''' Devon McKenzie Project Team Task String recognition ''' # get the required input from the user filename = input("What is the file to be scanned (do not include the .txt extension)? ") # the file to be opened search_type = input("Which search would you like to run ('simple' or 'full')? ").lower() # which function to run # if the user wants a full search, get a list of the items to search for if search_type == "full": types_input = input("What types of bread would you like to search for (separated by a comma and no space)? ") types = types_input.split(",") # splits the input string into a list # open the file to be scanned txt = open(filename + ".txt") # seperate the file into workable lines temp = txt.readline() lines = temp.split(". ") # SIMPLE VERSION. ONLY IDENTIFIES LINES CONTAINING "BREAD" def find_bread(text): # identifying lines that have bread lines_cont = [] # this will store a list of the lines containing "bread" line_indexes = [] # stores the location of bread in each stored line (will be used to highlight the word) for i in text: # check each line in the file location = i.find("bread") # will return the index of the first letter of "bread" if contained, otherwise returns -1 if location != -1: # check if "bread" was found lines_cont.append(i) # if it was, add the line to the list to be returned line_indexes.append(location) # append the location of "bread" in that line if len(lines_cont) != 0: # if the word bread was found print("\nThis text contains bread in these lines:") for j in range(0, len(lines_cont)): # for each line that "bread" was found in temp = lines_cont[j] # print the line but with "bread" capitalised print(temp[:line_indexes[j] - 1] + " " + temp[line_indexes[j]:line_indexes[j] + 5].upper() + " " + temp[line_indexes[j]+6:]) print("\nBread was found in this text {} time(s)".format(len(lines_cont))) else: # if the word bread was not found print("There's no bread in this text :(") # COMPLEX VERSION. IDENTIFIES ALL VARIETIES OF BREAD SPECIFIED BY THE USER def find_all_bread(text): total_count = 0 for t in types: # run the whole simple program, but for each type of bread lines_cont = [] # this will store a list of the lines containing the current variety line_indexes = [] # store the location of that variety in each line for i in text: # check each line in the file location = i.find(t) # returns the index of the first letter of the variety, if not present returns -1 if location != -1: # check if the variety was found lines_cont.append(i) # if it was, add the line to the list to be returned line_indexes.append(location) # append the location of the variety in that line if len(lines_cont) != 0: # if the variety was found print("__________________________________________________") # spacer to make the output more readable print("This text contains {} in these lines:".format(t)) for j in range(0, len(lines_cont)): # for each line bread was found in # get the line and the length of the current variety being checked temp = lines_cont[j] length = len(t) # print the line but with the variety capitalised print(temp[:line_indexes[j] - 1] + " " + temp[line_indexes[j]:line_indexes[j] + length].upper() + " " + temp[line_indexes[j] + length + 1:]) print("\n{} was found in this text {} time(s)".format(t.capitalize(),len(lines_cont))) total_count += len(lines_cont) else: # if the variety was not found print("__________________________________________________") print("This text does not contain {} :(".format(t)) print("__________________________________________________") print("Varieties of bread were found in this text a total of {} times".format(total_count)) # depending on search type requested by the user, run the two different functions if search_type == "simple": find_bread(lines) elif search_type == "full": find_all_bread(lines) else: # in case they mistyped or otherwise didn't give a correct search string print("You did not give a correct search type :(") # close the text file txt.close()
0acb1df03885834b7c45df594f90bef4ed26a8a7
doba23/Python_academy_Engeto
/4_lesson/use_case_2.py
243
4.09375
4
from time import sleep num_seconds = int(input('How many seconds to you need?: ')) while num_seconds: print(num_seconds) num_seconds = num_seconds - 1 if num_seconds > 0: sleep(1) else: print('Time has gone!')
5dfb274e73589d2c7b80bb6e3554cbf23e6ae957
nacho-vlad/chess-engine
/app/game.py
1,536
3.546875
4
from app.rustchess import Chessboard class Game: """A game of chess. It aslo records all moves made, and starts from the standard starting position. The game stops on a keyboard interrupt. Parameters ---------- white : Player player for white black : Player player for black ui : UI the ui for the game """ def __init__(self, white, black, ui): self.white = white self.black = black self.ui = ui def play(self): """Start the game.""" moves = [] board = Chessboard() white_turn = True while True: try: self.ui.draw(board) result = board.game_result() if result is not None: self.ui.game_over(result) break move = self.white.get_move(moves) if white_turn else self.black.get_move(moves) if move == 'quit': break try: if move == 'undo': board.undo() continue try: board.make_move(move) except Exception: board.make_move(move+'q') white_turn = not white_turn moves.append(move) except Exception: pass except KeyboardInterrupt: return
d3ad9fc60eecb2ee170487c61a1d4a59b8442ce7
ddari/my_python
/del_element_list.py
120
3.71875
4
l=list(map(str,input('Введите список:').split())) A=[i for i in l if i=='John' or i=='Paul'] print (A)
ed4c9b55ae93ed33463976f8f061bfce61483ef3
Scruf/BluebiteAssignment
/question3.py
569
3.59375
4
class Band: def __init__(self, genre="rock", name='Unknown'): self.genre = genre self.name = name class RollingStones(Band): def __init__(self, genre="rock"): Band.__init__(self, genre,name="Rolling Stones") self.genre = genre def __str__(self): return self.name class RedHotChiliPeppers(Band): def __init__(self, genre="rock"): Band.__init__(self, genre, name="Red Hot Chili Peppers") self.genre = genre def __str__(self): return self.name roll = RollingStones() rchp = RedHotChiliPeppers("funk") print(roll, roll.genre) print(rchp, rchp.genre)
97bfc2f2997c549e4dd2412fb627e9f55b8beeeb
MojitoBar/Python_Study
/python_study/lab6_12_1.py
656
3.640625
4
""" 챕터: day6 주제: exception 문제: 사용자로부터 1과 10사이의 숫자를 입력받아, 1부터 해당 숫자까지의 합을 구하라. 만약 숫자가 아닌 값이 입력되면, "숫자를 입력하세요"라는 문장을 출력한 후 다시 입력을 받는다. 작성자: 주동석 작성일: 2018. 11. 27 """ # exception을 사용하여 프로그래밍 while(True): s = 0 try: n = int(input("1과 10사이의 숫자를 입력해 주세요: ")) for i in range(1, n+1): s += i print(s) break except ValueError: print("숫자를 입력하세요")
803daa4c5b6015b923b960e7d97d96d2becc0c4f
RuzhaK/pythonProject
/Fundamentals/MidExamSecond/ProblemOne.py
422
3.78125
4
cost = float(input()) months = int(input()) budget = 0 for i in range(months): if (i + 1) % 2 != 0 and i + 1 > 1: budget -= 0.16 * budget elif (i + 1) % 4 == 0: budget = budget * 1.25 budget += 0.25 * cost if cost <= budget: print(f"Bravo! You can go to Disneyland and you will have {budget - cost:.2f}lv. for souvenirs.") else: print(f"Sorry. You need {cost - budget:.2f}lv. more.")
e1ab6a9b1131d513cc83b038759b9cceba83d329
ksingh7/python-programs
/Guess_secret_Number.py
847
4.03125
4
def guessNumber(): low = 0 high = 100 guess = 0 while low < high: mid = (low + high) / 2 print "Is your secret number " + str(mid) + "?" response = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ") if response == 'c' or response == 'C': print "Game over. Your secret number was: ", mid break elif response == 'h' or response == 'H': high = mid elif response == 'l' or response == 'L': low = mid else: for i in 'cChHlL': if response != i: print "Sorry, I did not understand your input." break print "Please think of a number between 0 and 100!" guessNumber()
913e1bd3cb39822625c37ff2ad11ad7a3808036c
fingerman/python_fundamentals
/intro/3_diff_instances_obk.py
221
3.734375
4
a = 5 b = 5 print(id(a)) print(id(b)) print(a is b) print(type(a)) c = [1, 2] d = [2, 2] print(id(c)) print(id(d)) print(type(c)) # is compares the value of the objects/instances, not values print(c == d) print(c is d)
4bc0d730b708bd407e20e000413e3db49dc2229b
Bradleywboggs/call-data-test
/src/tasks/extract.py
397
3.796875
4
import csv from typing import Dict, List # NOTE depending on the potential size of the data files, using a generator may be # a better option here, however for purposes of this exercise and this particular file, # we'll simply parse the file. def get_data(file_name) -> List[Dict[str, str]]: with open(file_name, newline="") as data_file: return list(csv.DictReader(data_file))
8d9f10cd0dd656e63ddf75733e99e9aa7e67ffa5
wengjinlin/Homework
/Day05/Calculator/calculator.py
398
3.90625
4
import func while True: func.menu_print() choice = input(">>:") if choice == "2": break if choice == "1": formula = input("请输入公式:") formula = formula.replace(" ", "").strip() res = func.calculation(formula) print("计算结果为:"+res) py_res = eval(formula) print("Python运行公式结果为:"+str(py_res))
329883c416c0983269daa35552bb90e284b33525
YiqiongZhou/Leetcode
/1108.ip-地址无效化.py
529
3.546875
4
# # @lc app=leetcode.cn id=1108 lang=python # # [1108] IP 地址无效化 # # @lc code=start class Solution(object): def defangIPaddr(self, address): """ :type address: str :rtype: str """ ans=[] for char in address: ans.append(char) if char=='.': ans.pop() ans.append('[') ans.append('.') ans.append(']') print(ans) return ''.join(ans) # @lc code=end
d3683ae91e4a6ba6c47c9556a68b683b83f94e6b
Midnex/edi-835-parser
/edi_835_parser/elements/__init__.py
365
3.765625
4
from abc import ABC, abstractmethod class Element(ABC): def __set_name__(self, owner, name): self.private_name = '_' + name def __get__(self, obj, objtype=None): return getattr(obj, self.private_name) def __set__(self, obj, value): value = self.parser(value) setattr(obj, self.private_name, value) @abstractmethod def parser(self, value): pass
259bb6514157db4abda14eb4b641e336a90b0b76
mazh661/distonslessons
/HomeWork2/example3.py
126
3.96875
4
a_dict = { 1:"one", 2:"two", 3:"three" } keys = a_dict.keys() keys = sorted(keys) for key in keys: print(key)
ca8dc8231f5b4fb59ecf4a8bcddbef2cf11c301e
carinazhang/deeptest
/第二期/上海-爱笑的眼睛/第二次任务_快学Python 3练习/List.py
522
3.578125
4
# -*- coding=utf-8 -*- #_author_ == u"smile eyes" if __name__=="__main__": list_demo = [1,2,3,4,5,6,7] print(u"内置函数处理list示例: ") # 计算list_demo中元素个数 print(len(list_demo)) # 返回list_demo中最大值的元素 print(max(list_demo)) # 返回list_demo中最小值的元素 print(min(list_demo)) # 将list转换成元组 list_demo = (1, 2, 3, 4, 5, 6) tuple1=list(list_demo) # 打印转换后的列表 print(tuple1)
d7a487f1465373449621defa738aeb2bb63f0dce
wkreiser/Kreiser-IQT-Project
/Python/Object_Oriented/Calculator/CalcFunctions/calcFunctions.py
1,470
4.25
4
#Error checking for integer input def get_user_input(): userInput = raw_input("Enter an integer: ").rstrip() try: userInput =int(userInput) except ValueError: print("Try again.\n") userInput = get_user_input() return userInput #Function to print the mathematical operations list def operator_list(): print "\n+ = Addition" print "- = Subtraction" print "* = Multiplication" print "/ = Division" print "** = Exponent" print "% = Modulus Division" print "F = Fibonacci" print "! = Factorial" print "N = New Numbers" print "Exit\n" #Operator error checking for input def operator_input(): operator_list() math_oper = str(raw_input("Please select an operator: ")).rstrip() if(math_oper == '+' or math_oper == '-' or math_oper == '*' \ or math_oper == '/' or math_oper == '**' \ or math_oper.upper() == 'F' \ or math_oper == '!'\ or math_oper.upper() == 'EXIT' or math_oper.upper() == 'N'\ or math_oper == '%'): return math_oper else: print "Invalid operator selected. Try again." math_oper = operator_input() #Iterative version of the Fibonacci sequence def fibonacci(num): if (num <= 0): print "Please enter a positive integer" elif (num == 1): return num else: x, y = 0, 1 for i in range(num): x, y = y, x + y return x
4d59e18cc15928b7e8bee89e6f31eace73e67e31
Yuan98Yu/solutions-to-leetcode-cn
/solutions/[212]单次搜索Ⅱ.py
2,009
3.59375
4
from typing import List from itertools import product class TrieNode(dict): def __init__(self, parent=None, val=None) -> None: super().__init__() self.word = False self.val = val self.parent = parent self.count = 0 class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: self.board = board self.ans_list = set() trie = TrieNode() for word in words: cur_node = trie for c in word: cur_node.count += 1 node = cur_node.setdefault(c, TrieNode(cur_node, c)) node.parent = cur_node cur_node = node cur_node.count += 1 cur_node.word = word for row, col in product(range(len(board)), range(len(board[0]))): self.__dfs(row, col, trie) return list(self.ans_list) def __dfs(self, row, col, root): def is_valid_pos(row, col): return (0 <= row < len(self.board) and 0 <= col < len(self.board[0]) and self.board[row][col] != '#') if not is_valid_pos(row, col): return False char = self.board[row][col] if root is None or root.get(char) is None: return False root = root.get(char) if root.word: cur_node = root self.ans_list.add(cur_node.word) while cur_node: cur_node.count -= 1 if cur_node.count == 0: print(cur_node.val) c = cur_node.val cur_node.parent.pop(c) cur_node = cur_node.parent tmp, self.board[row][col] = self.board[row][col], '#' for dir in [(-1,0), (1,0), (0,-1), (0,1)]: next_row, next_col = row+dir[0], col+dir[1] self.__dfs(next_row, next_col, root) self.board[row][col] = tmp
6bd58deaf984bc355d8f447fdfe8990792875cc1
JoGomes19/LA2
/Treino/Torneio 1/LA_2/ordenaNumeros.py
312
3.703125
4
import sys def getChave(l): return l[0] l = [] for s in sys.stdin: x = s.split(",") l.append(x) l = [[int(float(j)) for j in i] for i in l] # converte uma lista de listas de string para lita de lista de ints l.sort(key = getChave) # ordena uma lista de listas em relacao a chave! for i in l: print(i)
a43f4d803add8a227eee48b5b5ebad63ef5a4574
surya-232/assignment
/assignment3.py
1,391
4.03125
4
print("question1") print("enter the list items") list=[] x=input("1") y=input("2") z=input("3") print("the list is") list=[x,y,z] print(list) print("\n") print("question2") #['google','apple','facebook','microsoft','tesla'] list2=['google','apple','facebook','microsoft','tesla'] print(list2) print(list.extend(list2)) print(list) print("\n") print("question3") print(list.count('1')) print("\n") print("question4") l=[2,4,3,1,6] print(l) print(l.sort()) print(l) print("\n") print("question5") list3=[1,2,4,3,5] print(list3) list4=[6,8,7,9,0] print(list4) list3.sort() list4.sort() print(list3) print(list4) print("\n") tdlist=[list3,list4] print(tdlist) print("\n") print("question6") print("stack") list5=["I","me","myself"] print(list5) list5.append("attitude") list5.append("Ego") print(list5) print(list5.pop()) print(list5) print(list5.pop()) print(list5) print("\n") print("queue") from collections import deque list6 = deque(["three", "five", "four", "long"]) print(list6) list6.append("two") print(list6) list6.append("one") print(list6) print(list6.popleft()) print(list6.popleft()) print(list6) print("\n") print("question7") NUMBER_LIST = [1,2,3,4,5] even = 0; odd = 0; for numbers in NUMBER_LIST : if (numbers%2 == 1): odd = odd+1 if (numbers%2 == 0): even = even+1 print('number of evens is: ',even) print('number of odds is: ',odd)
32d4489d79a9f21a75e1b3322b50091346765fa6
vincent-vega/adventofcode
/2018/day_06/6.py
2,187
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re def _manhattan(a: (int, int), b: (int, int)) -> int: return abs(a[0] - b[0]) + abs(a[1] - b[1]) def _closest(locations: dict, target: (int, int)) -> int: min_distance = min_name = None for n, coordinate in locations.items(): if coordinate == target: return n d = _manhattan(coordinate, target) if min_distance is None or min_distance > d: min_distance = d min_name = n elif min_distance == d: min_name = None return min_name def part1(locations: dict, top_left: (int, int), bottom_right: (int, int)) -> int: min_X, min_Y = top_left max_X, max_Y = bottom_right counter = { n: 0 for n in range(len(locations)) } for x in range(min_X, max_X + 1): for y in range(min_Y, max_Y + 1): closest = _closest(locations, (x, y)) if closest is None or counter[closest] < 0: continue if x == 0 or y == 0 or x == max_X or y == max_Y: counter[closest] = -1 else: counter[closest] += 1 return max(counter.values()) def _sum_distance(locations: dict, target: (int, int)) -> int: return sum(_manhattan(coordinate, target) for coordinate in locations.values()) def part2(locations: dict, top_left: (int, int), bottom_right: (int, int), max_distance: int) -> int: min_X, min_Y = top_left max_X, max_Y = bottom_right return sum([ 1 for x in range(min_X, max_X + 1) for y in range(min_Y, max_Y + 1) if _sum_distance(locations, (x, y)) < max_distance ]) if __name__ == '__main__': with open('input.txt') as f: locations = { n: tuple(map(int, re.findall(r'-?\d+', line))) for n, line in enumerate(f.read().splitlines()) } top_left = (min(locations.values(), key=lambda x: x[0])[0] - 1, min(locations.values(), key=lambda x: x[1])[1] - 1) bottom_right = (max(locations.values(), key=lambda x: x[0])[0] + 1, max(locations.values(), key=lambda x: x[1])[1] + 1) print(part1(locations, top_left, bottom_right)) # 4771 print(part2(locations, top_left, bottom_right, 10_000)) # 39149
d95c06acb5a1c8649c30865ade7444a7fafd2f11
Wjun0/python-
/day05/05-函数结合return可以让多层循环终止-扩展.py
651
3.90625
4
# is_ok = False # for value1 in range(1, 4): # print("外层循环:", value1) # for value2 in range(5): # print("内层循环:", value2) # if value2 == 3: # is_ok = True # break # # if is_ok: # break # 简写方式: def show(): for value1 in range(1, 4): print("外层循环:", value1) for value2 in range(5): print("内层循环:", value2) if value2 == 3: # 表示内层循环要结束 return # 当函数执行了return表示函数执行结束,return后面即使还有更多的代码也不会执行 show()
836e07d1b666e2223057ff1c011e5a8eada3cf1a
akevinblackwell/Raspberry-Pi-Class-2017
/SortAssignment.py
2,714
4.5
4
''' Raspberry Pi Assignment - Sorting Sorting is simply reordering a list of items in a logical order, such as alphabetical or in increasing order. Sounds simple, huh? And it is for small lists of items. But computers are often asked to sort very large lists of items. And the bigger they get, the more computing power it takes to do it. The time required is not linear. It is logarithmic - which means if it takes 1 second to sort 1 million items, it will take much, much longer than 2 seconds to sort 2 million items. Some very intelligent people have made their life's work out of creating and optimizing sort algorithms. ASSIGNMENT 1 - BACKGROUND See https://en.wikipedia.org/wiki/Sorting_algorithm - you don't have to understand everything that you read, but get a feel for the topic. ASSIGNMENT 2 - EXPLORE THE .sort() method in Python. Record how long it takes this method to sort 100,000 items. Look at the code I wrote below. It starts with only 10 items but you can increase it up to millions. How can you change the code to record how long it takes to do the sort? ASSIGNMENT 3 - Repalce .sort() with your own algorithms. - An insertion sort How does your sort algorithm perform compared to the one Python comes with? An insertion sort is pretty easy to implement. You simply pick the first item in the list and compared it to the second item. Which ever is smaller then gets compared to the third item. You keep going until you get to the end of the list. Whatever number you have at the end of the list is the smaller number in the list. Append it to a new list and delete it from the original list. Then do it all over again until your original list has no more elements. Compare this to sorting cards. Take only the hearts from a deck and shuffle them. Then start at the first card compare it to the second. Keep the lowest card in your left hand. Then compare to the third and so on. At the end, you'll have the lowest card. Repeat to get the next card until you are done. ASSIGNMENT 4 - Implement a Bubble sort. (We'll do this together when we meet online.) ''' import random number_of_items = 10 # start small and increaes once working. # my_randoms=[] for i in range (number_of_items): my_randoms.append(random.randrange(1,101,1)) # lookup randrange and make sure you understand it. print ("\n\n\nThe list of random numbers in no particular order.") print (my_randoms) my_randoms.sort() print ("\n\nThe list of random numbers in ascending sorted order.") print (my_randoms) my_randoms.sort(reverse=True) print ("\n\nThe list of random numbers in descending sorted order.") print (my_randoms)
283cd95648b5552e286e1e14358ad6d08620d515
a313071162/letcode
/letcode_27_移除元素.py
2,010
3.828125
4
#!/usr/bin/env python #!/usr/bin/python # -*- coding: UTF-8 -*- """ @File:letcode_27_移除元素.py @Data:2019/7/30 @param: @return: """ # python偷懒方法 class Solution: def removeElement(self, nums: list, val: int) -> int: if val not in nums or not nums: return len(nums) for value in nums[::-1]: if value == val: nums.remove(val) return len(nums) # 双指针 ————感觉弄复杂了 class Solutions: def removeElement(self, nums: list, val: int) -> int: if val not in nums or not nums: return len(nums) left = 0 right = len(nums) - 1 nums.sort() while left <= right: mid = (left + right) // 2 if nums[mid] > val: right = mid - 1 elif nums[mid] < val: left = mid + 1 else: if left == right == len(nums) - 1: nums.pop() return len(nums) left = right = mid # 此处则需要处理,以免超过数组的最大长度 while nums[left - 1] == val: left = left - 1 if left < 0: left = left + 1 break while nums[right + 1] == val: right = right + 1 if right == len(nums) - 1: break del nums[left: right + 1] return len(nums) # 双指针,优化 class Solutionss: def removeElement(self, nums: list, val: int) -> int: if val not in nums or not nums: return len(nums) left = 0 right = len(nums) while left < right: # 相等就移动, if nums[left] == val: nums[left] = nums[right - 1] right = right - 1 else: left = left + 1 return right
e13d9523e192ac1d763ee20485b9ef0ebfb9f0f1
Scottjhollywood/MovieWatchlist
/main/Watchlist_Editor.py
2,103
4
4
from Movie_Extractor import FileExtractor def edit_watchlist(choices): movie_list = FileExtractor.extract_movie_dict("movies_length.txt") print("==================") print("Watchlist Editor") print("==================") print("1. Add movie(s) to your watchlist") print("2. Remove movie(s) from your watchlist") print("3. Exit") print("==================") editor_choice = int(input("Enter a number to continue: ")) if editor_choice == 1: edit_list = "Y" print("==================") for movie in movie_list: print(movie) print("==================") while edit_list != "N": addition_choice = input("What movie would you like to add to your watchlist?: ") if addition_choice in movie_list: if addition_choice in choices: print("That film is already in your watch list") else: print(addition_choice, "has been added to your watchlist") choices[addition_choice] = movie_list[addition_choice] else: print("We don't have that film in our selection") edit_list = input("Would you like to add anything else to your watchlist(Y/N):") return choices if editor_choice == 2: edit_list = "Y" print("==================") for movie in choices: print(movie) print("==================") while edit_list != "N": subtraction_choice = input("What movie would you like to remove from your watchlist?: ") if subtraction_choice in choices: choices.pop(subtraction_choice) print(subtraction_choice, "has been removed from your watchlist") else: print("You don't have that film in your watchlist") edit_list = input("Would you like to remove anything else to your watchlist(Y/N):") return choices if editor_choice == 3: return choices
3f41fe21dd41a7c4949ba461775ad8007c1b8580
pranithajemmalla/Cracking_The_Coding_Interview
/Data Structures/ArraysAndStrings/1.4 Palindrome Permutation.py
1,526
4.0625
4
# Palindrome Permutation # Given a string, write a function to check if it is a permutation of a palindrome class PalindromePermutation: def __init__(self): self.input_str = None def using_hash_table(self): str_dict = dict() for s in self.input_str: if s != " ": if s in str_dict: str_dict.pop(s) else: str_dict[s] = 1 return len(str_dict) == 0 or len(str_dict) == 1 def using_sort(self): sorted_str = "".join(sorted(self.input_str)) odd = None ind = 0 for i in range(int(len(sorted_str)/2)): if sorted_str[ind] == sorted_str[ind+1]: ind += 2 elif odd is None: odd = True ind += 1 else: return False return True def using_bit_vector(self): checker = 0 for s in self.input_str: index = ord(s) - ord('a') if (checker & 1 << index) > 0: checker = checker ^ 1 << index else: checker = checker | (1 << index) return (0 == checker) | (0 == (checker & (checker - 1))) if __name__ == '__main__': palindromePermutationObj = PalindromePermutation() palindromePermutationObj.input_str = input() print(palindromePermutationObj.using_hash_table()) print(palindromePermutationObj.using_sort()) print(palindromePermutationObj.using_bit_vector())
933fcff407c1cc2cb8c49b8efeee0b68b2b19762
aayush17002/DumpCode
/Foobar/invert.py
152
3.796875
4
g={0:[],1:[0,2,3,4],2:[3,4],3:[1,2],4:[0]} h={} for x in g: v=g[x] for node in v: if node in h: h[node].append(x) else: h[node]=[x] print(h)
f64b418c0d542b478d89b588bb032f54d64825d5
ivanlyon/exercises
/kattis/k_4thought.py
1,687
3.71875
4
''' Precompute equations of fixed operations and number. Status: Accepted ''' ############################################################################### def eval2(text): """Evaluate an expression without using eval()""" numbers, operators = [], [] for glyph in text.split(): if glyph.isdigit(): rhs = int(glyph) if operators and operators[-1] in '*/': lhs = numbers.pop() operating = operators.pop() if operating == '*': numbers.append(lhs * rhs) else: numbers.append(lhs // rhs) else: numbers.append(rhs) else: operators.append(glyph) while operators: lhs, rhs = numbers[0], numbers[1] operating = operators[0] if operating == '+': numbers = [lhs + rhs] + numbers[2:] else: numbers = [lhs - rhs] + numbers[2:] operators = operators[1:] return numbers.pop() ############################################################################### def main(): """Read input and print output""" precomp = {} for op1 in '+-*/': for op3 in '+-*/': for op5 in '+-*/': text = '4 ' + ' 4 '.join([op1, op3, op5]) + ' 4' precomp[eval2(text)] = text for _ in range(int(input())): number = int(input()) if number in precomp: print(precomp[number], '=', number) else: print('no solution') ############################################################################### if __name__ == '__main__': main()
faaac8523add98bcd3c00ccb352f059368738b37
mchhhhhhhhhhh/gameRPG
/gameRPG.py
4,338
3.984375
4
class hero: def __init__(self,name,health,attack,geo_x,geo_y): self.name=name self.health=health self.attack=attack self.geo_x=geo_x self.geo_y=geo_y def attack_to_hero(self,damage): self.health=self.health-damage return self.health def forward(self): self.geo_x=self.geo_x+1 def backward(self): self.geo_x=self.geo_x-1 def upward(self): self.geo_y=self.geo_y+1 def downward(self): self.geo_y=self.geo_y-1 class monster: def __init__(self,name,health,attack,geo_x,geo_y): self.name=name self.health=health self.attack=attack self.geo_x=geo_x self.geo_y=geo_y def attack_to_hero(self,damage): self.health=self.health-damage return self.health class sund: def __init__(self,geo_x,geo_y): self.geo_x=geo_x self.geo_y=geo_y print("Введите здоровье Коляна:") h_Kolyan=int(input()) print("Введите атаку Коляна:") A_Kolyan=int(input()) Kolyan=hero('Kolyan',h_Kolyan,A_Kolyan,0,0) ushlepok=monster('ushlepok',9,7,2,4) sund=sund(3,5) while(1): print("Шагай") a=input() if(a=='d'): Kolyan.forward() print("Координаты Коляна:", Kolyan.geo_x, Kolyan.geo_y) if(a=='a'): Kolyan.backward() print("Координаты Коляна:",Kolyan.geo_x, Kolyan.geo_y) if(a=='w'): Kolyan.upward() print("Координаты Коляна:",Kolyan.geo_x, Kolyan.geo_y) if(a=='s'): Kolyan.downward() print("Координаты Коляна:",Kolyan.geo_x, Kolyan.geo_y) if((Kolyan.geo_x==ushlepok.geo_x)and(Kolyan.geo_y==ushlepok.geo_y)): break if((Kolyan.geo_x==sund.geo_x)and(Kolyan.geo_y==sund.geo_y)): print("В сундуке ничё нет. Разочарование((((((((((((") print("Драка") while((Kolyan.health>0)or(ushlepok.health>0)): if(Kolyan.health>ushlepok.health): print("Бьёт Колян") ushlepok.attack_to_hero(8) print("Здоровье ушлёпка:", ushlepok.health) if((Kolyan.health<1)or(ushlepok.health<1)): break print("Бьёт ушлепок") Kolyan.attack_to_hero(7) print("Здоровье Коляна:",Kolyan.health) if((Kolyan.health<1)or(ushlepok.health<1)): break if(Kolyan.health<ushlepok.health): print("Бьёт ушлепок") Kolyan.attack_to_hero(7) print("Здоровье Коляна:",Kolyan.health) if((Kolyan.health<1)or(ushlepok.health<1)): break print("Бьёт Колян") ushlepok.attack_to_hero(8) print("Здоровье ушлёпка:", ushlepok.health) if((Kolyan.health<1)or(ushlepok.health<1)): break if(Kolyan.health==ushlepok.health): if(Kolyan.attack>ushlepok.attack): print("Бьёт Колян") ushlepok.attack_to_hero(8) print("Здоровье ушлёпка:", ushlepok.health) if((Kolyan.health<1)or(ushlepok.health<1)): break print("Бьёт ушлепок") Kolyan.attack_to_hero(7) print("Здоровье Коляна:",Kolyan.health) if((Kolyan.health<1)or(ushlepok.health<1)): break if(Kolyan.attack<ushlepok.attack): print("Бьёт ушлепок") Kolyan.attack_to_hero(7) print("Здоровье Коляна:",Kolyan.health) if((Kolyan.health<1)or(ushlepok.health<1)): break print("Бьёт Колян") ushlepok.attack_to_hero(8) print("Здоровье ушлёпка:", ushlepok.health) if((Kolyan.health<1)or(ushlepok.health<1)): break if((Kolyan.health<1)or(ushlepok.health<1)): break if(Kolyan.health<1): print("Колян проиграл") if(ushlepok.health<1): print("ушлёпок проиграл")
660f0a5039a7f1ed54cab4800fe56c770f251e00
WiceCwispies/HeiTerryAsteroids
/src/GA/chromosome.py
1,379
3.59375
4
import numpy as np class Chromosome: def __init__(self, string): self.string = string self.fitness = 0 self.normFitness = 0 def updateString(self,string): self.string = string def updateFitness(self,fitness): self.fitness = fitness def updateNormFitness(self,normFitness): self.normFitness = normFitness def __str__(self): rstr = "string: " + str(self.string) + "\n" + "fitness: " + str(self.fitness) return rstr def getString(self): return self.string def getFitness(self): return self.fitness def getNormFitness(self): return self.normFitness class Population: def __init__(self): self.population = [] def addChromosome(self,chrom): self.population.append(chrom) def __str__(self): for chrom in self.population: print(chrom,"\n") return "total number of Chromosomes: " + str(len(self.population)) def chromosome(self,number): return self.population[number] # Test if __name__ == "__main__": chrom = Chromosome(np.array([1,2,3,4,5,6])) chrom2 = Chromosome(np.array([1,2,3,4,5,6])) chrom.updateFitness(8) chrom2.updateFitness(4) population = [chrom,chrom2] print(list(map(lambda a: a.getFitness(),population)))
52a931bd34a44daa303251d5d0512aab9796c71a
Niranch/Py-codecollection
/FindingListRunnerup.py
403
3.6875
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 20 19:31:59 2020 @author: Niranch """ from array import * n=5 mylist=[6,6,6,6,6] mylist.sort() flag=False while n>0: if mylist[n-2]!=mylist[n-1]: runnerup = mylist[n-2] flag=True else: n=n-1 if(flag) or (n<0): break if(flag): print(runnerup) else: print("All are winners")
93f2875455f7933c5acbed538dea1b05490bba4e
shehryarbajwa/Algorithms--Datastructures
/Algorithms-Project-2/Project/Problem_3.py
3,817
3.625
4
import sys class HuffNode(object): def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def is_tree_leaf(self): if (self.left or self.right) is None: return True else: return False def element_frequency_list(data): frequency_dict = {} for element in data: if element not in frequency_dict: frequency_dict[element] = 1 else: frequency_dict[element] += 1 node_frequencies = [] for key, value in frequency_dict.items(): node_frequencies.append(HuffNode(key, value)) return node_frequencies def sort_node_frequencies(node_frequencies): sorted_frequencies = sorted(node_frequencies, key=lambda x:x.freq, reverse=True) return sorted_frequencies def build_huff_tree(text): frequencies = element_frequency_list(text) frequencies_sorted = sort_node_frequencies(frequencies) while len(frequencies_sorted) > 1: left = frequencies_sorted.pop() right = frequencies_sorted.pop() freq_count = left.freq + right.freq parent = HuffNode(None, freq_count) parent.left = left parent.right = right frequencies_sorted.append(parent) frequencies_sorted = sort_node_frequencies(frequencies_sorted) return frequencies_sorted[0] def assign_code_huff_tree(tree, code): huff_map = {} if not tree: return huff_map if tree.is_tree_leaf(): huff_map[tree.char] = code huff_map.update(assign_code_huff_tree(tree.left, code + '0' )) huff_map.update(assign_code_huff_tree(tree.right, code + '1')) return huff_map def decode_next_element(data, index, tree): if tree.is_tree_leaf(): return tree.char, index if data[index] == '0': return decode_next_element(data, index + 1, tree.left) else: return decode_next_element(data, index + 1, tree.right) def encode_tree(text): if text is None: return 'No data to encode!' huff_tree = build_huff_tree( text ) huff_map = assign_code_huff_tree( huff_tree, '' ) data = '' for char in text: data += huff_map[char] return data, huff_tree def decode_tree(data, tree): text, next_index = decode_next_element(data, 0, tree) while next_index < len(data): next_element, next_index = decode_next_element(data, next_index, tree) text += next_element return text def test_encoding(text): print ("Original Text:\t\t {}".format( text )) print ("Size:\t\t\t {}".format( sys.getsizeof(text) )) encoded_data, tree = encode_tree(text) print ("Huffman Encoding:\t {}".format(encoded_data)) #print ("Size:\t\t\t {}".format( sys.getsizeof(int(encoded_data, base=2)))) decoded_data = decode_tree(encoded_data, tree) print ("Decoded Text:\t\t {}".format(decoded_data)) print ("Size:\t\t\t {}".format( sys.getsizeof(decoded_data) )) ####Test Cases #Test case 1 print( test_encoding("AAAAAAA") ) # Original Text: AAAAAAA # Size: 56 # Huffman Encoding: 0000000 # Size: 28 # Decoded Text: AAAAAAA # Size: 76 #Test case 2 print( test_encoding("EXAMPLE") ) # Original Text: EXAMPLE # Size: 56 # Huffman Encoding: 110001101010110011 # Size: 28 # Decoded Text: EXAMPLE #Test case 3 print( test_encoding("")) # Original Text: BABAAABBAEIOULMNOP # Size: 67 # Huffman Encoding: 011101111111010111101010111100101100001000000111000010 # Size: 32 # Decoded Text: BABAAABBAEIOULMNOP # Size: 67
d1ce43b63d53dbeab48ce3af36ef20482130a389
hannah-544/python
/Arithmetic operators.py
477
4.28125
4
#Types of operators # Examples of Arithmetic Operator x = 9 y = 4 # Addition of numbers add = x+y # Subtraction of numbers sub = x - y # Multiplication of number mul = x * y # Division(float) of number div1 = x / y # Division(floor) of number floor = x // y # Modulo of both number mod = x % y # Power p = x ** y # print results print(add) print(sub) print(mul) print(div1) print(floor) print(mod) print(p)
60efa0774f1a9f5c0b9b2606a213b50fa28fdb3f
tomfedrizzi/python-2020
/Ejercicios alf, tipo de datos simples.py
5,662
4.40625
4
# #Ejercicio 1 # Escribir un programa que muestre por pantalla la cadena ¡Hola Mundo!. print("¡Hola Mundo!") # #Ejercicio 2 # Escribir un programa que almacene la cadena ¡Hola Mundo! en una variable y luego muestre por pantalla #el contenido de la variable. X="¡Hola Mundo!" print(X) # #Ejercicio 3 # Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario # lo introduzca muestre por pantalla la cadena ¡Hola <nombre>!, donde <nombre> es el nombre que el usuario # haya introducido. N=input("Nombre:") print("¡Hola", N + "!") # #Ejercicio 4 # Escribir un programa que pregunte el nombre del usuario en la consola y un número entero e imprima #por pantalla en líneas distintas el nombre del usuario tantas veces como el número introducido. nombre=input("Nombre:") n=input("Número:") print((nombre + "\n") * int(n)) # Ejercicio 5 # Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario #lo introduzca muestre por pantalla <NOMBRE> tiene <n> letras, donde <NOMBRE> es el nombre de usuario #en mayúsculas y <n> es el número de letras que tienen el nombre. Nombre=input("introduce el nombre:") print(Nombre.upper() , "tiene" , (len(Nombre)), "letras") # Ejercicio 6 # Escribir un programa que realice la siguiente operación aritmética (3+22⋅5)2. Calculo=((3+2)/(2*5))**2 print(Calculo) # Ejercicio 7 # Escribir un programa que pregunte al usuario por el número de horas trabajadas y el coste por hora. #Después debe mostrar por pantalla la paga que le corresponde. Horas=float(input("Horas trabajadas:")) Coste=float(input("coste hora:")) Paga=float(Horas*Coste) print(Paga) # Ejercicio 8 # Escribir un programa que lea un entero positivo, 𝑛, introducido por el usuario y después muestre en #pantalla la suma de todos los enteros desde 1 hasta 𝑛. La suma de los 𝑛 primeros enteros positivos puede #ser calculada de la siguiente forma: # suma=𝑛(𝑛+1)2 # Ejercicio 9 # Escribir un programa que pida al usuario su peso (en kg) y estatura (en metros), calcule el índice de #masa corporal y lo almacene en una variable, y muestre por pantalla la frase Tu índice de masa corporal #es <imc> donde <imc> es el índice de masa corporal calculado redondeado con dos decimales. P=float(input("Ingresa tu peso:")) E=float(input("Ingresa tu estatura:")) IMC=float(P/E) print("Tu indice de masa corporal es:", float(IMC) , "imc"), # Ejercicio 10 # Escribir un programa que pida al usuario dos números enteros y muestre por pantalla la <n> entre <m> da #un cociente <c> y un resto <r> donde <n> y <m> son los números introducidos por el usuario, y <c> y <r> #son el cociente y el resto de la división entera respectivamente. n=int(input("Numero entero:")) m=int(input("Numero entero:")) c=int(n//m) r=int(n%m) print("La", n , "entre la" , m ,"da un cociente de" , c , "y un resto de" , r) # Ejercicio 11 # Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de # años, y muestre por pantalla el capital obtenido en la inversión. C=float(input("Cantidad a invertir:")) I=float(input("Interes anual:")) A=int(input("Numero de años:")) Ca=C*I*A print("El capital obtenido para la inversion es:", Ca, "€") # Ejercicio 12 # Una juguetería tiene mucho éxito en dos de sus productos: payasos y muñecas. Suele hacer venta por #correo y la empresa de logística les cobra por peso de cada paquete así que deben calcular el peso de #los payasos y muñecas que saldrán en cada paquete a demanda. Cada payaso pesa 112 g y cada muñeca 75 g. #Escribir un programa que lea el número de payasos y muñecas vendidos en el último pedido y calcule el #peso total del paquete que será enviado. P=int(input("Cantidad de payasos:")) M=int(input("Cantidad de muñecas:")) S=P+M pesop=float(P*112) pesom=float(M*75) Peso=pesop+pesom print("Cantidad de payasos y muñecas vendidas:", S, "unidades") print("Su peso total es", Peso, "kg") # Ejercicio 13 # Imagina que acabas de abrir una nueva cuenta de ahorros que te ofrece el 4% de interés al año. #Estos ahorros debido a intereses, que no se cobran hasta finales de año, se te añaden al balance final #de tu cuenta de ahorros. Escribir un programa que comience leyendo la cantidad de dinero depositada en #la cuenta de ahorros, introducida por el usuario. Después el programa debe calcular y mostrar por #pantalla la cantidad de ahorros tras el primer, segundo y tercer años. Redondear cada cantidad a dos #decimales. C=float(input("Cantidad de dinero ca:")) primer=float(C*1+0.4) segundo=float(primer*1+0.4) tercero=float(segundo*1+0.4) print("la cantidad de ahorros en el primer año fue de", (round(primer, 2)), "€") print("la cantidad de ahorros en el segundo año fue de", (round(segundo,2)), "€") print("la cantidad de ahorros en el tercer año fue de" , (round(tercero, 2)), "€") # Ejercicio 14 # Una panadería vende barras de pan a 3.49€ cada una. El pan que no es del día tiene un descuento del 60%. # Escribir un programa que comience leyendo el número de barras vendidas que no son del día. Después el #programa debe mostrar el precio habitual de una barra de pan, el descuento que se le hace por no ser #fresca y el coste final total. Bv=int(input("Ingrese numero de barras que no son del dia:")) Preciobarra=3.49 Preciobarravieja=3.49*0.6 Descuento=60 Total=Preciobarra-Preciobarravieja print("el precio de una barra de pan es de:", Preciobarra, "€") print("el descuento por ser vieja es de ", Descuento, "%") print("Coste final es:", float(Bv*Total), "€")
277d6e3f339efd0c2f0212a171e17d50d98e05aa
JonLagrange/Machine-Learning
/kerasLearn/mlp.py
1,908
3.53125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data class hello_world: def __init__(self): self.mnist = input_data.read_data_sets("mnist_data/", one_hot=True) def inference(self): self.input = tf.placeholder(tf.float32, [None, 784]) #输入28*28的图 self.label = tf.placeholder(tf.float32, [None, 10]) #正确的分类标签 with tf.variable_scope('model'): w = tf.Variable(tf.truncated_normal([784,10],stddev=0.1)) #权重参数 b = tf.Variable(tf.zeros([10])) #偏置参数 y = tf.nn.softmax(tf.matmul(self.input, w) + b) # 10个分类输出(0-9数字) with tf.variable_scope('optimize'): cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.label * tf.log(y), reduction_indices=[1])) #使用交叉熵获得损失函数 self.train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) #使用梯度下降法最小化损失函数 with tf.variable_scope('accuracy'): correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(self.label, 1)) #预测值是否正确 self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #求正确率 def train(self): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): #训练1000轮,每次100条数据 batch_data, batch_label = self.mnist.train.next_batch(100) sess.run(self.train_step,{self.input:batch_data, self.label:batch_label}) print('accuracy : %f' % sess.run(self.accuracy,{self.input: self.mnist.test.images, self.label: self.mnist.test.labels})) if __name__ == '__main__': power = hello_world() power.inference() power.train()