blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
57356847d907e2c4d10f2fe3964cb487afe2b49e | Hvbyte/cursoemvideo-PYTHON | /Exercicios/ex74_maior_e_menor_valor.py | 252 | 3.5 | 4 | from random import randint
n = (randint(1,10), randint(1,10),randint(1,10),randint(1,10),randint(1,10))
print(f'Os valores sorteados foram:{n[0:]}',)
print(f'O maior valor sorteado da tupla foi: {max(n)}')
print(f'O menor valor sorteado foi: {min(n)}') |
3d60f139b4d129e00fd3b15fa6b8cd9a7f9e631d | CalPolyUROV/UROV2018 | /raspi/UI_p3/serial_finder.py | 1,481 | 3.515625 | 4 | import glob
import sys
import serial
from sys import platform
#finds all serial ports and returns a list containing them
#@retval: a list containg all the serial ports
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:return... |
f4fd83b935617035f159a1580410610da518af86 | netogalindo/python_fundamentals | /ErrorsPython.py | 962 | 4.1875 | 4 | # Errors help you track down problems and where and how they happened
# It's not ideal to be showing error results to users, but it's great to use them when you're testing the program
def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("Divisor cannot be zero")
return dividend / di... |
ee95ff1d5ce0560fe62ef40f8c5852b42dd03f63 | Aasthaengg/IBMdataset | /Python_codes/p02909/s944982538.py | 98 | 3.65625 | 4 | s = input()
list = ["","Sunny","Cloudy","Rainy"]
result = list.index(s)%3
print(list[result+1]) |
66746069ea4d4b27a324f241a74714fbde2a0319 | shuaijunchen/Python3 | /basic/string_io.py | 298 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from io import StringIO
f = StringIO()
print(f.write('hello'))
print(f.write(' '))
print(f.write('world!'))
print(f.getvalue())
s = StringIO('Hello\nHi\nGoodbye!')
while True:
string = s.readline()
if string == '':
break
print(string.strip()) |
6c6ec4e9d94cab10e04e795ab3dd835944194342 | suprita-hadimani/MyPythonCode | /prime number.py | 237 | 4.09375 | 4 | num=int(input("enter a number"))
if num >1:
for i in range(2,num):
if(num%i)==0:
print(num,"is not a prime")
break
else:
print(num,"is prime")
else:
print(num,"is not prime")
|
b7c9887e5013fe2899026c239c6007aec857f0d0 | pkula/music_lib | /display.py | 1,491 | 3.59375 | 4 | import file_handler
from prettytable import PrettyTable
def display_the_menu_options():
print("Press '1' to view all albums")
print("Press '2' to find an album by genre")
print("Press '3' to find an album by length")
print("Press '4' to find an album by artist")
print("Press '5' to find an album b... |
dc840d524206783ad84bd0f5461aef6d60f8828b | Trietptm-on-Coding-Algorithms/projecteuler-1 | /Problem9.py | 1,408 | 4.34375 | 4 | #! /usr/bin/env python
# conding: utf-8
"""\
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, \
\
a2 + b2 = c2 \
For example, 32 + 42 = 9 + 16 = 25 = 52.\
\
There exists exactly one Pythagorean triplet for which a + b + c = 1000. \
Find the product abc.\
Note that:
a = k * (m**2 - n**2)
... |
c98e5022dee0b5f4070c8230051c292e330fc35b | r-martin-/Code_College | /Exercise_code/100_exercises/Simple_GUI.py | 556 | 3.671875 | 4 | """
simple GUI programe
"""
from tkinter import *
class App():
def __init__ (self,master):
frame = Frame(master)
frame.pack()
self.button = Button(frame,
text = "Quit", fg = "blue",
command = frame.quit)
self.button.pack(side=LEF... |
30da0b9c4558326cd76d1169bbc06e01e82bcbf9 | cmu-delphi/nowcast | /src/fusion/opt_1d.py | 2,831 | 3.59375 | 4 | """
===============
=== Purpose ===
===============
Provides derivative-free optimization over a bounded, one-dimensional interval.
The function to optimize doesn't have to be convex, but it is assumed that it
has a single maximum and is monotonically decreasing away from that maximum in
both directions.
More genera... |
f790300971d8deb93e1e7f4398a68904d8ad091c | pflun/advancedAlgorithms | /characterReplacement.py | 1,473 | 3.609375 | 4 | # For a window s[l:r+1], if r - l + 1 - max_freq of s[l:r+1] <= k, we can perform
# at most k operation and change it to a string with repeating characters.
class Solution:
def characterReplacement(self, s, k):
counts = collections.Counter()
start = res = 0
# We use a window ranging from in... |
a4ee11832307f7b20003b9241dcfc42fe1d67981 | tiewangw/Python | /MachingLearning/chapter7/7.6 dt_weekday_name.py | 480 | 3.859375 | 4 | # 求一个日期向量中的每一个日期是星期几
import pandas as pd
dates = pd.Series(pd.date_range('2/2/2021',periods=5,freq='M'))
print(dates)
# 0 2021-02-28
# 1 2021-03-31
# 2 2021-04-30
# 3 2021-05-31
# 4 2021-06-30
# 查看星期几
print(dates.dt.weekday_name)
# 0 Sunday
# 1 Wednesday
# 2 Friday
# 3 Monday
# 4 Wed... |
8ee188301aee58affc0c241cd01161057070c2c8 | Info-lite/infolite | /contents/python/basic/04/prog/04_07.py | 170 | 3.5625 | 4 | junishi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']
year = int(input("Please input year: "))
print(junishi[(year % 12) - 4])
|
06fcad9592271a9f47e38d854457f96496bdb7a0 | tronov/csc_python | /6_classes/08_isinstance.py | 315 | 3.828125 | 4 | class A:
pass
class B(A):
pass
class C(B):
pass
a = A()
b = B()
c = C()
# Never do so
print(type(b) == A)
# Is instance of the class B is an instance of the class A?
print(isinstance(b, A))
# Is instance of the class B is an instance of the class A or the class C?
print(isinstance(b, (A, C)))
|
765e9cbcd68f3ac98cf7f62fe36e5dcfcc8756f3 | suflorcita/peuler | /p13.py | 326 | 3.65625 | 4 | # Enunciado : Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
# Escribo los números que dice el enunciado a un archivo txt
txt = open('peuler/num.txt','r')
num = 0
sum = 0
remainder = 0
for line in txt:
num = int(line)
sum += num
print(str(sum)[:10])
txt.clos... |
60b9af30be744aec3de24fd4f422c688570644f3 | toufiq007/Python-Tutorial-For-Beginners | /chapter eleven/args_as_arguement.py | 452 | 4.28125 | 4 |
# Args as arguements
def multiply_nums(*args):
print(args)
print(type(args)) # [1,2,3,4,5]
mutiply = 1
for i in args:
mutiply *= i
return mutiply
# when you pass a list or tuple by arguemnts in your function then you must give * argument after give your list or tuple name
number = [1,... |
5f04201e817ceb0b53cc17413de06885de944d70 | alexcaxtro/intro_python | /ejercicio1_100.py | 335 | 3.984375 | 4 | for i in range (1,101):
if i % 3 == 0:
if i % 5 == 0:
print("HolaMundo")
else:
print("Hola")
elif i % 5 == 0:
if i % 3 == 0:
print("HolaMundo")
else:
print("Mundo")
else:
print(i) ... |
6388a90b0d58f016d6e44efff2973704c4052e1b | mamunam/GRDB | /function practice assignment.py | 1,316 | 4.15625 | 4 | #function practice assignment
#1
def factorial(n):
result=[]
import math
result=math.factorial(n)
return result
factorial(5)
#2 - prime number is not divisible by anything
def is_prime(x):
n = 2
if x < n:
return 'Is not a prime number'
else:
while n < x:
... |
40ed2415582d98c2e9ee78a7492fc56fc5145331 | AmulyaVuon/Test | /_init_example.py | 438 | 4 | 4 | class person:
def __init__(self, name, age):
self.name=name
self.age=age
def myfunct(self):
print("hello my name is" + self.name)
p2 = person("amulya", 213)
p2.myfunct()
print(p2.name)
del p2.age
print(p2.age)
class Person:
def __init__(self, name, age):
self.name = name
... |
2737b645e588ae12b9e6c5d02f8503551cd91ebe | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/024分解数字-递归.py | 384 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-13 12:31:32
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : http://bbs.fishc.com/space-uid-437297.html
# @Version : $Id$
result = []
def get_digits(num):
if num > 0:
result.insert(0, num % 10)
get_digits(num // 10)
nu... |
dc14b76a4d39ff29617ca978063ad24645a8e165 | stephclleung/Quote-Guessing-Game | /scraping_project.py | 3,272 | 4.0625 | 4 | # Python 3 practice
# This script grabs data from http://quotes.toscrape.com
# and generates a guessing game.
import requests
from bs4 import BeautifulSoup
from random import choice
def makeHints(author, about_soup):
hints = []
# First , last name initials
hints.append(f"This person's first name begins with the le... |
7a9114aab8737041db4323959b492568d1097b06 | veekaybee/wired | /wired.py | 421 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import urllib2
from bs4 import BeautifulSoup
import re
address = "http://www.wired.com/2015/10/how-to-switch-android-ios/"
response = urllib2.urlopen(address)
soup = BeautifulSoup(response,"lxml")
paragraphs = soup.find('article').find_all('p')
for paragraph in paragraphs:
print paragraph.t... |
83bc714006db2bc4acf5fe469a276575c1176ab6 | chaitanyambilgikar/B551-Fall-2012 | /Homeworks/hw5/gridmap.py | 3,615 | 3.765625 | 4 | import math
from astar_fibheap import AStar
def gridcells(w,h,obstacles):
"""w,h are width, height
obstacles a list of x,y-coord 2-tuples.
Returns a w-by-h list of lists
Cells have value True except for x,y in obstacles, which
are False"""
cells = [[True]*w for i in xrange(h)]
for (x,y) in obstacle... |
fabba18f54cd1303a9da1b2b2bcec9b70648df8d | iwawomaru/Noh | /noh/wrapper.py | 4,252 | 3.546875 | 4 | from noh.component import Component
class Binder(object):
""" Binds a constant value to a keyword argument.
Given a key-value pair on instantiation, binds the value as a constant value
to a keyword argument for the bound :class: `Component`.
"""
def __init__(self, **kwargs):
self.args = ... |
cffa864c6fe6736d4672c5c0eb13a38a629a6c59 | mandos1995/online_judge | /BOJ/단계별로 풀어보기/ch03_for문/10871_X보다 작은수.py | 348 | 3.640625 | 4 | '''
문제
정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.
'''
# solution
N, X = map(int,input().split())
A = list(map(int,input().split()))
A_ = []
for i in A:
if i < X:
A_.append(i)
print(*A_, end=' ') # list 출력 방식
|
7e3f2589581688ed265f565877de11dfb32b986b | Gullesnuffs/StreetView-AI | /py/generate.py | 1,665 | 3.6875 | 4 | """
Script that generates a test case from a given place.
Uses Open Street Map data through the OSMnx python API.
Takes as input in seperat lines the place to generate the
graph from the total time in seconds and the number of cars
to be included in the test case.
problem:
- If a street is directed we... |
67afed30c35b6c08f00099bd27dd8b47c4cf2cd1 | sweersr/visions | /src/visions/application/summaries/frame/dataframe_summary.py | 437 | 3.6875 | 4 | import pandas as pd
def dataframe_summary(df: pd.DataFrame) -> dict:
"""Summarization for a DataFrame
Args:
df: a DataFrame object to summarize
Returns:
Summary of the DataFrame with `n_observations`, `n_variables` and `memory_size`.
"""
return {
"n_observations": df.shap... |
1c0ee328b472ec1f7607ca6e12d8dd41d03fcbb8 | anurag2301/artificial_intelligence | /spam_classifier_and_topic_classification/part1/spam.py | 31,180 | 3.671875 | 4 | # Considered abc@xyz as a single word rather that 2 words, as the accuracy is better this way
# Also, considered http:abc as a word as the accuracy is better
# Assumes pickle can be used. Used to save decision tree as an object
#
#
# Model 1: Word as a binary feature
# Probability for a word appearing in spam mail is c... |
70e5d19574c1549b11b542bc746d264a1e479af3 | LUCIA-RONCHI/Python_Assignment3 | /example_pkg/salad.py | 1,984 | 3.59375 | 4 | class salad():
import os
import glob
import re
# Initialize class
def __init__(self):
self.path = ""
self.salad_ingredients = []
self.n_items = []
# Define function to write files
def write(self, path, salad_ingredients, n_items):
# Set path to read and wr... |
c11246bf3dd6625fe3b478fa00d7eeab1a8c5f6f | GPegel/AdventOfCode_2019 | /Day1/calc_02.py | 448 | 3.671875 | 4 | with open(r'input.txt', 'r') as file:
input = file.read().strip().split('\n')
def fuel_required(weight):
return max((weight // 3) - 2, 0)
print("Day 1, Part 1 :", sum([fuel_required(int(x)) for x in input]))
def fuel_extra_weight(weight):
fuel_req = max((weight // 3) - 2, 0)
if fuel_req == 0: return ... |
0403af913f47bb61a53112a280e0f382420095f0 | jxie0755/Learning_Python | /LeetCode/LC092_reverse_linked_list_ii.py | 2,040 | 4.03125 | 4 | """
https://leetcode.com/problems/reverse-linked-list-ii/
LC092 Reverse Linked List II
Medium
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
"""
from A01_ListNode import *
class Solution_A:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
... |
aefd84f57fb5a9d70c20565ddc9cf43cbea3346b | west789/Algorithms-notes | /A-141-环形链表/hanCycle.py | 532 | 3.765625 | 4 | class ListNode(object):
def __init__(self, x):
self.value = x
self.next = None
class Solution(object):
def hasCycle(self, head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
... |
906ed2711093daad58f56e51c9e78d2665dd6c80 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/3006.py | 951 | 3.703125 | 4 | def parse_line():
plus_minus, flipper_size = input().strip().split()
pancakes = [(False if ch == '-' else True) for ch in plus_minus]
flipper_size = int(flipper_size)
return pancakes, flipper_size
def flip(i, pancakes, flipper_size):
for j in range(i, i + flipper_size):
pancakes[j] = not pa... |
341cd42fd36db17f4c5b8df11ff4f0dbf5d26bd1 | dstada/Python | /[Challenge] Calculate the Distance.py | 830 | 3.890625 | 4 | import math
from re import match
# check input
format = "^[^,\D]*,[^,\D]*$" # must be two numbers separated by a comma
while True:
coordA = input("Give x and y of the FIRST point, separated by a comma: ")
print(coordA)
if match(format, coordA):
break
else:
print("Wrong. Try again... |
c2cd004ee6b88724c5fc8aa5986203b4e43aefa2 | dlogushiv/AutomationTrainee | /OOP/Figures/Ellipse.py | 478 | 3.5625 | 4 | from OOP.Figures.Figure import Figure
from math import pi, sqrt
class Ellipse(Figure):
def __init__(self, name, colour, width, height):
super().__init__(name, colour)
self.width = width
self.height = height
def perimeter(self):
a = self.width // 2
b = self.height // 2
... |
9d22463fbe088165a0b45f613a2107aae4c10cb1 | lizetheP/PensamientoC | /programas/menu_Lab_Matrices.py | 1,552 | 3.90625 | 4 | import random
def crea_matriz(renglones, columnas):
matriz = []
for i in range(renglones): #numero de listas
matriz.insert(i, [])
for j in range(columnas): #número de elementos de cada lista
valor = int(input("Introduce un valor: "))
matriz[i].insert(j, valor)
return... |
6b7cb4806b5aa784f58a9e2d9d17eea8e3c85c6e | ter031/GitDemo | /StringsDemo.py | 196 | 3.640625 | 4 | str = "deepakthakursdet"
str1 = "bilaspur"
str3 = "thakur"
print(str[0:6])
print(str+str1)
print(str3 in str)
var = str.split("h")
print(var)
print(var[1])
str4 = " asddf "
print(str4.rstrip()) |
1a3facffab2591cf1c386c1ff67e04d6d5ca94da | Dana-Lucas/Data-Science | /Lucas HW6-1.py | 542 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 7 23:43:03 2020
@author: Dana
Q2.7.3
"""
def digit_sum(n):
""" Find the sum of the digits of integer n. """
s_digits = list(str(n))
dsum = 0
for s_digit in s_digits:
dsum += int(s_digit)
return dsum # This definition doesn... |
218c9b35c61b47d9bae5d851c07c293653906988 | daniel-reich/turbo-robot | /ic9aKYukaRH2MjDyk_23.py | 816 | 4.375 | 4 | """
Create a function that takes a string of words and return a _string_ sorted
alphabetically by the _last_ character of each word.
### Examples
sort_by_last("herb camera dynamic") ➞ "camera herb dynamic"
sort_by_last("stab traction artist approach") ➞ "stab approach traction artist"
sort_by... |
03391a21b02bc2c137ed3dc24d5a9dc952374866 | Izavella-Valencia/programacion | /Clases/edad.py | 426 | 3.84375 | 4 | #-----entradas-----
MENSAJE_BIENVENIDA = "Hola, como estas?"
PREGUNTA_EDAD = "¿cuantos años tienes? :"
MENSAJE_MAYOR_EDAD = "Eres mayor de edad, puedes seguir"
MENSAJE_MENOR_EDAD = "Eres menor de edad, no puedes seguir"
#------entrada de codigos------
print (MENSAJE_BIENVENIDA)
edad = int (input(PREGUNTA_EDAD))
isMayo... |
7050a20e4a5b1c72146a43934c85d5503a512af6 | freedream520/tkinter-5 | /combobox_spin.py | 566 | 3.5625 | 4 | #compo box and spin button
from tkinter import *
from tkinter import ttk
root = Tk()
month = StringVar() #variable
combobox = ttk.Combobox(root, textvariable = month)
combobox.pack()
#enter the values
combobox.config(values = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'))
#select... |
cb6f895f112f3ea7a5b2a9686c7d07f8efb032b3 | RomanPutsilouski/M-PT1-37-21 | /Lessons/lesson 03-15/input_example.py | 66 | 3.59375 | 4 | x = input('input your value: \n')
print(type(x))
print(float(x)+2) |
298f4e7d60807b294e226eb218292428f45db749 | Vatsal272120/pythonProblems- | /Problem Solving Patterns/Sliding Window/FirstNegative.py | 245 | 3.65625 | 4 |
def firstNegative(arr, k):
negative = []
for num in arr:
if num < 0:
negative.append(num)
return negative
s = firstNegative([12,-1,-7,8,-15,30,16,28], 3 )
print(s)
|
78cabae95380788ba88eaf9a4ac79dddd332f7ad | RyanLawWilson/The-Tech-Academy-Basic-Python-Projects | /TkInter/Phonebook/phonebook_main.py | 1,097 | 3.578125 | 4 |
import tkinter as tk
from tkinter import *
import tkinter.messagebox # messagebox won't work unless it is imported explicitly
import phonebook_func
import phonebook_gui
# ParentWindow is a tkinter frame - alows us to use tkinter objects
class ParentWindow(Frame):
def __init__(self, master, *args, **kwargs):
... |
28af37d3dcff3099940740fafff2e35adfa7b1ae | rifat6991/Projects- | /Python/Practice/Eg/Simple_Programs/test.py | 90 | 3.71875 | 4 | while True:
a = float(input("enter a float value:"))
b = int(a)
print (b)
|
ea8e8eb99ab6fd312e8f09680a7d657aaee28956 | keerthireddyk/pythonprogrames | /sum of natural.py | 71 | 3.671875 | 4 | i=int(raw_input())
sum=0
for x in range(1,i+1):
sum=sum+x
print(sum)
|
c5e030d64f5e49535370c26fae00044eb2237755 | alabarym/Python3.7-learning | /021_string_contain_symbol.py | 340 | 4.03125 | 4 | def does_contain(string, symbol):
counter = 0
while_counter = 0
while while_counter < len(string):
current_char = string[while_counter]
if current_char == symbol:
return True
while_counter += 1
return False
print(does_contain("sansa stark", "s"))
print(does_contain("... |
c7ac0292c652adda3ceb85a965532aaf6d638e16 | fredhu0514/Py2Mat | /processor/filter.py | 1,693 | 3.734375 | 4 | class Filter:
@classmethod
def tab_filter(cls, line):
"""
This is the function takes single line,
and return the num of tabs in front of the line,
and return the content after indentations.
"""
count = 0
for character in line:
if character ==... |
20b284183a411e89a9bac8f0592f1dce6e75a5aa | kkangjiyo/- | /0527/glueCode1.py | 327 | 3.890625 | 4 | def f1(x):
return (x + 1, str(x) + "+1")
def f2(x):
return (x + 2, str(x) + "+2")
def f3(x):
return (x + 3, str(x) + "+3")
x = int(input("정수 입력 : "))
log = "Ops:"
res, log1 = f1(x)
log += log1 + ";"
res, log2 = f2(res)
log += log2 + ";"
res, log3 = f3(res)
log += log3 + ";"
print(res, log) |
779158215a4ba7069b8d380a8431142b4d93d190 | YACHUENHSU/BMI | /BMI.py | 422 | 4.0625 | 4 | Height = input ('請輸入身高(單位公尺): ')
Height = float (Height)
Weight = input ('請輸入體重(單位公斤): ')
Weight = float (Weight)
BMI = Weight / (Height * Height)
print ('你的BMI是: ', BMI)
if BMI >= 24 and BMI < 27:
print('過重')
elif BMI >= 27 and BMI < 30:
print('輕度肥胖')
elif BMI >= 30 and BMI < 35:
print('中度肥胖')
elif BMI >= 35:
prin... |
562616e41c71cb4db8679d34d3a5cca83c94f639 | Industrial-Functional-Agent/cs231n | /Assignment1/doogie/numpy_prac/Numpy_prac.py | 11,303 | 4.65625 | 5 | import numpy as np
# Arrays
# A numpy array is a grid of values, all of the same type, and is indexed by
# a tuple of nonnegative integers. The number of dimensions is the rank
# of the array; the shape of an array is a tuple of integers giving the size of the
# array along each dimension.
a = np.array([1, 2, 3]) # ... |
17d143a0a0b0dcbd6ba5c54a798547521e42b7ba | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/8ae47fe4115d4cff9d635a2df6d17ebb.py | 513 | 3.625 | 4 | def hey(question):
if len(question.strip()) == 0:
return "Fine. Be that way!"
hasWord = False
isShout = True
for w in question:
if w.isalpha():
hasWord = True
for c in w:
if c.isalpha() and not c.isupper():
isShout = False
... |
37bebcec11eb345bf74b9d593d9d9fc0d42902ca | Subarin38/MacGyver | /Object.py | 572 | 3.65625 | 4 | import random
from constantes import *
class Object:
def __init__(self, my_map):
"""Set parameters for Object."""
self.my_map = my_map
self.case_x = 0
self.case_y = 0
self.x = 0
self.y = 0
def randomize_position(self):
"""Generate a random position for... |
fd1d5e3608290354b06a031e4b8644b0447b63ef | Girishsh640/test1 | /basedondfs.py | 973 | 3.625 | 4 | xc=int(input("Enter the capacity of x"))
yc=int(input("Enter the capacity of y"))
xg=int(input("Enter the goal state of x"))
yg=int(input("Enter the goal state of y"))
bfs_tree={}
ol,cl=[(0,0)],[]
while((xg,yg) not in cl and len(ol)!=0):
x,y=ol.pop()
l,l1=[],[]
if(x==xg and y==yg):
cl.append((x,y... |
1593ea1f84d734a9994e837f655e80aa094bf820 | Beowulfdgo/HackerRank | /Grid Challenge.py | 437 | 3.609375 | 4 | n_test_cases = int(input())
for test in range(n_test_cases):
n_rows = int(input())
matrix = []
for row in range(n_rows):
new_row = input()
sorted_row = sorted(new_row)
matrix.append(sorted_row)
possible = "YES"
columns = [list(column) for column in zip(*matrix)]
for colu... |
b485263196b5f85a01c5ba90ff5f04d943c1d628 | DavidHromyk/Daves_Python_Code | /rock_paper_scissors.py | 3,970 | 3.953125 | 4 | import random
import os
import sys
player_wins = 0
computer_wins = 0
def check_win(choice, computer_choice):
global computer_wins
global player_wins
if choice == 1 and computer_choice == 1 or choice == 2 and computer_choice == 2 or choice == 3 and computer_choice == 3:
print('\nDraw!')
if cho... |
02261df0c0f3afbd32d7678cee88bded8ecded57 | binyao2020/Multi-package-delivery | /code/generate_instance.py | 1,983 | 3.59375 | 4 | '''
generate 3 random instances with 100 orders and uncertain customers
All customers are generated in a 2D planes [-50,50]*[-50,50], where depot locates at (0,0)
extract medium instances with 50 orders by considering the first 50 orders in the large instance
extract small instances with 25 orders by considering the f... |
56211ccf0e4573d2e4e5f278512581d5bbf48702 | SanchelliosProg/symbols-generator | /binary_search.py | 1,501 | 3.828125 | 4 | class Search:
max_num = 0.
min_num = 0.
search_num = 0.
is_integer = True
def __init__(self):
pass
def input_max_and_min(self):
self.max_num = raw_input("Enter max number: ")
self.min_num = raw_input("Enter min number: ")
self.change_type_of_numbers()
def i... |
cec278e1a42b2b56688bb3b582812945d743f029 | jessiecantdoanything/Week10-24 | /crypto.py | 1,489 | 4 | 4 | # Transposition Cipher
# encryption function
def scramble2Encrypt(plainText):
evenChars = ""
oddChars = ""
charCount = 0
for ch in plainText:
if charCount % 2 == 0:
evenChars = evenChars + ch
else:
oddChars = oddChars + ch
charCount = charCount + 1
ci... |
4d45a365370be614f2684d0ece7fec059f1ec46c | akashjnvlko/simulations-statistical-mechanics | /2-D random walk.py | 1,589 | 3.984375 | 4 | '''
Author: Akash Yadav
1710003
Integrated M.Sc Physics
National Institute of Technology, Patna
'''
# lets simulate random walk in two dimensions for one random walker
import random as rnd
import matplotlib.pyplot as plt
import numpy as np
import math
# we need a random dir... |
6004e73a0cdfdf9d902761cfc3859f339142151a | Djusk8/Exercism | /python/armstrong-numbers/armstrong_numbers.py | 162 | 3.671875 | 4 | def is_armstrong_number(number):
arm_number = sum([int(num) ** len(str(number)) for num in str(number)])
return True if arm_number == number else False
|
d8726cf4939f0fe2742dfb08fac1d68e9e3912db | Vitality999/HSE_1 | /Task_2.py | 545 | 3.984375 | 4 | # 2. (2 балла)
# Для двух строк l1 и l2, а так же числа n вывести строчку l3, состоящую из конкатенации l1 и l2, повторенной n раз.
# Например, для l1='hello', l2='world', n=2, l3 будет равно 'helloworldhelloworld'
l1 = str(input('Введите первое слово.\n'))
l2 = str(input('Введите второе слово.\n'))
n = int(input('Вве... |
cd4a78d45760abfcf6d7bba43a0d62bd6e69cdab | ayushiagarwal99/leetcode-lintcode | /leetcode/binary_tree/617.merge_two_binary_trees/617.MergeTwoBinaryTrees_JohnJim0816.py | 1,824 | 3.921875 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: johnjim0816@gmail.com
Date: 2020-08-30 09:56:11
LastEditor: John
LastEditTime: 2020-08-30 09:56:34
Discription:
Environment:
'''
# Source : https://leetcode.com/problems/merge-two-binary-trees/
# Author : JohnJim0816
# Date : 2020-08-30
#################... |
a5666cc6467b0fd6dce422e820166e91886fe315 | ideahitme/contest | /hackerrank/greedy/fucking_florist/code.py | 621 | 3.703125 | 4 | import sys
def calc_sum(start, end, prices):
sum = 0
for i in range(start, end):
sum += prices[i]
return sum
first_line = sys.stdin.readline().split()
num_flowers = int(first_line[0])
num_people = int(first_line[1])
prices = [int(num) for num in sys.stdin.readline().split()]
prices.sort()
if (num_people >= num_... |
c8596ab281e90e63307620c11fe5b704b973ecc3 | GianluigiPiluso/ColorDetectionClass | /ColorDetection.py | 7,749 | 3.640625 | 4 | #https://www.learnopencv.com/find-center-of-blob-centroid-using-opencv-cpp-python/
# Python program for Detection of a
# specific color(blue here) using OpenCV with Python
import cv2
import numpy as np
import math
import time
from Motor import *
#variabili globali
MOTOR_DUTY=900
AREA_MAX_RED=5000
AREA_MAX_GREEN=5... |
b3231c5057e02461202ec1d233f1e0afeffe8cdc | liojulien/pythonCode | /shuffle.py | 339 | 4.1875 | 4 | userMessage = input("Enter msg: ")
shiftValue = int(input("Enter a shift value: "))
encryptedMsg = ""
for character in userMessage:
if character.isalpha() == True:
x = ord(character)
x += shiftValue
encryptedMsg += chr(x)
else:
encryptedMsg += character
print("Encrypted message i... |
d20e87e93ed486a8cff1c719256c25239cb53edc | brydenu/forex-converter | /conversion.py | 1,442 | 3.75 | 4 | from forex_python.converter import CurrencyRates, CurrencyCodes
codes = CurrencyCodes()
rates = CurrencyRates()
class Conversion:
"""Creates all necessary information for conversion between two currencies"""
def __init__(self, curr_from, curr_to):
"""Calls forex_python methods to create all informat... |
b34583253c86472d3001b92a006dacf115eb13d2 | shivang-06/Python | /CodeChef Beginner/ATM.py | 134 | 3.609375 | 4 | (X, Y) = (input().split())
Y = float(Y)
nY = Y - 0.5
X = int(X)
if X % 5 == 0 and X <= nY:
print(nY - X)
else:
print(Y) |
fc5bc7a1e1669b3b34e7c649c3e496bd892706c5 | wiput1999/Python101 | /6 Extra 3/x1/3.py | 95 | 3.984375 | 4 | x = int(input("x : "))
y = int(input("y : "))
while y != 0:
r = x % y
x = y
y = r
print(x) |
665bc6b60323ec2e9a47aeb055ab1226b7ce6529 | colinbazzano/sorting-basics | /main.py | 1,423 | 3.71875 | 4 | import random
# def my_for_loop(n):
# print(n)
# my_for_loop(10)
# my_range = 1000
# my_size = 1000
# my_random = random.sample(range(my_range), my_size)
# # # print(my_random)
# # def print_number(n, arr):
# # print(arr[n])
# # print_number(4, my_random)
# def print_array(arr):
# for i in range(... |
b2e4c76c658062a612946c974febfcdac4d6d2d4 | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/practice4-solution/binary_tree.py | 14,561 | 3.875 | 4 | class Node:
def __init__(self, data, parent=None):
self.data = data
self.parent = parent
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = root
def __str__(self):
"""
algorithm:
- get row for each nod... |
2be806125efa1b33932ec5e7b2cce9fbffbae037 | falabretti/uri-online-judge | /python3/beginner/1006.py | 165 | 3.828125 | 4 | v1 = float(input())
v2 = float(input())
v3 = float(input())
v1 = v1 * 2
v2 = v2 * 3
v3 = v3 * 5
media = (v1 + v2 + v3) / 10
print("MEDIA = {:.1f}".format(media))
|
8552e2172e69897e46a6fbb55e4769143aff266b | cedadev/jasmin-workshop | /tutorials/tut02/code/extract-annual-max-series.py | 4,206 | 3.609375 | 4 | #!/usr/bin/env python
"""
extract-annual-max-series.py
=============================
Script to extract a time series of maximum temperature observations from
all measurements for a given county. The resulting time series is written
to an output file for later use.
Usage:
------
extract-annual-max-series.py <cou... |
4385b43237a1105391bd582fa119e2bc8b82871e | icesat2py/icepyx | /icepyx/core/temporal.py | 16,922 | 4.34375 | 4 | import datetime as dt
import warnings
"""
Helper functions for validation of dates
"""
def convert_string_to_date(date):
"""
Converts a string to a datetime object.
Throws an error if an invalid format is passed in.
Parameters
----------
date: string
A string representation for the ... |
02909b351abbc36c53ba3ec12652f87744f85aeb | nathanrogers18/vector-victor | /linear_algebra.py | 4,086 | 3.8125 | 4 | class ShapeError(Exception):
pass
def shape(vector):
"""shape takes a vector or matrix and return a tuple with the
number of rows (for a vector) or the number of rows and columns
(for a matrix.)"""
rows = len(vector)
if isinstance(vector[0], list):
cols = len(vector[0])
return (... |
754c0738fe96027a7e4b9a47ceecb7a1d24aa88c | pkrishn6/problems | /api/simpifyPath.py | 654 | 3.78125 | 4 | def simplifyPath(input):
if not input:
return ""
stack = []
if input[0] == '/':
stack.append(input[0])
for token in input.split('/'):
if token == "..":
if stack and stack[-1] == "..":
stack.append(token)
elif stack[-1] == "/":
... |
ab9dda317ff5c3e2f3505cd0f846916959b5a63f | lucaschf/python_exercises | /exercise_3.py | 924 | 4.0625 | 4 | # a) Faça uma função que receba duas listas e retorne True se são iguais ou False caso contrário.
# Duas listas são iguais se possuem os mesmos valores e na mesma ordem.
# b) Faça uma função que receba duas listas e retorne True se têm os mesmos elementos ou False
# caso contrário
# Duas listas possuem os mesmos elemen... |
c22e2eca8022ca27392a41b3e39b379d5c08783b | ppinko/python_exercises | /loops/hard_replace_with_next_largest.py | 609 | 3.90625 | 4 | """
https://edabit.com/challenge/kEww9Hjds5Zkgjyfj
"""
def replace_next_largest(lst: list) -> list:
L = sorted(lst)
return [- 1 if i == max(lst) else L[L.index(i) + 1] for i in lst]
""" Alternative solution """
def replace_next_largest(lst):
s = sorted(lst) + [-1]
return [s[s.index(i)+1] for i in ls... |
f5d82318aff82eae4419ff09f8fc8d8b5b9849dd | ankit12192/Data_scraper | /main.py | 342 | 3.75 | 4 | #Simple script which fetches links from a website and prints it , will be building on this script
import urllib2
from bs4 import BeautifulSoup
url = "http://newtonhq.com"
page = urllib2.urlopen(url)
soup = BeautifulSoup(page,"html.parser")
#print soup.prettify()
all_link = soup.find_all("a")
for link in all_link:
... |
7037f36d45457574265f00d58dbfdb134fa19158 | Telerivet/telerivet-python-client | /telerivet/datatable.py | 7,890 | 3.625 | 4 |
from .entity import Entity
class DataTable(Entity):
"""
Represents a custom data table that can store arbitrary rows.
For example, poll services use data tables to store a row for each response.
DataTables are schemaless -- each row simply stores custom variables. Each
variable name is e... |
513625d1b89a248603efa4c59343db7efcc15d8c | ducnhse130201/CTF-almost-Crypto- | /PTITCTF/Xor.py | 762 | 3.96875 | 4 | encrypted_flag = "7074497447744a9f736f619963746861942b9763659293956b68636b9393646c95676f636b9599979d".decode("hex")
grep = "PTITCTF{"
toGrep = ""
#loop to find hidden pad
string = encrypted_flag[:8]
for pad in range(1,21): # cause pad from the code is random from 0,20.So i starta loop to find it
for char in str... |
e0a7876f8fa476bf2e1b8f988e8fedefd5babd53 | java-abhinav07/MIT_6.00.1x | /Week_3/memoization.py | 474 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 21:24:12 2019
@author: javaa
"""
# fibonacci with a dict
def fib_efficient(n, d):
global numFibCalls
numFibCalls += 1
if n in d:
return d[n]
else:
ans = fib_efficient(n-1, d) + fib_efficient(n-2, d)
d[n] = ans
... |
bdf8b80928603cbb779465be636ec91319f02271 | anmolrajaroraa/core-python-july | /07-functions.py | 1,063 | 3.84375 | 4 | # def square(num):
# return num * num
# # print() # unreachable code
# # number = 849493
# # print(f"Square of {number} is {square(number)}")
numbers = list(range(1, 100))
# square_of_numbers = []
# for number in numbers:
# # sq = square(number)
# # print(f"Square of {number} is {sq}")
# square_o... |
ab05ae99cccd4c8f57fed3b85be81cdbe17a5189 | chunghyunhee/SimulatedAnnealing | /src/SA_algorithm.py | 2,801 | 3.71875 | 4 | import time
import random
import math
import numpy as np
## custom section
initial_temperature = 100
cooling = 0.8 # cooling coef.
number_variables = 2
upper_bounds = [3,3]
lower_bounds = [-3, -3]
computing_time = 1 # seconds
## custom objective function
def objective_function(X):
x = X[0]
y = X[1]
value ... |
6aec2dda318596761d3d96840b96f292e932aaf8 | kazuma-shinomiya/leetcode | /24.swap-nodes-in-pairs.py | 532 | 3.703125 | 4 | #
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[... |
458f4a731a663beb1d78abe2dbcdbfb34b400d99 | Tejas-Naik/Python-refresh-Mosh | /6formatted_string.py | 395 | 4.28125 | 4 | # Formatted strings are used to format strings the way we want
# If you wanna print John [Smith] is a coder!
first_name = "Tejas"
last_name = "Naik"
print(first_name + " ["+ last_name +"] is a coder")
# OMG Look at the code above do you understand that at the first glance?
# this is where the formatted strings come in... |
9d3e699e27b7863d638b98f22756bd20391c7dc4 | byteh/learn-python3 | /printfmt.py | 433 | 4.03125 | 4 | language=7
age=27
rice="rice"
print("Language %s: I am Python. What's for supper? %s haha."%(language,rice))
print ("His name is %s"%("Aviad"))
print ("He is %d years old"%age)
print ("His height is %f m"%(1.83))
print ("His height is %.2f m"%(1.83))
#指定占位符宽度
print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))
#... |
e7970f507b813ebe87d52c7f2b1a55b9fe582800 | domlobo/Upside-Down | /me/samfreeman/Helper/Line.py | 813 | 3.75 | 4 | from me.samfreeman.Helper.Vector import Vector
class Line:
def __init__(self, pointA, pointB, thickness):
self.pointA = pointA
self.pointB = pointB
self.thickness = thickness
def draw(self, canvas):
canvas.draw_line(self.pointA.getP(), self.pointB.getP(), self.thickness, "Blue... |
7f549ca326fd0d0ee8659234934f662429523506 | TheRootOf3/SACAT | /sacat_project/src/pretest/pre_tests.py | 2,291 | 3.515625 | 4 | """
To run the pretests, import your sorting algorithm, initialise a PreTest object
and use the method .run(your_sorting_algorithm). This method will return a string
but the return type can be modified for integration into the final program.
Note: exception handling is left to the run environment.
Written by Tim
"""
... |
e01a85ffc36560c32c8af6cb5e537b1a055f3afa | Kubyshina/Python | /Lesson1/3.py | 410 | 3.84375 | 4 | # 3. Узнайте у пользователя число n.
# Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
value = input("Enter the number:\n")
while not value.isdigit():
value = input("Input must be a number:\n")
result = int(value) + int(value+value) + int(value+value+value)
pr... |
ab56909e9ba08cb443fe4aacc913b796e6b717ad | JorgePerC/IntroToCV | /L0_displayImagVid.py | 852 | 3.625 | 4 | import cv2
print ("OpenCV imported")
#-------------------- Show still
img = cv2.imread("imgs/penguins.jpg")
# Create a window with the image on it
cv2.imshow("WindowName", img)
# Shows the img until the delay (0) in milis has passed
# However, if the delay is 0, then we have infinite delay
cv2.waitKey(0)
#-------... |
9cc44890a4b8a14981be8bc7c065e45f626e893e | mxmoca/python | /slice.py | 798 | 3.578125 | 4 | def split_name(s):
space = s.find(' ')
start = s[:space]
end = s[space+1:]
return start + '\n' + end
print( split_name('John Shaft'))
def bondify(name):
s = ''
space = name.find(' ')
start = name[space+1:]
return start + '... ' + name
print (bondify('Mr DW'))
def find_last(s, key):
... |
8e045ba5796229fc246d87c2122a33d27db0e35d | mishimingyue/hou | /algorithm/刷题/6_列表是链式存储.py | 1,110 | 3.796875 | 4 | hou = [1, 2, 3, 4]
for i in range(len(hou)):
print(id(hou[i]))
hou[2] = 9
for i in range(len(hou)):
print(id(hou[i]))
'''
(一)顺序存储结构和链式存储结构的优缺点比较,以及使用情况。
1 优缺点
① 顺序存储时,相邻数据元素的存放地址也相邻(逻辑与物理统一);要求内存中可用存储单元的地址必须是连续的。
优点:存储密度大(=1),存储空间利用率高。缺点:插入或删除元素时不方便。
②链式存储时,相邻数据元素可随意存放,但所占存储空间分两部分,一部分存放结点值,另一部分存放表示结点间关系的指针
优点... |
fa348b08b3b7831f758c66f9bf762129bc41de21 | alonsovidales/interview_questions | /division.py | 589 | 3.5625 | 4 | # a/b
def add(x, y):
a = True
while a:
a = x & y
b = x ^ y
x = a << 1
y = b
return b
def mult(a, b):
r = 0
for i in xrange(b):
r = add(r, a)
return r
def division(a, b, precission=0.001):
prev_guess = 0
guess = a
while abs(a - mult(guess, b... |
5814974c68e77953703e6f3accdb1275d838452f | florespadillaunprg/t07_flores.padilla | /flores/iteracion/ejercicio04.py | 271 | 3.6875 | 4 | # Sumar los "b" primeros numeros multiplicados por su mismo numero (i*i)
import os
b=int(os.sys.argv[1])
i=1
suma=0
while(i<=b ):
suma += i*i
i += 1
#fin_while
print("La suma de los", b," primeros numeros multiplicados por su mismo numero (i*i) es:", suma)
|
08ff587db3d1c034bd08474a0d65e15cf60a6971 | kafkalm/LeetCode | /LeetCode/19.py | 973 | 3.859375 | 4 | #!/usr/bin/env python
# encoding: utf-8
'''
@author: kafkal
@contact: 1051748335@qq.com
@software: pycharm
@file: 19.py
@time: 2019/1/29 029 17:09
@desc:删除倒数第N个链表节点
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def removeNthFromEnd(head, n):
"""
:type head: ListNo... |
b00bef7d3220543529d1848073c9fecb9f8d7cb2 | Aparecida-Silva/ExercicioProva2Bim | /Questão13.py | 508 | 4.15625 | 4 | '''
Faça um programa que peça dois números, base e expoente, calcule e mostre o primeiro
número elevado ao segundo número. Não utilize a função de potência da linguagem.
'''
base = eval(input("Digite um número: "))
expoente = eval(input("Digite um número: "))
x = 1
resultado = 1
while (x <= expoente):
resultado =... |
f23e249b418b0b659746c4114e4f6fc655bfab63 | EfrainDuarte95/quiz09 | /q4.py | 176 | 3.625 | 4 | #Efrain Duarte Lopez
def fib(n):
if n==0 or n==1:
return n
else:
a=0
b=1
for i in range(n-1):
c=a+b
a=b
b=c
return c
# tests added by Ken
print(fib(0))
print(fib(10))
|
08262d7914894fcbf8765922e709e74cb70180e8 | darkcode357/ctf_toolkit2 | /ctf/atualizar/files/python-prompt-toolkit/prompt_toolkit/reactive.py | 1,843 | 3.671875 | 4 | """
Prompt_toolkit is designed a way that the amount of changing state is reduced
to a minimum. Where possible, code is written in a pure functional way. In
general, this results in code where the flow is very easy to follow: the value
of a variable can be deducted from its first assignment.
However, often, practicali... |
47a446b255ffd1773f6a109ac80ede2b94c4e52b | Phabibi/Python | /Assignment 6/Peer/p.py | 412 | 3.890625 | 4 | # Own question
# Upper Fruit
# Parsa habibi
def Upperfruit(st):
i=0
n=''
count=0
while i<len(st):
if st[i].isalpha():
if st[i].isupper():
n=n+len(st[i])*"orange"+" "
count+=1
i+=1
if count==0:
res="No frui... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.