blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
350577069c64762c5e082f0bbac3d2da88f64cdf | youwantsy/DeepLearningPractice | /Basiccodes/Matplotlib/example01.py | 637 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.1, 1, 0.01)
y = (1/(2*np.pi)*x)*np.exp(-1/2*x*x)
plt.plot(x, y)
plt.show()
#%%
x = np.arange(0, 2*np.pi, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure(1)
plt.plot(x, y1)
plt.figure(2)
plt.plot(x, y2)
plt.show()
#%%
plt.plot(x,y1)
plt.plot(x,y2)
pl... |
476500fa204f2bfd2f9661e1dee3d97c9e7aa15c | Mazzya/Aprendiendo-Python | /Estructuras de datos/adivina.py | 1,266 | 4.0625 | 4 | #Importar una libreria de números aleatorios
import random
def leer_numero():
es_numero = False
while es_numero==False:
try:
usuario = int(input("Adivina el número: "))
es_numero=True
except ValueError:
print("No ha introducido un número. Vuelva a i... |
c1c62b821d00af9a1510c8fe2f76b2d295d5c6c9 | sarahvestal/ifsc-1202 | /Unit 1/01.03 Square.py | 100 | 3.625 | 4 | firstnumber = input("First number is: ")
square = int(firstnumber) * int(firstnumber)
print (square) |
7f31cef3e2fb000c0e72bad5c4c2edc6521744a0 | gomtinQQ/algorithm-python | /codeUp/codeUpBasic/1563.py | 446 | 3.5625 | 4 | '''
1563 : [기초-함수작성] 함수로 세 정수 중 중간 값 리턴하기
int 형 정수 세 개를 입력 받아
중간 값을 출력하시오.
단, 함수형 문제이므로 함수 mid()만 작성하여 제출하시오.
'''
def mid(x, y, z):
lst = [x,y,z]
maxNum = max(lst)
minNum = min(lst)
sumNum = sum(lst)
return sumNum-maxNum-minNum
x, y, z = input().split()
x = int(x)
y = int(y)
z = int(z)
print(mid(x... |
e9a1c66225f08ed8917d69956543f0c8af83441e | keyllalorraynna/Desafios | /Desafio4/inverteValores.py | 268 | 4.03125 | 4 | ''' Faça um programa que peça um numero inteiro positivo e em seguida mostre este
numero invertido.
•Exemplo:
12376489
=> 98467321 '''
insere_valor = input('Digite os valores que devem ser invertidos: ')
for i in reversed(insere_valor):
print (f'{i}', end = '') |
0ca55f7c90b11b13685da73bcb6360608d16930b | githubMay/myTest | /truple/draw_five_star.py | 925 | 4.0625 | 4 | import turtle
def drawFiveStar(t,b):
"""画五角星函数,t是画板的形式参数,b是五角星的边长"""
#t.pendown()
t.begin_fill()
t.fillcolor('yellow')
for i in range(0,5):
t.speed(1)
t.forward(b)
t.left(72)
t.forward(b)
t.right(144)
t.penup()
t.end_fill()
def drawPentagram(m,angle,... |
60b2eae752ca6fabf1b17d80d711e90f3cfc4e53 | StpdFox/HU_ALDS_Ref | /ALDS_Week_1/alds_w1_1.py | 422 | 4.34375 | 4 | def max(arr):
"""
Function that finds and returns the maximum value of array(list) arr
Time complexity O(n)
:param arr: array(list) containing integers
:return highest: integer containing highest number in arr
"""
tempMax = float("-inf")
for nr in arr:
if nr >... |
e94f04933bb5df33727afed811438811ce89778c | ayushchitrey/Think-Code | /Python_Programming - 360DigiTMG/Assignment1_DataTypes_Q3.py | 812 | 4.21875 | 4 | ''' Q3. Create a data dictionary of 5 states having state name as key and number of covid-19 cases as values.
a. Print only state names from the dictionary.
b. Update another country and it’s covid-19 cases in the dictionary.'''
dictionary={"Maharashtra":990795,"Andhra Pradesh":537687,"Tamil Nadu":486052,"Karnatak... |
1345195d6aac48e0241044693c7543aa98ab8671 | ReZeroE/Leetcode-Answers | /Medium/2. Add Two Numbers/solution.py | 1,389 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = []
num2 = []
result = 0
w... |
19e9de9e533d0c6e7ee5a88ae21628014e6214e5 | SumMuk/data-struct-algo | /turing.py | 129 | 3.53125 | 4 | def comp(nums):
m = float("-inf")
for n in nums:
if n > m:
m+= 1
return m
print(comp([1,2,3])) |
8ac27295fa2e7e6915bb5f3092207ffd41ba2231 | fjfhfjfjgishbrk/AE401-Python | /zerojudge/e621.py | 412 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 10:30 2020
@author: fdbfvuie
"""
n = int(input())
for i in range(n):
a = [int(j) for j in input().split(" ")]
noPark = True
for j in range(a[0] + 1, a[1], 1):
if j % a[2] != 0:
print(j, end=" ")
n... |
38f0493a5d45384f2530c79e695e612624138c57 | zhouchuang/pytest | /test24.py | 292 | 4.0625 | 4 | """
题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
程序分析:请抓住分子与分母的变化规律
"""
fz=2
fm=1
sum = 0
for i in range(0,20):
sum = sum + fz/fm
tempfz = fz
fz = fz+fm
fm = tempfz
print(sum)
|
45a61aa8c2af758566cd093b18e8639a05f3c1ae | DomPedrotti/python-exercises | /4.1_python_introduction_exercises.py | 516 | 4.53125 | 5 | # Create a hello world program. Create a text file named 4.1_python_introduction_exercises.py and write a program that prints "Hello, World!" to the console. Run this program from the command line.
# Inside of your hello world program, create a variable named greeting that contains the message that you will print to th... |
811912d2f507d5771a5b654d400c0c8f69287ef7 | rexhzhang/LeetCodeProbelms | /BFS/LeetCode200_NumberOfIslands.py | 1,427 | 3.859375 | 4 | """
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
... |
3f50e703f26bfc88620dc8d9240cc5fc77225b6a | ambika0203/NLP | /Preprocessing.py | 1,440 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 01:15:57 2019
@author: Ambika
"""
# Word tokenization
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
my_text = "Hi Mr. Smith! I’m going to buy some vegetables (tomatoes and cucumbers) from the store. Should I pick up some black-e... |
498fcb32cbd75682e4b94ab6dde60d19f7a81c04 | pragmatizt/Intro-Python-I | /src/05_lists.py | 1,311 | 4.6875 | 5 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
"""this is a good link for some list methods: https://lucidar.me/en/python/insert-append-extend-concatanate-lists/"""
# Change x so th... |
a77052a511316c58742ba11369c4d17d5dc2dc7f | Crasti/Homework | /Lesson6/Task6.3.py | 1,972 | 4.1875 | 4 | """
Реализовать базовый класс Worker (работник), в котором определить атрибуты: name, surname, position (должность),
income (доход). Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия,
например, {"profit": profit, "bonus": bonus}. Создать класс Position (должность) на б... |
6c41a294d04e3562c258375eb6079f512c5267e3 | EnriPython/Enri_Python | /Algebra_Vectorial.py | 5,572 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import time
import os
import sys
def limpiar():
"""Limpia la pantalla"""
if os.name == "posix":
os.system("clear")
elif os.name == "ce" or os.name == "nt" or os.name == "dos":
os.system("cls")
def salir... |
113750e0e386d1fa102c715d4b64eac139efba22 | captainblobbles/python | /Logix/Palindrome Detector.py | 308 | 4.46875 | 4 | user_string = input("Please enter a string.")
reversed = ""
# It is looping from String length back to -1.
for item in range(len(user_string) - 1, -1, -1):
reversed += user_string[item]
if user_string == reversed:
print("The entered is a palindrome.")
else: print("The entered is not a palindrome.") |
74f5f6fc331d26e19ed327f9052d65e7489c27c4 | mrfreer/57Exercises | /Program15.py | 144 | 3.515625 | 4 | import getpass
pw = getpass.getpass('What is the password?')
if pw == "abc$123":
print("Welcome!")
else:
print("I don't know you.") |
05ab68ee0b02aae8b268b357b3dcd657281efe42 | reema-eilouti/python-problems | /CA11/problem3.py | 499 | 4.15625 | 4 | # Problem 3
# You are given a list of words. Write a function called find_frequencies(words) which returns a dictionary of the words along with their frequency.
# Input: find_frequencies(['cat', 'bat', 'cat'])
# Return: {'cat': 2, 'bat': 1}
my_dict={}
my_list=['cat' , 'cat' , 'dog' , 'bat' ,'bat']
def find_fre... |
c9b8f321d964ef1d965756b28079799c87662cfe | cpe202spring2019/lab1-jwalla13 | /lab1.py | 2,089 | 4.09375 | 4 | l = [1, 2, 3, 8, 4, 5, 6]
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, returns None. If list is None, raises ValueError"""
def max_list_iter(int_list): # must use iteration not recursion
if int_list is None:
raise ValueError
if type(int_list) != l... |
16f1a1c044e98033d96efa83e9725da4779b5f1f | mataralhawiti/Online_Courses | /Udacity - Data Analyst Nanodegree/P05_Identifying_Fraud_From_Enron_Email/Lessons/Features_Scaling/features_scaling.py | 960 | 3.921875 | 4 | """ quiz materials for feature scaling clustering """
### FYI, the most straightforward implementation might
### throw a divide-by-zero error, if the min and max
### values are the same
### but think about this for a second--that means that every
### data point has the same value for that feature!
### why would you... |
ed64b744759533fa3de3da57c9281bac6836c09d | mr-zhouzhouzhou/LeetCodePython | /剑指 offer/把字符串转换成整数.py | 910 | 3.640625 | 4 | """
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
"""
"""
微软面试的时候 考过这题
"""
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
if s == None or len(s) ==0 :
return 0
flag = True
s = s.strip()
if s.startswith("+") or s.s... |
959cdcceb2e45b74a5fafeb1e9b4090838b7b6da | antoinebelley/Phys512_assignments | /Final_Project/ode.py | 694 | 3.625 | 4 | import numpy as np
def leap_frog(x,v,f_now,f_next,dt):
"""Update the particles position and momenta using the leap frog method
-Arguments: - x (array): The current position of the particles
- v (array): The current momenta of the particles
- f_now (array): The forces o... |
dc92d898735b8bdeb3200661dc2e20ba21b9d495 | fromgopi/DS-Python | /v2/src/search/linear_search.py | 532 | 3.5 | 4 | import random
import timeit
def linear_search(array, key):
for index, value in enumerate(array):
if value == key:
return index
return -1
if __name__ == '__main__':
array = [random.randrange(1, 99999, 1) for i in range(10000)]
key = 12
start = timeit.default_timer()
res = li... |
77ad82105dd78ee0021754167b78a0171922f3f5 | biagioboi/Programmazione-Avanzata | /esempioYield.py | 794 | 3.921875 | 4 | # Quando lo yield viene messo ad un assegnamento ex. x = yield allora aspetterà una send per ricevere
# il valore da assegnare a x, contestualmente potrebbe anche restituire un valore 'yield x',
# che restituisce il valore di x
def raddoppia():
while True:
# viene restiuito none in quanto non è specificato... |
c6527c92aed55fcef6da6bc1b3e741883de4bab3 | Sunghwan-DS/TIL | /Python/BOJ/BOJ_2937.py | 756 | 3.75 | 4 | def MergeSort(lst):
if len(lst) == 1:
return lst
left = MergeSort(lst[:len(lst)//2])
right = MergeSort(lst[len(lst)//2:])
L, R = 0, 0
sorted_list = []
while L < len(left) and R < len(right):
if left[L] <= right[R]:
sorted_list.append(right[R])
R += 1
... |
3ad048c48e9553b893552da486aff5442543f208 | rlavanya9/cracking-the-coding-interview | /recursion/magic-array.py | 798 | 3.71875 | 4 | # def magic_array(myarr):
# return magic_array_helper(myarr, 0)
# def magic_array_helper(myarr, i):
# if not myarr:
# return -1
# while myarr:
# if myarr[i] == i:
# return i
# magic_array(i+1)
def magic_array(myarr, low, high):
if high >= low:
mid = (lo... |
a13193bb6057fd44d4050784f6d53c0a3a6e5c5d | Kimyehoon/python | /src/chap05/p222_bisection.py | 693 | 3.96875 | 4 | ##
# 이 프로그램은 이분법을 구현한다.
#
# 함수를 정의한다.
def f(x):
return(x**2-x-1)
def bisection_method(a, b, error):
if f(a)*f(b) > 0:
print("구간에서 근을 찾을 수 없습니다.")
else:
while (b - a)/2.0 > error: # 오차를 계산한다.
midpoint = (a + b)/2.0 # 중점을 계산한다.
# print(midpoint)
if f(m... |
38775b101a5f6baaababbc220475d549420cf597 | mciaccio/Introduction-To-Data-Analysis | /accessingElementsOfADataFrame.py | 7,355 | 3.609375 | 4 | import pandas as pd
# Subway ridership for 5 stations on 10 different days
ridership_df = pd.DataFrame(
data=[[ 0, 0, 2, 5, 0],
[1478, 3877, 3674, 2328, 2539],
[1613, 4088, 3991, 6461, 2691],
[1560, 3392, 3826, 4787, 2613],
[1608, 4802, 3932, 4477, 2705],
... |
27052ad4ab4dede590aa17dc5f41e389afa8f0ee | spedas/pyspedas | /pyspedas/themis/common/check_args.py | 1,956 | 4.21875 | 4 | def check_args(**kwargs):
"""
Check arguments for themis load function
Parameters:
**kwargs : a dictionary of arguments
Possible arguments are: probe, level
The arguments can be: a string or a list of strings
Invalid argument are ignored (e.g. probe = 'g', level=... |
471c2f3b259b7416f27efaa808b11c9b28a0a93c | lukebiggerstaff/simple-python-ds | /datastructures/binarytree/binarytree.py | 4,101 | 3.921875 | 4 | '''
Python representation of binary tree
'''
class Node(object):
def __init__(self, data, parent=None, left=None, right=None):
self.data = data
self.parent = parent
self.left = left
self.right = right
def _is_leaf_node(self):
return not self.left and not self.right
... |
f1b870fee8fb968d65fa0585ae3a744cc61f2ec3 | avinav10/python_programs | /random_programming_primenumber.py | 638 | 3.984375 | 4 | ##prime number---- 2,3,5,7,11 number is divisible by itself
def prime_number(number):
store=[]
for i in range(2,number+1):
isPrime = True
for num in range(2,i):
if (i%num)==0:
isPrime = False
if isPrime:
store.append(i)
return store
prin... |
a9fba55e5933093f0596c594386911b1c66a1762 | soy-sauce/cs1134 | /hw3/cz1529_hw3_q3.py | 514 | 3.78125 | 4 | def find_duplicates(lst):
dic={} #create dictionary holding nums and how may times it appears
dups=[]
for i in range(len(lst)):
item=lst[i]
if item in dic:
dic[lst[i]]+=1 #increase value if appears again
else:
dic[lst[i]]=1
for k,v in dic.items():... |
42819180eb1509b3681934319a2d25c680826e2c | zhangjiang1203/Python- | /009-class/test1.py | 1,107 | 3.90625 | 4 | message = "你好,python"
print(message)
message = "你好,开始学习python之路"
print(message)
#程序中可以随时修改变量的值,而python将始终记录变量的最新值
'This is a string'
"This is also a string"
name = "ada lovelace"
#title() 是以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写
print(name.title())
print(name.upper())
print(name.lower())
first_name = "zhang"
last_name = "jiang... |
02f70a907c8c336dc807185241308604f3c35ac6 | yuanguLeo/yuanguPython | /CodeDemo/shangxuetang/一期/序列/list列表/列表元素的访问和计数.py | 686 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/23 9:42
# 通过索引直接访问
a = [10,20,30,10,40,50,60,20,20]
print(a[2])
print("-----------------------------")
# index() 获取指定元素的列表中首次出现的索引
print(a.index(20))
print("-----------------------------")
# count() 获得元素在列表中出现的次数
print(a.count(20))
print("-------------... |
ca4a7b4ba041da7714638f04e7bdd8140e7686bc | adrianmendez03/algos | /python/linked-list/mergetwolinkedlist.py | 783 | 3.625 | 4 | class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
result = None
while(l1 or l2):
if l1 and l2:
if l1.val <= l2.val:
t = ListNode(l1.val)
l1= l1.next
else:
... |
0c5038eef3fb5839dbe7d4a2a3499648ce79a27a | Viiic98/holbertonschool-machine_learning | /supervised_learning/0x06-keras/0-sequential.py | 1,088 | 3.6875 | 4 | #!/usr/bin/env python3
""" NN with Keras library """
import tensorflow.keras as K
def build_model(nx, layers, activations, lambtha, keep_prob):
""" builds a neural network with the Keras library
@nx: is the number of input features to the network
@layers: is a list containing the number of nodes ... |
fd8157fa5b553e05f64cd852373cbe943a593a5f | AlvaroRuizDelgado/L5R_4E_dice_roller | /roll.py | 3,265 | 3.625 | 4 | #!/usr/local/bin/python3
# Last edited: 18/08/15
import sys
from random import randint
def roll(argv):
if (len(argv) == 0 or "--help" in argv or "-h" in argv):
print_help()
sys.exit(0)
# Die characteristics
die_range = 10
# Explode mechanic
unskilled_flag = False
explosion_th... |
b22f6aa7cd19e4c427df559ac971f2027dc47517 | lukas9557/dw_matrix | /DW_Matrix01_MachineLearing.py | 3,810 | 3.890625 | 4 | #DataWorkShop - Matrix exercise. Analysis of Men's Shoe Prices, and simple perdiction model
#on the basis of data.world/datafiniti/mens-shoe-prices file named 7004_1.csv.
########### DAY 3 ##########
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def currency_bar_chart(x,y): #it's a fu... |
3d8067944b972d2069584d8212d35446372cc465 | amagid/EECS-293-Project-3 | /gone/tile_types.py | 246 | 3.53125 | 4 | # TileTypes is an Enum representing the value contained in a tile on the board.
# Every cell in the 2-D board array must always contain exactly one TileType.
from enum import Enum
class TileTypes(Enum):
WHITE = 1
BLACK = 2
EMPTY = 3 |
686a15541f716a0b2b76600e5069bb3def41e747 | laurocjs/criptomigo | /sorteio.py | 2,939 | 3.546875 | 4 | # coding= utf-8
import random
from Crypto.PublicKey import RSA
# Função para sortear os pares
def sorteiaPares(listaDeParticipantes): # Recebe lista com nome dos participantes
# e o valor é a chave pública dela
dictSorteado = {} # Dict a ser retornado
numeroDePar... |
ed6b067bd0c1eb3e4a5e737fdbf6eb7cb6aa3916 | Prabhnometery/problem-set-codeforces | /231A - Team.py | 282 | 3.625 | 4 | # Solution to problem 231A - Team
# Link - https://codeforces.com/problemset/problem/231/A
n = int(input())
count = 0
for i in range(0,n):
num = str(input())
if num == '1 1 0' or num == '1 0 1' or num == '1 1 1' or num == '0 1 1':
count = count + 1
print(count)
|
1c609aa90f6dbb83e8ea4639ef8b7586ae94585f | ifern/Company-Search | /ScrapeTest.py | 676 | 3.546875 | 4 | import urllib
import csv
import requests
wordsfile = csv.DictReader(open("words.csv"))
#links = ['http://econpy.pythonanywhere.com/ex/001.html','http://www.itrade4profit.in/showscripfca0.htm?sym=APCOTEXIND']
#Search for every word in the words list in every URL in the links list. Print both word and the URL if foun... |
2a5b0dbb9987c01889f2c4aad183cb1957c78ec8 | prashantpandey9/codesseptember2019- | /hackerearth/supernatural.py | 433 | 4 | 4 | import math
def primeFactors(n):
q=0
while n % 2 == 0:
## print(2)
q+=1
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
## print(i)
q+=1
n = n / i
# Condition if n is a prime
# nu... |
57149892524d8d172638a0e8beedd211ca9ce585 | nguyen-viet-hung/tabml | /tabml/metrics.py | 7,367 | 3.734375 | 4 | import abc
from typing import Collection, Dict, List, Union
import numpy as np
from sklearn import metrics as sk_metrics
class BaseMetric(abc.ABC):
"""Base class for metrics.
Usually, one metric returns one score like in the case of accuracy, rmse, mse, etc.
However, in some cases, metrics might contain... |
d9112bf6339b71aa43b0b5541aec6e7ef4c40d66 | appym/hacker_rank_playground | /poissonExpectation.py | 354 | 3.53125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
lamA, lamB = [float(x) for x in raw_input().split()]
# C = 160 + 40 * X^2
# E[C] = 160 + 40 * E[X^2]
# E[C] = 160 + 40 ( Var(X) + (E[X])^2)
ansA = 160 + 40 * (lamA + lamA ** 2)
ansB = 128 + 40 * (lamB + lamB ** 2)
print '{:0.3f}'.format(... |
cf7cfcfef36fdd735b61d31a705e69bd6b1f7ad0 | jiaojiening/AlignedReID-Re-Production-Pytorch | /aligned_reid/utils/distance.py | 3,599 | 3.5625 | 4 | """NOTE the input/output shape of methods."""
import numpy as np
def normalize(nparray, order=2, axis=0):
"""Normalize a N-D numpy array along the specified axis."""
norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True)
return nparray / (norm + np.finfo(np.float32).eps)
def compute_dist(array1, ... |
abec9d0c2c0abffdc5735c8f38d4ead87a684af5 | Ondrej-Martinek/Algorithms-Coding-problems | /Daily Coding Problem/31. Palindrome integers.py | 530 | 4.125 | 4 | # Palindrome integers
'''Given an integer, check if that integer is a palindrome. For this problem do not convert the integer to a string to check if it is a palindrome.'''
def is_palindrome(num):
res = []
div = 10
while div < num*10:
res.append(int((num % div) // (div/10)))
div *= 10
... |
e3952372576b876bd21f795b4845438c238043f1 | JenZhen/LC | /lc_ladder/Adv_Algo/binary-search/Find_Peak_Element_II.py | 6,806 | 3.78125 | 4 | #! /usr/local/bin/python3
# https://lintcode.com/problem/find-peak-element-ii/description
# There is an integer matrix which has the following features:
# The numbers in adjacent positions are different.
# The matrix has n rows and m columns.
# For all i < m, A[0][i] < A[1][i] && A[n - 2][i] > A[n - 1][i].
# For all ... |
0aa64064c17c2e7225999f9cf0ce97145b4a87c0 | PrettyCharity/Random-Walks-of-a-Drunk | /Simulation.py | 5,942 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 6 16:17:08 2021
@author: ersoy
"""
import matplotlib.pyplot as plt
import math
from Location import *
def walk(f, d, num_steps):
"""Assumes: f a Field, d a Drunk in f, and num_steps an int >= 0.
Moves d num_steps times; returns the distance betwee... |
ef7d06c4058e1e518da97e3e2646b760a42acad3 | mikereil80/cs581 | /youtube_data.py | 1,637 | 3.78125 | 4 | # Author: Cheryl Dugas
# youtube_data.py searches YouTube for videos matching a search term
# To run from terminal window: python3 youtube_data.py
from googleapiclient.discovery import build # use build function to create a service object
# put your API key into the API_KEY field below, in quotes
API_KEY ... |
d9a7f08bd5cd6353b2c4b2407f786ee26a36e595 | Milktea17/python | /1-2장/doit_2-5-딕셔너리.py | 1,985 | 3.6875 | 4 | #딕셔너리
dic = {'name':'pey', 'phone':'0119993323', 'birth':'0118'}
#value에 리스트도 넣을 수 있다.
a={'a':[1,2,3]}
#딕셔너리 쌍 추가
a={1:'a'}
a[2]='b'
print(a) #{1:'a', 2:'b'}
a['name'] = 'pey'
print(a) #{1: 'a', 2: 'b', 'name': 'pey'}
#딕셔너리 요소 삭제하기
del a[1]
print(a) #{2: 'b', 'name': 'pey'}
#딕셔너리에서 key의 value를 얻기
print(a['name']) ... |
1627bf47c3b3dadc7e0713ba3f68af3432b2e715 | bbsngg/Introduction-to-ML | /Basic/hw 3/hw3-exercise.py | 8,118 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 人工智能基础 Homework 3
#
# # 机器学习 - 线性回归
# ## 一、一元线性回归
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# get_ipython().run_line_magic('matplotlib', 'inline')
# In[1]:
print("My Student Number and Name are: 171250628 宋定杰 ") #此处替换成你的学号和姓名
path... |
aa320b737f60838e1c309db4b438f31bf607f0f3 | linjunyi22/datastructures | /冒泡排序.py | 653 | 4.0625 | 4 | """
冒泡排序,有 n 个数,每一个数比较一趟,那么就要比较 n-1趟
每一个数要跟其他数比较,每比较一次,下一个要比较的数的比较次数就少一次
"""
l = [3,1,4,5,2,0,7,9]
def bubble_sort(lists):
for i in range(0,len(lists)-1): # n 个数,比较 n-1趟
for j in range(0,len(lists)-i-1): # 第一个数与 n-1个数比较,第二个数与 n-1-1个数比较,...,第 n 个数与 n-i-1个数比较
if lists[j+1] < lists[j]: # 比较,符合就调换,不符合就保留原位
temp... |
a1c90696d3b7c9f23a28bcca421fd2e9853de004 | nessie2013/electricitymap-contrib | /parsers/lib/config.py | 641 | 3.828125 | 4 | from datetime import timedelta
def refetch_frequency(frequency: timedelta):
"""Specifies the refetch frequency of a parser.
The refetch frequency is used to determine the how much data is returned by the parser.
i.e. if we refetch from d1 to d2 and the frequency is timedelta(days=1), then we will only
... |
16f53be0bd46fa1a711dd0b6abac4e56d9097dce | p-uday/Image-similarity-and-clustering | /avghash.py | 1,714 | 3.546875 | 4 | from sys import argv
from sys import exit
from PIL import Image
from PIL import ImageStat
def AverageHash(theImage):
# Convert the image to 8-bit grayscale.
theImage = theImage.convert("L") # 8-bit grayscale
# Squeeze it down to an 8x8 image.
theImage = theImage.resize((8,8), Image.ANTIALIAS)
# Ca... |
db462030f53d2ec8a7ac75b46de14729ef81c3c8 | NickKletnoi/Python | /01_DataStructures/03_Trees/07_Lca.py | 5,344 | 3.703125 | 4 |
#Copyright (C) 2017 Interview Druid, Parineeth M. R.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
from __future__ import print_function
import sys
from PrintTreeHelper import Prin... |
49e4493a59dc07b0978f68482f5e276f4e772954 | kapoorsanj/python2-class | /Conditions.py | 97 | 3.515625 | 4 | rains="False"
if(rains=='True'):
print("Carry an Umberlla")
else:
print("Wear a hat") |
05ad4a7e819f4ccbd74ae630c7743d9820f9a90d | victorsemenov1980/Coding-challenges | /encodeUrl.py | 1,567 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 21:53:50 2020
@author: user
"""
'''
TinyURL is a URL shortening service where you enter a
URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode met... |
5f38805c55a661a4fe7db24af1d37b22a4477a08 | lidongze6/leetcode- | /784. 字母大小写全排列-2.py | 468 | 3.53125 | 4 | class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
res=[]
def helper(res,tmp,S):
if not S:
res.append(tmp)
else:
if S[0].isalpha():
helper(res,tmp+S[0].upper(),S[1:])
helper(res,tmp+S[0... |
774303a090723f2dbf50d98503de29f15382abe7 | andreieftime/Full-Eftime-Poker | /core/HandStrength.py | 11,581 | 3.65625 | 4 | from enums.Number import Number
#we will have separate functions to check for each poker combination
def checkFlush(cards):
suit = cards[0].suit
for card in cards:
if card.suit != suit:
return 0
return 1
def checkStraight(cards):
numbers = [0 for i in range(14)]
for card in ... |
4d66f6280f86174799a489ae5adf39f79cfaaca7 | ClintonTak/CodeChallengeAnswers | /Python/IslandPerimeter.py | 2,099 | 3.75 | 4 | '''
This one was a lot of fun to work on and posed an interesting problem. I had to use pen and paper to quickly jot
down the different cases. From Leetcode:
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically ... |
72dfb4d2b92577a1d8deeabcdf575573085eae20 | arthurDz/algorithm-studies | /SystemDesign/multithreading and concurrency/implementing_semaphore.py | 1,928 | 4.21875 | 4 | # Python does provide its own implementation of Semaphore and BoundedSemaphore, however, we want to implement a semaphore with a slight twist.
# Briefly, a semaphore is a construct that allows some threads to access a fixed set of resources in parallel. Always think of a semaphore as having a fixed number of permits t... |
a22c0c1e6128e3c5f0e304f7f64c62b6996eea80 | PanOrka/Metaheuristics | /Tabu_Search_Walking_Agent/wag.py | 4,953 | 3.5 | 4 | import time
from random import randint
def check_in_exit(cur_pos, crate):
return crate[cur_pos[0]][cur_pos[1]] == '8'
def check_cycle(step, prev_step):
if step == 'U' and prev_step == 'D':
return False
elif step == 'D' and prev_step == 'U':
return False
elif step == 'L' and prev_step... |
f9cba9c0798d64d1fb58e4b46bede4d8aaf2199e | cnovacyu/python_practice | /automate_the_boring_stuff/Chapter8_MadLibs.py | 1,380 | 4.0625 | 4 | #! python 3
# Opens and reads a file that contains a mad lib. Ask a user for inputs
# for placeholders in the mad lib. Create a new file that replaces the
# placeholders in the mad lib with user inputs. Do not overwrite the original file.
import os, re, pyperclip
# Open the file and read the contents
madLibFile = o... |
ba54333e64218d8f4b5b96a7ae6f6f333daf1d12 | limisen/Programmering-1 | /04/04-06.py | 455 | 3.671875 | 4 | X = float(input("Vänligen ange din ålder: "))
Y = float(input("Vad är din brutto inkomst? "))
Z = (input("Har du några kredit-anmärkningar?(ja eller nej) "))
if Z != "ja" and Z != "nej":
Z = (input("Svara snälla med ja eller nej, tack!\n Har du några kredit-anmärkningar? " ))
pass
if X >= 18 and Y >= ... |
dacb0452ab41263ec0143d5cadffe90a9c2565fc | eranraz1/DS | /recursive.py | 748 | 3.5 | 4 | # def recu_sum(numList):
# if len(numList) ==1:
# return numList[0]
# return numList[0] + recu_sum(numList[1:])
# print(recu_sum([1,3,5,7,9]))
# def b_(num):
# if num == 1:
# return -5
# return -5+ b_(num-1) + 9
# print(b_(4))
print('\n')
def lookval(ls, look_val):
nmax= len(ls)... |
31398f2d9eb46b50fae02e0cfb7661cc3bfc1d6c | NagahShinawy/problem-solving | /pynative/8_dictionary/ex_6.py | 964 | 4 | 4 |
"""
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
keysToRemove = ["name", "salary"]
Expected output:
{'city': 'New york', 'age': 25}
"""
def remove_keys(dic, keys):
result = dict()
for key in dic:
if key not in keys:
result.update({key: dic[key]... |
d158b276d7bbe2369665260cfcd0f2c4264dfc2f | becodev/python-utn-frcu | /guia01python/ejercicio8.py | 352 | 3.625 | 4 | """
El entrenador de un equipo de básquet desea determinar la eficiencia en tiros de campo
de un jugador "X".
"""
tirosTotal = int(input("Ingrese la cantidad total de tiros: "))
tirosAdentro = int(input("Ingrese cantidad de tiros embocados: "))
eficiencia = tirosAdentro / tirosTotal * 100
print("La eficiencia del ju... |
1723df37a99d556ac3f1a6530bd8d3b0a82fb420 | eyuparslana/substringIsland | /met_case1.py | 1,232 | 3.765625 | 4 |
def get_all_substrings(entry):
length = len(entry)
return [entry[i:j + 1] for i in range(length) for j in range(i, length)]
def get_island_count(entry, substring):
s_len = len(substring)
tmp_list = ['0'] * len(entry)
for i in range(len(entry)):
if entry[i] == substring[0] and entry[i: i ... |
bb5dbb4cbcde0e47d02d3ab49ad2dbc61b080b97 | linda-oranya/algo-rhymes | /hackerank/Easy/counting_valleys/solutions/python/solution.py | 472 | 3.84375 | 4 | def counting_valleys(n, path):
valley_count, depth_tracker, sea_level = 0, 0, 0
paths_arr = list(path)
for path in paths_arr:
if path == "U":
sea_level += 1
else:
sea_level -= 1
if sea_level == -1:
depth_tracker = sea_level
if depth_track... |
1dd8d790605c7bb69084218571cb52744f18c940 | ohouse9009/rosalind | /prob4_FIB - Rabbits and Recurrence Relations.py | 198 | 3.8125 | 4 | #!/usr/bin/python
# http://www.rosalind.info/problems/fib/
def fib(n,k):
popn = 1
for gen in range(n):
yield popn
popn *= k+1
return
n = 40
k = 5
print list(fib(n,k)) |
ede92a3d031703399bed4dc3e3b8642829125e0d | SamarpanCoder2002/Smart-Calculator-Dolly | /Scientific Calculator Dolly.py | 22,814 | 3.65625 | 4 | from tkinter import *
from tkinter import messagebox
import math
class Calculator:
def __init__(self,window):
self.window=window
self.text_value = StringVar()
self.textoperator = StringVar()
self.textoperator2 = StringVar()
self.fact = 1
self.widget()
def butn(s... |
2bd132689be7042f4e936516feafd3bfa4362c9a | OliviaFortuneUCD/Readingkagglecsv | /main.py | 477 | 3.546875 | 4 | #Read the file
import pandas as pd
covid_vaccination = pd.read_csv("country_vaccinations.csv")
#Read hedings and 10 records
print(covid_vaccination.head(10))
#Print the headings and their details
print(covid_vaccination.info())
#print the values which are null
print(info_covid = covid_vaccination.isnull().sum())
... |
44cfc392f31a177ca6a24903b4e686d9a2dd0685 | erindubuc/CS50 | /pset6/bleep/bleep.py | 1,551 | 3.984375 | 4 | # Program that censors messages that contain words appearing on a list of supplied "banned words"
from cs50 import get_string
from sys import argv
def main():
# Get the text file containing banned words
if len(argv) != 2:
print("Usage: python bleep.py dictonary(text)")
exit(1)
... |
5fe78ebf8fcaa2ad062489f14e575b0c125c7500 | jied314/IQs | /1-Python/Medium/missing_number.py | 1,599 | 3.625 | 4 | # 10/1 - Array, Math, Bit Manipulation (M)
# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
# find the one that is missing from the array.
# For example, Given nums = [0, 1, 3] return 2.
# Note: Your algorithm should run in linear runtime complexity.
# Could you implement it using only c... |
e55d915996a607ed4db3c0c4abd1c7517975695b | jinxin0924/Algorithms-Design-and-Analysis | /Huffman's Algorithm.py | 681 | 3.671875 | 4 | __author__ = 'Xing'
#greedy
#not understand,unfamiliar with tree!
from heapq import heapify, heappush, heappop
from itertools import count
def huffman(seq, frq):
num = count()
trees = list(zip(frq, num, seq)) # num ensures valid ordering
heapify(trees) # A min-heap based on frq
wh... |
3789bcd829d0a7b60782fd80ddff6ef5f1188288 | pyxll/pyxll-examples | /highcharts/highcharts_xl.py | 3,561 | 3.59375 | 4 | """
Functions for display charts in Excel using Highcharts.
Please be aware that the Highcharts project itself, as well as Highmaps and Highstock,
are only free for non-commercial use under the Creative Commons Attribution-NonCommercial license.
Commercial use requires the purchase of a separate license. Pop over to H... |
fcffc6f94abb8ab7a54ce0473fae0ed67e74d4a7 | UtsavRaychaudhuri/Learn-Python3-the-Hard-Way | /ex18.py | 481 | 4.25 | 4 | # unpacking args Notice how he unpacks args nice way of doing it
def print_two(*args):
arg1,arg2= args
print(f"args1:{arg1},args:{arg2}")
# This takes two arguments
def print_two_again(arg1,arg2):
print(f"arg1: {arg1},arg2: {arg2}")
# This takes one argument
def print_one(arg1):
print(f"arg1:{arg1}")... |
8c009579fda6e1f6a93cbf3e07d06ec1861a56d7 | DingChiLin/Practice | /test2.py | 208 | 4.0625 | 4 | from itertools import combinations
dict1 = {
"3": {"1":1, "2":3,"3":2},
"1": {"1":1, "2":3,"3":2},
"2": {"1":1, "2":3,"3":2},
"4": {"1":1, "2":3,"3":2}
}
res = combinations(dict1, 2)
print(list(res))
|
6b8a232995f939426d8b04918fa9865598df1a3a | Ziqi-Li/Cracking-the-code-for-interview | /Ch2. Linked List/2.4.py | 1,388 | 3.84375 | 4 | '''
Ziqi Li
2.4 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 ... |
becd182312bd65808704f3b11366c525e84f2d28 | BabakAbdzadeh/Python-Class-Spring2019 | /ClassWorks/Class , Q by teacher.py | 710 | 3.796875 | 4 | def quiz(input_string):
i = 0
output_string = ""
while i != len(input_string):
ascii_input = ord(input_string[i])
if int(ascii_input) != 32 or int(ascii_input) != 121 or int(ascii_input) != 122:
ascii_1char_out_put = int(ascii_input) + 2
if ascii_input == 121:
... |
5f2a5396cbfe0a40a7aa9f739d4cad978df7c6a3 | MastersAcademy/Programming-Basics | /homeworks/olexandr.datsenko_sashok15/homework-1/homework-1.py | 395 | 4.03125 | 4 | name = input("What is your name? ")
age = int(input("How old are you? "))
city = input("Where do you live? ")
university = input("Where do you study? ")
say_for_self = ("My name is %s, my age is %i, "
"i live in %s and i study in %s" % (name, age, city, university))
print(say_for_self)
f = open('homewor... |
1616db8108e7a4d0a1099ceb88d9f835bfbc0362 | nurnisi/algorithms-and-data-structures | /leetcode/contests/biweekly-contest-3/4-1102. Path With Maximum Minimum Value.py | 1,755 | 3.53125 | 4 | # 1102. Path With Maximum Minimum Value
class Solution:
def maximumMinimumPath2(self, A) -> int:
s = set()
for i in range(len(A)):
for j in range(len(A[0])):
s.add(A[i][j])
arr = sorted(s)
chset = set()
for x in arr:
chset.add(x)
... |
2493c3f034c8c584cfae2a8158df388599321ac8 | kulalrajani/placement-training | /day2/p11.py | 288 | 3.890625 | 4 | # n = int(input("Enter number of pair of shoes : "))
# p = int(input("Enter maximum pair of shoes that purchaser can buy"))
total_and_max = input().split(" ")
n = int(total_and_max[0])
p = int(total_and_max[1])
array = []
for i in range(n):
array.append(int(input()))
print(array) |
6e7ae6043fd1279f093847e54353911be00546e9 | smn98/Python-notepad | /pytext.py | 9,694 | 3.703125 | 4 | from tkinter import *
import tkinter.scrolledtext as Text1 #Text1 is an alias
from tkinter.filedialog import *
from tkinter.messagebox import *
class notepad:
def __init__(self):
#CONSTRUCTOR FUNCTION
self.root=Tk() #Creates a window root of the class Tk()
... |
4e66d93532b8399b66a5d5e2bdd9571b18acab78 | mdjibran/Algorithms | /HashTables/PalindromePermutation.py | 566 | 3.59375 | 4 | '''
Palindrom string
'''
from collections import defaultdict
def SetDict(s: str):
dict = defaultdict(str)
for c in s:
if c not in dict:
dict[c] = 1
else:
dict[c] = dict[c] + 1
return dict
def CheckPalindrom(str1: str, str2: str):
if len(str1) != len(str2):
... |
c5343c882d57e0b5749c2d0a3f5c023e3a13ae2a | cozymichelle/algorithm_in_python | /jump_search.py | 1,158 | 3.875 | 4 | '''
Jump Search
Input:
- arr: a given sorted array
- x: an element to find
- m: number of elements to jump ahead
Output: index of the element x
The optimal block size is m = sqrt(n).
worst case scenario: (n / m) jumps + (m - 1) comparisons
'''
def lin_search(arr, x, l, r):
# do linear search on arr from index... |
09f6e8a8deaa659a7a3f276e32f812e043e04f3c | lrlab-nlp100/nlp100 | /moajo/chapter1/p02.py | 254 | 3.828125 | 4 | #!/usr/bin/env python
def zip_str(s1, s2):
if len(s1) == 0:
return s2
if len(s2) == 0:
return s1
return s1[0] + s2[0] + zip_str(s1[1:], s2[1:])
if __name__ == "__main__":
print(zip_str("パトカー", "タクシー"))
|
c61d82b12c31ce6b65ee85cc365d1361a898b29c | kobyyoshida/pynative-solutions | /Lists/exercise2.py | 366 | 3.90625 | 4 | #Exercise 2: Concatenate two lists index-wise
list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
solution = []
for i in range(0,len(list1)):
newWord = list1[i] + list2[i]
solution.append(newWord)
print(solution)
#list1 = ["M", "na", "i", "Ke"]
#list2 = ["y", "me", "s", "lly"]
#list3 = [i + j... |
10491dd55bdf7abb2428ae6474037949c358137d | NataliaDiaz/BrainGym | /arrange-tiles.py | 1,086 | 4.09375 | 4 |
"""
How many different ways are there of covering a Nx3 grid having available infinite
tiles of size 2x1 and 1x2 in a way that each tile in the grid is covered only
once, and each part of the tile is covering one grid space.
Return the result, as it will be a large number, modulo (10**9)+7.
Example:
Input: 10
Output:... |
4c54971f33c1902114e4a60486e872beaecd2419 | chris-peng-1244/py4e | /11-Re.py | 145 | 3.546875 | 4 | import re
filename = input("Enter file name:")
h = open(filename)
nums = [ int(num) for num in re.findall(r'\d+', h.read()) ]
print(sum(nums))
|
99df53c3fda223a8189ccf8aef71c2854a8e90ee | anshul217/sortdict | /sortdict/__init__.py | 561 | 3.828125 | 4 | from operator import itemgetter
def dict_sort(list_dict, sort_keys=None):
"""Get sorted list of dictonaries
Keyword arguments:
list_dict -- list of dictionary to be sorted eg:- [{'name':'alex', 'age':10}, {'name':'mike', 'age':20}]
sort_keys -- list of key on to which sorting needs to be done. eg:- ['... |
3a64501fc828f6c8edc489edf3afb827a06f82b5 | kis619/SoftUni_Python_Basics | /3.Conditional_statements_advanced/LAB/10. Invalid Number.py | 161 | 4.03125 | 4 | number = int(input())
if not(100 <= number <= 200 or number == 0):
print("invalid")
# a = 100 <= number <= 200 or number == 0
# if not a:
# print("invalid") |
1c43ce8aa4d191ab74d453e74e254638e0ad8398 | Madhav2108/Python- | /if/el5.py | 160 | 4 | 4 | a=int(input("enter age"))
if a>18:
print("Greater than 18")
else:
print("Less 18")
|
f137062ac62d4e9b3199dfb7ff138b64108fbef9 | konstantinagalani/ABLR_network | /BO_dataset/maximizer.py | 1,447 | 3.78125 | 4 | import numpy as np
class RandomSampling():
def __init__(self, objective_function, lower, upper, init_d,n_samples=100, rng=None):
"""
Samples candidates uniformly at random and returns the point with the highest objective value.
Parameters
----------
objective_function: ac... |
4352e8f6d6e026bb63a7a9b0beb9ec6402419dce | htmlprogrammist/kege-2021 | /tasks_12/task_12_10290.py | 236 | 3.671875 | 4 | s = '1' + '8' * 80
while '18' in s or '288' in s or '3888' in s:
if '18' in s:
s = s.replace('18', '2', 1)
elif '288' in s:
s = s.replace('288', '3', 1)
else:
s = s.replace('3888', '1', 1)
print(s)
|
fa2a5453391a2e5227411c3d986289b114c324b4 | lihongwen1/XB1929_- | /ch09/except_tpye.py | 226 | 3.578125 | 4 | def check(a,b):
try:
return a/b
except ZeroDivisionError: #除數為0的處理程序
print('除數不可為0')
a=int(input('請輸入被除數:'))
b=int(input('請輸入除數:'))
print(check(a,b))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.