blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b3caf3831004632892e925a98b66858fb7f6a38e
RamonCz/Ciencias
/EstructurasDiscretas/Practica9/funciones.py
2,984
3.953125
4
""" --Estructuras Discretas 2018-1 --Profesor: Laura Freidberg Gojman --Ayudante: Ricardo Jimenez Mendez --Practica 9 --Alumno: Cruz Perez Ramon --No. de Cuenta: 31508148 """ import types """ La funcion distancia de la pracica 1 """ def distancia((x1,y1),(x2,y2)): r = (((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)) )**(0.5...
282257b7beba48fd0d324e45872c4dd6c37c08bd
AdamISZ/matasano-solutions
/challenges/matasano6.py
5,485
3.6875
4
import base64 import binascii import matasano3 def count_nonzero_bits(a): '''a should be a hex string returned will be how many non zero bits are in the binary representation''' return sum([bin(x).count('1') for x in map(ord,a.decode('hex'))]) def hamming_distance(a,b): '''Given two strings a,...
09ec9d5dcd7c3b4dd6a922b41f8d5c4437fcd14c
SinaSarparast/CPFSO
/JupyterNotebook/bagOfWords.py
1,151
3.796875
4
from sklearn.feature_extraction.text import CountVectorizer def get_word_bag_vector(list_of_string, stop_words=None, max_features=None): """ returns a vectorizer object To get vocabulary list: vectorizer.get_feature_names() To get vocabulary dict: vectorizer.vocabulary_ To convert a list...
cb118d8ffde483159094a69c572e6e0b8654e143
ashigirl96/fagents
/fagents/snippets/multi_process.py
857
3.734375
4
"""Snippets for how to code multi process""" import multiprocessing import time def _worker(i): print("I'm {0}'th worker".format(i)) time.sleep(1) return def f(conn): conn.send([42, None, 'hello']) conn.close() def main1(): parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process...
eb2c8203183b49044ab87ff7a8a0181f2ced1aa5
OskarLundberg/Intentionally-Bad-Name-Generator
/Intentionally Bad Name Generator.py
1,418
3.75
4
import time import random import os def clear(): return os.system('cls' if os.name == 'nt' else 'clear') # approx 44.4% chance of crashing def counting(): problem = False for num in range(1, 101): clear() print("picking one of all the possible names") print("Loadin...
1893fdb59156c0bb9f78af01183b1a23e670b779
chsergey/xmlcls
/xmlcls/xml_elem.py
4,054
3.5
4
# -*- coding: utf-8 -*- """ Base class for wrappers over XML elements If class name ends with 'List' then: - class must contains '_list_item_class' attribute with class name - class constructor returns list of objects with type of '_list_item_class' attribute's value If 'xpath' attribute is None - the root el...
12deaeb9f12fd624459faade33c7d07ac6d9b2e6
csteinberg23/Lab5-
/test_arraylist.py
4,271
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 30 08:35:53 2020 @author: christina """ """ This program tests various functionality of an array list implemented in the arraylist.py. Assume the student has completed the array list implementation. Xiannong Meng 2019-11-14 """ from arraylist im...
46e3119db13c6cf91480abd401f1e750cda69eea
bhagya97/newProj5409
/fibonacci.py
1,246
3.703125
4
import time import logging import random fibonacci() def fibonacci(): logging.basicConfig(filename="logfile.log",level=logging.DEBUG) starting_time=time.time() ### generate random numbers each time input1= random.randint(0,100) ### taking input from file #input_file= open("fib_in...
8150ef9af406dee91979fef3539286e7e92551ef
mnoskoski/scripts-template-python
/function-print-string.py
274
3.796875
4
print("hello, world!".upper()) # set all text to upper print("The itsy bitsy spider\nclimbed up the waterspout.") print("My", "name", "is", "Monty", "Python.", sep="-") print("Monty", "Python.", sep="*", end="*\n") print("Programming","Essentials","in",sep="***",end="...")
5ca276e780a1214a9393eeb006ad6ce8e9760cb4
mnoskoski/scripts-template-python
/06exercicio.py
529
3.984375
4
""" Estruturas logiscas and (e) or (ou) not (nao) operadores unarios - not operadores binarios - and, or, is Para o and ambos valores precisam ser True Para o or um ou outro valor precisa ser True Para o not o valor do booleano é invertido, se for True vira false e for false vira True Para o is o valor é compa...
8c6aff095e83e240fbf00a05b5bec40ff2adec66
sazemlame/Take-Home-Challenge
/takehome.py
9,324
4.21875
4
""" Automated Parking System: This application helps you manage a parking lot of n slots. The program has the following functionalities: 1. Park a car in empty slot and store the licence plate number and age of the driver 2. Record which car has left the parking spot 3. Search for the slot nu...
51309c0f241bd6641845e18b6e7655bc787e1b1c
it-worker-tango/PythonBase
/day03/Day03_2.py
717
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 29 21:50:00 2018 @author: Tango """ # = 简单的赋值运算符 x = 20 y = x print("x:",x) print("y:",y) print("-" * 30) # =+ 加赋值 x+=y 等价于 x= x +y x += y print("x:",x) print("y:",y) print("x+=y:",x) print("-" * 30) # -= 减赋值 x-=y 等价于 x=x -y x = 20 y = 5 x-=y print("x:",x) print("y:",y)...
5739eba75117bb3040d6e93e6be2e109749a08e6
it-worker-tango/PythonBase
/day10/demo3.py
308
3.59375
4
hello = "你好啊朋友" # 定义一个全局变量 def read(): '''看书的功能''' hello = '你好啊朋友,一起看书吧。' print(hello) if __name__ == "__main__": print("我去书店。。。。") read() print("我回家...") hello = "吃饭。。。" print(hello)
c95e2097506e549414b9cd73079c1d793e2fd098
it-worker-tango/PythonBase
/day11/demo2.py
203
3.859375
4
# 读取文件中的指定个数的字符 with open("demo.txt", 'r') as file: string = file.read(3) # 读取前3个字符 print("前3个字符为:", string) # 运行结果:前3个字符为: abc
92e01c676746653ac390ca7482cd9764c3c73bab
it-worker-tango/PythonBase
/day06/demo4.py
301
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 1 21:30:35 2019 @author: Tango if 嵌套 """ number = int(input("请输入去年的销量:")) if number >= 1000: print("销量不错") else: if number >= 500: print("销量还过得去") else: print("还需要努力啊")
1ff7a6d9db89df7d52d699d83f84871d3f82234f
carlos8410/Python_Class
/IntroGUI/GUI_Intr.py
1,483
3.984375
4
"""Write a GUI-based program that provides two Entry fields, a button and a label. When the button is clicked, the value of each Entry should (if possible) be converted into a float. If both conversions succeed, the label should change to the sum of the two numbers. Otherwise it should read "***ERROR***.""" from tkin...
2b35e0b81932a55bef05b180b3048c152fe7d5ba
jvansteeter/CS-360
/python/htbin/headlines.py
335
3.546875
4
#!/usr/bin/env python import requests from bs4 import BeautifulSoup print "Content-type: text/html" print print "<h1>Headlines</h1>" request = requests.get("http://news.google.com") soup = BeautifulSoup(request.content, 'html.parser') results = soup.find_all("span", {"class":"titletext"}) for i in results: print s...
2b88a13415abe1fbd15bbf70e50e05ae1cb8395a
IRC-SPHERE/sphere-challenge
/visualise_data.py
12,500
3.546875
4
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as pl import itertools as it import json import os def slice_df(df, start_end): """ This slices a dataframe when the index column is the time. This function slices the dataframe 'df' between a window defined by the '...
69a48b8681be3c0a77a2be589519d1a2e35533db
sreetamadas/sample_Python_code
/get_threshold_kneeCurve.py
4,897
4
4
### calculate threshold X from knee curve ### ## GOOGLE: how to find knee of a curve in noisy data # method 1: analytical (distance calculation with original data - may be affected by noise in data) # method 2: distance calculation with Y from curve fitted to original data # method 3: https://www1.icsi.berkeley.edu/~...
8a60d618f47ce9917bf2c8021b2863585af07672
sreesindhu-sabbineni/python-hackerrank
/TextWrap.py
511
4.21875
4
#You are given a string s and width w. #Your task is to wrap the string into a paragraph of width w. import textwrap def wrap(string, max_width): splittedstring = [string[i:i+max_width] for i in range(0,len(string),max_width)] returnstring = "" for st in splittedstring: returnstring += s...
3eefb470c6da99f23213785fba479914399f8728
Nouw/Programming-class
/les-8/8.1_while-loop_numbers.py
264
3.671875
4
running = True som = 0 getallen = -1 while running: getal = int(input("Geef en getal:")) som += getal getallen += 1 if getal == 0: running = False print("Er zijn " + str(getallen) + " getallen ingevoerd, de som is: " + str(som))
d4613de5a15162d087a76da28fd82077cfebc928
Nouw/Programming-class
/les-11/11.2_json-files_schrijven.py
961
3.609375
4
import json import os def store(name, firstl, birthdate, email): # Basically checks if the data.json file exists if not then create data.json file files = [] for f_name in os.listdir('.'): files.append(f_name) if 'data.json' not in files: with open('data.json', 'w') as file: ...
90d57fc0012c7370848d13f914790c03a9f10054
Nouw/Programming-class
/les-8/ns-kaartautomaat.py
2,035
4.1875
4
stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', "'s-Hertogenbosch", 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht'] def inlezen_beginstation(stations): running = True while running: ...
4ab0c17cea4ecc2344962dd34235a0afd3eea132
Nouw/Programming-class
/les-6/6.5_string_functions.py
491
3.796875
4
# Schrijf functie gemiddelde(), die de gebruiker vraagt om een willekeurige zin in te voeren. De functie berekent vervolgens de gemiddelde lengte van de woorden in de zin en print dit uit. def gemiddelde(zin): words = zin.split() print(words) totalLength = 0 wordCount = 0 for word in words: ...
a0d1ec47af81124c47b0c16ea678b230255f2ec7
Iretiayomide/Week-8
/Assignment 7b.py
594
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[9]: #import libraries import matplotlib.pyplot as plt import pandas as pd #create dataset names = ['Bob','Jessica','Mary','John','Mel'] status = ['Senior','Freshman','Sophomore','Senior', 'Junior'] grades = [76,95,77,78,99] GradeList = zip(status,grades) #create datafram...
8bf44c4718c44c230b4cac4d0fc5589c0313e31b
lexatnet/school
/python/17-pygame/01-ball/05-collision/engine/collision.py
2,246
3.5
4
def ball_to_box_collision(ball, box): return { 'x': ball_to_box_collision_x(ball, box), 'y': ball_to_box_collision_y(ball, box) } def ball_to_box_collision_x(ball, box): width = box['size']['width'] height = box['size']['height'] if (ball['rect'].left < 0) or (ball['rect'].right > width): return...
f6b956a6dc2d4a44bb586c79f16d541ac2c66cff
matanyehoshua/13.10.21
/Page 38_8.py
243
4
4
# Page 38_8 x = int(input("Enter a number: ")) y = int(input("Enter another number: ")) # prints the row x times and how many each row y times: for i in range(x): for i in range(y): print ('*', end = ' ') print()
2c8771dfe733ce5d3e7fb1af3105edd36d18534e
JVLJunior/Exercicios-URI---Python
/URI_1153.py
91
3.515625
4
n = int(input()) cont = n fat = 1 while cont > 0: fat *= cont cont -= 1 print(fat)
582a8b75d58698a4d89826aecb927d5dd22458d8
zhuweida/Tracing-Trends-in-Macronutrient-Intake-and-Energy-Balance-Across-Demographics-with-Statistics-and-Ma
/code/pr2.py
4,428
4
4
""" the function of converting RDD into csv file is based on http://stackoverflow.com/questions/31898964/how-to-write-the-resulting-rdd-to-a-csv-file-in-spark-python/31899173 And some of the initialization code is provided by our instructor Dr. Taufer. """ import re import argparse import collections import s...
820dcba436961e21d6b9b5eb93ad76608904b663
El-akama/week7_task_oop_encapsulation
/task_oop_incapsulation.py
2,072
3.78125
4
# task1 # class Car: # def __init__(self, make, model, year, odometer=0, fuel=70): # self.make = make # self.model = model # self.year = year # self.odometer = odometer # self.fuel = fuel # def __add_distance(self, km): # self.odometer += km # def __subtrac...
9264d91dbaf742726eb9c3bf7d70d8931b4556eb
519984307/BaseHouse
/Python/Base/ProducerConsumer/MultiThread.py
2,357
3.671875
4
import random import time from threading import Thread, Lock, Condition from queue import Queue class Producer(Thread): def __init__(self, queue, lock, condition): super().__init__() self._queue = queue self._lock = lock self._condition = condition def run(self): while ...
1560e2c88d1c43d1d8dce3f9aeee17b1b861bd73
gracenamucuo/PythonStudy
/ClassAndInstance.py
3,412
4.125
4
class Animal(object): def run(self): print('Animal is running') def run_teice(animal): animal.run() animal.run() #对于Python这样的动态语言来说,不一定需要传入Animal类型,只需要保证传入的对象有一个run()方法就可以。 #判断一个变量是不是某个类型 isinstance(a,Animal) #判断对象类型,使用type()函数: #type()函数返回的是Class类型 #判断一个对象是否是函数 import types de...
96ecc6d78dea8ae6abfb7123f10867092a0697cd
KatherineCG/TargetOffer
/3-相关题目.py
974
3.84375
4
class Solution: def SortInsert(self, a1, a2): if a1 == [] and a2 == []: return a1len = len(a1) a2len = len(a2) for i2 in range(a2len): for i1 in range(len(a1)): if a1[0] > a1[1]: if a2[i2] >= a1[i1]: ...
7443a803eb8dbb482fdb44a726b928adeb29a871
KatherineCG/TargetOffer
/24-二叉搜索树的后序遍历序列.py
925
3.765625
4
#coding=utf-8 #AC笔记:函数返回布尔值 class Solution(): def VerifySquenceOfBST(self, sequence): length = len(sequence) if length <= 0 or sequence == None: return False root = sequence[len(sequence)-1] for i in range(0, length): if sequence[i] > root: ...
676bc805b36c49dbfb1ecc01daa8b0eb50e63fce
KatherineCG/TargetOffer
/4-替换空格牛客.py
388
3.796875
4
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here if not s: return s res = '' for ch in s: if ch == ' ': res += '%20' else: res += ch return res te...
ed0e02d164d7d65d7a132809961b80845439aed8
KatherineCG/TargetOffer
/45-圆圈中最后剩下的数字.py
489
3.59375
4
# -*- coding:utf-8 -*- class Solution: def LastRemaining_Solution(self, n, m): # write code here if n == 0 or m == 0: return -1 array = [i for i in range(n)] i = 0 while len(array) > 1: remainder = (m-1) % len(array) array = array...
fb19b66574d2de75d864c3e5b10abd3050346c8d
KatherineCG/TargetOffer
/27-二叉搜索树与双向链表.py
2,694
3.6875
4
# -*- coding:utf-8 -*- import re class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Convert(self, pRootOfTree): # write code here pLastNodeInList = None pLastNodeInList = self.ConvertNode(pRootOfTr...
586de144105ea4e2cd2f0358e08cd6d4eee20714
KatherineCG/TargetOffer
/29.1-数组中出现超过一半的数字.py
1,148
3.578125
4
# -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here if self.CheckInvalidArray(numbers): return 0 number = numbers[0] times = 1 for i in range(1,len(numbers)): if numbers[i] == number: ...
dc06c6c46c4c9c07f2ea7c75cc3a486f1fd4f9fc
KatherineCG/TargetOffer
/3-二维数组的查找.py
1,681
3.96875
4
# coding=utf-8 ''' 在一个二维数组中,每一行都按照从左到右递增的顺序排序 每一列都按照从上到下递增的顺序排序。 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 ''' ''' 查找方式从右上角开始查找 如果当前元素大于target, 左移一位继续查找 如果当前元素小于target, 下移一位继续查找 进行了简单的修改, 可以判定输入类型为字符的情况 ''' class Solution: def Find(self, array, target): if array == []: return...
e8e5aadff96ec0b43260a3f7503e459fbdd88161
KatherineCG/TargetOffer
/33-把数组排成最小的数.py
1,104
3.703125
4
# -*- coding:utf-8 -*- class Solution: def PrintMinNumber(self, numbers): # write code here if not numbers: minnum = '' else: length = len(numbers) numbers = map(str, numbers) self.Compare(numbers, 0, length-1) minnum = ''...
f6c4fb4ad8819c4706d19709aa5955c0221bf3a5
KatherineCG/TargetOffer
/13-在O(1)时间删除链表结点.py
1,358
3.78125
4
# coding=utf-8 class ListNode: def __init__(self, data, next = None): self.data = data self.next = None def __del__(self): self.data = None self.next = None class Solution: def __init__(self): self.head = None def DeleteNode(self, pListHead,...
44869bc89939ee9719d4955b5ba8f24542d9df35
KatherineCG/TargetOffer
/13-调整数组顺序使奇数位于偶数前面.py
481
3.671875
4
# -*- coding:utf-8 -*- ''' 用两个列表,一个存储奇数,一个存储偶数 返回奇数列表+偶数列表 ''' class Solution: def reOrderArray(self, array): # write code here if not array: return [] evenres = [] oddres = [] for ch in array: if ch % 2 == 0: evenres.appe...
4f2e3b81459c7de30038d44b7232fea76c621e36
Z3roTwo/GuessTheNumber
/GuessTheNumber.py
1,335
3.796875
4
import random import json loop = True guess = 0 number = 0 rounds = 0 name = 0 #q = 0 name = input("Display name: ") number = random.randint(1, 10) #try: #with open('Storage.json', 'r') as JSON: #data = json.load(JSON) #type(data) #print(data["name"]) #q = data[rounds] #except: ...
dff00f606c61a85f97eadf87e8a939121ed22462
mananaggarwal2001/The-Perfect-Guess-Game
/project2-the_perfect_guess.py
999
4.03125
4
import os import random randInt = random.randint(1, 100) userGuess = None Gussess = 0 highScore=None while(userGuess != randInt): userGuess = int(input("Enter Your Guess: ")) if(userGuess == randInt): print("You Guessed it Right") else: if userGuess > randInt: print("...
25001af33ac7a663e5f20810c42d5cba3ac73242
AhmedElkhodary/Python-3-Programming-specialization
/1- Python Basics/FinalCourseAssignment/pro5.py
620
4.15625
4
#Provided is a list of data about a store’s inventory where each item #in the list represents the name of an item, how much is in stock, #and how much it costs. Print out each item in the list with the same #formatting, using the .format method (not string concatenation). #For example, the first print statment shou...
a53c2faa1c8da8d9f736720d2f653811898ea67a
AhmedElkhodary/Python-3-Programming-specialization
/1- Python Basics/Week4/pro3.py
256
4.3125
4
# For each character in the string already saved in # the variable str1, add each character to a list called chars. str1 = "I love python" # HINT: what's the accumulator? That should go here. chars = [] for ch in str1: chars.append(ch) print(chars)
0362c1ae9a526f1ba7b5923d7e28e1d043648556
ContextLab/quail
/docs/_build/html/_downloads/plot_pnr.py
515
3.625
4
# -*- coding: utf-8 -*- """ ============================= Plot probability of nth recall ============================= This example plots the probability of an item being recalled nth given its list position. """ # Code source: Andrew Heusser # License: MIT # import import quail #load data egg = quail.load_example...
a92b0b7e4b40c97f9dcc7aa74f342b4727212f96
Aakaaaassh/Coding
/Greedy_florist.py
555
3.734375
4
n,x = list(map(int,input().split())) list1 = [] for i in range(n): y = int(input("enter price of flower")) list1.append(y) print("number of flowers are " + str(n) + " and their prices are ", list1) Buyer = x print("Number of buyers are :", Buyer) res = sorted(list1, reverse=True) print(res) def TotalP...
c3a03b2fda7d388c9626f9a9213d49239e659d67
Aakaaaassh/Coding
/kth_smallest_element.py
318
3.65625
4
n = int(input("Enter no. of test cases: ")) list2 = [] for i in range(n): a = int(input("Enter size of array: ")) list1 = list(map(int, input().split())) k = int(input("Enter kth smallest element: ")) res = sorted(list1) res = res[k-1] list2.append(res) for i in list2: print(i)
fba8df5f519498639cd582e945b592200227eaf6
IbrahimIrfan/ctci
/1/7.py
580
3.78125
4
# O(M*N) in place def set0(matrix): rows = set() cols = set() m = len(matrix) n = len(matrix[0]) #O(M*N) for r in range(0, m): for c in range(0, n): # O(1) if (matrix[r][c] == 0): rows.update([r]) cols.update([c]) # O(M*N) ...
80a40c327baf5f1e7f3e287815d584918410124a
golbeck/PythonExercises
/NeuralNets/MLP pure numpy/NeuralNetV1.py
9,514
3.984375
4
#implements logistic classification #example: handwriting digit recognition, one vs. all import numpy as np import os #################################################################################### #################################################################################### def grad_cost(bias,theta,X,Y,ep...
453a816c318a213493b5f6cc9cd9ca2567ae55b9
golbeck/PythonExercises
/twitter/tweet_parserV1.py
5,928
3.6875
4
import oauth2 as oauth import urllib2 as urllib import numpy as np from pandas import DataFrame, Series import pandas as pd import json # See Assignment 1 instructions or README for how to get these credentials access_token_key = "89257335-W8LCjQPcTMIpJX9vx41Niqe5ecMtw0tf2m65qsuVn" access_token_secret = "5tmU9RDxP3tiF...
57df74cd1011bcce2d372806326c2f61adc6ea14
naveen-kulkarni0/tensorflow
/flower-classification-tensorflow/data-genr.py
3,608
3.890625
4
"""# Data Loading In order to build our image classifier, we can begin by downloading the flowers dataset. We first need to download the archive version of the dataset and after the download we are storing it to "/tmp/" directory. After downloading the dataset, we need to extract its contents. """ _URL = "https://st...
5be89cf95fc14294714788db895b2f1ebfc3156b
DiegoCol93/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
192
3.78125
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): a_new_dictionary = a_dictionary.copy() for value in a_dictionary: a_new_dictionary[value] *= 2 return(a_new_dictionary)
a1b182cd04c27dc9c000923a627c7e6cb2a2ff3b
DiegoCol93/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,275
4.25
4
#!/usr/bin/python3 """ Module for storing the Square class. """ from models.rectangle import Rectangle from collections import OrderedDict class Square(Rectangle): """ Por Esta no poner esta documentacion me cague el cuadrado :C """ # __init__ | Private | method |-------------------------------------------| ...
dec9ef388badcb3f32458c369c96a74e7f132c90
DiegoCol93/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
303
3.921875
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): if my_list: list_TF = [] index = 0 for i in my_list: if i % 2 == 0: list_TF.append(True) else: list_TF.append(False) index += 1 return list_TF
49e4ff54cc9940d752f512059d312e3be381c885
DiegoCol93/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
238
3.9375
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): new_list = my_list.copy() i = 0 while i < len(my_list): if my_list[i] == search: new_list[i] = replace i += 1 return new_list
b6474efae6cd4d892f987547912e85c73bb9fb0e
limelier/advent-of-code-2020
/19/main.py
2,233
3.640625
4
import re from typing import List def get_input(): rules = {} with open('input.txt') as file: for line in file: line = line.strip() if line: index, contents = line.split(':') index = int(index) contents = contents.strip() ...
b220a0f233abe8c47401f5f91da93abc776434f1
Jokerzhai/OpenCVPython
/test2/UsingMatplotlib.py
445
3.546875
4
#Matplotlib is a plotting library for Python which gives you wide variety of plotting methods. # You will see them in coming articles. Here, you will learn how to display image with Matplotlib. # You can zoom images, save it etc using Matplotlib. import numpy as np import cv2 from matplotlib import pyplot as plt img ...
e4e7696f0a6eb2eeec5a62723bb85bbcc2fd96b6
manasakandimalla/ICG-Lab
/Lab_5/transition.py
337
3.9375
4
import matplotlib.pyplot as plt import math def translation(x,y,h,k): plt.plot(x,y,marker = 'o') plt.plot(x+h,y+k,marker='o') print "enter the co-ordinates of point :" x0 = input() y0 = input() print "enter the co-ordinates of the new origin :" h = input() k = input() translation(x0,y0,h,k) plt.axis([-10,10,-10,...
1c226cd18e417faf1cc865499b4f801b0481f6a2
nrvanwyck/DS-Unit-3-Sprint-2-SQL-and-Databases
/SC/demo_data.py
1,207
3.859375
4
import sqlite3 conn = sqlite3.connect("demo_data.sqlite3") curs = conn.cursor() create_demo_table = """ CREATE TABLE demo ( s TEXT, x INT, y INT ); """ curs.execute(create_demo_table) insert_row = """ INSERT INTO demo (s, x, y) VALUES ('g', 3, 9);""" curs.execute(insert_row) ...
3160db69d05f0aed6bbc63f9b2b84020ef4343e0
CorSar5/Python-World2
/exercícios 36-71/ex051.py
209
3.765625
4
num = int(input('Primeiro termo: ')) r = int(input('Indique a razão da PA(Progressão Aritmética)')) décimo = num +(10-1)*r for c in range(num,décimo,r): print('{}'.format(c), end='->') print('ACABOU')
31a9968211779836bb0e80e1f2c698f69db92b28
CorSar5/Python-World2
/exercícios 36-71/ex049.py
99
3.796875
4
t = int(input('Digite um número:')) for n in range(1,11): print(f'{n}*{t} é igual a {n * t}')
7496d32ad90fe4e113b616d72ee8773c9a923897
CorSar5/Python-World2
/exercícios 36-71/ex050.py
274
3.796875
4
soma = 0 cont = 0 print('Peço-lhe que me indique 6 números') for c in range(1, 7): num = int(input(f'Digite o {c}º valor: ')) if num %2 ==0: soma += num cont += 1 print('Deu {} números pares e a soma dos números pares foi {}.'.format(cont,soma))
cf09393ec6a76c29cdd9ba6b187edc1121fe612b
CorSar5/Python-World2
/exercícios 36-71/ex052.py
220
4.15625
4
n = int(input('Escreva um número: ')) if n % 2 == 0 or n % 3 == 0 or n % 5== 0 or n % 7 == 0: print('Esse número {} não é um número primo'.format(n)) else: print('O número {} é um número primo'.format(n))
a9b43780275bd7e9d95650b80cf984f2619f60ea
SjoerdvanderHeijden/endless-ql
/Jordy_Dennis/QL/expressionnode.py
8,583
4.21875
4
""" An expression can be a single variable, or a combination of a variables with an operator (negation) and multiple other expressions. All of the types are comparable with boolean operators: If the variable is 0 or unset, the variable will be converted to a boolean False, True otherwise (just like python does it) On...
388da7afc9018562b7670d03135ae6fa5d649aa1
SjoerdvanderHeijden/endless-ql
/Jordy_Dennis/GUI/form_scroll_frame.py
2,087
3.875
4
""" A scrollframe is basically a modifyable frame with a scrollbar Each scrollFrame contains a scrollbar, a canvas, and a contentsFrame. The contentsFrame can contain widgets. The canvas is only used to attach the scrollbar to the contents frame """ from .gui_imports import * class ScrollFrameGui: ...
e729e644c6046753e00b30d7d121a6a192054fb6
merv1618/Python-short-programs
/sample_prime_script.py
353
3.859375
4
from prime_count import primecount def random_polynomial(x): return x**2 + 3*x + 1 if __name__ == '__main__': n = primecount(10) print("Look at me, I calculated the 10th prime number - it's %i" % n) print("Now watch me calculate some random polynomial of the 10th prime number") print("Oh look, ...
4c374bce6543ab75b8ff194de2eaa543457c6159
ezalos/Rhinoforcement
/state.py
7,393
3.671875
4
#!/usr/bin/env python import numpy as np import copy from color import * MAX_ROWS = 6 MAX_COLS = 7 class state(): def __init__(self): self.init_board = np.zeros([MAX_ROWS, MAX_COLS]).astype(str) self.init_board[self.init_board == "0.0"] = " " self.player = "X" self.board = self.i...
e63ebf17f9e55783a8c81d4e88cd29870d62c29c
grvn/aoc2018
/15/day15-1.py
3,312
3.65625
4
#!/usr/bin/env python3 from sys import argv from heapq import heappop from heapq import heappush ######################################### # Denna innehåller problem med hörnfall # # påverkar ej resultatet av input # # dessa är fixade i day15-2.py # # har ej orkat fixa dem här # ############...
b6d45c2603128eac609cb2199510960df3fbac95
grvn/aoc2018
/02/day2-2.py
437
3.53125
4
#!/usr/bin/env python3 from sys import argv def main(): with open(argv[1]) as f: input=f.readlines() id1,id2=next((x,y) for x in input for y in input if sum(1 for a,b in zip(x,y) if a!=b)==1) # Hitta de två rätta ID där endast ett enda tecken diffar svar="".join(x for x,y in zip(id1,id2) if x==y).strip() # j...
676a6639f3231701b8c3d53f9a5572bc8948e394
Daniel-HarrisNL/sprintproject
/graphing/main.py
9,978
3.75
4
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Homework Helper This program prompts for an input name of an algebraic function then prompts the user for necessary coefficiencts. It will compute the graph and ask the user if they wish to disp...
56351369d6585b08ddc07a36b49e940e08003dae
Omkar-Atugade/Python-Function-Files-and-Dictionaries
/week2.py
8,680
4.1875
4
#1. At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals. #Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had...
971187848e721a42aec82fb6aa5d13f881d84ff4
johnmwalters/dsp
/python/q8_parsing.py
1,242
4.40625
4
# The football.csv file contains the results from the English Premier League. # The colums labeled 'Goals and 'Goals Allowed' contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to rea...
e14986cfefedad1430fb1686076503a05adcc7e1
pavelkasyanov/euler_problems
/src/problem_5/main.py
345
3.75
4
def ifDividesAll(num): for i in (3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19): if num % i != 0: return False return True def main(): num = 20 while True: if ifDividesAll(num): break else: num = num + 10 print(num) if __name__ =...
09ebba380e8d5b0fb3681b64d0b9613293f0769b
pavelkasyanov/euler_problems
/src/problem_2/main.py
474
3.8125
4
MAX_FIB_NUMBER = 4 * 1000000 def main(): result_sum = 2 n1 = 1 n2 = 2 while True: print("=== start iteration ===") print("n1={}, n2={}".format(n1, n2)) n = n1 + n2 print("n={}".format(n)) if n > MAX_FIB_NUMBER: print("result sum={}".format(re...
714808135eb230b3fca687200a112a888a7809fd
dutraph/python_2021
/basic/while_calc.py
675
4.21875
4
while True: print() n1 = input("Enter 1st number: ") n2 = input("Enter 2nd number: ") oper = input("Enter the operator: ") if not n1.isnumeric() or not n2.isnumeric(): print("Enter a valid number...") continue n1 = int(n1) n2 = int(n2) if oper == '+': pri...
fa747700c4617f59a616d2f7cf12d8ad3e85e77f
dutraph/python_2021
/basic/guess_game.py
853
4.09375
4
secret = 'avocado' tries = [] chances = 3 while True: if chances <= 0: print("You lose") break letter = input('Type a letter: ') if len(letter) > 1: print('type 1 letter...') continue tries.append(letter) if letter in secret: print(f'awesome letter {lette...
c750ed33c5ec4069676685a31f4257f58055d9b0
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio023 - Separando digitos de um numero.py
811
4.1875
4
""" Desafio 023 Faça um programa que leia um número de 0 a 9999 e mostre na tela um dos dígitos separados. Ex: Digite um número: 1834 Unidade: 4 Dezena: 3 Centena: 8 Milhar: 1 """ # Solução 1: com está solução só é possível obter o resulatdo esperado quando se coloca as quatro unidades num = input('Digite um número en...
c2e3b043f0166381203eeda2ef0305c7f67a9290
nataliaqsoares/Curso-em-Video
/Mundo 02/desafio064 - Tratando varios valores v1.0.py
556
4.0625
4
""" Desafio 064 Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag) """ num = int(input('Informe um número ou 999 ...
6282e26c75b7c3673cdbbe6a5418af6232cfa647
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio035 - Analisando triangulos v1.0.py
574
4.21875
4
""" Desafio 035 Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo """ reta1 = float(input('Informe o valor da primeira reta:')) reta2 = float(input('Informe o valor da segunda reta:')) reta3 = float(input('Informe o valor da terceira reta:')) if (re...
dd1ae1af46e3a860d227f51cc14f5270e6e4d66d
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio004 - Dissecando uma variavel.py
718
4.25
4
""" Desafio 004 Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele """ msg = input(' Digite algo: ') print('O valor {} e ele é do tipo primitivo desse valor é {}'.format(msg, type(msg))) print('Esse valor é númerico? {}'.format(msg.isnumeric()))...
1bc9ada8524c22e186391996992ee6458c992b98
nataliaqsoares/Curso-em-Video
/Mundo 03/desafio075 - Analise de dados em uma tupla.py
853
4.28125
4
""" Desafio 075 Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: a) quantas vezes apareceu o valor 9; b) em que posição foi digitado o primeiro valor 3; c) quais foram os números pares; """ conjunto = (int(input('Informe um número: ')), int(input('Informe um númer...
0048caeb7b3546c1ae8cc917685d0df5242ad2b3
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio033 - Maior e menor valores.py
600
4.15625
4
""" Desafio 033 Faça um programa que leia três números e mostre qual é o maior e qual é o menor. """ n1 = int(input('Informe um número: ')) n2 = int(input('Informe mais um número: ')) n3 = int(input('Informe mais um número: ')) maior = 0 menor = 0 if n1 > n2 and n1 > n3: maior = n1 if n2 > n1 and n2 > n3: ma...
474e5fbf97eca5b09a0527b9cf59290b4f4ff08c
nataliaqsoares/Curso-em-Video
/Mundo 02/desafio053 - Detector de palindromo.py
579
3.921875
4
""" Desafio 053 Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. Ex.: Apos a sopa / A sacada da casa / A torre da derrota / O lobo ama o bolo / Anotaram a data da maratona """ frase = str(input('Informe uma frase: ')).lower().split() frase = ''.join(frase) cont_f...
fccf2bdb5f6afe42e695468b8cefc57fedb19783
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio028 - Jogo de Adivinhacao v.1.0.py
526
4.25
4
""" Desafio 028 Escreva um programa que faça o computador 'pensar' em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu """ from random import randint print('Estou pensando em um número ent...
693dd4620876b1525d56d4b03c47a34f032feb20
nataliaqsoares/Curso-em-Video
/Mundo 02/desafio036 - Aprovando emprestimo.py
842
4.1875
4
""" Desafio 036 Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou então o empréstimo será negado """ ...
4fdbc344aff48594e6fedfe984943a25854f6aed
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio012 - Calculando desconto.py
292
3.65625
4
""" Desafio 012 Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto """ preco = float(input('Informe o preço do produto: ')) novopreco = preco - (preco * 0.05) print('O produto de preço {} com desconto fica por {:.2f}'.format(preco, novopreco))
b32e3fa30f283a656532c6154c7795e319ef6c84
nataliaqsoares/Curso-em-Video
/Mundo 03/desafio100 - Funcoes para sortear e somar.py
754
4.0625
4
""" Desafio 100 Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores pares sorteados pela função anterior """ from random import randint f...
967aa21504999e6fd116ebd555c548bc26f6903c
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio002.1 - Data de nascimento.py
514
4.125
4
""" Desafio002.1 Crie um programa que leia o dia, o mês e o ano de nascimento de uma pessoa e mostre uma mensagem com a data formatada (mensagem de saida = Você nasceu no dia x de x de x. Correto?) """ # Solução 1 nasci = input('Quando você nasceu? ') print('Você nasceu em', nasci, 'Correto?') # Solução 2 dia = inp...
acfc2d6ff4b396815192db8f0e87fc8a514fc55d
Guilherme-Avellar/primeiras_aulas
/jogo do ppt aprimorado.py
1,227
4.03125
4
# jogo do pedra, papel ou tesoura, com biblioteca de sorteio print("Jogo do pedra papel ou tesoura") player = input("Joque pedra, papel ou tesoura: ") from random import * computador = randint(0,2) if player == "pedra" or player == "Pedra" or player == "PEDRA": player = 0 else: if player == "papel...
a916c4834eeb10336fe9c75e2e58e83684fafac8
thales-mro/python-cookbook
/3-numbers-dates-hours/15-convert-string-to-datetime.py
487
4.0625
4
from datetime import datetime #way faster solution than showed in main() def parse_ymd(s): year_s, month_s, day_s = s.split('-') # only works if you know the string format return datetime(int(year_s), int(month_s), int(day_s)) def main(): text = '2020-01-25' y = datetime.strptime(text, '%Y-%m-%d') ...
68a32e533997a2817579198a90aafaad911e3fbd
thales-mro/python-cookbook
/2-strings/5-search-and-replace.py
650
3.9375
4
import re from calendar import month_abbr def replace_callback(m): mon_name = month_abbr[int(m.group(2))] return '{} {} {}'.format(m.group(1), mon_name, m.group(3)) def main(): text = 'yeah, but no, but yeah, but no, but yeah' print(text.replace('yeah', 'yep')) text = "Today is 02/01/2020. In...
499b850f68b05aceb843bcd4f6f94c9cb1077afc
thales-mro/python-cookbook
/2-strings/4-pattern-match-and-search.py
1,181
4.125
4
import re def date_match(date): if re.match(r'\d+/\d+/\d+', date): print('yes') else: print('no') def main(): text = 'yeah, but no, but yeah, but no, but yeah' print(text.find('no')) date1 = '02/01/2020' date2 = '02 Jan, 2020' date_match(date1) date_match(date2) ...
881166784fd6a82253a5b189f956582a7a8de5e0
firebirdrazer/CodingTests
/check_paren.py
1,952
4.40625
4
def check_bracket(Str): stack = [] #make a empty check stack while Str != "": #as long as the input is not empty tChar = Str[0] #extract the first character as the test character ...
5794112ddeb0e6706ded784d7fec7249659e9450
mango915/haliteRL
/Modules/encode.py
22,954
3.84375
4
import numpy as np def one_to_index(V,L): """ Parameters ---------- V: LxL matrix with one entry = 1 and the others = 0 L: linear dimension of the square matrix Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row. Returns ------- integer corre...
85e4570b02806f103b50429e1d73ec2652e009fe
iamparul08/Hands-on-P6
/fileio2_ADID.py
394
3.65625
4
#reading first 11 characters from the file print("First 11 characters of the file:") f = open("in1_ADID.txt", "r") print(f.read(11)) f.close() #reading first line print("\nReading first line of the file:") f = open("in1_ADID.txt", "r") print(f.readline()) f.close() #using read() method print("\nRead ...
cea334a02a27c95069e54496cc08c6c77eb439e1
Miranjunaidi/SRMAP_CodingClub_Tests
/Test1/Solutions/Binary/binStrings.py
568
3.625
4
def all_n_BinStrings(n): if n == 1: return ["0", "1"] else: given = all_n_BinStrings(n-1) res = [] for bistr in given: res.append(bistr + '0') res.append(bistr + '1') return res def numsubString(n, pattern): return sum([(pattern in s) for s ...
00b2a919a2f0cb213dfc003e78d64d1957cd5c70
Lyra2108/AdventOfCode
/2015/Day2/Presents.py
623
3.546875
4
def calculate_package_needs(boxes): paper = 0 ribbon = 0 for box in boxes: sizes = list(map(lambda size: int(size), box)) x, y, z = sizes sizes.remove(max(sizes)) x_small, y_small = sizes paper += 2*x*y + 2*x*z + 2*y*z + x_small*y_small ribbon += 2*x_small + 2...
e6484be2f1f99100731c9fe5043e918fad434070
Lyra2108/AdventOfCode
/2019/Day1/rocketFuel.py
926
3.75
4
from functools import reduce def read_in_modules(): input_file = open("input.txt", "r") return list(map(lambda x: int(x), input_file.readlines())) def simple_calculate_fuel(modules): return reduce(lambda x, y: x + y, map(lambda module: calculate_fuel(module), modules)) def calculate_fuel(module): ...