blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
61a2d136c424dd22879900020fa5d846e5384103
MillicentMal/alx-higher_level_programming-1
/0x01-python-if_else_loops_functions/100-print_tebahpla.py
99
3.765625
4
#!/usr/bin/python3 for i in range(0, 26, 2): print("{:c}{:c}".format(122-i, 89-i), end='')
caf493232358a30eb08b99fc7ce8d60c41c64f92
javaInSchool/python1_examples
/les4/example3.py
380
3.78125
4
bitcoin = 45000 print("Очень дорогой биткоин, подождем") while ( bitcoin > 35000 ): bitcoin = bitcoin - 1 print("Падает до : " + str(bitcoin) ) print("О, цена подходит, куплю биткоин") while( True ): # бесконечный цикл bitcoin = bitcoin + 1 print("Падает до : " + str(bitcoin))
1cdc7fc72a077976521d96334aaba9f292f4e46f
bgoonz/UsefulResourceRepo2.0
/GIT-USERS/amitness/ML-From-Scratch/mlfromscratch/examples/genetic_algorithm.py
1,265
3.75
4
from mlfromscratch.unsupervised_learning import GeneticAlgorithm def main(): target_string = "Genetic Algorithm" population_size = 100 mutation_rate = 0.05 genetic_algorithm = GeneticAlgorithm(target_string, population_size, mutation_rate) print("") print("+--------+") print("| GA |") print("+--------+") print("Description: Implementation of a Genetic Algorithm which aims to produce") print("the user specified target string. This implementation calculates each") print( "candidate's fitness based on the alphabetical distance between the candidate" ) print( "and the target. A candidate is selected as a parent with probabilities proportional" ) print("to the candidate's fitness. Reproduction is implemented as a single-point") print("crossover between pairs of parents. Mutation is done by randomly assigning") print("new characters with uniform probability.") print("") print("Parameters") print("----------") print("Target String: '%s'" % target_string) print("Population Size: %d" % population_size) print("Mutation Rate: %s" % mutation_rate) print("") genetic_algorithm.run(iterations=1000) if __name__ == "__main__": main()
9bfea64d9237814ddf272ae64278314eda0e3c20
sysinit2811/python
/while_1.py
159
4.03125
4
num = 0 input_str = raw_input('inpu a number: ') while input_str !='pc': num = num + int(input_str) input_str = raw_input('input a number: ') print num
ad13fb3a13059b2156b4572b93d92542d0c1e87e
kaioschmitt/programming-logic
/python/if_else/if_else#01.py
297
4.1875
4
st_number = input('Insert the first number: ') nd_number = input('Insert the second number: ') if st_number > nd_number: print(f"{st_number} is greater than {nd_number}") elif st_number < nd_number: print(f"{st_number} is less than {nd_number}") else: print('The numbers are equals')
9517019e77b42bf83110b18e3ea916ceac5abefd
Vandor13/SmartCalculator
/Problems/Memory test/main.py
225
3.875
4
numbers = input().split() answers = input().split() correct_set = set() for number in numbers: correct_set.add(number) answer_set = set() for answer in answers: answer_set.add(answer) print(correct_set == answer_set)
ea66d04a2376ba101a23604d7ffc74d8609e1d4d
riddhitg/c99
/fileOrganiser.py
714
4.15625
4
import os import shutil #enter the name of the folder to be sorted path = input("enter the name od the directory to be sorted: ") #list of all the files and folders in the directory list_of_files = os.listdir(path) #go through each and every file for file in list_of_files: name,ext = os.path.splitext(file) #store the extension type ext = ext[1:] #if it is a directory, go to the next loop if ext == '': continue #move the file to the folder name ext if os.path.exists(path + '/'+ext): shutil.move(path+'/'+file,path+'/'+ext+'/'+file) else: os.makedirs(path+'/'+ext) shutil.move(path+'/'+file,path+'/'+ext+'/'+file)
7069c7621cdecf2b25337f05fddaeb3321002ac6
cntsp/homework
/day7/ftpclient/core/main.py
4,490
3.5625
4
import socket import os import json import hashlib from authentication import User import commands class FtpClient(object): """ define the ftpclient class """ def __init__(self, host="localhost", port=9999): self.client = socket.socket() self.host = host self.port = port self.client_user = User() self.connection(self.host, self.port) def connection(self, *args): # print(args[0], args[1]) # self.client = socket.socket() c1 = self.client.connect((args[0], args[1])) # print("line25: ", c1) if not c1: username = self.client_user.login(self.client) if username: commands.cmd.help() self.handle(username) self.client.close() else: print("the client failed to connect to the server") def handle(self, username): """ analyze the data entered, in order to get command and filename. :return: """ # 实例化一个所有命令的对象 command1 = commands.cmd(self.client) flag = True home_directory = "/home/%s" % username current_directory = home_directory while flag: # print("current_directory:", current_directory) while True: enter_data = input("\033[32;1mftp>[%s]\033[0m" % current_directory).strip() if len(enter_data) > 0: enter_data_tuple = enter_data.split() break if enter_data_tuple[0].startswith('put') or enter_data_tuple[0].startswith('get'): command = enter_data_tuple[0] filename = enter_data_tuple[1] if hasattr(command1, "cmd_{}".format(command)): # print("@@@@:command1", commands.cmd(self.client)) # filepath = up_down_file_path + "/" + filename if os.path.isfile(filename) or enter_data_tuple[0].startswith('get') : # print("ftpclient line 38:") try: size = os.stat(filename).st_size except FileNotFoundError as e: size = 0 msg_dict = { "username": username, "action": command, "filename": filename, "file_size": size, "override": True, "home_directory": home_directory, "current_directory": current_directory } func = getattr(command1, "cmd_{}".format(command)) # print("line 68", func) current_directory = func(msg_dict) else: print("your operate {} file is not exist!".format(filename)) elif enter_data_tuple[0].startswith('ls') or enter_data_tuple[0].startswith('cd') or enter_data_tuple[0].startswith('mkdir'): try: command = enter_data_tuple[0] second_parameter = enter_data_tuple[1] # print("line 71:",command, second_parameter) msg_dict = { "action": command, "second_parameter": second_parameter, "username": username, "home_directory": home_directory, "current_directory": current_directory } # print("@@@ line 57:") except IndexError as e: print("your enter commands has a false:", e) if hasattr(command1, "cmd_{}".format(enter_data_tuple[0])): func = getattr(command1, "cmd_{}".format(enter_data_tuple[0])) current_directory = func(msg_dict) # print("### current_directory:", current_directory) elif enter_data_tuple[0].startswith('exit'): flag = False else: print("\033[32;1mthe data of your enter has error! please Usage: \033[0m") commands.cmd.help() if __name__ == "__main__": f1 = FtpClient()
1d3bbb5b0674386fb991f14cd49d1ec97f665628
barthezz16/python_base_lessons
/lesson_004/02_global_color.py
3,435
3.703125
4
# -*- coding: utf-8 -*- import simple_draw as sd sd.set_screen_size(900, 900) # Добавить цвет в функции рисования геом. фигур. из упр lesson_004/01_shapes.py # (код функций скопировать сюда и изменить) # Запросить у пользователя цвет фигуры посредством выбора из существующих: # вывести список всех цветов с номерами и ждать ввода номера желаемого цвета. # Потом нарисовать все фигуры этим цветом # Пригодятся функции # sd.get_point() # sd.line() # sd.get_vector() # и константы COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_PURPLE # Результат решения см lesson_004/results/exercise_02_global_color.jpg def figures(start_point=sd.get_point(400, 400), angle=0, length=200, width=3): line = sd.get_vector(start_point, angle, length, width) line.draw(color=colors[color_number]) return line.end_point def shapes_draw(start_point, end_point, next_angle=0, length=200, width=3, angle_step=0): for angle in range(0, 360 - angle_step, angle_step): start_point = figures(start_point, angle + next_angle, length, width) else: sd.line(start_point=start_point, end_point=end_point, color=colors[color_number], width=3) sd.set_screen_size(900, 900) point = sd.get_point(400, 400) colors = (sd.COLOR_RED, sd.COLOR_ORANGE, sd.COLOR_YELLOW, sd.COLOR_GREEN, sd.COLOR_CYAN, sd.COLOR_BLUE, sd.COLOR_PURPLE) print('Возможные цвета', '\n', '0 : red', '\n', '1 : orange', '\n', '2 : yellow', '\n', '3 : green', '\n', '4 : cyan', '\n', '5 : blue', '\n', '6 : purple') while True: user_input = input("Введите желаемый цвет ") color_number = int(user_input) if color_number <= len(colors) - 1: break else: print('Введен некорректный номер') length = 200 start_point_hexagon_x = point.x + 150 start_point_hexagon_y = point.y - 150 start_point_pentagon_x = point.x - 150 start_point_pentagon_y = point.y - 150 start_point_square_x = point.x - 150 start_point_square_y = point.y + 150 start_point_triangle_x = point.x + 150 start_point_triangle_y = point.y + 150 triangle_point = sd.get_point(start_point_triangle_x, start_point_triangle_y) hexagon_point = sd.get_point(start_point_hexagon_x, start_point_hexagon_y) pentagon_point = sd.get_point(start_point_pentagon_x, start_point_pentagon_y) square_point = sd.get_point(start_point_square_x, start_point_square_y) triangle_angle = 120 square_angle = 90 pentagon_angle = 72 hexagon_angle = 60 shapes_draw(start_point=triangle_point, end_point=triangle_point, next_angle=triangle_angle, length=length, width=3, angle_step=triangle_angle) shapes_draw(start_point=square_point, end_point=square_point, next_angle=square_angle, length=length, width=3, angle_step=square_angle) shapes_draw(start_point=pentagon_point, end_point=pentagon_point, next_angle=pentagon_angle, length=150, width=3, angle_step=pentagon_angle) shapes_draw(start_point=hexagon_point, end_point=hexagon_point, next_angle=hexagon_angle, length=125, width=3, angle_step=hexagon_angle) sd.pause() sd.pause() #зачет!
b51e5ad59569d99b72c5f092211adf593e999526
jsburckhardt/theartofdoing
/22_database_admin_app.py
1,199
4.09375
4
# Greeting app = "Database Admin" print(f"Welcome to the {app} app!\n") database = { "mooman74": "alskes145", "meramo1986": "kehns010101", "nickyd": "world1star", "george2": "boo3oha", "admin00": "admin1234", } # input from user username_input = input("Enter your username: ").strip().lower() if username_input in database.keys(): password_input = input("Enter your password: ").strip() if password_input == database[username_input]: print(f"\nHello {username_input}! You are logged in!") if username_input == 'admin00': for user, value in database.items(): print(f"Username: {user}\t\tPassword: {value}") else: change_password = input("Would you like to change your password (yes/no): ").strip().lower() if change_password == 'yes': new_password = input("What would you like your new password to be: ").strip() if len(new_password) > 8: database[username_input] = new_password else: print(f"{new_password} not the minimum eight characters.") print(f"\n{username_input} your password is {database[username_input]}") else: print("wrong option") else: print("User not in database")
7ee0f54fa1a968f1b27eb75caba8f2f3eda16d56
ctec121-spring19/programming-assignment-3-loops-and-numerics-Treydog14
/Prob-5/Prob-5.py
666
3.828125
4
# Module 2 # Programming Assignment 3 # Prob-5.py # Trevor Bromley def main(): slice = 2.0 largeDrink = 1.5 donut = .56 sum = 0 print("Pizza @ 2:\t", slice * 2) sum = slice * 2 print("Drink:\t\t", largeDrink) sum = sum + largeDrink print("Donut @ 2:\t", donut * 2) sum = sum + donut print("---------") tax = .56 print("Tax:\t\t", tax) sum = sum + tax print("\nTotal:\t\t", sum) print() tendered = eval(input("Please enter an amount: ")) print("Tendered:\t{0:.2f} xyz {1:.2f}".format(tendered, sum)) change = tendered - sum print("Change:\t\t{0:.2f}".format(change)) main()
834f749d67710093e7b99f02a6bf33e24b191716
raghav-menon/EPAiSession11
/Polygon_Sequence.py
2,400
4.34375
4
from Polygon import Polygon class Polygons: """Implementaion Of Custom Sequence of Polygons which takes largest \ polygon num of edges and circumradius as input""" def __init__(self, m, R): """ Function initialising the number of edges and circumradius""" if m < 3: raise ValueError('m must be greater than 3') self._m = m self._R = R self._polygons = [Polygon(i, R) for i in range(3, m+1)] def __len__(self): """Function returning the length of sequence""" return self._m - 2 def __repr__(self): """Repr Function to print regarding the initialized variables""" return f'Polygons(m={self._m}, R={self._R})' def __getitem__(self, s): """Function to retrieve a particular element in the sequence or a \ list of elements""" return self._polygons[s] def __iter__(self): """Iterator Function--> This function converts this class to an \ Iterator returning an Iterator object""" return self.PolygonIter(self) @property def max_efficiency_polygon(self): """Function to calculate the maximum efficiency of the Polygon""" sorted_polygons = sorted(self._polygons, key=lambda p: p.area/p.perimeter, reverse=True) return sorted_polygons[0] class PolygonIter: """This is an Iterator class which converts the main class into an \ Iterator""" def __init__(self, polyobj): """Function initializing the polygon sequence object and \ index. Index is used to return the next element in the polygon\ sequence when used as a iterator""" self._polyobj = polyobj self._index = 0 def __iter__(self): """Iterator function which makes it an iterator object""" return self def __next__(self): """Next function to return the next element from an polygon \ sequence iterator object""" if self._index >= len(self._polyobj): raise StopIteration else: item = self._polyobj._polygons[self._index] self._index += 1 return item
439328ae5f819e5284635239d8417b536ade66f4
anchuanxu/Python-Elementary-Exercise-100-Questions
/PycharmProjects/test11-20/11.py
146
3.859375
4
# 斐波那契数列 f1=1 f2=1 for i in range(1,22): print('%12ld%12ld'%(f1,f2)) if(i%3==0): print (' ') f1=f1+f2 f2=f1+f2
9d69eb04b9a7b7d7f6eb6600a56da563ab779e22
HyunAm0225/Python_Algorithm
/정렬/quick.py
995
3.78125
4
array = [5,7,9,0,3,1,6,2,4,8] def quick_sort(array,start,end): if start >= end: # 원소가 1개인 경우 종료 return pivot = start # 피벗은 첫 번째 원소 left = start + 1 right = end while left <= right: # 피벗보다 큰 데이터를 찾을 떼 까지 반복 while left <= end and array[left] <= array[pivot]: left += 1 # 피벗보다 작은 데이터를 찾을 때 까지 반복 while right > start and array[right] >= array[pivot]: right -= 1 if left > right: # 만약 엇갈렸다면 작은 right -= 1 데이터와 피벗을 교체합니다 array[right], array[pivot] = array[pivot], array[right] else: array[left], array[right] = array[right], array[left] # 분할 이후 왼쪽 부분과 오른쪽 부분에서 각각 정렬 수행 quick_sort(array,start,right-1) quick_sort(array,right+1,end) quick_sort(array,0,len(array)-1) print(array)
bfa6cfb66cef59a155d506921ecc25c40a747b66
pedroromn/pywork
/pycode/decimal_to_binary.py
499
4.28125
4
# -*- coding: utf-8 -*- """ Date: 28/08/2015 author: peyoromn """ def decimal_to_binary(decimal): bstring = "" while decimal > 0: remainder = decimal % 2 decimal = decimal / 2 bstring = str(remainder) + bstring return bstring def main(): decimal = input("Enter a decimal integer: ") binary = decimal_to_binary(decimal) print "The binary representation is: {}".format(binary) if __name__ == '__main__': main()
43f85f9eb32c0ef8f9ea1fce5fad2156d79bee31
arnogils/language-detector
/tests/detector_tests.py
823
3.609375
4
import unittest from language_detector import LanguageDetector class LanguageDetectorTests(unittest.TestCase): def setUp(self): self.detector = LanguageDetector() def test_language_not_detected(self): self.assertEqual('Language not detected', self.detector.guess_language('')) def test_dutch_detected(self): message = "de het en een" self.assertEqual('Dutch', self.detector.guess_language(message)) def test_english_detected(self): message = "the it and a" self.assertEqual('English', self.detector.guess_language(message)) def test_german_detected(self): message = "der die das und" self.assertEqual('German', self.detector.guess_language(message)) def tearDown(self): print "Finished {0}".format(self._testMethodName)
0f26fe81ca67b4b96b837cefc21c35a1edae5a19
daltonb3657/cti110
/M2HW1_DistanceTraveled_BrandonDalton.py
416
3.8125
4
# CTI-110 # M2HW1 - Distance Traveled # Brandon Dalton # 9/10/2017 # speed = 70 distanceAfter6 = speed * 6 distanceAfter10 = speed * 10 distanceAfter15 = speed * 15 print('The distance the car will travel in 6 hours is', distanceAfter6, 'miles') print('The distance the car will travel in 10 hours is', distanceAfter10, 'miles') print('The distance the car will travel in 15 hours is', distanceAfter15, 'miles')
926d25f9424fb88283a55a61ba4d9fa7bc550cda
wuxu1019/leetcode_sophia
/dailycoding_problem/XOR_linkedlist.py
1,654
4.125
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses. """ class ListNode(object): def __init__(self, val): self.val = val self.xor = 0 class LinkedList(object): def __init__(self): self.head = None self.tail = None def add(self, element): newnode = ListNode(element) newaddr = dereference_pointer(newnode) if not self.head and not self.tail: self.head, self.tail = newnode, newnode return self.tail.xor ^= newaddr self.tail = newnode return def get(self, index): pre, cur = 0, self.head start = 0 while start < index and cur != self.tail: pre, cur = dereference_pointer(cur), get_pointer(pre ^ cur.xor) start += 1 if start == index: return cur.val else: return None if __name__ == '__main__': l = LinkedList() l.add(1) l.add(2) l.add(3) rt1 = l.get(0) rt2 = l.get(1) rt3 = l.get(2) rt4 = l.get(3) print rt1, rt2, rt3, rt4
4a38969ab9e1cbe958faedc81a168c678fa07ff9
pingyangtiaer/DataStructureAlgorithmDesign
/python/QuickSort.py
671
3.953125
4
#!/usr/bin/env python def partition(ls, l, r): # choose the last element as pivot pivot = ls[r] #due to the fact that we input the full array every time, #beware of the lower and upper label of this range for i in xrange(l, r): if ls[i] < pivot: ls[l], ls[i] = ls[i], ls[l] l += 1 # put pivot in the right position ls[r], ls[l] = ls[l], ls[r] return l def quickSort(ls, l, r): if l > r: return po = partition(ls, l, r) #the input is the full array each time quickSort(ls, l, po-1) quickSort(ls, po+1, r) ls = [1, 5, 3, 7, 4, 10, 9, 12] quickSort(ls, 0, len(ls)-1) print ls
a210ac26b30cf43767a3993db5f2944be9ddb1b0
chaofan-zheng/tedu-python-demo
/month02/day11/exercise01_server.py
997
3.640625
4
""" 练习3:上传头像的练习 假设客户端需要将自己的头像上传给服务端 请编写程序完成该工作,在服务端以当前日期 保存为jpg格式 2020-12-10.jpg 客户端: 读文件 发送文件内容 服务端: 接收文件内容 写入本地 """ from socket import * from time import localtime # 接收文件 (具体事件) def recv_image(connfd): # 组织文件名 filename = "%s-%s-%s" % localtime()[:3] + ".jpg" file = open(filename, "wb") while True: # 边收边写 data = connfd.recv(1024) if not data: break file.write(data) file.close() connfd.close() def main(): # 创建tcp套接字 tcp_socket = socket() tcp_socket.bind(("0.0.0.0", 8888)) tcp_socket.listen(5) while True: connfd, addr = tcp_socket.accept() print("Connect from", addr) # 调用函数接收图片 recv_image(connfd) if __name__ == '__main__': main()
60f7fed644c7d5b7e7af1ed2205095b35e2dd276
artbohr/codewars-algorithms-in-python
/7-kyu/tram-capacity.py
1,696
3.90625
4
def tram(stops, descending, onboarding): on_board = 0 max_cap = 0 for x in range(stops): on_board -= descending[x] on_board += onboarding[x] if on_board > max_cap: max_cap = on_board return max_cap ''' Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Your task Calculate the tram's minimum capacity such that the number of people inside the tram never exceeds this capacity at any time. Note that at each stop all exiting passengers exit before any entering passenger enters the tram. Example tram(4, {0, 2, 4, 4}, {3, 5, 2, 0}) ==> 6 Explaination: The number of passengers inside the tram before arriving is 0. At the first stop 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. At the second stop 2 passengers exit the tram (1 passenger remains inside). Then 5 passengers enter the tram. There are 6 passengers inside the tram now. At the third stop 4 passengers exit the tram (2 passengers remain inside). Then 2 passengers enter the tram. There are 4 passengers inside the tram now. Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer. '''
5c124e2205548c5d19f19798abc5fbb44f057d51
zhongshj/leetcode
/101-150/141.linked-list-cycle.py
665
3.953125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ # go through the list and set each .next to one node # if ends with that node, circle exist; else it should ends with None terminate = ListNode('#') p1 = head p2 = head while p1 != None: p1 = p1.next p2.next = terminate p2 = p1 if p1 == terminate: return True return False
8bdb5a76063373bb0439763ad6eae72ceb38f078
yedidimr/machineLearning
/python_ex/game_of_life_3d.py
1,005
3.65625
4
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D n=100 #size # starting board A = np.random.choice(a=[0,1], size=n*n*n).reshape(n,n,n) movements = equals to [(i,j,k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, 1) if (i != 0 or j != 0 or k!=0)] #create black and white image fig = plt.figure() # use axes instead of im = plt.imshow in order to disable x,y ticks and not opening two windows ax = fig.add_axes([0, 0, 0, 1, 1, 1], xticks=[], yticks=[], zticks=[], frameon=False, projection='3d') # todo: load 3d matrix # im = ax.imshow(A, cmap='Greys', interpolation='nearest', animated=True) def next_step(*args): global A #sum any cell's neighbours sum_square = sum(np.roll(np.roll(np.roll(A, i, 0), j, 1), k, 2) for (i, j, k) in movements) # todo: fill conditions im.set_data(A) return im, ani = animation.FuncAnimation(fig, next_step, interval=150, blit=True) plt.show()
23a45fd8cfa7929b52dab07ba67e9fb9e03dc1f4
robertdahmer/Exercicios-Python
/Projetos Python/Aulas Python/Estudos aleatórios/Desafio 052.py
391
3.828125
4
#Faça um programa que leia um número inteiro e diga se ele é ou não um número primo. primo = int(input('Digite número: ')) tot = 0 for c in range(1, primo + 1): if primo % c == 0: print('\033[34m', end='') tot += 1 else: print('\033[m', end='') print('{} '.format(c), end='') print('\n\033[mO número {} foi divisível {} vezes'.format(primo, tot))
7420f15ff987219d1740af6e17a55bfbd69117d2
seanwentzel/crypto-hons
/tut6-elgamal/q3_helper.py
999
3.671875
4
def f(u, g, a, m, b_1, b_2): if u <= b_1: return (g*u % m, 1) if u <= b_2: return (u**2 % m, 2) return (a*u % m, 3) def exponents(b,c,m, set_num): if set_num == 1: b = (b + 1) % m if set_num == 2: b = (2*b) % m c = (2*c) % m if set_num == 3: c = (c+1) % m return (b,c) def rho(g,a,m,b,b_1,b_2): print("\\begin{tabular}{l l l l}") print("i & $u_i \mod {0}$ & $b_i$ & $c_i$ \\\\\\hline".format(m)) u = [g**b % m] c = 0 i = 1 print_row(i,u[0],b,c) i+=1 done = False while not done: val, set_num = f(u[-1], g,a,m,b_1,b_2) b,c = exponents(b,c,m-1,set_num) print_row(i, val, b, c) u.append(val) if len(u) % 2==0: if u[-1] == u[(len(u)-1)//2]: done = True i += 1 print("\\end{tabular}") return u def print_row(i,u,b,c): print("{0} & {1} & {2} & {3} \\\\\\hline".format(i,u,b,c)) rho(2,58,83,27,55,33)
410fd3f9dd7a1c422088012e32111a1b6794afde
Alek-dr/GraphLib
/core/algorithms/bfs.py
1,497
3.578125
4
from collections import OrderedDict, deque from typing import Dict, Union from core.exceptions import VertexNotFound from core.graphs.graph import AbstractGraph, edge from core.graphs.walk import Walk def bfs( graph: AbstractGraph, origin: Union[str, int], target: Union[str, int] = None, ) -> Dict[Union[int, str], Walk]: """ BFS algorithm :param graph: graph object :param origin: name or id of origin node :param target: node to find path. If target is None all paths will be returned :return: shortest path to target or all possible paths to all nodes if target is not specified """ if (target is not None) and (not graph[target]): raise VertexNotFound(f"Cannot find vertex {target}") p = Walk(origin) if origin == target: return {origin: p} visited = set() visited.add(origin) queue = deque() e = edge(origin, origin, 0, None) queue.append(e) walks = OrderedDict() walk = Walk(origin) walk.add_step(e) walks[origin] = walk while queue: curr_edge = queue.pop() for e in graph.get_adj_edges(curr_edge.dst): if e.dst not in visited: path = Walk(e.dst) path.add_step(e) walks[e.dst] = walks[e.src] + path if (target is not None) and (walks.get(target)): return {target: walks[target]} queue.appendleft(e) visited.add(e.dst) return walks
0a12df3a8504a68b53dea8efde0dec73ec41d29e
ErickS05/EjerciciosFinal
/Ejecicios -Modulo 2/python mario.py
268
3.953125
4
n = 0 while n < 8: numero = int(input('Ingresa numero entero ')) validos = [1, 2, 8] if numero in validos: for i in range(1,numero+1): print(" " * (int(numero) - i) + '#' * int(i)) else: print('entrada invalida')
a269ee21ff2bbdf4b6791bfb2719eb03543cfeee
ReethP/Kattis-Solutions
/fizzbuzz.py
228
3.546875
4
uint = input().split() a = int(uint[0]) b = int(uint[1]) c = int(uint[2]) for i in range(1,c+1): if(i%a ==0 and i%b == 0): print("FizzBuzz") elif(i%a == 0): print("Fizz") elif(i%b == 0): print("Buzz") else: print(i)
91c16bec74c4cd322c710709c225e0ff23feb805
yxtay/how-to-think-like-a-computer-scientist
/Files/files_ex3_students_minmax.py
302
3.546875
4
def int_list(lst): outlist = [] for el in lst: outlist.append(int(el)) return outlist infile = open("studentdata.txt") line = infile.readline() while line: values = line.split() scores = int_list(values[1:]) print values[0], min(scores), max(scores) line = infile.readline() infile.close()
8a8beff978f204b4f8c1ee568b65fd310b40c26f
SamriddhiMishra/DSA-Solutions
/Recursion/Day-2/power_set.py
471
3.65625
4
# I - Array , O - Power Set(Including Empty) # Time- O(n*n) Space - O(n *2^n) def power_set(arr, n): if n >= len(arr): return [[]] f = arr[n] p = power_set(arr, n+1) for i in range(len(p)): if len(p[i]) == 0: p.append([f]) else: e = p[i].copy() # don't put like p[i].copy().insert(0,f) gives None e.insert(0,f) p.append(e) return p print(power_set([1,2,3], 0))
8682381712edd47790aff3efb48e4ae76cbe6ff2
yosef8234/test
/hackerrank/python/data-types/tuples.py
1,168
4.28125
4
# -*- coding: utf-8 -*- # Tuples are data structures that look a lot like lists. Unlike lists, tuples are immutable (meaning that they cannot be modified once created). This restricts their use because we cannot add, remove, or assign values; however, it gives us an advantage in space and time complexities. # A common tuple use is the swapping of 22 numbers: # a,b = b,a # Here a,ba,b is a tuple, and it assigns itself the values of b,ab,a. # Another awesome use of tuples is as keys in a dictionary. In other words, tuples are hashable. # Task # You are given an integer, NN, on a single line. The next line contains NN space-separated integers. Create a tuple, TT, of those NN integers, then compute and print the result of hash(TT). # Note: hash() is one of the functions in the __builtins__ module. # Input Format # The first line contains an integer, NN (the number of elements in the tuple). # The second line contains NN space-separated integers describing TT. # Output Format # Print the result of hash(TT). # Sample Input # 2 # 1 2 # Sample Output # 3713081631934410656 N = int(input()) T = tuple(int(i) for i in input().split()) print(hash(T))
807cc52470006b68d445a214936b6bc2d429f4aa
r3mas/python_tutorial
/codecademy/lesson10.py
177
3.890625
4
my_dict = { "Name": "Guido", "Age": 56, "BDFL": True, "Lazy": True } print my_dict.keys() print my_dict.values() for key in my_dict: print key,my_dict[key]
18eedfd78d64a85eae2a9a32fd40283c358c8f22
krivchnik/visualization_task
/visualizer/visualizer.py
10,098
3.578125
4
import random import numpy import scipy from math import sqrt class Node: def __init__(self): self.mass = 0.0 self.old_dx = 0.0 self.old_dy = 0.0 self.dx = 0.0 self.dy = 0.0 self.x = 0.0 self.y = 0.0 class Edge: def __init__(self): self.node1 = -1 self.node2 = -1 self.weight = 0.0 # Repulsion function. 'n1' and 'n2' are nodes. def lin_repulsion(n1, n2, coefficient=0): xDist = n1.x - n2.x yDist = n1.y - n2.y distance2 = xDist * xDist + yDist * yDist # Distance squared if distance2 > 0: factor = coefficient * n1.mass * n2.mass / distance2 n1.dx += xDist * factor n1.dy += yDist * factor n2.dx -= xDist * factor n2.dy -= yDist * factor # Gravity repulsion function. def lin_gravity(n, g): xDist = n.x yDist = n.y distance = sqrt(xDist * xDist + yDist * yDist) if distance > 0: factor = n.mass * g / distance n.dx -= xDist * factor n.dy -= yDist * factor # Strong gravity force function. `n` should be a node, and `g` should be a constant by which to increase the force. def strong_gravity(n, g, coefficient=0): xDist = n.x yDist = n.y if xDist != 0 and yDist != 0: factor = coefficient * n.mass * g n.dx -= xDist * factor n.dy -= yDist * factor # Attraction function. `n1` and `n2` should be nodes. # Will directly ajust positions def lin_attraction(n1, n2, e, distributed_attraction, coefficient=0): xDist = n1.x - n2.x yDist = n1.y - n2.y if not distributed_attraction: factor = -coefficient * e else: factor = -coefficient * e / n1.mass n1.dx += xDist * factor n1.dy += yDist * factor n2.dx -= xDist * factor n2.dy -= yDist * factor def apply_repulsion(nodes, coefficient): i = 0 for n1 in nodes: j = i for n2 in nodes: if j == 0: break lin_repulsion(n1, n2, coefficient) j -= 1 i += 1 def apply_gravity(nodes, gravity, use_strong_gravity=False): if not use_strong_gravity: for n in nodes: lin_gravity(n, gravity) else: for n in nodes: strong_gravity(n, gravity) def apply_attraction(nodes, edges, distributedAttraction, coefficient, edgeWeightInfluence): # Optimization, since usually edgeWeightInfluence is 0 or 1, and pow is slow if edgeWeightInfluence == 0: for edge in edges: lin_attraction(nodes[edge.node1], nodes[edge.node2], 1, distributedAttraction, coefficient) elif edgeWeightInfluence == 1: for edge in edges: lin_attraction(nodes[edge.node1], nodes[edge.node2], edge.weight, distributedAttraction, coefficient) else: for edge in edges: lin_attraction(nodes[edge.node1], nodes[edge.node2], pow(edge.weight, edgeWeightInfluence), distributedAttraction, coefficient) # Adjust speed and apply forces step def adjust_speed_and_apply_forces(nodes, speed, speed_efficiency, jitter_tolerance): # Auto adjust speed. swing_amount = 0.0 # How much irregular movement total_effective_traction = 0.0 # How much useful movement for n in nodes: swinging = sqrt((n.old_dx - n.dx) * (n.old_dx - n.dx) + (n.old_dy - n.dy) * (n.old_dy - n.dy)) swing_amount += n.mass * swinging total_effective_traction += .5 * n.mass * sqrt( (n.old_dx + n.dx) * (n.old_dx + n.dx) + (n.old_dy + n.dy) * (n.old_dy + n.dy)) # Optimize jitter tolerance. estimated_optimal_jit_tolerance = .05 * sqrt(len(nodes)) min_jit_tolerance = sqrt(estimated_optimal_jit_tolerance) max_jit_tolerance = 10 jt = jitter_tolerance * max(min_jit_tolerance, min(max_jit_tolerance, estimated_optimal_jit_tolerance * total_effective_traction / ( len(nodes) * len(nodes)))) min_speed_efficiency = 0.05 # Protect against erratic behavior if swing_amount / total_effective_traction > 2.0: if speed_efficiency > min_speed_efficiency: speed_efficiency *= .5 jt = max(jt, jitter_tolerance) target_speed = jt * speed_efficiency * total_effective_traction / swing_amount if swing_amount > jt * total_effective_traction: if speed_efficiency > min_speed_efficiency: speed_efficiency *= .7 elif speed < 1000: speed_efficiency *= 1.3 # Speed shoudn't rise too much too quickly max_rise = .5 speed = speed + min(target_speed - speed, max_rise * speed) # Apply forces. for n in nodes: swinging = n.mass * sqrt((n.old_dx - n.dx) * (n.old_dx - n.dx) + (n.old_dy - n.dy) * (n.old_dy - n.dy)) factor = speed / (1.0 + sqrt(speed * swinging)) n.x = n.x + (n.dx * factor) n.y = n.y + (n.dy * factor) values = {} values['speed'] = speed values['speed_efficiency'] = speed_efficiency return values class ForceAtlas2: def __init__(self, # Размазывание по краям distribute_outbound_attraction=False, # Влияние веса ребра edge_weight_influence=1.0, # Степень свободы jitter_tolerance=1.0, # Степень оттлакивания scaling_ratio=2.0, # Режим сильной гравитации strong_gravity_mode=False, # Гравитация (к центру) gravity=1.0): self.distribute_outbound_attraction = distribute_outbound_attraction self.edge_weight_influence = edge_weight_influence self.jitter_tolerance = jitter_tolerance self.scaling_ratio = scaling_ratio self.strong_gravity_mode = strong_gravity_mode self.gravity = gravity def init(self, G, # 2D numpy ndarray or scipy sparse matrix format pos=None # Array of initial positions ): is_sparse = False if isinstance(G, numpy.ndarray): # Check correctness assert G.shape == (G.shape[0], G.shape[0]), "G is not 2D square" assert numpy.all(G.T == G), "G is not symmetric" assert isinstance(pos, numpy.ndarray) or (pos is None), "Invalid node positions" elif scipy.sparse.issparse(G): # Check correctness for scipy assert G.shape == (G.shape[0], G.shape[0]), "G is not 2D square" assert isinstance(pos, numpy.ndarray) or (pos is None), "Invalid node positions" G = G.tolil() is_sparse = True else: assert False, "G is of unsupported type" # Put nodes into a data structure we use nodes = [] for i in range(0, G.shape[0]): n = Node() if is_sparse: n.mass = 1 + len(G.rows[i]) else: n.mass = 1 + numpy.count_nonzero(G[i]) n.old_dx = 0 n.old_dy = 0 n.dx = 0 n.dy = 0 if pos is None: n.x = random.random() n.y = random.random() else: n.x = pos[i][0] n.y = pos[i][1] nodes.append(n) # Put edges into a data structure we use edges = [] es = numpy.asarray(G.nonzero()).T for e in es: # Iterate through edges # No duplicates if e[1] <= e[0]: continue edge = Edge() edge.node1 = e[0] # The index of the first node edge.node2 = e[1] # The index of the second node edge.weight = G[tuple(e)] edges.append(edge) return nodes, edges # This function returns a NetworkX layout. def forceatlas2_layout(self, G, pos=None, iterations=100): import networkx assert isinstance(G, networkx.classes.graph.Graph), "Not a networkx graph" assert isinstance(pos, dict) or (pos is None), "pos must be specified as a dictionary, as in networkx" M = networkx.to_scipy_sparse_matrix(G, dtype='f', format='lil') if pos is None: l = self.forceatlas2_not_networkx(M, pos=None, iterations=iterations) else: poslist = numpy.asarray([pos[i] for i in G.nodes()]) l = self.forceatlas2_not_networkx(M, pos=poslist, iterations=iterations) return dict(zip(G.nodes(), l)) # This should be used if not expecting networkx def forceatlas2_not_networkx(self, G, # 2D numpy ndarray or scipy sparse matrix format pos=None, # Array of initial positions iterations=100 # Number of times to iterate the main loop ): # speed and speed_efficiency stand for a scaling factor of dx and dy speed = 1.0 speed_efficiency = 1.0 nodes, edges = self.init(G, pos) outbound_att_compensation = 1.0 if self.distribute_outbound_attraction: outbound_att_compensation = numpy.mean([n.mass for n in nodes]) niters = range(iterations) for i in niters: for n in nodes: n.old_dx = n.dx n.old_dy = n.dy n.dx = 0 n.dy = 0 apply_repulsion(nodes, self.scaling_ratio) apply_gravity(nodes, self.gravity, use_strong_gravity=self.strong_gravity_mode) apply_attraction(nodes, edges, self.distribute_outbound_attraction, outbound_att_compensation, self.edge_weight_influence) values = adjust_speed_and_apply_forces(nodes, speed, speed_efficiency, self.jitter_tolerance) speed = values['speed'] speed_efficiency = values['speed_efficiency'] return [(n.x, n.y) for n in nodes]
ca2bcc330503cfdfa17873899988535bd2c11ace
crrimson/hello-world
/simple_stack.py
3,200
4.3125
4
# # implement a stack in python class StackNode(): """ a node in a stack """ def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def get_next_node(self): return self.next_node def get_value(self): return self.value def set_next_node(self, node): self.next_node = node class Stack(): """ define a stack object, that supports push/pop """ def __init__(self): self.top_node = None self.length = 0 def push(self, value): """ add a new node to the top of the stack """ # add the new item to the stack. self.current_top_node = self.top_node self.top_node = StackNode(value, next_node=self.current_top_node) self.length += 1 def pop(self): """ remove the node from the top, return it's value """ if self.top_node == None: return None else: # get the value, and then set the new top node, to the one below self.value = self.top_node.get_value() self.top_node = self.top_node.get_next_node() self.length -= 1 return self.value def get_length(self): return self.length class SetOfStacks(): """ Create a set of stacks, with each being x height """ def __init__(self, stack_height=10): self.stack_height = stack_height self.array_of_stacks = [] # Add the first stack to the array self.active_stack = Stack() self.array_of_stacks.append(self.active_stack) self.num_stacks = 1 self.active_stack def push(self, value): # Add a new item to the active stack, if we aren't too high if self.active_stack.get_length() < self.stack_height: self.active_stack.push(value) else: #too high, create a new Stack and add it to the array self.active_stack = Stack() self.active_stack.push(value) self.array_of_stacks.append(self.active_stack) self.num_stacks += 1 def pop(self): # take the top item off the active stack # if the stack is not empty, pop. If it is, we need to look for the previous stack. if self.active_stack.get_length() > 0: return self.active_stack.pop() elif self.num_stacks > 1: del self.array_of_stacks[self.num_stacks - 1] self.num_stacks -= 1 self.active_stack = self.array_of_stacks[self.num_stacks - 1] return self.active_stack.pop() else: return None def pop_at(self, index): # pop item off stack at a given index if index < self.num_stacks and index >= 0: return self.array_of_stacks[index].pop() else: return None def get_length(self): return self.num_stacks
8b473b420a92c32e453225683d6022fc0cabb9c6
Sourav-28/python-flask
/Day_7.py
505
3.828125
4
#task-1 # a=input("Enter a string: ") # list1=['a','e','i','o','u'] # b=a.lower() # list2=[i for i in range(len(b)) for j in list1 if b[i]==j] # print(list2) #task-2 # b=input("Enter a string: ") # l=b.split() # for i in l[::-1]: # c=i # print(c,end=" ") #task-3 q=int(input("Enter how many numbers you want to enter: ")) w=[] for i in range(q): a=int(input("Enter the numbers: ")) w.append(a) q=[] for i in w: if i not in q: q.append(i) print(q)
be9bec23d7614aa6256aec1cdc903192439e292b
dnjsdos/MachineLearning
/softmaxonehot.py
1,060
3.53125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./data/", one_hot=True) x = tf.placeholder(tf.float32, shape=[None, 784]) y = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros(shape=[784, 10])) b = tf.Variable(tf.zeros(shape=[10])) logits = tf.matmul(x, W) + b y_pred = tf.nn.softmax(logits) loss = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pred), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): batch_x, batch_y = mnist.train.next_batch(100) _, current_loss = sess.run([train_step, loss], feed_dict={x:batch_x, y:batch_y}) correct_prediction = tf.equal(tf.math.argmax(y, 1), tf.math.argmax(y_pred, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("정확도 : {}".format(sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})))
43ce7dbc591e228d96bf23113c029396613d5534
fedorsirotkin/BookHelloPython
/3_Операторы/3_4_Цикл_WHILE.py
367
3.71875
4
# Угадай лучший автомобиль print("Угадай лучший автомобиль") print("Название автомобиля нужно вводить строчными буквами") response = "" while response != "bmw": response = input("Какой авто самый лучший?: ") print("Ура! Вы это сделали!")
65f7383cb4a55862354fa15c88e5275b209c31b5
arielmad/Coding-1
/first.py
310
4.0625
4
print("Hello World!") print("My name is Ariel") print("ham sandwich") print("hi") print("Hello") print("My name is Ariel") print("I am 13 years old") celsius=eval(input("Enter a temperature in degrees celsius: ")) fahrenheit = 9/5 * celsius + 32 print("The temperature is", fahrenheit , "degrees Fahrenheit.")
a634cd2b7ae644784929ee4178407ce7011e8d83
ramboozil/python-learn-notes
/lesson2.py
544
4
4
#/usr/bin/env python3 # -*- coding: utf-8 -*- l=['java','php','python','c++'] print(l[-1]) print(l[-2]) print(len(l)) str = 'java,php,python,c++' a,b,c,d = str.split(',') print('\t'.join([a,b,c,d])) l.append('kotlin') print(l) l.insert(2,'c#') print(l) l.pop(-1) print(l) m=['java','php',['kotlin','c++']] print(len(m)) print(m[2][0]) L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] # 打印Apple: print(L[0][0]) # 打印Python: print(L[1][1]) # 打印Lisa: print(L[2][2])
b0ee525a0029ee414cbd3ba98862d76bb34dbad7
NaiveteYaYa/data-structrue
/38. 外观数列.py
1,443
3.5
4
# -*- coding: utf-8 -*- # @Time : 2020/3/25 20:19 # @Author : WuxieYaYa """ 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 1 被读作  "one 1"  ("一个一") , 即 11。 11 被读作 "two 1s" ("两个一"), 即 21。 21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211。 给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。 注意:整数序列中的每一项将表示为一个字符串。 示例 1: 输入: 1 输出: "1" 解释:这是一个基本样例。 示例 2: 输入: 4 输出: "1211" 解释:当 n = 3 时,序列是 "21",其中我们有 "2" 和 "1" 两组,"2" 可以读作 "12",也就是出现频次 = 1 而 值 = 2;类似 "1" 可以读作 "11"。所以答案是 "12" 和 "11" 组合在一起,也就是 "1211"。 链接:https://leetcode-cn.com/problems/count-and-say """ def countAndSay(n): if n==1: return '1' ans = countAndSay(n-1) ans = ans + '0' i = 0 m = 1 result = '' while i < len(ans)-1: if ans[i] == ans[i+1]: m += 1 else: result += str(m) + ans[i] m = 1 i += 1 return result if __name__ == '__main__': print(countAndSay(6))
f4a3693fbe42a9a9d8c2c295992c40bb29614828
gagandeepsinghbrar/codeSignal
/rotatingBox.py
3,730
3.8125
4
''' You need to move a large rectangular box over a rough, hazardous surface. Since you don't have any tools to help you move it, your only option is to perform a series of 90 degree rotations (basically just repeatedly pushing the box over onto its side). Every time you rotate the box, it hits the ground and some damage is done - the amount of damage depends on the fragility of the side of the box that it landed on, as well as the roughness of the ground in the region where it was dropped. what it looks like More specifically, we calculate the damage by multiplying the box's fragility by the ground's roughness for each pair of vertically adjacent cells. So for the box above, dropping it into its current position would cause a total of 4*7 + 0*4 + 5*9 = 73 damage. And the next turn will cause 5*7 + 3*0 + 4*7 = 63 damage. Given boxWeakness, an array of strings representing how fragile the box is in each location, and surfaceRoughness, a string of digits representing how damaging each section of the surface is, your task is to find the total amount of damage the box will receive after being rotated across the entire surface Note: The length of the surface might not perfectly fit the box; if there's some overhang on the last step, that part won't be damaged. Example For boxWeakness = ["01", "21", "10"] and surfaceRoughness = "39513695380152438476", the output should be fragileRotatingBox(boxWeakness, surfaceRoughness) = 56. example The total damage is 1*3 + 0*9 + 0*5 + 1*1 + 1*3 + 1*6 +0*9 + 0*5 + 2*3 + 1*8 + 1*0 + 0*1 + 0*5 + 1*2 + 1*4 + 1*3 + 0*8 + 0*4 + 2*7 + 1*6 = 56 Input / Output [execution time limit] 4 seconds (py3) [input] array.string boxWeakness An array of strings representing a picture of the box, in terms of how vulnerable each part of it is. Guaranteed constraints: 1 ≤ boxWeakness.length ≤ 9 1 ≤ boxWeakness[i].length ≤ 9 boxWeakness[i][j] ∈ {"0" - "9"} [input] string surfaceRoughness A string of digits representing how damaging the surface is in each location. Guaranteed constraints: 0 ≤ surfaceRoughness.length ≤ 105 surfaceRoughness[i] ∈ {"0" - "9"} [output] integer An integer representing the total amount of damage done to the box while rotating it over the full length of the surface. ''' def fragileRotatingBox(boxWeakness, surfaceRoughness): parts=[boxWeakness[-1],"".join([i[-1] for i in boxWeakness])[::-1],boxWeakness[0][::-1],"".join([i[0] for i in boxWeakness])] willcover=list(map(lambda x:len(x),parts)) completeTurns=math.floor(len(surfaceRoughness)/sum(willcover)) remainingTurn=len(surfaceRoughness)%sum(willcover) toCrop=completeTurns*sum(willcover) return findRemaining(parts,surfaceRoughness[toCrop:],willcover,remainingTurn)+findRepeatedly("".join(parts),surfaceRoughness) def findRemaining(partsToRoll,bottomArea,lengthOfParts,manyTimes): if manyTimes==0: return 0 IndexWecareAbout=checkCareAbout(lengthOfParts,manyTimes) try: overLap=partsToRoll[:IndexWecareAbout] except: pass overLap=[str(k) for k in overLap] overLap="".join(overLap) return sum([int(x)*int(y) for x,y in list(zip(overLap,bottomArea))]) def findRepeatedly(combinedStr,rough): result=0 while len(rough)>=len(combinedStr): mylist=list(zip(rough,combinedStr)) result = result + sum([int(x)*int(y) for x,y in mylist]) rough=rough[len(combinedStr):] return result def checkCareAbout(lst,num): if num==0: return 0 count=0 for i in range(len(lst)): if num<=0: return i num=num-lst[i]
34f1ef558aaeda44f8a44a451f58e82227a5955a
hubert-cyber/EjerciciosEnPython
/Ejercicio17.py
726
3.515625
4
#define datos de entrada print("Ejercicio 17") #datos de entrada paqueteA="A: 1 televisor, 1 modular, 3 pares de zapatos, 5 camisas y 5 pantalones" paqueteB="B: 1grabadora, 3 pares de zapatos, 5 camisas y 5 pantalones" paqueteC="C: 2 pares de zapatos, 3 camisas y 3 pantalones" paqueteD="D: 1 par de zapatos, 2 pares de camisas y 3 pares de pantalones" Trecibido= int(input("Ya llego diciembre, coloque Ud. el monto recibido:")) if Trecibido >= 50000 : podracomprar = paqueteA elif Trecibido <50000 and Trecibido >= 20000 : podracomprar = paqueteB elif Trecibido <20000 and Trecibido >= 10000 : podracomprar = paqueteC elif Trecibido <10000 : podracomprar = paqueteD print("Ud. podra comprar el paquete", podracomprar)
f795d9f90b722053b4f4a1266d4395bccb267fae
Wef2/ProjectEuler
/python/problem020.py
119
3.546875
4
value = 1 result = 0 for i in range(1, 101): value *= i for i in str(value): result += int(i) print(result)
c756f72b97777be0b09770fb1ed338348f928815
tobiascarson/beuler
/p10.py
276
3.75
4
#!/usr/bin/python def isprime(n): n = abs(int(n)) if n < 2: return False if n == 2: return True if not n & 1: return False for x in range(3, int(n**0.5)+1, 2): if n % x == 0: return False return True max=2000000 print sum(i for i in range(max) if isprime(i))
09caed61bed1a406069fe6107ad32426991e782f
christinabranson/hackerrank-python
/PythonCertificate/SampleQuestions/StringAnagram/StringAnagram.py
912
4
4
#!/bin/python3 def getAnagrams(dictionary, queries): anagram_counts = [] sorted_dictionary = {} for word in dictionary: sorted_word = "".join(sorted(word)) if sorted_word in sorted_dictionary: sorted_dictionary[sorted_word] += 1 else: sorted_dictionary[sorted_word] = 1 print(sorted_dictionary) for query in queries: sorted_word = "".join(sorted(query)) if sorted_word in sorted_dictionary: anagram_counts.append(sorted_dictionary[sorted_word]) else: anagram_counts.append(0) return anagram_counts if __name__ == '__main__': # Sample 1 - Correct answer: 85 dictionary = ["hack", "a", "rank", "khac", "ackh", "kran", "rankhacer", "a", "ab", "ba", "stairs", "raits"] query = ["a", "nark", "bs", "hack", "stairs"] result = getAnagrams(dictionary, query) print(result)
88cf9d94601d100f27b20fe33e5f972d01570381
brosiak/genetic-algorithm
/Flight.py
3,358
3.671875
4
import datetime import time class Flight: def __init__(self, flight_type = '', airline = '', sequence_number = 0, flight_number = '', airplane_type = '', unit_loss = 0, estimated_time = 0, actual_time = 0, runway = -1, delay_losses = -1, relation = {} ): """Intialization of flight Keyword Arguments: flight_type {str} -- approach or departure (default: {''}) airline {str} -- name of airline (default: {''}) sequence_number {int} -- sequence number of flight (default: {0}) flight_number {str} -- airline's flight number (default: {''}) airplane_type {str} -- type of airplane (default: {''}) unit_loss {int} -- unit time delay loss (default: {0}) estimated_time {int} -- estimated approach/departure time (default: {0}) actual_time {int} -- actual approach/departure time (default: {0}) runway {int} -- number of runway (default: {-1}) delay_losses {int} -- delay losses (default: {-1}) """ self.flight_type = flight_type self.airline = airline self.sequence_number = sequence_number self.flight_number = flight_number self.airplane_type = airplane_type self.unit_loss = unit_loss self.estimated_time = estimated_time self.actual_time = actual_time self.runway = runway self.delay_losses = delay_losses self.delay_time = 0 self.relation = relation # def get_type(self): # return(self.flight_type) # def get_runway(self): # return(self.runway) # def get_delay_time(self): # return(self.delay_time) # def get_actual_time_s(self): # return self.hms_to_s(self.actual_time) # def get_estimated_time(self): # return self.hms_to_s(self.estimated_time) def get_actual_time_s(self): return self.actual_time def get_estimated_time(self): return self.estimated_time # def get_unit_loss(self): # return(self.unit_loss) # def get_actual_time(self): # return(self.actual_time) # def get_sequence_number(self): # return(self.sequence_number) def hms_to_s(self, hms_time): """changes time string in format hours:minutes:seconds to seconds Arguments: hms_time {string} -- h:m:s Returns: int -- seconds """ hours, minutes, seconds = hms_time.split(':') secs = int(datetime.timedelta(hours = int(hours), minutes = int(minutes), seconds = int(seconds)).total_seconds()) return secs def s_to_hms(self, secs): return(time.strftime('%H:%M:%S', time.gmtime(secs))) # def calc_delay(self): # """calculating delay of flight # """ # a_secs = self.hms_to_s(self.actual_time) # e_secs = self.hms_to_s(self.estimated_time) # self.delay_time = a_secs - e_secs # return(self.delay_time) def calc_delay(self): """calculating delay of flight """ self.delay_time = self.actual_time - self.estimated_time return(self.delay_time) def is_delayed(self, delta_t): if(delta_t < self.calc_delay()): return True else: return False
174987f3891c7ad0c33f0eed21df029e83fdf5a1
lukkerr/clientes-python
/funcoes.py
7,789
3.53125
4
###Testar se Existe determinado Contéudo no Texto### def validador (arqtexto,x): #Find - Procura Contéudo da Varíavel X no Arqtexto e Retorna sua Posição resultado = arqtexto.find(x) #Resultado Igual a -1 se Contéudo não for Encontrado no Texto if resultado==-1: resultado = False #Se Diferente de -1 o Contéudo foi encontrado no Texto else: resultado = True #Retorna Valor True se Contéudo foi Encontrado, e False se não return resultado ###Dividir o Nome do Usuário para fazer o Email### def divisionuser (nome): #Converte todo o Nome dado para Mínusculo nome = nome.lower() #Separa o Nome dado, retornando o como uma Lista (sendo "Espaço em Branco" o Valor Default para a Divisão) resultado = nome.split() #Retorna uma Lista com o Nome Dividido onde havia "Espaços em Branco" return resultado ###Gerar Opcoes de Emails### def emailconstruct (nome,cpf,dominio): #Construindo Email com Nome do Cliente (Sendo Nome uma Lista feita com o Divisionuser User Acima), CPF e Dominio Padrão #Construindo Alternativa de Email 1 mail1 = cpf + "@" + dominio #Construindo Alternativa de Email 2 mail2 = nome[0] +"."+ nome[-1] + "@" + dominio #Construindo Alternativa de Email 3 mail3 = nome[0] +"."+ cpf[0:3] + "@" + dominio #Resultado vai ser uma lista com todos as Alternativas de Email resultado = [mail1,mail2,mail3] #Retorna um Lista de Emails return resultado ####Editar Lista### def editarlista (lista,conteudo): #Lembrando que a lista dada todos os Usuário sendo cada elemento uma linha de Dados daquele Usuário #Retorna a Quantidade de Linhas da Lista Dada cont = len(lista) #Percorrer o Numero equivalente ao numero de elemento da Lista for i in range(cont): #Entrar no If se o contéudo for Encontrado naquele elemento da Lista if lista[i].find(conteudo)!=-1: #Deve-se Dividir a Lista contando como Separador o ";",salvando o resultado em uma nova Lista listacop = lista[i].split(";") #Salvando Localização daquele Elemento na lista Original loc = i #Mudando o Texto do Espaço do Nome do Cliente listacop[1] = input("Digite o Novo Nome a ser Adicionado: ") #A Posição do Elemento Encontrado Anteriormente vai ser Sobreescrito, porém com o "listacop[1]" Alterado ou seja o Nome lista[loc] = listacop[0] +";"+ listacop[1] +";"+ listacop[2] #Declarando Variável String listanova = "" #Convertendo todo o Texto da Nova Lista Alterada em uma String for i in lista: #Cada Linha esta sendo adicionada em uma String listanova = listanova + i #Retorna Todo Texto da Lista dada Anteriormente, porém agora como String e com Nome Especificado Alterado return listanova ###Separar Dados de Usúarios por Elemento na Lista### def splitelemento (listageral,ident): #Retorna a Quantidade de Linhas da Lista Dada cont = len(listageral) #Percorrer o Numero equivalente ao numero de elemento da Lista for i in range(cont): #Entrar no If se o contéudo for Encontrado naquele elemento da Lista if listageral[i].find(ident)!=-1: #Deve-se Dividir a Lista contando como Separador o ";",salvando o resultado em uma nova Lista identsplit = listageral[i].split(";") #Retorna uma Lista com o Contéudo da Linha do Elemento Procurado return identsplit ###Exluir Usuário### def excluirelemento (listaex,elemento): #Retorna a Quantidade de Linhas da Lista Dada cont = len(listaex) #Retorna uma Lista com o Contéudo da Linha do Elemento Procurado listacopex = splitelemento(listaex,elemento) while True: #A Variável Listacopex Retorna os Valores de CPF, Nome e Emails, separados pela função Splitelemento print("---Cliente a ser Deletado---\n") print("CPF: ",listacopex[0]) print("Nome: ",listacopex[1]) print("Email:",listacopex[2]) select = input("Deseja Realmente Deletar Usuário (S/N): ") #Converte a Resposta dada para Minusculo select = select.lower() #Cria Variável com String listanovaex = "" #Entra no IF se digitou s/S if select=="s": #Laço com Quantidade de Giros Equivalente ao Numero de Elementos Lista "Original" for i in range(cont): #Ao Encontrar Linha do Usúario com Elemento Dado, entrar no IF if listaex[i].find(elemento)!=-1: #Substituir todo o Valor da Linha do Usuário por "Nada" listaex[i] = "" #Entrar no IF se a Respota foi Valida if select=="s" or select=="n": #Percorrer a Lista Original, que agora esta com a Linha do Elemento Dado Apagada for i in listaex: #Adicionando Elementos todos os Elementos da Lista em uma String listanovaex = listanovaex + i #Sair do Laço break #Se Digitar qualquer Valor Diferente de s/S ou n/N, fica preso no Laço else: print("\n---Opção Inválida---\n\n") #Retorna String com todo o Texto, sendo que com a Linha do Elemento Contido Apagada se tiver Digitado s/S return listanovaex ###Pesquisar Usuário### def pesquisar(listapes,cpf): #Retorna uma Lista com o Contéudo da Linha do Elemento Procurado user = splitelemento(listapes,cpf) #Retorna a Quantidade de Linhas da Lista Dada cont = len(user) #Texto que Ficaram a Frente dos Dados idenc = [" CPF: "," Nome: ","Email: "] #Lista de Espaços para Formatação pulalinha = ["\n","\n",""] #Criando Variavel String userprint = "" #Entrando em Laço de 3, por serem 3 Linhas cada Dado CPF, Nome e Email for i in range(3): #Salva uma Linha com Cada Dado com seus Respectivos Dados de Formatação e salva todos em uma String userprint = userprint + idenc[i] + user[i] + pulalinha[i] #Retorna uma String com todos os Valores prontos pra Print return userprint ###Gerar Lista Vazio### def listavazia(x,y): #Laço para Preencher a Lista "X" com uma Quantidade "Y" de Valores for i in range(y): x.append("0") #Retorna uma Lista com uma Quantidade "Y" de Zeros return x ###Listar Usuários### def listar(users): #Retorna a Quantidade de Linhas da Lista Dada cont = len(users) #Criando Lista Vazio userslista = [] #Função Listavazia - Retorna um Lista "Vazia" (Zerada) com o Mesmo Numero de Elementos da Lista Dada Originalmente nesta Função userslista = listavazia(userslista,cont) #Percorrer o Numero equivalente ao numero de elemento da Lista for i in range(cont): #Divide todos os Elementos da Lista onde Existe ";", gerando uma Lista de Listas userslista[i] = users[i].split(";") #Criando Lista Vazia usersfinal = [] #Função Listavazia - Retorna um Lista "Vazia" (Zerada) com o Mesmo Numero de Elementos da Lista Dada Originalmente nesta Função usersfinal = listavazia(usersfinal,cont) #Lista com Texto de Formatação que Ficaram a Frente dos Dados idenc = ["CPF: ","Nome: ","Email: "] #Percorrer o Numero equivalente ao numero de elemento da Lista for i in range(cont): #Adicionando Cada Linha da Lista Original a uma Unica Linha da Lista Final, estando agr Formatada #(Sendo Cada Elemento da Nova Lista um Cliente) usersfinal[i] = str(i+1) +" - "+ idenc[0] + userslista[i][0] + " | " + idenc[1] + userslista[i][1] + " | " + idenc[2] + userslista[i][2] #Retorna Lista com Todos os Clientes e já Formatado, sendo cada elemento os dados de um único Cliente return usersfinal
9242aef96ac166d90675f9f33ff9979c1ecbd4a3
atfost3r/AutomateTheBoringStuff
/AutomatingTasks/Chapter_11/lucky.py
607
3.53125
4
#! /usr/bin/python3 #lucky.py - Opens several Google search results. import requests, sys, webbrowser, bs4, pyperclip search = 'python programming tutorial' print('Googling...') # display text while downloading the google page res = requests.get('http://google.com/search?=' + ''.join(search)) res.raise_for_status() #Retrieve top search result links soup = bs4.BeautifulSoup(res.text, 'features="lxml"') #Open a browser tab for each result. linkElems = soup.select('.r a') numOpen = min(5, len(linkElems)) for i in range(numOpen): webbrowser.open('http://google.com' + linkElems[i].get('href'))
409f67723d5479566826bcd909eac84cea0d99b0
Natsu1270/Codes
/Hackerrank/LinkedList/DeleteNode.py
505
3.796875
4
from LinkedList import * def deleteNode(head,pos): if pos == 0: return head.next temp = head prev = None while pos > 0: prev = temp temp = temp.next pos -= 1 prev.next = temp.next del temp return head def deleteNodeRec(head,pos): if pos == 0: return head.next head.next = deleteNodeRec(head.next,pos-1) return head llist = input_linkedlist() pos = int(input()) head = deleteNode(llist.head,pos) print_linkedlist(head)
98f126a5af9defbf167520554060bcc1f868ca88
N-Shilpa/python
/Hello1.py
84
3.671875
4
i=10 j=20 if(i<j): print(i) print(j) print(i+j) else: print("hello")
cf32d5269f46fe11b5dc6d83c41cad7fbed3fc36
h0cem/flaskProject
/genetic_algo.py
22,123
3.5
4
import sys import random import tools as t # covid graph from termcolor import colored import numpy as np import matplotlib.pyplot as plt # to plot from datetime import datetime, timedelta class GA: """ size: population size graph: covid graph that was created randomly n: numpy vector have id of nodes population: population that have (size) m individuals """ def __init__(self, graph, generation, size, budget, elite, selection_strategy, crossover_strategy, p_mutation, p_crossover, k): self.graph = graph self.generation = generation self.size = size self.budget = budget self.elite = elite self.selection_strategy = selection_strategy self.crossover_strategy = crossover_strategy self.P_CROSSOVER = p_crossover self.P_MUTATION = p_mutation self.tournament_k = k self.persons_id = t.get_persons_id(self.graph) self.population = self.initialization() """ The genetic algorithm creates three types of children for the next generation: 1° Elite are the individuals in the current generation with the best fitness values. These individuals automatically survive to the next generation. 2° Crossover are created by combining the vectors of a pair of parents. 3° Mutation children are created by introducing random changes, or mutations, to a single parent. """ def ga(self): generation = 0 gen = [] solution = [] start_time = datetime.now() old_pop = self.population solution.append(min(old_pop, key=lambda x: x.fitness).fitness) gen.append(generation) random.seed() while generation < self.generation and datetime.now() - start_time < timedelta(seconds=150): # create a new population new_pop = [] # the new population must have the same size while len(new_pop) < self.size and datetime.now() - start_time < timedelta(seconds=150): start = datetime.now() parent_1 = [] parent_2 = [] # SELECTION :: check if parent_1 != parent_2 while True and datetime.now() - start < timedelta(seconds=8): parent_1 = self.best_selection(old_pop) parent_2 = self.selection(old_pop) if not self.check_if_same_parents(parent_1, parent_2): break # CrossOver if random < p_crossover if random.random() < self.P_CROSSOVER: child_1, child_2 = self.crossover(parent_1, parent_2) # Mutation self.mutation(child_1) # Add child if not new_pop and self.fitness(child_1): new_pop.append(child_1) else: if not self.check_if_in_population(new_pop, child_1) and self.fitness(child_1): new_pop.append(child_1) # check size of population then add child if len(new_pop) < self.size: # Mutation self.mutation(child_2) if not self.check_if_in_population(new_pop, child_2) and self.fitness(child_2): new_pop.append(child_2) else: break # if no crossover happens, we will chose the best of parents and add it to the population else: if len(new_pop) < self.size: if parent_1.fitness < parent_2.fitness: # Mutation self.mutation(parent_1) if not new_pop and self.fitness(parent_1): new_pop.append(parent_1) else: if not self.check_if_in_population(new_pop, parent_1) and self.fitness(parent_1): new_pop.append(parent_1) else: # Mutation self.mutation(parent_2) if not new_pop and self.fitness(parent_2): new_pop.append(parent_2) else: if not self.check_if_in_population(new_pop, parent_2) and self.fitness(parent_2): new_pop.append(parent_2) old_pop = new_pop generation += 1 solution.append(min(old_pop, key=lambda x: x.fitness).fitness) gen.append(generation) plt.figure() plt.title("risk") plt.plot(sorted(solution, reverse=True)) plt.show() print("best risk: ", min(solution)) def ga2(self): generation = 0 gen = [] solution = [] mean = [] old_pop = self.population.copy() solution.append(min(old_pop, key=lambda x: x.fitness).fitness) gen.append(generation) random.seed() while generation < self.generation: # and datetime.now() - start_time < timedelta(seconds=150): # create a new population new_pop = [] parent_1, parent_1_index = self.best_selection(old_pop) new_pop.append(parent_1) # the new population must have the same size # while len(new_pop) < self.size: # and datetime.now() - start_time < timedelta(seconds=150): for parent_2_index in range(len(old_pop)): if parent_2_index == parent_1_index: continue else: parent_2 = old_pop[parent_2_index] # CrossOver if random < p_crossover if random.random() < self.P_CROSSOVER: child_1, child_2 = self.crossover(parent_1, parent_2) # Mutation self.mutation(child_1) # Add child self.append_individual(new_pop, child_1) # check size of population then add child if len(new_pop) < self.size: # Mutation self.mutation(child_2) self.append_individual(new_pop, child_2) else: break # if no crossover happens, we will chose the best of parents and add it to the population else: if len(new_pop) < self.size: self.append_parent(new_pop, parent_1, parent_2) else: break old_pop = new_pop generation += 1 a = 0 for s in old_pop: a += s.fitness solution.append(min(old_pop, key=lambda x: x.fitness).fitness) mean.append(a / len(old_pop)) gen.append(generation) self.display(solution) self.display(mean) for i in min(old_pop, key=lambda x: x.fitness).individual: if not i.isolated: print(i.id, end=' ') g = self.update_graph_attr(min(old_pop, key=lambda x: x.fitness)) print(1 - t.total_RNB(g)) print() def append_individual(self, pop, individual): if self.fitness(individual): pop.append(individual) def append_parent(self, pop, parent_1, parent_2): if parent_1.fitness < parent_2.fitness: # Mutation self.mutation(parent_1) self.append_individual(pop, parent_1) else: self.mutation(parent_2) self.append_individual(pop, parent_2) def display(self, solution): plt.figure() plt.title("risk") plt.plot(solution) plt.show() print("best risk: ", min(solution)) def print_chromosome(self, i): for j in i.individual: # print(j.id, end=' ') if j.isolated: print("0", end=' ') else: print("1", end=' ') print(i.fitness) def create_individual(self): individual = [] for i in range(len(self.persons_id)): individual.append(t.Gene(self.persons_id[i], random.choice([True, False]))) return individual def create_neighbor(self, individual): neighbor = individual.copy() n = len(self.persons_id) - 1 # while True: offset = random.randint(0, n) if neighbor[offset].isolated: neighbor[offset].isolated = False # break return neighbor def create_population(self): # here we create the population population = [] i = 0 individual = self.create_individual() while i < self.size: g = self.graph.copy() t.update_copy_graph_attr(g, individual) if t.check_budget(g, self.budget): chromosome = t.Individual(individual, t.sum_risk_persons(g)) if not population: population.append(chromosome) i += 1 else: if not self.check_if_in_population(population, chromosome): population.append(chromosome) i += 1 individual = self.create_individual() else: individual = self.create_neighbor(individual) return population def initialization(self): """ Initialization The search starts with a random population of N individuals. Each of those individuals corresponds to a 'chromosome', which encodes a sequence of genes representing a particular solution to the problem we’re trying to optimize for. Depending on the problem at hand, the genes representing the solution could be bits (0’s and 1’s) or continuous (real valued). """ return self.create_population() def fitness(self, child): """ Fitness The fitness of each individual is what defines what we are optimizing for, so that, given a chromosome encoding a specific solution to a problem, its fitness will correspond to how well that particular individual fares as a solution to the problem. Therefore, the higher its fitness value, the more optimal that solution is. After all, individuals have their fitness score calculated, they are sorted, so that the fittest individuals can be selected for crossover. """ g = self.update_graph_attr(child) if self.constraint(g): child.fitness = t.sum_risk_persons(g) return True else: return False def reparation(self, chromosome): g = self.update_graph_attr(chromosome) n = len(self.persons_id) - 1 while not self.constraint(g): offset = random.randint(0, n) if chromosome.individual[offset].isolated: chromosome.individual[offset].isolated = False else: chromosome.individual[offset].isolated = True g = self.update_graph_attr(chromosome) return g def mutation(self, chromosome): """ Mutation is the process by which we introduce new genetic material in the population, allowing the algorithm to search a larger space. If it were not for mutation, the existing genetic material diversity in a population would not increase, and, due to some individuals “dying” between generations, would actually be reduced, with individuals tending to become very similar quite fast. In terms of the optimization problem, this means that without new genetic material the algorithm can converge to local optima before it explores an enough large size of the input space to make sure that we can reach the global optimum. Therefore, mutation plays a big role in maintaining diversity in the population and allowing it to evolve to fitter solutions to the problem. """ if random.random() < self.P_MUTATION: self.mutate(chromosome) def mutate(self, chromosome): n = len(self.persons_id) - 1 offset = random.randint(0, n) if chromosome.individual[offset].isolated: chromosome.individual[offset].isolated = False else: chromosome.individual[offset].isolated = True def check_duplications(self, pop1, pop2): check = True for i in range(self.size): for j in range(self.size): if i == j: continue if not self.check_if_same_parents(pop1[i], pop2[j]): check = False else: return True return check def check_if_in_population(self, pop, chromosome): check = False for i in pop: if self.check_if_same_parents(i, chromosome): return True return check def check_if_same_parents(self, parent_1, parent_2): check = False n = len(self.persons_id) for i in range(n): a = parent_1.individual[i].isolated b = parent_2.individual[i].isolated if a == b: check = True else: return False return check def print_parents(self, parent_1, parent_2): print('parent_1 == parent_2') for j in parent_1.individual: print(j.id, j.isolated, end=' ') print(parent_1.fitness) for j in parent_2.individual: print(j.id, j.isolated, end=' ') print(parent_2.fitness) def update_graph_attr(self, individual): g = self.graph.copy() t.update_copy_graph_attr(g, individual.individual) return g def constraint(self, g): return t.check_budget(g, self.budget) def selection(self, pop): """ Selection Selection is the process by which a certain proportion of individuals are selected for mating between each other and create new offsprings. Just like in real-life natural selection, individuals that are fitter have higher chances of surviving, and therefore, of passing on their genes to the next generation. Though versions with more individuals exist, usually the selection process matches two individuals, creating pairs of individuals. There are four main strategies: pairing: This is perhaps the most straightforward strategy, as it simply consists of pairing the top fittest chromosomes two-by-two (pairing odd rows with even ones). random: This strategy consists of randomly selecting individuals from the mating pool. roulette wheel: This strategy also follows a random principle, but fitter individuals have higher probabilities of being selected. tournament: With this strategy, the algorithm first selects a few individuals as candidates (usually 3), and then selects the fittest individual. This option has the advantage that it does not require the individuals to be sorted by fitness first. """ if self.selection_strategy == "random": return self.random_selection(pop) elif self.selection_strategy == "roulette_wheel": return self.roulette_wheel_selection(pop) elif self.selection_strategy == "tournament": return self.tournament_selection(pop) elif self.selection_strategy == "pairing": pass else: print(colored('Error: undefined selection strategy', 'red')) def random_selection(self, pop): """ random: This strategy consists of randomly selecting individuals from the mating pool. :return: individual """ # Return a random parent index from population between 0 and size of population (both included) index = random.randint(0, len(pop) - 1) return pop[index] def roulette_wheel_selection(self, pop): """ This selection will have problems when fitness differs very much if chromosome_1 = 90% than other chromosomes will have very few chances to be selected """ # Computes the totality of the population fitness population_fitness = sum([1 / chromosome.fitness for chromosome in pop]) # Computes for each chromosome the probability chromosome_probabilities = [1 / chromosome.fitness / population_fitness for chromosome in pop] # Making the probabilities for a minimization problem chromosome_probabilities = np.array(chromosome_probabilities) # Selects one chromosome based on the computed probabilities selected = np.random.choice(pop, p=chromosome_probabilities) return selected def tournament_selection(self, pop): """ In tournament selection, each parent is the fittest out of k randomly chosen chromosomes of the population """ k = self.tournament_k n = len(pop) - 1 # first random selection selected = random.randint(0, n) while k > 0: index = random.randint(0, n) # check if better (e.g. perform a tournament) if pop[index].fitness <= pop[selected].fitness: selected = index k -= 1 return pop[selected] def best_selection(self, pop): return min(pop, key=lambda x: x.fitness), pop.index(min(pop, key=lambda x: x.fitness)) def crossover(self, parent_1, parent_2): """ Crossover This is the step where new offsprings are generated, which will then replace the least fit individuals in the population. The idea behind crossing over individuals is that, by combining different genes, we might produce even fitter individuals, which will be better solutions to our problem. Or not, and in that case, those solutions won’t survive to the next generations. In order to perform the actual crossover, each of the pairs coming from the selection step are combined to produce two new individuals each, which will both have genetic material from each of the parents. There are several different strategies for performing the crossover, so for brevity, we’ll only discuss one of them. """ if self.crossover_strategy == "one_point": return self.one_point_crossover(parent_1, parent_2) elif self.crossover_strategy == "two_point": return self.two_points_crossover(parent_1, parent_2) else: print(colored('Error: undefined CrossOver strategy', 'red')) def one_point_crossover(self, parent_1, parent_2): """ TODO: 1. check offset of crossOver value ... done 3. pretty print 4. random selection with same parent 5. check redandante ... in pop https://towardsdatascience.com/introducing-geneal-a-genetic-algorithm-python-library-db69abfc212c 1. The crossover gene of each offspring is calculated according to the rule given by: P_new1 = P_1a - \beta [P_1a-P_2a] P_new2 = P_2a 2 \beta [P_1a-P_2a] """ chromosome_1 = [] chromosome_2 = [] # generating the random number [0, n] to perform crossover, n is size of individual n = len(self.persons_id) - 1 offset = random.randint(0, n) # interchanging the genes chromosome_1.extend(parent_1.individual[:offset]) chromosome_1.extend(parent_2.individual[offset:]) chromosome_2.extend(parent_2.individual[:offset]) chromosome_2.extend(parent_1.individual[offset:]) new_chromosome_1 = t.Individual(chromosome_1, sys.maxsize) new_chromosome_2 = t.Individual(chromosome_2, sys.maxsize) return new_chromosome_1, new_chromosome_2 def two_points_crossover(self, parent_1, parent_2): """ TODO: 1. check offset of crossOver value ... done 3. pretty print 4. random selection with same parent 5. check redandante ... in pop https://towardsdatascience.com/introducing-geneal-a-genetic-algorithm-python-library-db69abfc212c 1. The crossover gene of each offspring is calculated according to the rule given by: P_new1 = P_1a - \beta [P_1a-P_2a] P_new2 = P_2a 2 \beta [P_1a-P_2a] """ chromosome_1 = [] chromosome_2 = [] # generating the random number [0, n] to perform crossover, n is size of individual n = len(self.persons_id) - 1 start = random.randint(0, n) end = random.randint(start, n) # interchanging the genes chromosome_1.extend(parent_1.individual[:start]) chromosome_1.extend(parent_2.individual[start:end]) chromosome_1.extend(parent_1.individual[end:]) chromosome_2.extend(parent_2.individual[:start]) chromosome_2.extend(parent_1.individual[start:end]) chromosome_2.extend(parent_2.individual[end:]) new_chromosome_1 = t.Individual(chromosome_1, sys.maxsize) new_chromosome_2 = t.Individual(chromosome_2, sys.maxsize) return new_chromosome_1, new_chromosome_2 def elitism(self, pop, k): """ Elitism reserves two slots in the next generation for the highest scoring chromosome of the current generation, without allowing that chromosome to be crossed over in the next generation :return: two chromosomes """ sorted_pop = sorted(pop, key=lambda x: x.fitness, reverse=False) return sorted_pop[:k]
ccff9acce2bdffcc3bf280d02ef6cf3a237cb9e5
deltonmyalil/PythonInit
/filters.py
791
3.8125
4
from random import randint newlist = [randint(1,50) for x in range (10)] print(newlist) evenNos = list(filter(lambda x: x%2==0,newlist)) #filter chose the els of the list where the boolean condition of the lambda returned true print(evenNos) def isOdd(n): if n%2 == 0: return False else: return True nextlist = [randint(1,100) for x in range(20)] print(nextlist) oddNos = list(filter(isOdd,nextlist)) #filter using a function instead of a lambda print(oddNos) anotherList = [randint(1,60) for j in range(10)] print(anotherList) divByThree = list(filter(lambda x:x%3==0,anotherList)) #if the first parameter of the filter function (should be a callable parameter like a function or a lambda) returns True, the item is included in the returned list print(divByThree)
5c286f457c579ce1e72d18b5536fc6b32fdc6f00
iffatunnessa/Artificial-intelligence
/lab3/New folder/s3p1.py
691
4.15625
4
# Writing to and reading from a file in Python f1=open('stdfile.py', "w") print("\n") for i in range(2): name=str(input("Enter the name:")) dept=str(input("Enter the department:")) cgpa=str(input("Enter the cgpa:")) std=name+"\t"+dept+"\t"+cgpa print(std, end="\n", file=f1) f1.close f1=open('stdfile.py', "r") for l in f1: name, dept, cgpa =l.split("\t") print(name, dept, float(cgpa), end="\n") f1.close # Including files import s3Module1 as m1 m1.display_file_lines('stdfile.py',2) n=m1.num_of_lines('stdfile.py') print("Number of lines in {} is {}.".format('stdfile.py',n)) m1.display_file('stdfile.py')
2a72ab16ed90046f93d9b17f910d2b1927c336f7
sungsikyang92/pythonStudy
/CodeUp/1366_0222.py
644
3.859375
4
n = int(input()) #첫째줄 for x in range(n): print("*", end="") print() #중간영역1 for x in range(1, int(n/2)): for y in range(n): if y==0 or y==x or y==n-1 or y==n-x-1 or y==int(n/2): print("*", end="") else: print(" ", end="") print() #중간줄 for x in range(n): print("*", end="") print() #중간영역2 for x in range(int(n/2)-1,0,-1): for y in range(n): if y==0 or y==x or y==n-1 or y==n-x-1 or y==int(n/2): print("*", end="") else: print(" ", end="") print() #마지막줄 for x in range(n): print("*", end="") print()
01905284ff9bbd0a9ab4c4c55c3724e8c7c35752
Avani1992/python
/Sherlock and the Valid String.py
1,111
3.96875
4
""" Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just 1 character at 1 index in the string, and the remaining characters will occur the same number of times. Given a string s, determine if it is valid. If so, return YES, otherwise return NO. """ s="aabbc" def isValid(s): d={} l1=list() l2=list() l3=list() if(len(s)==1): return "YES" else: for i in s: if(i in d): d[i]=d[i]+1 else: d[i]=1 print(d) for j in d.values(): l1.append(j) current=l1[0] for k in range(0,len(l1)): sliced=l1[k+1:] for p in sliced: if(current==p): l2.append(current) elif(current>p or current<p): l3.append(p) break print(l3) if(len(l2)==(len(s)/2)): return "YES" if(len(l3)>=2): return "No" else: for q in l3: if(q==(current+1) or q==(current-1) or q==1): return "Yes" else: return "No" result=isValid(s) print(result)
8c17a29d4554f760e3efb32d7c73d33fe0a5567d
benadaba/Data-Management-and-Visualization
/Making Data Management Decisions.py
2,877
3.703125
4
# -*- coding: utf-8 -*- “”“ Created on Sat Dec 26 14:26:14 2015 @author: Bernard ”“” #import statements import pandas import numpy #load the gapminder_ghana_updated dataset csv into the program data = pandas.read_csv(‘gapminder_ghana_updated.csv’, low_memory = False) #print number of observations(rows) which is the number of years this data #has been looked at; print length print(“number of observations(rows) which is the number of years this data has been looked at: ”) print(len(data)) #print number of variables (columns) print(“number of variables (columns) available in the dataset: ”) print(len(data.columns)) print(“data index: ”) print(len(data.index)) #Converting datat to numeric data[“incomeperperson”] = data[“incomeperperson”].convert_objects(convert_numeric=True) data[“lifeexpectancy”] = data[“lifeexpectancy”].convert_objects(convert_numeric=True) data[“literacyrate”] = data[“literacyrate”].convert_objects(convert_numeric= True) #displaying rows or observation in Dataframe. #inc_pp_count is the name that will hold the result from incomeperperson count # sort = false ; i use value false so that the data will be sorted according #to the original format and sequence of the loaded data print(“counts for incomeperperson - 2010 Gross Domestic Product per capita in constant 2000 US$ of Ghana. ”) inc_pp_count = data[“incomeperperson”].value_counts(sort = False) #print the count of inc_pp_count ; incomeperperson print(inc_pp_count) print(“percentages for incomeperperson - 2010 Gross Domestic Product per capita in constant 2000 US$ of Ghana. ”) inc_pp_percent = data[“incomeperperson”].value_counts(sort=False, normalize =True) #print the percentage of incomeperperson print(inc_pp_percent) print(“counts for lifeexpectancy- 2011 life expectancy at birth (years) of Ghana”) life_exp_count = data[“lifeexpectancy”].value_counts(sort = False) #print the count of life_exp_count ; lifeexpectancy print(life_exp_count) print(“percentages for lifeexpectancy- 2011 life expectancy at birth (years) of Ghana ”) life_exp_percent = data[“lifeexpectancy”].value_counts(sort =False, normalize = True) #print the percentage of life_exp_count ; lifeexpectancy print(life_exp_percent) print(“counts for literacyrate - 2010, Literacy rate, adult total (% of people ages 15 and above) of Ghana”) lit_rate_count = data[“literacyrate”].value_counts(sort = False ,dropna=False) #dropna displays missen values #print the count of lit_rate_count ; literacyrate print(lit_rate_count) print(“percentages literacyrate - 2010, Literacy rate, adult total (% of people ages 15 and above) of Ghana ”) lit_rate_percent = data[“literacyrate”].value_counts(sort =False, normalize = True) #print the percentage of lit_rate_count ; literacyrate print(lit_rate_percent)
a026e2ed0a40c56a1705a55b43a9aba7c2a99ab8
jainamandelhi/Machine-Learning-Algorithms
/Simple Linear Regression/Simple Linear Regression.py
2,706
3.859375
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 19 12:41:14 2018 @author: AMAN """ #Import libraries from random import seed from random import randrange from csv import reader from math import sqrt #Function to load csv file def read_my_file(filename): dataset=list() with open(filename,'r') as file: csv=reader(file) for row in csv: if not row: continue dataset.append(row) return dataset # Convert string column to float def string_to_float(dataset,column): for row in dataset: row[column] = float(row[column].strip()) # Split a dataset into a training and test set def train_test_split(dataset,split): dataset_copy=list(dataset) train=list() train_size=split*len(dataset) while(len(train)<train_size): index=randrange(len(dataset_copy)) train.append(dataset_copy.pop(index)) return train,dataset_copy #Calculate root mean square def rms(actual,predicted): squared_error=0.0 for i in range(len(actual)): squared_error+=(actual[i]-predicted[i])**2 squared_error/=float(len(actual)) return sqrt(squared_error) # Evaluate an algorithm def evaluate_algorithm(dataset, algorithm, split, *args): train, test = train_test_split(dataset, split) test_set = list() for row in test: row_copy = list(row) row_copy[-1] = None test_set.append(row_copy) predicted = algorithm(train, test_set, *args) actual = [row[-1] for row in test] rmse = rms(actual, predicted) return rmse #Calculate the mean def mean(values): return sum(values)/float(len(values)) #Calculate covariance def covariance(x,y,mean_x,mean_y): sum=0.0 for i in range(len(x)): sum+=(x[i]-mean_x)*(y[i]-mean_y) return sum # Calculate the variance def variance(values, mean): return sum([(x-mean)**2 for x in values]) # Calculate coefficients def coefficients(dataset): x = [row[0] for row in dataset] y = [row[1] for row in dataset] x_mean, y_mean = mean(x), mean(y) b1 = covariance(x,y,x_mean, y_mean) / variance(x, x_mean) b0 = y_mean - b1 * x_mean return [b0, b1] # Simple linear regression algorithm def simple_linear_regression(train, test): predictions = list() b0, b1 = coefficients(train) for row in test: yhat = b0 + b1 * row[0] predictions.append(yhat) return predictions # Simple linear regression seed(0) # load and prepare data filename = 'ammm.csv' dataset =read_my_file(filename) for i in range(len(dataset[0])): string_to_float(dataset, i) # evaluate algorithm split = 0.8 rmse = evaluate_algorithm(dataset, simple_linear_regression, split) print('RMSE: %.3f' % (rmse)) #RMSE=35.537
685eebb6806efc434e73d5fe67251be03fe7392b
Vaishnavi02-eng/InfyTQ-Answers
/PROGRAMMING FUNDAMENTALS USING PYTHON/Day3/Assignment26.py
650
3.90625
4
#PF-Assgn-26 def solve(heads,legs): error_msg="No solution" chicken_count=0 rabbit_count=0 #Start writing your code here #Populate the variables: chicken_count and rabbit_count if legs%2==0: rabbit_count=legs//2-heads chicken_count=heads-rabbit_count print(rabbit_count) print(chicken_count) else: print(error_msg) # Use the below given print statements to display the output # Also, do not modify them for verification to work #print(chicken_count,rabbit_count) #print(error_msg) #Provide different values for heads and legs and test your program solve(5,10)
064c6e7e350807bc6fe5ef214633e8e0ae012fe4
ewalldo/URI-OnlineJudge-Problems
/Beginner/3037 - Playing Darts by Distance/main.py
415
3.671875
4
n_cases = int(input()) for x in range(n_cases): joao_score = 0 for j in range(3): score, distance = map(int, input().split(' ')) joao_score += (score * distance) maria_score = 0 for j in range(3): score, distance = map(int, input().split(' ')) maria_score += (score * distance) if maria_score > joao_score: print("MARIA") elif joao_score > maria_score: print("JOAO") else: print("EMPATE")
c78d9488eff6d68d0fe96d5970d53301d4bbeb2e
andrewp-as-is/elapsed.py
/tests/examples/datetime/example.py
406
3.8125
4
#!/usr/bin/env python import datetime import time import elapsed dt = datetime.datetime.now() time.sleep(2) print("elapsed.get(datetime): %s" % elapsed.get(dt)) print("") print("elapsed.seconds(datetime): %s" % elapsed.seconds(dt)) print("elapsed.minutes(datetime): %s" % elapsed.minutes(dt)) print("elapsed.hours(datetime): %s" % elapsed.hours(dt)) print("elapsed.days(datetime): %s" % elapsed.days(dt))
e756d281407e384ac54d5c5804c6aceb3ecfbf06
CescWang1991/LeetCode-Python
/python_solution/251_260/PaintHouse.py
3,463
3.78125
4
# 256. Paint House # There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of # painting each house with a certain color is different. You have to paint all the houses such that no two adjacent # houses have the same color. # # The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] # is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so # on... Find the minimum cost to paint all houses. # # Note: # All costs are positive integers. class Solution: # dp[i][j]表示刷到第i个房子用颜色j的最小花费(j = 0, 1, 2)。 # dp[i][j] = costs[i][j] + min(dp[i-1][j-1], dp[i-1][j+1])。 # 如果当前的房子要用红色刷,那么上一个房子只能用绿色或蓝色来刷,那么我们要求刷到当前房子,且当前房子用红色刷的最小花 # 费就等于当前房子用红色刷的钱加上刷到上一个房子用绿色和刷到上一个房子用蓝色的较小值,这样当我们算到最后一个房子时, # 我们只要取出三个累计花费的最小值即可。 def minCost(self, costs): """ :type costs: list[list[int]] :rtype: int """ if not costs or not costs[0]: return 0 for i in range(1, len(costs)): # dp[i][j]表示刷到第i个房子用颜色j的最小花费(j = 0, 1, 2)。这里我们可以用costs代替dp。 # dp[i][j] = costs[i][j] + min(dp[i-1][j-1], dp[i-1][j+1])。由于j只有三种,我们可以分开计算。 costs[i][0] = costs[i][0] + min(costs[i-1][1], costs[i-1][2]) costs[i][1] = costs[i][1] + min(costs[i-1][0], costs[i-1][2]) costs[i][2] = costs[i][2] + min(costs[i-1][0], costs[i-1][1]) return min(costs[-1]) # 265. Paint House II # There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with # a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. # # The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] # is the cost of painting house 0 with color 0; costs[1][2]is the cost of painting house 1 with color 2, and so on... # Find the minimum cost to paint all houses. # # Note: # All costs are positive integers. # # Follow up: # Could you solve it in O(nk) runtime? class Solution2: def minCosts(self, costs): """ :type costs: list[list[int]] :rtype: int """ if not costs or not costs[0]: return 0 for i in range(1, len(costs)): min1 = min(costs[i-1]) # 找到第i个房子costs的最小值以及颜色的index index = costs[i-1].index(min1) min2 = min(costs[i-1][:index] + costs[i-1][index+1:]) # 找到第二小的值 # 除了index颜色的costs,其余的均要用到min1,costs[i][index]则要用到min2,这里的min1,min2对应上一题的min,即 # 前i-1个房子粉刷,最后一个房子不用j颜色的最小花费 for j in range(len(costs[i])): if j != index: costs[i][j] += min1 else: costs[i][j] += min2 return min(costs[-1])
879cbb11f5b0244d37775de0953ec30532fac9bc
Xponential11/Jenkins
/Exercise_numpy_3.py
3,282
4.03125
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt def tax_sums(journal_df, months=None): """ Returns a DataFrame with sales and tax rates - If a number or list is passed to 'months', only the sales of the corresponding months will be used. Example: tax_sums(df, months=[3, 6]) will only use the months 3 (March) and 6 (June)""" if months: if isinstance(months, int): month_cond = journal_df.index.month == months elif isinstance(months, (list, tuple)): month_cond = journal_df.index.month.isin(months) positive = journal_df["gross amount"] > 0 # sales_taxes eq. umsatzsteuer sales_taxes = journal_df[positive & month_cond] negative = journal_df["gross amount"] < 0 # input_taxes equivalent to German Vorsteuer input_taxes = journal_df[negative & month_cond] else: sales_taxes = journal_df[journal_df["gross amount"] > 0] input_taxes = journal_df[journal_df["gross amount"] < 0] sales_taxes = sales_taxes[["tax rate", "gross amount"]].groupby("tax rate").sum() sales_taxes.rename(columns={"gross amount": "Sales Gross"}, inplace=True) sales_taxes.index.name = 'Tax Rate' input_taxes = input_taxes[["tax rate", "gross amount"]].groupby("tax rate").sum() input_taxes.rename(columns={"gross amount": "Expenses Gross"}, inplace=True) input_taxes.index.name = 'Tax Rate' taxes = pd.concat([input_taxes, sales_taxes], axis=1) taxes.insert(1, column="Input Taxes", value=(taxes["Sales Gross"] * taxes.index / 100).round(2)) taxes.insert(3, column="Sales Taxes", value=(taxes["Expenses Gross"] * taxes.index / 100).round(2)) return taxes.fillna(0) with pd.ExcelFile("net_income_method_2020.xlsx") as xl: accounts2descr = xl.parse("account numbers", index_col=0) journal = xl.parse("journal", index_col=0, ) journal.index = pd.to_datetime(journal.index) # print(journal.index) account_sums = journal[["account number", "gross amount"]].groupby("account number").sum() # print(account_sums) income_accounts = account_sums[account_sums["gross amount"] > 0] # print(income_accounts) plot = income_accounts.plot(y='gross amount', figsize=(5, 5), kind="pie") expenses_accounts = account_sums[account_sums["gross amount"] < 0] # print(expenses_accounts) acc2descr_expenses = accounts2descr["description"].loc[expenses_accounts.index] # print(acc2descr_expenses) expenses_accounts.set_index(acc2descr_expenses.values, inplace=True) expenses_accounts *= -1 labels = [''] * len(expenses_accounts) plot = expenses_accounts.plot(kind="pie", y='gross amount', figsize=(5, 5), labels=labels) plot.legend(bbox_to_anchor=(0.5, 0.5), labels=expenses_accounts.index) plt.show() journal.drop(columns=["account number"]) print(tax_sums(journal, months=[5, 6]))
447b7988bf01a785607292d10948e0b047d6102f
mollyincali/whatsthatface
/src/graphing.py
4,182
3.546875
4
''' code for graphing used throughout capstone ''' import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set() from skimage import io import PIL from sklearn.metrics import confusion_matrix def cluster_images(df): ''' show kmeans cluster of animals ''' for i in range(5): group = df[df['cluster'] == i].copy() plt.figure(figsize=(10, 10)) for idx, img in enumerate(group.sample(9).iloc[:,1]): animal = io.imread(f'../animals/val/w.wild/{img}') ax = plt.subplot(3, 3, idx + 1) plt.imshow(animal) plt.axis("off") plt.show() def get_before_after(x, decoded): ''' show before entering autoencode and after running through autoencoder ''' plt.figure(figsize=(20, 4)) for i in range(10): # display original ax = plt.subplot(2, 10, i + 1) plt.imshow(x[i]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, 10, i + 1 + 10) plt.imshow(decoded[i]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() def graph_model(history, epochs): ''' code to run accuracy on test and validation ''' pink = '#CC9B89' blue = '#23423F' # gold = '#B68D34' epochs = 20 acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss=history.history['loss'] val_loss=history.history['val_loss'] epochs_range = range(epochs) if min(val_acc) < min(acc): min_ = min(val_acc) else: min_ = min(acc) plt.figure(figsize=(8, 8)) plt.subplot(1, 2, 1) plt.plot(epochs_range, acc, label='Training Accuracy', linewidth = 2, color = blue) plt.plot(epochs_range, val_acc, label='Validation Accuracy', linewidth = 2, color = pink) plt.legend(loc='lower right') plt.ylim((min_,1)) plt.title('Training and Validation Accuracy') plt.subplot(1, 2, 2) plt.plot(epochs_range, loss, label='Training Loss', linewidth = 2, color = blue) plt.plot(epochs_range, val_loss, label='Validation Loss', linewidth = 2, color = pink) plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.show() def heatmap(true, pred): ''' creates heatmap of true and predicited animals ''' cm = confusion_matrix(true, pred) group_names = ['True Cat',' ',' ', ' ','True Dog',' ', ' ',' ','True Wild'] group_counts = ['{0:0.0f}'.format(value) for value in cm.flatten()] group_percentages = ['{0:.2%}'.format(value) for value in cm.flatten()/np.sum(cm)] labels = [f'{v1}\n{v2}\n{v3}' for v1, v2, v3 in zip(group_names,group_counts,group_percentages)] labels = np.asarray(labels).reshape(3,3) sns.heatmap(cm, annot=labels, fmt='', cmap='Blues', xticklabels=['Cat','Dog','Wild'], yticklabels=['Cat','Dog','Wild']) plt.show(); def hist_prep(animalidx): ''' takes in the index of the particular animal we are hoping to graph on a histogram ''' animal = flat_values[animalidx] animal = animal[(animal != 0)] return animal def pixel_hist(animal1, animal2, label1, label2): ''' graphs the pixel intensity of the latent features for two animals one 1 graph ''' plt.hist(animal1, bins = 150, alpha = 0.3, label = label1) plt.hist(animal2, bins = 150, alpha = 0.6, label = label2) plt.title('Histogram of pixel intensities') plt.xlabel('Pixel intensity') plt.ylabel('Count') plt.legend() plt.show() def latent_features(animalidx): ''' graphs the latent features for a particular animal ''' animal = flat_values[animalnum].reshape(64,64,8) plt.figure(figsize=(16, 10)) for i in range(8): # display original ax = plt.subplot(1, 8, i + 1) plt.imshow(animal[i]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() if __name__ == "__main__": pass
fbbed797e0e2fef3f539924064991d874a0a13f3
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3986/codes/1636_2450.py
124
3.890625
4
n1=input("nome 1 :") n2=input("nome 2 :") if (n1.upper() > n2.upper()) : print(n2) print(n1) else : print(n1) print(n2)
115d8fd9ef2a4317333e366b50d699a495efac1d
avocardio/MLinPractice
/code/feature_extraction/video_bool.py
914
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Simple feature that tells whether a video is in the tweet or not. Created on Wed Sep 29 12:29:25 2021 @author: shagemann """ import numpy as np from code.feature_extraction.feature_extractor import FeatureExtractor # class for extracting the video as a feature class VideoBool(FeatureExtractor): """Create a feature based on if a video exists or not.""" # constructor def __init__(self, input_column): super().__init__([input_column], "{0}_bool".format(input_column)) # don't need to fit, so don't overwrite _set_variables() # use 'video' column as a feature # 0 if no video, return 1 else def _get_values(self, inputs): values = [] for index, row in inputs[0].iteritems(): values.append(int(row)) result = np.array(values) result = result.reshape(-1, 1) return result
2485204816372050e19ba0093bf737fc12395843
lssxfy123/PythonStudy
/tkinter_test/gui_test2.py
481
3.5625
4
# Copyright(C) 2018 刘珅珅 # Environment: python 3.6.4 # Date: 2018.6.8 # 自定义按钮 from tkinter import * # 自定义Button class HelloButton(Button): def __init__(self, parent=None, **config): super().__init__(parent, **config) self.pack() self.config(command=self.callback) def callback(self): print('Goodbye world...') self.quit() if __name__ == '__main__': HelloButton(text='Hello subclass world!').mainloop()
07c0ca609a798c5cad6069950b71d4c98c6c0ad8
fwangboulder/DataStructureAndAlgorithms
/#3LengthOfLongestSubstring.py
1,152
3.8125
4
""" 3. Longest Substring Without Repeating Characters Add to List QuestionEditorial Solution My Submissions Total Accepted: 237674 Total Submissions: 1002030 Difficulty: Medium Contributors: Admin Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. Hide Company Tags Amazon Adobe Bloomberg Yelp Hide Tags Hash Table Two Pointers String Hide Similar Problems (H) Longest Substring with At Most Two Distinct Characters """ class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ d = dict() start = 0 maxl = 0 for i, num in enumerate(s): if num in d and start <= d[num]: start = d[num] + 1 else: maxl = max(maxl, i - start + 1) d[num] = i return maxl
98bf926b3434e649e4125a0aa94854e7a1a1739a
pmk2109/Week0
/Code1/worldcup.py
4,126
3.875
4
from datetime import datetime import os import sys def read_game_info(filename): ''' INPUT: string OUTPUT: tuple of string, string, string, int, int Given the filename of a game, return the time, team names and score for the game. Return these values: time: string representing time of game team1: first team name team2: second team name score1: score of first team score2: score of second team ''' data = [] with open(filename) as f: for line in f: data.append(line.strip()) time = data[0] team1 = data[3].split('-')[0].strip() team2 = data[3].split('-')[1].strip() score1 = int(data[4].split('-')[0]) score2 = int(data[4].split('-')[1]) return (time, team1, team2, score1, score2) def display_game(time, team, other, team_score, other_score): ''' INPUT: string, string, string, int, int OUTPUT: string Given the time, names of the teams and score, return a one line string presentation of the results. ''' disp_game_string = "{time}: {team1} ({score1}) - {team2} ({score2})" \ .format(time=time, team1=team, score1=team_score, team2=other, score2=other_score) return disp_game_string def display_summary(team, data, detailed=False): ''' INPUT: string, list of tuples, bool OUTPUT: string Given the data (list of tuples of game data), return a string containing the summary of results for the given team. This includes # games played, # wins, # losses, # ties, and # goals scored. If detailed is True, also include in the string all the games for the given team. ''' wins=losses=ties=total_goals=total_games = 0 for row in data: if row[1]==team and row[3]>row[4]: wins+=1 total_goals+=row[3] total_games+=1 elif row[2]==team and row[4]>row[3]: wins+=1 total_goals+=row[4] total_games+=1 elif row[1]==team and row[3]<row[4]: losses+=1 total_goals+=row[3] total_games+=1 elif row[2]==team and row[4]<row[3]: losses+=1 total_goals+=row[4] total_games+=1 elif (row[1] == team or row[2]==team) and row[3]==row[4]: ties+=1 total_goals+=row[3] total_games+=1 else: pass if detailed: addition = "\n"+"\n".join(data) else: addition = "" summary_string = "{team} played a total of {tot_games} games.\n"\ "{wins} win(s), {losses} loss(es), {ties} tie(s),"\ " {tot_goals} total goal(s){detail}" \ .format(team=team, tot_games=total_games, wins=wins, losses=losses, ties=ties, tot_goals=total_goals, detail=addition) return summary_string def run(directory, team): ''' INPUT: string, string OUTPUT: None Given the directory where the data is stored and the team name of interest, read the data from the directory and display the summary of results for the given team. ''' data = [] for filename in os.listdir(directory): data.append(read_game_info(os.path.join(directory, filename))) print display_summary(team, data, detailed=True) def main(): ''' INPUT: None OUTPUT: None Get the directory name and team name from the arguments given. If arguments are valid, display the summary of results. Otherwise, exit the program. ''' error_message = "Usage: python worldcup.py directory team\n" \ " e.g. python worldcup.py worldcup USA" if len(sys.argv) != 3: print error_message exit() directory = sys.argv[1] if not os.path.exists(directory): print "{0} is not a valid directory.".format(directory) print error_message exit() team = sys.argv[2] run(directory, team) if __name__ == '__main__': main()
1339d9c73fc2339961ba48dad20f0e9a3e0459fb
SachaRbs/ft_linear_regression
/src/predict.py
510
3.734375
4
import pandas as pd def predict_(t0, t1, mileage): pred = t0 + (t1 * mileage) return pred # return None def main(): theta = pd.read_csv(r'../data/theta.csv') t0 = float(theta.columns[0]) t1 = float(theta.columns[1]) print("enter the mileage of the house...") try: mileage = int(input()) except ValueError: print("please enter a number") pred = predict_(t0, t1, mileage) print("prediction : {}".format(pred)) if __name__ == "__main__": main()
eb52d830d45f7de84e9eb65f055f9c6976164f96
bOOmerSpb/lukogorskii-python
/Lecture_2_Collections_homework/hw3.py
652
4
4
""" Write a function that takes K lists as arguments and returns all possible lists of K items where the first element is from the first list, the second is from the second and so one. You may assume that that every list contain at least one element Example: assert combinations([1, 2], [3, 4]) == [ [1, 3], [1, 4], [2, 3], [2, 4], ] """ from typing import Any, List from itertools import product def combinations_iter(klists): for i in product(*klists): yield list(i) def combinations(*klists: List[Any]) -> List[List]: result = [] for i in combinations_iter(klists): result.append(i) return result
98280d5ffc5551691aa1b2663e62aa96d23fd1fd
AlexandruSte/100Challenge
/Paduraru Dana/17_odd_int.py
409
3.875
4
# https://www.codewars.com/kata/find-the-odd-int/train/python def find_odd_int(seq): for elem in seq: if seq.count(elem) % 2: return elem print(find_odd_int([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5])) print(find_odd_int([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5])) print(find_odd_int([10])) print(find_odd_int([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1])) print(find_odd_int([]))
04aba31265e5b491652e5c72b0f049aa9672b96c
huangjenny/wallbreakers
/week2/subdomain_visit_count.py
1,984
3.5625
4
# Jenny Huang # Wallbreakers Cohort #3 # Week 2 # Subdomain Visit Count # https://leetcode.com/problems/subdomain-visit-count/ from collections import defaultdict class Solution(object): def subdomainVisits(self, cpdomains): """ :type cpdomains: List[str] :rtype: List[str] """ # key = domain list # value = domain value cpdomains_dict = defaultdict(int) for domain in cpdomains: # split at the space to separate the domain value and domain list domain_list = list(domain.split()) domain_value = int(domain_list[0]) domain_only = domain_list[1] # insert first domain value into dictionary if domain_only in cpdomains_dict.keys(): cpdomains_dict[domain_only] += domain_value else: cpdomains_dict[domain_only] = domain_value # split at the '.' split_domain = domain_only.split(".") # look at the rest of the subdomains for subdomain in range(1,len(split_domain)): new_list = split_domain[subdomain::] string = "" # build subdomain strings for i in range(len(new_list)): if new_list[i] == new_list[-1]: string = string + new_list[i] else: string = string + new_list[i] + "." # clean up subdomain strings if string in cpdomains_dict.keys(): cpdomains_dict[string] += domain_value else: cpdomains_dict[string] = domain_value cpdomains_list = [] string = "" # convert dictionary to list for key, value in cpdomains_dict.items(): string = str(value) + " " + str(key) cpdomains_list.append(string) return cpdomains_list
f580d4926d1cc7356964a3ccfd204e0603e2d7fc
jishnuvinayakg/pygeo
/tests/test_intersect.py
4,687
3.71875
4
from src.pygeo.intersect import ( intersect, _intersect_ray_with_sphere, _intersect_ray_with_triangle, ) from src.pygeo.objects import Ray, Sphere, Triangle,Point,Vector import numpy as np # Test cases for intersect # 1.test _intersect_ray_with_sphere def test_ray_sphere_intersection_2_point_return_true(): '''Test case : intersection of ray @ 2 points with a sphere. Sphere : center [0,0,0], radius = 5 Ray : Begin [-6,3,0], direction[1,0,0] Expected intersection points : [-4,3,0] & [4,3,0]''' point_1 =[-4,3,0] point_2 =[4,3,0] assert_flag = False ray = Ray(Point((-6,3,0)),Vector((1,0,0))) sphere = Sphere(Point((0,0,0)),5) num_intersection_point,points = _intersect_ray_with_sphere(ray,sphere) if ((points[0] == point_1 or points[0] == point_2) and (points[1] == point_1 or points[1] == point_2)): assert_flag = True assert(num_intersection_point==2 and assert_flag)is True def test_ray_sphere_intersection_1_point_return_true(): '''Test case : intersection of ray @ 1 point with a sphere. Sphere : center [0,0,0], radius = 5 Ray : Begin [-6,5,0], direction[1,0,0] Expected intersection points : [0,5,0] ''' point_3 =[0.0,5.0,0.0] assert_flag = False ray = Ray(Point((-6,5,0)),Vector((1,0,0))) sphere = Sphere(Point((0,0,0)),5) num_intersection_point,points = _intersect_ray_with_sphere(ray,sphere) print(point_3) print(points[0]) print(points[0] == point_3) if points[0] == point_3: assert_flag = True assert(num_intersection_point==1 and assert_flag)is True def test_ray_sphere_no_intersection_return_true(): '''Test case : intersection of ray @ 0 point with a sphere. Sphere : center [0,0,0], radius = 5 Ray : Begin [-6,6,0], direction[1,0,0] Expected intersection points : No intersection ''' ray = Ray(Point((-6,6,0)),Vector((1,0,0))) sphere = Sphere(Point((0,0,0)),5) num_intersection_point,_ = _intersect_ray_with_sphere(ray,sphere) assert(num_intersection_point==0)is True # 2. _intersect_ray_with_triangle def test_traingle_ray_intersection_return_true(): '''Test case : ray and traingle having an intersection point Traingle : vertices (2,0,0) , (5,0,0) , (2,5,0) Ray : Begin(3,1,2) , direction (0,0,-1) Expected result : True''' a = Point((2,0,0)) b = Point((5,0,0)) c = Point((2,5,0)) point_b = Point((3,1,2)) vector_vb = Vector((0,0,-1)) ray_b = Ray(point_b,vector_vb) traingle_a = Triangle(a,b,c) assert_flag,_ = _intersect_ray_with_triangle(ray_b,traingle_a) assert (assert_flag) is True def test_traingle_ray_no_intersection_return_false(): '''Test case : ray and traingle having no intersection point Traingle : vertices (2,0,0) , (5,0,0) , (2,5,0) Ray : Begin(1,4,1) , direction (0,0,-1) Expected result : False''' a = Point((2,0,0)) b = Point((5,0,0)) c = Point((2,5,0)) point_b = Point((1,4,1)) vector_vb = Vector((0,0,-1)) ray_b = Ray(point_b,vector_vb) traingle_a = Triangle(a,b,c) assert_flag,_ = _intersect_ray_with_triangle(ray_b,traingle_a) assert (assert_flag) is False #3 : Test cases for intersect function #ray sphere intersection def test_ray_sphere_intersect_return_true(): '''Test case : check if intersect methods call the correct fuction when a ray and sphere is passed as arguments. Sphere : center [0,0,0], radius = 5 Ray : Begin [-6,3,0], direction[1,0,0] Expected intersection points : [-4,3,0] & [4,3,0] implies coreect methods was invoked''' point_1 =[-4,3,0] point_2 =[4,3,0] assert_flag = False ray = Ray(Point((-6,3,0)),Vector((1,0,0))) sphere = Sphere(Point((0,0,0)),5) num_intersection_point,points,_ =intersect(sphere,ray) if ((points[0] == point_1 or points[0] == point_2) and (points[1] == point_1 or points[1] == point_2)): assert_flag = True assert(num_intersection_point==2 and assert_flag)is True def test_ray_triangle_intersect_true(): '''Test case : check if intersect methods call the correct fuction when a ray and triangle is passed as arguments. Traingle : vertices (2,0,0) , (5,0,0) , (2,5,0) Ray : Begin(3,1,2) , direction (0,0,-1) Expected result : True . implies correct method was invoked''' a = Point((2,0,0)) b = Point((5,0,0)) c = Point((2,5,0)) point_b = Point((3,1,2)) vector_vb = Vector((0,0,-1)) ray_b = Ray(point_b,vector_vb) traingle_a = Triangle(a,b,c) _,_,assert_flag = intersect(ray_b,traingle_a) assert (assert_flag) is True
040aa62d812ba7ab2ff57ebf65dfb25642c02086
tlcsanshao/PythonDemo
/multiprocessingDemo/mp3.py
762
3.5625
4
import multiprocessing,time def reader(d): while True: time.sleep(1) print(d) def writer(d): d["abc"] = 123 if __name__ == "__main__": manager = multiprocessing.Manager() #生成Manager 对象 d = manager.dict() #生成共享dict jobs = [] # p1 = multiprocessing.Process(target = reader,args=(d,)) # p1.start() # jobs.append(p1) # # time.sleep(10) # # p2 = multiprocessing.Process(target = writer,args=(d,)) # p2.start() # jobs.append(p2) # # # for p in jobs: # p.join() pool = multiprocessing.Pool() pool.apply_async(reader,args=(d,)) time.sleep(10) pool.apply_async(writer,args=(d,)) pool.close() pool.join() print("end loop")
9278389cf96bc4b1bf38ae8c2cde5577abe51601
beepscore/python_play
/tests/test_user.py
1,113
3.90625
4
#!/usr/bin/env python3 import unittest from user import User class TestUser(unittest.TestCase): def test_add_attribute(self): user = User() # print(help(user)) """ Help on User in module python_collections_play.user object: class User(builtins.object) | simplest possible class | Python 3 class implicitly inherits from object | Therefore implicitly inherits object constructor __init__(self) | https://stackoverflow.com/questions/4015417/python-class-inherits-object | | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) """ self.assertEqual(user.__dict__, {}) # code outside a class can add an attribute to the class user.ball = 'red' self.assertEqual(user.ball, 'red') self.assertEqual(user.__dict__, {'ball': 'red'}) if __name__ == '__main__': unittest.main()
a8de8a0d7135659b2d931c4e2fce34d5707ad2a6
ismailsinansahin/PythonAssignments
/Assignment_13/Question_71.py
519
4.21875
4
""" Create a method called populate that accepts an empty int array and populates it with numbers counting up. Sample Output: populate(new int[3]) returns:[1,2,3] populate(new int[5]) returns:[1,2,3,4,5] """ def populate(arr): newInt = [] for i in range(arr[0]): newInt.append(i+1) return newInt # MAIN arr1 = [3] arr2 = [5] print("\ninput : arr1[3]") print("output :", populate(arr1)) print("\ninput : arr2[5]") print("output :", populate(arr2))
c3b4963ef78a1c8b636b82eb996807ba774b4df2
AndreyPetrovGit/pythonhw
/basics/Task6.py
149
3.546875
4
def caesar_cipher(stri, sh): ans = "" for i in stri: ans += chr((ord(i) + sh) % 256) return ans print(caesar_cipher("abc", 1))
0771d7f0ae9812152aadf16a0a2645f9ff14d896
lilyluoauto/algorithm008-class02
/Week_02/groupAnagrams.py
614
3.75
4
# coding:utf-8 #!/usr/bin/python # ======================================================== # Project: project # Creator: lilyluo # Create time: 2020-04-20 23:17 # IDE: PyCharm # ========================================================= import collections class Solution: def groupAnagrams(self, strs): ans = collections.defaultdict(list) for s in strs: ans["".join(tuple(sorted(s)))].append(s) return list(ans.values()) if __name__ == "__main__": strs = ["eat","tea","tan","ate","nat","bat"] so = Solution() value = so.groupAnagrams(strs) print(value)
4a8363a034993b9b9fdb6648d0a7da262f9cf46c
SmallConcern/python_self_study
/algorithms/graphs/topological_sort.py
924
3.5625
4
import random def _topological_sort(dag, node, visited, sorted): if node not in visited: visited.add(node) for child in dag[node]: _topological_sort(dag, child, visited, sorted) sorted.append(node) def topological_sort(dag): visited = set() sorted = [] while len(visited) < len(dag.keys()): node_to_check = random.choice(list(set(dag.keys()) - visited)) if node_to_check not in visited: _topological_sort(dag, node_to_check, visited, sorted) return list(reversed(sorted)) class TestTopologicalSort(object): simple_dag = {'A': ['C'], 'B': ['C', 'D'], 'C': ['E'], 'D': ['F'], 'E': ['H', 'F'], 'F': ['G'], 'G': [], 'H': []} def test_topological_sort(self): print topological_sort(self.simple_dag)
9362eee6b9fadacb84dd2b9eba19532206b1051a
ing-prog/webpy_2019_1_g2
/Lesson 04.03/program4.py
168
3.90625
4
for i in range(0,10): print(i) name = ["Alice", "Bob", "Alex", "Luis","Yandex"] for i in range(0, len(name)): print(name[i]) for t in name: print(t)
a203216a05f95c0f2ba251c49b690d37b0dd4475
fwr666/ai1810
/aid/day20.py/chongzai.py
557
3.84375
4
class MyNumber: def __init__(self,value): self.data = value def __repr__(self): return "MyNumber(%d)" % self.data def __add__(self,other): print('MyNumer.__add__方法被调用') v = self.data + other.data return MyNumber(v)#创建一个新的对象并返回 def __sub__(self,rhs): v = self.data - other.data return MyNumber(v) n1 = MyNumber(100) n2 = MyNumber(200) print(n1) # n3=n1.__add__(n2) n3 = n1 + n2#等同于# n3=n1.__add__(n2) print(n3) n4 = n2 - n1 print(n4)
85ad965a64b40b1bd955733260937c78c10e2975
parulmittal1996/python
/md.py
337
3.5625
4
#!/usr/bin/env python # coding: utf-8 # In[13]: def f1(x,y): a=0 if (x>y): a = x else: a = y for i in range(a,(x*y+1)): if(i%x==0 and i%y==0): return ("lcm=",i) break # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
906db754678d34b12d886dc57d9420b2a41a7911
BigPieMuchineLearning/python_study_source_code
/exer_6.2_5.py
80
3.609375
4
total=0 num=100 while(num<100001): total+=num num+=5 print(total)
c806d2952eae3035f6c8cb50a7c24f179dbf9927
gal421/MIT-intro-to-cs-python
/bubble_sort.py
421
3.734375
4
def bubble(L): if len(L) == 0 or len(L) == 1: return L else: count = 0 i = 0 biggest = L[0] while count < len(L): for j in range(len(L)): print L[i], L[j], L if biggest > L[j]: biggest = L[j] count += 1 return L print bubble([3, 7, 2, 9, 5,4,1])
e7af34db35bc28ad32ac7035f4bc30116f1534e4
jmstudyacc/python_practice
/POP1-Exam_Revision/mock_exam1/question7.py
1,187
3.765625
4
class Person: def __init__(self, f_name, l_name): self.f_name = f_name self.l_name = l_name def get_info(self): return f"{self.f_name} {self.l_name}" def get_name(self): return (self.f_name, self.l_name) class Adult(Person): def __init__(self, f_name, l_name, phone): super().__init__(f_name, l_name) self.phone = phone def get_phone(self): return f"{self.phone}" class Child(Person): def __init__(self, f_name, l_name, p1, p2): super().__init__(f_name, l_name) self.p1 = p1 self.p2 = p2 def get_info(self): return f"{super().get_info()} {self.p1.get_info()} {self.p2.get_info()}" # return f"{self.f_name} {self.l_name} {self.p1.get_info()} {self.p2.get_info()}" def get_parents(self): return (self.p1, self.p2) p = Person("Mary", "Ann") print(p.f_name, p.l_name) a = Adult("John", "Doe", "1234567") assert a.get_info() == "John Doe" print(a.f_name, a.l_name, a.phone) c = Child("Richard", "Doe", p, a) #print(c.get_info()) assert c.get_info() == "Richard Doe Mary Ann John Doe" #print(str(c.get_parents())) assert c.get_parents() == (p, a)
9ea0e8a34dd527903574e3d5741ecd258d1b193d
ChangxingJiang/LeetCode
/0801-0900/0817/0817_Python_1.py
616
3.59375
4
from typing import List from toolkit import ListNode class Solution: def numComponents(self, head: ListNode, G: List[int]) -> int: G = set(G) ans = 0 part = False while head: if head.val in G: if not part: ans += 1 part = True else: part = False head = head.next return ans if __name__ == "__main__": print(Solution().numComponents(ListNode([0, 1, 2, 3]), [0, 1, 3])) # 2 print(Solution().numComponents(ListNode([0, 1, 2, 3, 4]), [0, 3, 1, 4])) # 2
99df96f328c88bd87159990fdf634db4f1c1a8e9
cfrasier/Portfolio
/SingleCellProject/bin_graph.py
1,528
3.53125
4
# Import packages # mplot3d creates three dimensional plots from mpl_toolkits import mplot3d import matplotlib.pyplot as plt # pandas is a module designed to help read in many different types of files and data types import pandas as pd import numpy as np # Read in the geometry.txt file as a data frame. Pandas data frames are called series, so the data type will need to be changed later. sep='\s+' refers to an unknown amount of white space used to delimit the data in file1. with open('geometry.txt', 'r') as file1: df_coords = pd.read_table(file1, sep='\s+') # Change the data type from a one column series to a list for each column in the series. xdata = df_coords['xcoord'].tolist() ydata = df_coords['ycoord'].tolist() zdata = df_coords['zcoord'].tolist() # Assign fig to call the plot fig = plt.figure() # Makes the projection in matplotlib three dimensional ax = plt.axes(projection = '3d') # Create scatterplot. zdir is the data associated with the z direction. c is color ax.scatter3D(xdata, ydata, zdata, zdir='zdata', c='gray') # Need to mirror ycoord to get full embryo. # May need to reference an Axes object to keep drawing on the same subplot. # Assign axis labels ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Plot the figure fig plt.show() fig.savefig('figure1.png') # Rotates plot and saves as png. Degree must equal 360 at max i. #for i in range(10): # degree = i * 36 # ax.view_init(35, degree) # filename='figure' + '_' + str(degree) + '_' + 'rotation' # savefig(filename.png)
410075d05f57223cad831d55d79944dba594dc68
niamargareta/project_euler
/experiment_with_for_loops.py
164
3.984375
4
print("foo") for x in range(1, 4): # print("bar", x, x // 3, x % 3, x/3) print("bar", x) for y in range(0, 3): print('dan', x, y) print("baz")
88c0171ef22e44f511e63c3b48cfb02f08c8ce62
matheus-valentim/projetos-python
/pequenos projetos/identificar valores.py
526
3.75
4
lista = [] maior = menor = menorP = maiorP = 0 for n in (range(0, 5)): lista.append(int(input(f'diga um valor para a posição {n}: '))) if n == 0: maior = menor = lista[n] menorP = maiorP = n else: if lista[n] > maior: maior = lista[n] maiorP = n elif lista[n] < menor: menor = lista[n] menorP = n print(f'o maior valor é {maior} e ele esta na posição {maiorP}') print(f'o menor valor é {menor} e esta na posição {menorP}')
2f5a045cbd4da8c288d9df035f749d0ea8efa2bf
Mica210/python_michael
/Mid-Course_Exercises/Targil7.py
568
4.1875
4
''' Write a Python program to convert height (in feet and inches) to centimeters. ''' from time import sleep print("\nConvert height imperial units to metric unit\n\nChoose your option\n---------") choise=input("1.Inches\n2.Feet\n") if(choise=="1"): inch=float(input("Enter your height: ")) sleep(1) print("\nYour height is: " + str("%.0f" % (inch*2.54)+ " cm.")) elif(choise=="2"): feet=float(input("Enter your height: ")) sleep(1) print("\nYour height is: " + str("%.0f" % (feet*30.48) + " cm.")) else: print("\nChoose 1 or 2 only!!")
42913d0ba647504e816dc2df52c5837764c7a675
lsyleo/HelloPython
/Python/inSuBunHe.py
1,900
3.640625
4
isGood = False fNum = 0 sNum = 0 tNum = 0 divNum = [1,0] wasNeg = False while True: fNum = int(input("이차항의 계수 :")) #이차항 계수 입력 if fNum <0: wasNeg = True if fNum == 0: while True: print("이차항의 계수는 0이 될 수 없습니다") fNum = int(input("이차항의 계수 :")) #이차항 계수 입력 완료 sNum = int(input("일차항의 계수 :")) #일차항 계수 입력 tNum = int(input("상수항의 계수 :")) #상수항 계수 입력 #합차 공식 일때 if sNum == 0 and fNum ==1: print("(x+"+str(tNum**0.5)+")(x-"+str(tNum**0.5)+")") #완전 제곱식 일때 elif fNum == 1 and sNum / 2 ** 2 == tNum and tNum > 0: if fNum < 0: print("x"+str(int(tNum))+")²") else: print("x+"+str(int(tNum))+")²") #ax²+ (a+b)x + ab꼴의 식 elif fNum == 1: if wasNeg == True: tNum *= -1 while divNum[0] + divNum[1] != sNum or isGood ==True : if tNum % divNum[0] == 0: divNum[1] = tNum / divNum[0] else: divNum[0] += 1 if tNum <= divNum[0] : isGood = True #출력 if divNum[0] < 0: print("(x"+str(divNum[0])+")(x+"+str(divNum[1])+")") elif divNum[1] < 0: print("(x+"+str(divNum[0])+")(x"+str(divNum[1])+")") elif divNum[0] < 0 and divNum[1] < 0: print("(x"+str(divNum[0])+")(x"+str(divNum[1])+")") elif divNum[0] < 0 and divNum[1] < 0: print("(x+"+str(divNum[0])+")(x+"+str(divNum[1])+")")
4266e64c16cce71aaa9f4c35f48798ce2f777a9c
edu-athensoft/ceit4101python
/stem1400_modules/module_2_basics/c5_datatype/datatype_numbers/decimal4.py
205
3.796875
4
print(16.0/7) ### round to 2 decimals from decimal import Decimal # First we take a float and convert it to a decimal x = Decimal(16.0/7) # Then we round it to 2 places output = round(x,2) print(output)
70a38a0d984637e17fdff8d62e015382e9d0a068
JoTaijiquan/Python
/Python101-New130519/2-1-2.py
964
4
4
#Python 3.9.5 #Example 2-1-2 def hello(): 'ป้อนเลข 1-7 แล้วพิมพ์ค่าออกมาตามเงื่อนไข' word = { "1":"สวัสดีวันอาทิตย์", "2":"สวัสดีวันจันทร์์", "3":"สวัสดีวันอังคาร", "4":"สวัสดีวันพุธ", "5":"สวัสดีวันพฤหัสบดี", "6":"สวัสดีวันศุกร์", "7":"สวัสดีวันเสาร์", "0":"ลาก่อน" } loop = True while loop: x = input("ป้อนเลข 1-7 (ป้อน 0 เพื่อออกจากโปรแกรม) :") if x == "0": print (word["0"]) loop = False elif x in word: print (word[x]) if __name__=='__main__': hello()
b68ffffc2204bd7668db00ece552f7efe496b0f3
PrajjawalBanati/python_certification
/Module_1/Assignment_17.py
1,249
4.3125
4
print("Hello Everyone! The following program will take two string as an input \ from your and will concatenate all the capital letters from both the strings") #Storing a string of capital letters in compiler to compare it with strings 1 and 2 default="ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Storing two Empty strings in which we insert the capital letter string capital_string_1="" capital_string_2="" #Store length a=len(default) string_1 = input("Enter string 1: ") b=len(string_1) #Comparing each letter of string with the alphabet string for i in range(0,b,1): for j in range(0,a,1): if string_1[i]==default[j]: capital_string_1 = capital_string_1 + string_1[i] print("The capital string in string_1 is",capital_string_1) string_2 = input("Enter string 2: ") b=len(string_2) for i in range(0,b,1): for j in range (0,a,1): '''If the element gets equal to any alphabet in default string it will get stored in the empty capital_string_2''' if string_2[i]==default[j]: capital_string_2 = capital_string_2 + string_2[i] print("The capital string in string_2 is:",capital_string_2) print("So the concatenated string is:",capital_string_1 + capital_string_2)
079c81ae397e63ddfe24d98c055b09ff0200ee27
hanchangjie429/algorithm010
/Week03/50.pow-x-n.py
1,054
3.578125
4
# # @lc app=leetcode.cn id=50 lang=python3 # # [50] Pow(x, n) # # @lc code=start class Solution: def myPow(self, x: float, n: int) -> float: # Method 1: 直接用公式 ''' return pow(x,n) ''' # Method 2: 暴力循环法 # 处理n为负数的情况,也就是将x转换成1/x,然后不断乘1/x ''' if n < 0: x = 1/x n = -n ans = 1 for _ in range(n): ans *= x return ans ''' # Method 3 递归 二分法 #https://leetcode-cn.com/problems/powx-n/solution/powx-n-by-leetcode-solution/ def divide(x, n): if n == 1: return x if n%2 != 0: half = divide(x, n//2) return half * half * x else: half = divide(x, n//2) return half * half if n==0 or x == 1: return 1 if n < 0: return 1/divide(x,-n) return divide(x,n) # @lc code=end
8474a7594a61d3d633239ca9c4fa92550ac6cef7
deepaksharran/Python
/tupletostr.py
96
3.703125
4
x=input("Enter comma seperated values: ").split(",") tup=tuple(x) s="".join(tup) print(s)
b9cf4c9bd42df87a4f18d5560888ac9eb7fbf816
quocvietit/code-wars
/5 kyu/moving-zeros-to-the-end.py
338
3.578125
4
''' 5kyu - Moving Zeros To The End https://www.codewars.com/kata/moving-zeros-to-the-end/solutions/python ''' def move_zeros(array): l = 0 arr = [] for i in range(0,len(array)): if array[i] == 0 and type(array[i]) in (int, float): l+=1 else: arr.append(array[i]) return arr+[0]*l
7c9d897a0f72b2d7281853071dba582617f0029d
seyyalmurugaiyan/Django_projects
/Demo_Projects/Day_1 - Basics/passitive_negative.py
131
4.0625
4
number = int(input("Enter Your Number: ")) if number>=0: print(f"{number} is correct.") else: print(f"{number}It is wrong")
3f7648f4465d51d2cb9e550f18cfc19e55c16bd5
sanusiemmanuel/DLBDSMLUSL01
/Unit_2_Clustering/2_1_ElbowCriterion.py
632
3.5625
4
# IU - International University of Applied Science # Machine Learning - Unsupervised Machine Learning # Course Code: DLBDSMLUSL01 # Elbow criterion #%% import libraries import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from yellowbrick.cluster import KElbowVisualizer #%% create sample data X= np.random.rand(50,2) Y= 2 + np.random.rand(50,2) Z= np.concatenate((X,Y)) #%% create a k-Means model an Elbow-Visualizer model = KMeans() visualizer = KElbowVisualizer(model, k=(1,8), \ timings=True) #%% fit the visualizer and show the plot visualizer.fit(Z) visualizer.show()
cb819a4afef7f87df40c7eae95e1da5ffcbf1a4d
krkartikay/CodeForces-solutions
/codeforces/982/A.py
481
3.578125
4
import os, sys, math import re def main(): T = int(input()) #for _ in range(T): testcase() def testcase(): l = input() if solve(l): print("Yes") else: print("No") def solve(l): if l=="0": return False if re.search("11",l): return False if re.search("000",l): return False if re.search("00$",l): return False if re.search("^00",l): return False return True def debug(*args): if 'DEBUG' in os.environ: print(*args) if __name__ == '__main__': main()