blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bae54183f26da0fbd491b73ab2f92afa70e56c27 | smlacava/Metis | /data_loader.py | 1,204 | 3.578125 | 4 | from scipy.io import loadmat
from pathlib import Path
import numpy as np
class data_loader():
def load_data(self, data_file):
"""
The load_data method allows to load a matrix from a file (.mat).
:param data_file: is the name of the file (with its path) containing the matrix
... |
56e2a73c20f998213a9fecc4e581f4931b551d40 | WeijieH/ProjectEuler | /PythonScripts/10001st_prime.py | 636 | 4.0625 | 4 | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
def ith_prime(i):
count = 0
n = 1
while count < i:
n += 1
if isprime(n):
count += 1
continue
return n
def... |
e64fa593fa30d03523e513dc0d3ffe1dff69cca6 | Onotoko/codeforces | /graph/guilty_prince.py | 1,671 | 3.53125 | 4 | from queue import Queue
"""
The idea:
- Read data into a matrix which has shape [h+2, w+2] (added padding to all border)
- Build a graph with (h+2)*(w+2) nodes
- Build a list edges. Two points (i,j) and (i,j+1) it called edges if (i,j) = '.'
and (i,j+1) = '.'
- Remember store position of start '@'
- Usin... |
451d287b72e8f4d2c68f62b6aa629a6aa436a23a | randhid/learnpyhardway | /ex6.py | 701 | 4.28125 | 4 | types_of_people = 10
x = f"There are {types_of_people} types of people."
# making string variables using the pre defined
# variables
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
#printing statements
print(x)
print(y)
# using print statements with the strign variables
# th... |
8956cbce23c196dc454218093e4c402324ada03a | darioradio1man/yandex_training | /lesson3/turtles.py | 308 | 3.71875 | 4 | def turtles_truth(n: int) -> int:
count = 0
s = set()
for _ in range(n):
s.add(input())
for i in s:
j = list(map(int, i.split()))
if j[0] + j[1] == n - 1 and j[0] >= 0 and j[1] >= 0:
count += 1
return count
n1 = int(input())
print(turtles_truth(n1))
|
7262de4fe2c621332cf31090aa770f8a3cac5464 | jormao/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 405 | 4 | 4 | #!/usr/bin/python3
"""7-save_to_json_file.py - Save Object to a file"""
import json
def save_to_json_file(my_obj, filename):
"""function that writes an Object to a text file,
using a JSON representation
ARGS:
my_obj: object to write in a text file
filename: text file
"""
with ope... |
178a0fd06825bcff318cbd45260769f98a7642a3 | aeberspaecher/TheoHandouts | /Mechanik-GreensFkt/deltaPlot.py | 2,021 | 3.859375 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
"""Plot various representations of the Dirac's Delta function.
"""
import numpy as np
import matplotlib as mpl
mpl.use("module://backend_pgf")
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
def rectangle(x, x0, epsilon):
y = np.zeros(len(x))
y[np.where(... |
25ac379390d92b13f58164103b955bb4dcf5624e | UWSEDS/hw4-exceptions-and-unit-tests-samirpdx | /data_action.py | 1,257 | 3.59375 | 4 | import pandas as pd
import os
import requests
def get_data(url):
#df = pd.DataFrame()
url = url
csv_name = url[url.rfind("/")+1:]
check = ""
if os.path.exists(csv_name):
#print("File exists locally, skipping download.")
check = "File exists locally, skipping download."
else:
... |
14c642df153620f7abb20c96f5317736269f47cc | leoliuyt/workspace_python | /python_grammar/my_controltest.py | 394 | 3.921875 | 4 | #!/usr/local/bin/python3
inputStrH = input("请输入身高(m):")
inputStrW = input("请输入体重(kg):")
h = float(inputStrH)
w = float(inputStrW)
bim = w / (h**2)
print(bim)
if bim < 18.5:
print("过轻")
elif bim >= 18.5 and bim < 25:
print("正常")
elif bim >= 25 and bim < 28:
print("正常")
elif bim >= 28 and bim < 32:
print... |
7395f488158de2536275ca7ffdbb64b494a5e934 | Thesohan/DS_python | /bit_manipulation/no_of_bits.py | 443 | 4.125 | 4 | """
Write a function that takes an unsigned integer and returns the number of 1 bits it has.
Example:
The 32-bit integer 11 has binary representation
00000000000000000000000000001011
so the function should return 3.
"""
class Solution:
# @param A : integer
# @return an integer
def numSetBits(self, A):
... |
ef9a2463f898541e86818be75bd49523108ce6f2 | YogalakshmiS/thinkpython | /chapter 5/Exc 5.3.py | 965 | 4.28125 | 4 | ''' Exercise 5.3. Fermat’s Last Theorem says that there are no positive integers a, b, and c such that
a
n + b
n = c
n
for any values of n greater than 2.
1. Write a function named check_fermat that takes four parameters—a, b, c and n—and that
checks to see if Fermat’s theorem holds. If n is greater than 2 and i... |
48b8b066340095001f0c337de40dde5838d6e2d2 | isfaaghyth/algorithm-playground | /Game of Thrones - I/solution.py | 1,451 | 3.75 | 4 | """
https://www.hackerrank.com/challenges/game-of-thrones/problem
Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom.
But, to lock the door he needs a key that is an anagram of ... |
cf6d8b130d85e58d16e14cc980fbc90dbed337fc | toledoneto/Python-TensorFlow | /02 TensorFlow Basics/07 TF Regression Exercise.py | 3,651 | 3.5 | 4 | # Regression Exercise
#
# California Housing Data
#
# This data set contains information about all the block groups in California from the 1990 Census.
# In this sample a block group on average includes 1425.5 individuals living in a geographically compact area.
#
# The task is to aproximate the median house value of e... |
b6880bc3c60319d0149b1dd417397650d95b03d6 | Aasthaengg/IBMdataset | /Python_codes/p03796/s827733716.py | 141 | 3.65625 | 4 | N = int(input())
power = 1
for i in range(1,N+1):
power *= i
if power >= 10**9+7:
power %= 10**9+7
print(power % (10**9+7)) |
3e117dd63a4596fa8a8f303744f91a447c13aad5 | jaecheolkim99/CodingPlayground | /LeetCode/Compare Version Numbers.py | 3,098 | 4.09375 | 4 | """
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1; otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate numb... |
63354e69bb1ac1f7c084dfb44ef83bdf4310f6f0 | icoding2016/study | /DS/array_kadane.py | 3,304 | 3.84375 | 4 | """
Largest Sum Contiguous Subarray (via Kadane’s Algorithm)
Given an array arr[] of size N. The task is to find the sum of the contiguous subarray within a arr[] with the largest sum.
The idea of Kadane’s algorithm is to maintain a variable max_ending_here that stores the maximum sum contiguous subarray ending at cur... |
ac1111ef6e07b2609495e92227e31c021aaac065 | Antherine/First-day-of-Python | /templates/hello_world.py | 583 | 3.984375 | 4 | # encoding: utf-8
def main(x):
"""
你好
:param x:
:return:
"""
if x == 2:
print "hello, world"
else:
print "F**k you, world"
def calculator(x, op, y):
if op == "+":
return x + y
elif op == "-":
return x - y
elif op == "x":
return x * y
... |
3389147655ce338f0389eb5d9482fdfdbabc343a | openturns/openturns.github.io | /openturns/master/_downloads/1d69a82405aa339fe03c15bbefb04818/plot_random_mixture_distribution_discrete.py | 1,069 | 3.75 | 4 | """
Create a discrete random mixture
================================
"""
# %%
# In this example we are going to build the distribution of the value of the sum of 20 dice rolls.
#
# .. math::
# Y = \sum_{i=1}^{20} X_i
#
# where :math:`X_i \sim U(1,2,3,4,5,6)`
#
# %%
from __future__ import print_function
import ... |
ab064b2a02706735a92d64dbf786f4083b83cb88 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mrgsac001/question1.py | 463 | 4.21875 | 4 | """palindromes
Sachin Murugan
9/5/2014"""
string=input("Enter a string:\n")
def Palindrome(string):
#testing for base case
if len(string)== 0 or len(string)==1: #check if word is only 1 or zero letters
print("Palindrome!")
else:
if string[0]==string[-1]:#check first and last letter
... |
e842c92514d23208bb483f1423526375dfeda48f | minseoch/algorithm | /300-LongestIncreasingSubsequence.py | 2,250 | 3.828125 | 4 | # 300. Longest Increasing Subsequence
# https://leetcode.com/problems/longest-increasing-subsequence/discuss/152065/Python-explain-the-O(nlogn)-solution-step-by-step
class Solution:
# O(n*m) solution. m is the sub[]'s length
def lengthOfLIS(self, nums):
sub = []
print(f"nums={nums}")
for va... |
96fdd0185ab2348d6163db7441264991b2c51dbe | CarlosPolo019/taller-algoritmo-condicionales | /punto5.py | 461 | 3.96875 | 4 | valorCarro = float(input('Digite el valor del carro: '))
valorTerreno = float(input('Digite el valor del terreo: '))
incrementoTerreno = 0.10 * valorTerreno * 3
desvaluacionCarro = 0.10 * valorCarro * 3
print(f'Valor Terreno {desvaluacionCarro}')
if (desvaluacionCarro < (incrementoTerreno*0.50)):
print(f'Calculos ... |
c2be250bca11b5af8c8e1c1b38470ee6b76ff25a | Yi-Pin-chen/yzu_python_20210414 | /day05/List 串列2.py | 739 | 3.609375 | 4 | import random as r
scores=[100,-10,90,80,999]
# error_scores=scores.pop(1)
# print(error_scores,scores)
# error_scores=scores.pop(3)
# print(error_scores,scores)
#利用POP () 將不合法的分數挑出
for x in scores:
if x> 100 or x < 0:
error_scores = scores.pop(scores.index(x))
print(scores)
#利用POP () 將不合法的分數挑出
scores1=[1... |
b9ef3cae09d0e7bd97d046057e825bfdb4cfd022 | laurachaves/pendulo | /pendulo.pyde | 633 | 3.59375 | 4 | teta = PI/3
R = 200 #comprimento
g = 980.0 #aceleração da gravidade
vt = 0.01
h = R-R*cos(teta)
EM = g*h+(vt**2)/2
oldt = millis()/1000.0
ver = 1.0
def setup():
size(800,800)
def draw():
global oldt, teta, R, vt, g, h, EM, ver
t = millis()/1000.00
dt = t - oldt
oldt = t
omega = ve... |
3ea1ec72d315a57c1bb1c8609ae3689ac3f3f362 | tanchao/algo | /interviews/amazon/rotate_min.py | 763 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tanchao'
def find_min(A):
if not A: return None
if len(A) == 1: return A[0]
left, right = 0, len(A) - 1
while left < right and A[left] >= A[right]:
mid = left + (right - left) / 2
if A[mid] < A[right]:
right = mid... |
75287a08413994b22206e38d142dac5ccf16bbc1 | zhenhuiguo1995/CS5001 | /Othello_Part_2/Othello/player.py | 597 | 3.9375 | 4 | class Player():
"""Instantiates a human player or a computer player object"""
def __init__(self, name, board, color):
self.name = name
self.board = board
self.color = color
def has_legal_move(self):
"""Return a boolean value representing if the player has a
legal mov... |
cb59b63c23fd2ce97f024e21036a985143970231 | Aasthaengg/IBMdataset | /Python_codes/p02582/s949198943.py | 157 | 3.9375 | 4 | s=input()
if (s=="RRR"):
print(3)
elif (s=="SRR" or s=="RRS"):
print(2)
elif (s=="SSR" or s=="RSS" or s=="SRS" or s=="RSR"):
print(1)
else:
print(0) |
6c7f78bf245e88ccf32447cdef2fdefe75c0b4aa | sumanshreyansh/python-projects | /billcalculator.py | 297 | 4.09375 | 4 | #to make a program which keeps adding number till the user doesn't press q.
sum = 0
while(True):
a = input("Enter the price \n")
if a != "q":
sum = sum + int(a)
print(f"order so far {sum}")
else:
print("The total price is ",sum)
break |
29c18bc3fe30d4223ff74d2d6e8de6578ae85d6f | nithi-sree/IBMLabs | /LeapYear.py | 322 | 4.15625 | 4 | year = int(input("Enter the year: "))
if(year%4) == 0:
if (year%100) == 0:
if (year%400) == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")... |
ba9757e0d0a846e044ad67642fea35df0b8ff3b2 | microsoft/Reactors | /coding-languages-frameworks/code-garden-advent-of-code-2022/day10.py | 2,060 | 3.53125 | 4 | #!/usr/bin/env python3
instructions = [x.strip() for x in open("day10-data.txt").readlines()]
class CPU:
def __init__(self):
self.clock = 0
self.X = 1
self.signal_beats = []
self.display = []
def log(self):
if (self.clock+20) % 40 == 0:
print(self.clock... |
9b1f954e78e2759a4282a3be2056b5651e4899db | TanveerAhmed98/Full-Stack-Programming | /Programming Concepts/error_handling.py | 380 | 3.953125 | 4 | def read_file(file_name):
try:
file = open(file_name, "r")
stuff = file.read()
print(stuff)
file.close()
except:
print("There is an error in read file function")
read_file("apple.txt")
password = input("Please enter the password: ")
if len(password) < 10:
raise Exce... |
8d99772a839081b35f3ab27608c26d0b73030d37 | wjymath/leetcode_python | /108. Convert Sorted Array to Binary Search Tree/Convert_Sorted_Array_to_Binary_Search_Tree.py | 647 | 3.734375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
input_l = ... |
9458758501f45a7d531d5f84020fb2b50778b9a5 | pearlselvan/PythonPractise | /DS/PriorityQueueUsingheapq.py | 832 | 3.875 | 4 | '''
A priority queue is common use for a heap, and it presents several implementation challenges:
http://www.bogotobogo.com/python/python_PriorityQueue_heapq_Data_Structure.php
'''
# Simplest
try:
import Queue as Q # ver. < 3.0
except ImportError:
import queue as Q
q = Q.PriorityQueue()
q.put(10)
q.put(1)
... |
06ebfa7a313d82d47078a8c3a293243787a5758b | Min3710/Mypython | /chaper 2/p03.py | 145 | 3.625 | 4 | radius=int(input("반지름을 입력하세요"))
size=3.14159*radius*radius#rdaius**2
print("반지름이",radius,"인 원의 넓이=",size)
|
ba37906f8b325810cc8bf3f60069dbdc435f6fbb | kimdg1105/Algorithm_Solving | /BOJ/10814.py | 397 | 3.546875 | 4 | N = int(input())
list = []
for i in range(N):
age, name = input().split()
list.append([age, name, i])
# for i in range(N):
# for j in range(N):
# if list[j][0] > list[i][0]:
# temp = list[j][0]
# list[j][0] = list[i][0]
# list[i][0] = temp
list.sort(key=lambda x: ... |
8be1c3c159422a305e036dca57ae1e6e0f3e8cc1 | zhousir1234/zhourui | /python入门/第二章.py | 708 | 3.84375 | 4 | #1.输入直角三角形的两个直角边的长度a、b求c的长度
num1=float(input('请输入一条边的长'))
num2=float(input('请输入另外一条边的长'))
a=num1
b=num2
c=((a**2)+(b**2))**(1/2)
print('c的长度是',c)
#2. 编写一个程序,用于实现两个数的交换
num1=float(input('请输入一个数'))
num2=float(input('请输入另一个数'))
a=num1
b=num2
#使用3个变量
c=a
a=b
b=c
print('b的值为',b)
#使用两个变量
#使用两个变量的第一种方法
a ... |
7d453088c2129fe4c1d9274f1a65e80897f0bf87 | sankey94/Python | /Python Base Work/fibonacci.py | 110 | 3.875 | 4 | num=int(input("Enter number:" ))
a=0
b=1
print(a)
for i in range(num):
c=a+b
print(c)
b=a
a=c
|
3a77ccc29a7d025f158003fa6535e75aa5ccb735 | jasonncleveland/cs2613 | /assignments/A4/read_csv.py | 264 | 3.9375 | 4 | import csv
def read_csv(filename):
"""Read a CSV file, return list of rows"""
rows = []
with open(filename, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
for row in reader:
rows.append(row)
return rows
|
4d658a19044192671889554ddd9a225a0b0a73e1 | TheMoonlsEmpty/test | /类/类练习2.0.py | 1,896 | 3.71875 | 4 | # 利用上题的类,生成20个随机数字,两两配对,形成二维坐标,并这些坐标打印出来
import random
# 方法一:
class Randomint7:
def __init__(self, count=10, start=1, stop=100):
self._count = count
self.start = start
self.stop = stop
self._gen = self._generate() # 生成器对象
def _generate(self):
# 用生成器的无限生成,要多少不在这里控制。
... |
0df9200bcd9a6aec68d1587d742528e137656a9e | busekara/image-processing | /ders-4.py | 1,576 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[20]:
import math #standart sapma ve ortalama hesaplama fonksiyonu
def my_f_1(my_list=[2,4,3,40,5,6,3,3,2,1]):
toplam=0
total=0
for i in my_list:
toplam+=i
#hist=?
mean=toplam/len(my_list) #ortalama
#print(mean)
for i in my_list:
... |
e55fa48df9d9d61aca5d16ac4725baa48cdc4900 | korowood/algorithm-and-data-structures | /5 - Хеш-таблицы/A. Set.py | 1,830 | 3.515625 | 4 | """
Реализуйте множество с использованием хеш таблицы.
input:
insert 2
insert 5
insert 3
exists 2
exists 4
insert 2
delete 2
exists 2
output:
true
false
false
"""
import sys
class HashSet:
def __init__(self):
self.M = 10 ** 6
self.A = 4481
self.P = 2004991
self.data = ['' for _ i... |
ca98a1e382c29063737107b65ff3b3232a65c7df | aparajit0511/DS-Algo | /linked list/Reverse Linked List.py | 469 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
ptr = new = None
current = head
while current is not None:
... |
3d9e0e132fc6ed24fae7b8c48b221e5ff00cb303 | shimmee/competitive-programming | /AtCoder/Practice/茶緑埋め/ARC006B.py | 2,005 | 3.53125 | 4 | # ARC006B - あみだくじ
# URL: https://atcoder.jp/contests/arc006/tasks/arc006_2
# Date: 2021/02/20
# ---------- Ideas ----------
# 今なんの列にいるのかnowで管理しながら,左右に'-'があれば移動する,という感じで上から下に走査する
# ------------------- Answer --------------------
#code:python
N, L = map(int, input().split())
field = [input() for _ in range(L)]
goal = i... |
de0808e51214bbb009111f12697f806037f1db56 | LaBravel/Tedu-code | /python_base/weekly test02/5.py | 329 | 3.609375 | 4 | def calculate(i,j = 0) :
k = i + j
i = int(k / 2)
j = int(k % 2)
return [i,j]
L = [int(input("有多少钱?")),0]
num = 0
while 1 :
num += L[0]
L = calculate(*L)
if sum(L) == 1 and L[0] == 1 :
num += 1
break
elif sum(L) == 1 and L[1] == 1 :
break
print("能买",num,'瓶') |
c438e46b3e054242945310092c189c1fd3cc289e | pydevjason/Python-VS-code | /scope_closures.py | 596 | 4.0625 | 4 | # a closure is a programming pattern in which a scope retains access to an enclosing scopes names
# example
def outer():
candy = "Snickers"
def inner():
return candy
return inner() # returning inner is the closure
print(outer())
print()
def multiply(a, b):
return a * b
d... |
c683dcf4128c66c84ff242955e239ed37b1f3748 | kirypto/Challenges | /AdventOfCode/2019/day2.py | 2,049 | 3.546875 | 4 | from itertools import product
from typing import List, Tuple, Union
from python_tools.advent_of_code.puzzle_runner_helpers import AdventOfCodeProblem, TestCase
from python_tools.advent_of_code.y2019_int_code_computer import IntCodeComputer
def part_1_solver(part_1_input: List[int]) -> List[int]:
input_program, n... |
06184a9d213045bf1748ee132468043b1bda76c7 | chiragbagde/PHI-Education | /data structures/priority queue.py | 1,257 | 4.15625 | 4 | class PriorityQueue():
def __init__(self):
self.queue = []
def __str__(self):
return ' '.join([str("priority: "+str(i[0])+ " element: "+str(i[1])+" ") for i in self.queue])
def isEmpty(self):
return len(self.queue) == 0
def insert(self, data, priority):
s... |
d2e3afaf3e1dab6b735464bdc4cd64d1865e4397 | calvindajoseph/patternrecognition | /ClassifierGUI.py | 2,271 | 4 | 4 | """
A simple tkinter GUI for model demonstration.
"""
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")
# Import ModelClassifier
from ModelClasses import ModelClassifier
# Import tkinter
import tkinter as tk
# Set the classifier
# May take some time, especially if loaded to CPU
classifier = ModelC... |
412e6c6aaaa4f737ba831ba6151451056bfc58f0 | blessey15/pehia-python-tutorials | /q7.py | 203 | 3.65625 | 4 | l=[]
print('Enter the no. of rows & columns:')
(r, c)=map(int, input().split(','))
for i in range(r):
a=[]
for j in range(c):
y=i*j
a.append(y)
l.append(a)
print(l)
|
fcea316a1c4e15eb7533a16cca5dabeaaf2c7581 | 815382636/codebase | /python/foundation_level/my_caculate.py | 558 | 3.734375 | 4 | """
1.使用 and 、 or 时,尽量将每一小部分用()括起来,利于和他人配合工作,防止歧义等
"""
"""
数值之间做逻辑运算
(1)and运算符,只要有一个值为0,则结果为0,否则结果为最后一个非0数字
(2)or运算符,只有所有值为0结果才为0,否则结果为第一个非0数字
"""
print(0 and 1)
print(2 and 3)
print(0 or 0)
print(0 or 1)
print(2 or 3)
"""
算数运算优先级:
混合运算优先级顺序: () 高于 ** 高于 * / // % 高于 + -
""" |
4cc58a287a8fe864968bcc37688cd51e87f6cc67 | ZimingGuo/MyNotes01 | /MyNotes_01/Step01/2-BASE02/day04_08/demo03.py | 1,445 | 3.9375 | 4 | # author: Ziming Guo
# time: 2020/2/11
"""
demo03:
函数内存图
"""
# 在方法区中存储函数代码,不执行函数体
def fun01(a):
a = 100
num01 = 1
# 因为调用函数,所以开辟一块内存空间,叫做栈帧
# 用于存储在函数内部定义的变量(包含参数).
fun01(num01) # 这句话就是要把 num01 给 a
# 也就是让 a 指向 num01 所指向的数据
# 这句话就是:在内存里开辟了一块栈帧,告诉栈帧 a = num01
# 函数执行完毕后,栈帧立即释放(其中定... |
83f51c51de853f1053812650fd76442d74f01b7b | Palash51/Python-Programs | /program/selection.py | 353 | 3.640625 | 4 | def sel_sort(A):
for i in range(len(A)):
least = i
for j in range(i+1,len(A)):
if A[j] < A[least]:
least = j
temp = A[i]
A[i] = A[least]
A[least] = temp
# swap(A,least,i)
#def swap(A,x,y):
# temp = A[x]
# A[x] = A[y]
# A[y] = temp
A = [1,3,8,4,2,5,9,7]
fun = s... |
f4b8ee28747c4891c943427c05b0623f758381d4 | jofre44/EIP | /scripts/calculator.py | 1,456 | 4.03125 | 4 | class calculadora:
_counter = 0
def __init__(self, num_1, num_2):
try:
num_1 = float(num_1)
num_2 = float(num_2)
except:
raise ValueError('Valores introducidos no son numeros')
calculadora._counter += 1
self.id = calculadora._counter
... |
cd775bd9ec6e53258c96aa3c4607707588ef0cfd | roxolea5/pythonRefresh | /Sesion1/retos.py | 2,479 | 4.0625 | 4 | # Reto 1
print("Ingresa el primer número")
reto1_str1 = input()
reto1_num1 = int(reto1_str1)
print("Ingresa el segundo número")
reto1_str2 = input()
reto1_num2 = int(reto1_str2)
print ("El resultado de la concatenación de {} y {} es {}".format(reto1_str1, reto1_str2, reto1_str1 + reto1_str2))
print ("El resultado de l... |
a7bf909b39f09af1cfbd580fc85d404d45c3cb38 | Niksonber/production | /sql.py | 4,857 | 3.671875 | 4 | import sqlite3
import os
import io
class DB():
def __init__(self):
self.name = 'data.db'
self.exists = False
if os.path.isfile(self.name):
self.exists = True
self.pedidos = "(client_id)"
def initDB(self):
self.connection = sqlite3.connect(self.name)
... |
59b95287136977497a0860abdc6e8524e84ec2ff | puneethrchalla/ds-algos | /recursion/recursive_range.py | 163 | 3.734375 | 4 | def recursive_range(num):
if num == 1:
return 1
return num + recursive_range(num-1)
print(recursive_range(6)) # 21
print(recursive_range(10)) # 55 |
7227de6f763ed78f50d40c7782a653c5cac9fd63 | Aigarsss/py | /bubble.py | 3,424 | 4.09375 | 4 | # bubble sort. check out https://www.calhoun.io/lets-learn-algorithms-implementing-bubble-sort/
# li = [4, 6, 1, 2, 5, 13, 46]
# def bubble_sort(a):
# for x in range(len(a)):
# for i in range(len(a)-1):
# if a[i] > a[i+1]:
# a[i], a[i+1] = a[i+1], a[i]
# return a
# prin... |
46bc020b5f29cef13c594a24fb2fd25b9096eda7 | aheui/snippets | /_tools/aheuilize/aheuilize.py | 1,845 | 3.90625 | 4 | import math
def divide(a):
b = int(a / 2)
if a % 2 == 1:
return [b, b + 1]
return [b, b]
def factorization(a):
primes = []
factor = 2
if a < 2:
return [a]
while a > 1:
while a % factor:
factor += 1
primes.append(factor)
a = int(a / factor... |
7cc0d7514cedf6e5fa21b1e87f1400d87a0fcf0b | Giby666566/programacioncursos | /tarea4.py | 278 | 4.21875 | 4 | #congetura de collatz
numero=int(input('dame un número '))
while numero>=1:
if numero%2==0:
print(numero)
numero=numero/2
elif numero%2==1:
print(numero)
numero=(numero*3)+1
if numero==1:
print(numero)
break
|
ec64b987cce394bc9cb016f8d274a9b652cb12c0 | davidyc/GitHub | /davidyc/simplepython/file.py | 1,306 | 3.78125 | 4 | poem = '''\
Программировать весело.
Если работа скучна,
Чтобы придать ей весёлый тон -
используй Python!
'''
f = open('poem.txt', 'w') # открываем для записи (writing)
f.write(poem) # записываем текст в файл
f.close() # закрываем файл
f = open('poem.txt') # если не указан режим, по умолчанию подразумевается
# режим чте... |
13e8c28e6341bb3d0a3fe9c23569ef5ad82f435d | leonardocouy/mini_curso_python | /input.py | 483 | 4 | 4 | nome = input("Digite seu nome:")
idade = int(input("Digite sua idade: "))
dinheiro = float(input("Digite quant dinheiro: R$"))
print("%s, você tem %i anos e R$%.2f" % (nome, idade, dinheiro))
try:
num = int(input("Digite um numero:"))
print(num)
except ValueError:
print("Ops, verifique se digitou um num... |
92f5d37272ac5b92976d5d5f21c18d4715de8be7 | xjtu-BeiWu/python_base | /base_tensorflow/rnn_classification_example.py | 2,661 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# Author: bellawu
# Date: 2021/3/15 21:33
# File: rnn_classification_example.py
# IDE: PyCharm
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.ops.rnn import dynamic_rnn
tf.set_random_seed(1)
mnist = input_data.read_data_sets('MNIST_D... |
dc647f44294b38b6116bb845b2a24ffabf661421 | JohnsonWang0319/MystanCodeProjects | /stanCode_Projects/my_drawing/bouncing_ball.py | 1,689 | 3.6875 | 4 | """
File: Bouncing_ball.py
Name: Johnson
"""
from campy.graphics.gobjects import GOval
from campy.graphics.gwindow import GWindow
from campy.gui.events.timer import pause
from campy.gui.events.mouse import onmouseclicked
VX = 3
DELAY = 10
GRAVITY = 1
SIZE = 20
REDUCE = 0.9
START_X = 30
START_Y = 40
... |
b1bae692accd519aab2e2f1616a97d1d88cc3819 | leeyou34/JumpToPython | /02-6 집합 자료형/set.py | 1,025 | 3.84375 | 4 | # 집합(set)자료형 : { 값, , ,}
# 요소의 순서가 정해져 있지 않다(unordered)
# 요소의 중복(X)
s = {1,5,2,2,3,3,7}
print('s=', s)
print(8 in s)
s = set('apple')
print('s=', s)
s = set('자바211기 화이팅!')
print('s=', s)
s = set()
print('type(s)', type(s))
a = {1,2,3,4,5,6}
b = {3,4,5,6,7,8}
print('a=', a)
print('b=', b)
... |
e2ee0dbe3da76948e048c60aeb85aeaecb139a8d | mike567984/Computer-vision-with-ants | /ants.py | 533 | 3.71875 | 4 | import cv2
import numpy as np
def canny(image):
gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)#changes the 3 color grops to gray only for easy detecetion of edges
canny = cv2.Canny(gray, 50 ,150)#sets threashold to the low and high and anything inbetween is shown/uses dirivite in all directions
return cann... |
3fe6785a397763917fb62502b319f12a37aa3d7b | hyjae/udemy-data-wrangling | /DataExtraction/NREL_csv.py | 1,121 | 3.75 | 4 |
"""
The data comes from NREL (National Renewable Energy Laboratory) website. Each file
contains information from one meteorological station, in particular - about amount of
solar and wind energy for each hour of day.
The data should be returned as a list of lists (not dictionaries).
You can use the csv modules "reade... |
26120b7b7711c9a36ad09b1334be3ca5f89750ec | gordonfierce/blackjack | /blackjack/dealer.py | 1,350 | 3.734375 | 4 | from blackjack.hand import Hand
class Dealer:
"""The dealer is one of the two agents in the game, and plays
deterministically against the player.
Responsibilities:
The dealer posesses a hand.
The dealer will hit whenever the dealer's hand is under 17.
The dealer discards cards at the end of a... |
720802def1a11569203c8bbcd023054f67fa2603 | Sujjzit/Codefights | /splittingint.py | 243 | 3.609375 | 4 | Example
For n = 1230, the output should be
isLucky(n) = true;
For n = 239017, the output should be
isLucky(n) = false.
def isLucky(n):
return sum(map(int, list(str(n)[:(len(str(n))/2)]))) == sum(map(int, list(str(n)[(len(str(n))/2):])))
|
52107a682c08dcb701b699c4178e146c20acb48d | asim09/Algorithm | /decorator/decorator.py | 751 | 3.8125 | 4 | import time
import functools
def do_twice(func):
def wrapper_do_twice(*args, **kwargs):
# func(*args, **kwargs)
func(*args, **kwargs)
return func(*args, **kwargs)
return wrapper_do_twice
def timer(func):
"""Print the runtime of the decorated function"""
@functools.wraps(func)
... |
a16ac9217deaf5e6485cacd9e0e3581f2b7da25f | nilam1996/first_test | /armstrong.py | 209 | 4.09375 | 4 | index=0
sum=0
input=int(raw_input("Enter your num"))
num=input
while(num>0):
reminder=num%10
sum+=reminder**3
num//=10
if sum==input:
print("number is armstrong")
else:
print("number is not armstrong")
|
c200ca889c354e2b2da185e7de5f779b7db90f6d | memphis95/Algorithms | /cses/Introductory Problem/8_two_sets_2.py | 1,136 | 4.0625 | 4 | """
PS: To divide the numbers 1,2,...,n into two sets of equal sum
"""
def is_two_sets(n):
a = []
b = []
sum_n = (n * (n+1))//2
"""
The below approach as works :
each set of values have same sum so that will be 1/2 of sum_of_n_numbers
assign subset_sum = 1/2 (sum_of_n_numbers)
for each number... |
a67dc87a28d9452580871951c78c9d92e11392d3 | rsurpur20/ComputerScienceHonors | /game.py | 3,577 | 4.28125 | 4 | # Roshni Surpur
# 9/24/18
# OMH
# For this assignment, you will work on a text game. Examples of text games are choose your own adventures, perhaps a dice or card game with text output, fortune tellers, etc. Choose content for your game that is engaging; games that don’t have ... |
e31fb0f35973a161249b594e20493bd73399c7db | SilviaAmAm/tf_hackathon | /cubic_function.py | 2,378 | 3.921875 | 4 | """
This script is an example of how to overfit a cubic function using a small feed forward neural network with only one hidden
layer.
"""
import numpy as np
import tensorflow as tf
import seaborn as sns
import matplotlib.pyplot as plt
# -------------- ** Generating sample data ** ------------------
x = np.linspace(... |
aeb7425b250c2060592666628cd22a96e9d8f15f | mazurcaionut/Python-2.7-programs | /sentence.py | 611 | 3.609375 | 4 | from Tkinter import *
e = "Enuntul este aici.Scrie raspunsul:"
rc = "raspunsul corect"
fereastra = Tk()
fereastra.title("Intrebare")
fereastra.geometry("300x100")
cadru = Frame(fereastra)
cadru.grid()
enunt = Label(cadru,text=e)
enunt.grid()
raspuns=Entry(cadru)
raspuns.grid()
def handler_buton(... |
ba557439bd6ee144bae9d0bb01f297f9d1026c4c | rhivent/py_basic | /19abstract_class.py | 1,739 | 3.65625 | 4 | '''
abstract class itu semacam class templating,
dimana kita hanya mengakses method2,varibel2 yg
ada di dlm abstract class, dan kita tidak ingin menginstasiasi
class abstract karena hanya berisi interface/ template method
yg digunakan oleh Child class atau implement dari kelas lain
caranya membuat abstract class yaitu:... |
67672fe727895f8474674f5adaabba5b0d6ebc3c | chrisesharp/aoc-2019 | /day22/shuffle.py | 1,167 | 3.671875 | 4 | def new_stack(stack):
return stack[::-1]
def increment(stack, point):
i=0
new_stack=[0]*len(stack)
while stack:
new_stack[i]=stack.pop(0)
i = (i+point)%len(new_stack)
return new_stack
def cut(stack, point):
return stack[point:] + stack[:point]
def shuffle(input, stack):
fo... |
c2f70acc01adc3d01cc526e360a9815106306225 | Farhajaleel/pythonProject | /CO1/15_color_list.py | 388 | 4.03125 | 4 | # printout all colors from color list 1 not contained in color list 2
color_list_1 = ["red", "black", "green", "yellow", "silver", "orange"]
color_list_2 = ["blue", "white", "silver", "gold", "grey", "black"]
print("Color list 1:", color_list_1)
print("Color list 2:", color_list_2)
print("Colors for list 1 not contain... |
1fd54da0f0cc4637cde869459ef78da07f149062 | nozimica/engin310-python | /scripts/e10while01.py | 608 | 4.1875 | 4 | # -*- coding: cp1252 -*-
# creo un arreglo vaco
valores = []
# le solicito nmeros al usuario
num = raw_input('Ingrese un nmero ("" para terminar): ')
# mientras no me entregue un ""
while num != "":
# lo recibido lo convierto a nmero y lo agrego al arreglo
valores = valores + [float(num)]
# vuelvo a soli... |
f3327f6aa558461947f302d1af4773efc8603305 | petrLorenc/python-academy | /lesson5/for_search_solution.py | 626 | 3.5 | 4 | text = '''
Situated about 10 miles west of Kemmerer,
Fossil Butte is a ruggedly impressive
topographic feature that rises sharply
some 1000 feet above Twin Creek Valley
to an elevation of more than 7500 feet
above sea level. The butte is located just
north of US 30N and the Union Pacific Railroad,
which traverse the va... |
d4a3be7ad09be93d0645c159c1466227328d845b | zaldeg/codewars | /test2.py | 548 | 3.578125 | 4 | def mmultiply_matrix(a, b):
return [
[a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],
[a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]],
]
Q = [[5, 3], [2, 2]]
print(multyply_fib(Q, Q))
# def multiply_matrix(a, b):
# result = [... |
e21f0d7ab06ae4dc4d762ad2aea683637d955dd5 | Deepika-Purushan/Python_Activities | /Activity6.py | 152 | 4.25 | 4 | """
Using Loops:Write a Python program to construct the following pattern, using a nested loop number.
"""
for i in range(10):
print(str(i)*i) |
ad65e56b799b7555daef91086c11e1f62a2e2466 | youguanxinqing/RoadOfDSA | /算法训练营/07-递归/098/中序遍历-数组法.py | 707 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=98 lang=python3
#
# [98] 验证二叉搜索树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
ca... |
6dd6b2974cdffcfcecf4b6b3336cee1dad6791b7 | Trolley33/python-dump | /misc/bottles.py | 270 | 3.671875 | 4 | import sys
import time
for i in range(1,100):
if 100-i>1:
plural="bottles"
else:
plural="bottle"
print("{0} {1} of beer on the wall, {0} {1} of beer, take one down, pass it around and there's {2} {1} of beer on the wall.".format(100-i,plural,99-i))
time.sleep(2) |
db221f00ffccda25f7f8bed0932f799371bd7982 | AbiramiRavichandran/DataStructures | /Tree/SortedLevels.py | 956 | 4.125 | 4 | import queue as Q
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def print_levels(root):
if not root:
return
current = Q.PriorityQueue()
next_ = Q.PriorityQueue()
q = [root]
current.put(root.data)
while q:
n = len(q)
... |
0011695dc9c6a08a901af7bfc4ddd34aba0c8034 | morluna/Elements-of-Software-Design | /Assignment 10/ExpressionTree.py | 4,423 | 3.796875 | 4 | # File: ExpressionTree.py
# Description: This program performs creates a tree from a given expression and computes the answer
# Student's Name: Marcos Ortiz
# Student's UT EID: mjo579
# Course Name: CS 313E
# Unique Number: 51320
#
# Date Created: 11/28/2016
# Date Last Modified: 12/02/2016
import time
import ... |
a4cd2fbdd29b59173ca9b76b4176fa116d6f5523 | aruzhansadakbayeva/WebDevelopment | /lab7/task1/informatics/b/e.py | 87 | 3.78125 | 4 | a=int(input())
b=int(input())
if a>b: print('1')
elif b>a: print('2')
else: print('0')
|
810488225eb5feaf2a6910a6e118588fee7ebaa3 | aoyono/sicpy | /Chapter2/exercises/exercise2_17.py | 542 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_thm_2.17
"""
from Chapter2.themes.lisp_list_structured_data import car, cdr, lisp_list
def last_pair(l):
if cdr(l) is None:
return car(l), # Simulates the fact that we don't really include None in a pair
retur... |
469432e7affd422c94b193a248d18439e7bfd324 | Ddjones001/data_structures | /Binary Search.py | 1,779 | 3.96875 | 4 | def binary_search(search_list, number_to_find):
left_index = 0
right_index = len(search_list) - 1
mid_index = 0
while left_index <= right_index:
mid_index = (left_index + right_index) // 2
mid_number = search_list[mid_index]
if mid_number == number_to_find:
... |
119f1c4dfbeada760dd06813f558f3ae8c0a06aa | acc-cosc-1336/cosc-1336-spring-2018-zachdiamond000 | /src/midterm/main_exam.py | 478 | 4.375 | 4 | #write import statement for reverse string function
from exam import reverse_string
'''
10 points
Write a main function to ....
Loop as long as user types y.
Prompt user for a string (assume user will always give you good data).
Pass the string to the reverse string function and display the reversed string
'''
again =... |
0e9b6a9547e046df55d884f4835fbbf35d616ff8 | TemistoclesZwang/Algoritmo_IFPI_2020 | /exerciciosComCondicionais/A_CONDICIONAIS/02A_EX21.py | 642 | 4.15625 | 4 | # 21. Realize arredondamentos de números utilizando a regra usual da matemática: se a parte fracionaria for
# maior do que ou igual a 0,5, o numero é arredondado para o inteiro imediatamente superior, caso
# contrario, é arredondado para o inteiro imediatamente inferior.
def main():
numero = float(input('Insira u... |
ca79c72bf7984495c76f125f202a180844e5e73d | masinogns/boj | /algorithm/2.Data_Structure_1/BOJ_basic_17.py | 1,033 | 3.90625 | 4 | """
BOJ_basic_14 : 스택 문제 참고
"""
if __name__ == '__main__':
queue = list()
N = int(input())
for numbers in range(N):
InputCommand = list(input().split())
queueSize = len(queue)
if InputCommand[0] == "push":
queue.append(InputCommand[1])
elif Inpu... |
ba19336f4b2654f456a2f435d1d899d2ac785f75 | Tamara-Adeeb/Python_stack | /_python (the underscore IS IMPORTANT)/python_fundamentals/For_Loop_Basic II.py | 3,383 | 4.34375 | 4 | #Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big".
def biggie_size(a):
for i in range(len(a)):
if a[i] > 0:
a[i] = "big"
return a
print(biggie_size([-1, 3, 5, -5]))
#Count Positives - Given a list of numbers, create a function to replace th... |
8263dd504d7433ff0675ffb7ceec09458898ee51 | dkarpelevich/checkio | /BLIZZARD/when-is-friday.py | 410 | 3.59375 | 4 | from datetime import date
def friday(day):
day = day.split('.')
day_number = date(int(day[2]), int(day[1]), int(day[0])).weekday()
return 4 - day_number if day_number <= 4 else 4 - day_number + 7
if __name__ == '__main__':
print(friday('23.04.2018'))
assert friday('23.04.2018') == 4
assert fr... |
2a3942dca2863ed0f528cd6584cc0d1965edecb8 | jialing3/corner_cases | /Relue/Eu94.py | 1,997 | 4 | 4 | '''
let x be the length_of_two_sides
then height = sqrt( (1.5 x +/- 0.5) (0.5x -/+ 0.5) )
if x is even, then height needs to be even
if x is odd, then height needs to be int
for y in range(1, 10 ** 9 // 4 + 1)
x = 2y covers the even cases
x = 2y + 1 covers the odd cases
but, the *real* problem here is there exists
a ... |
1289e1e6dd504cdb526fe5b96204ed34ca52614a | YtrioSalmitoAzevedo/URI-Online-Judge | /Iniciante/1044 Múltiplos.py | 183 | 3.578125 | 4 | multiplos = raw_input().split(" ")
a, b = multiplos
a, b = int(a),int(b)
if a > b:
mm,m=a,b
else:
mm,m=b,a
if mm % m == 0:
print "Sao Multiplos"
else:
print "Nao sao Multiplos"
|
d4b85a537febb709f164519d3a58836be0891b40 | Clockwork757/DragonHacks-2018 | /US_CODE/Room.py | 2,667 | 3.734375 | 4 | #========================================
#Project Name: Room Type/Size
#Date: 04/15/2017
#Programmer Name: Matthew Marschall
#Modified: 01/06/2018
#Modifier: Dresden Feitzinger
#========================================
import numpy as np
class Point:
''' Return a cartesian coordinate point '''
d... |
124de78de94d4ab0034424507a42b7add24b8dcc | amyamyc/SI507_Project1_Flask | /SI507_project_1.py | 1,308 | 3.609375 | 4 | from flask import Flask
from lab3_code import *
app = Flask(__name__)
@app.route('/')
def home():
return 'Just the home page, nothing interesting.'
@app.route('/bank/<name>')
def see_new_bank_name(name):
new_bank_name = Bank(name, Dollar, 0)
return "Welcome to {}".format(new_bank_name.name)
@app.route('... |
5cad1d316bb02c8e06138912df0513bd195cba60 | yjh8806/python-2019-July | /13일/15.함수/03.function.py | 485 | 3.921875 | 4 | def odd_even(num):
if num % 2 == 0:
print("짝수입니다.")
else:
print("홀수입니다.")
num = int(input("정수 입력 : "))
odd_even(num)
def total(a):
result = 0
for i in range(1, a + 1):
result += i
return result #반환값
print("누적합계 : %d"%total(10))
#제곱
def power(a, b):
... |
5e09da630f90f1e76706d15fccae24f133d6f750 | modelarious/Artificial_Net_Simple | /inputFuncs.py | 6,226 | 3.84375 | 4 | import pandas as pd
import numpy as np
import sys
def get_Samples(data='Balance_Data.csv', categorical=True):
'''
read in a csv file
must have a column named 'class'
must have the same number of features for each training example
any holes in data must have value NaN
if categorical is Fals... |
3cbd0542b51c0f128b56179bb64919b839b1c697 | basharbme/BioPrinterGCode | /Generator/tkinter_utils.py | 4,409 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import * # from x import * is bad practice
from ttk import *
import Tkinter as tk
# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
# Button with press and release events
class HoldableButton(Button):
def __init__(self, root, text="hold me"):
... |
7757dafa1e43e0f7c69b94e95e32a3522f000c24 | NC-Coyote/Portfolio | /Digit Recognizer - Convolutional Neural Network/digitRecognizer.py | 4,912 | 4.09375 | 4 | # Handwritten digit recognition for MNIST dataset using Convolutional Neural Networks
# Step 1: Import all required keras libraries
from keras.datasets import mnist # This is used to load mnist dataset later
from keras.utils import np_utils as npu # This will be used to convert your test image to a categorical class (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.