blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ae8896ff9726b1d799c479b5375e3d062d8d7f66 | Tompparella/advent_of_code_2020 | /1/1.1/summer.py | 1,432 | 4 | 4 | import re
FILENAME = "input.txt"
NUMBER = 2020
# I know this is not needed, but I just wanted to practice it.
def quickSort(A):
length = len(A)
if (length <= 1):
return A
else:
pivot = A.pop()
items_greater = []
items_lower = []
for i in A:
if (i > pivot):
... |
f98ce31673fa54ccc97af4eeef05ef884d1c546c | huangsusan/semantic-segmentation-deeplearning | /image_preprocessing.py | 5,293 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 14:34:19 2019
@author: david
"""
import cv2
import numpy as np
import math
IMG_SIZE = 256
def preprocess_image_array(image_array, attribute, method = "normalization"):
"""
This function preprocesses an image. Specifically, it adds padd... |
25642f9aaa261cd533eca023800b3033bf477eb1 | Welvis3004/Aprendendo-Python | /Aula07aD010.py | 105 | 3.640625 | 4 | din = float(input('Quanto Dinheiro: '))
print('Seus {} reais, são {} dolares.'.format(din, din / 3.27)) |
66bb9bdb591c2376f4a0bdc2dffa208e9e1b3f11 | Welvis3004/Aprendendo-Python | /Aula07aD011.py | 214 | 3.828125 | 4 | largura = float(input('Digite a Largura: '))
altura = float(input('Digite a Altura: '))
area = largura*altura
tinta = area/2
print('A area total é {} m², a tinta necessaria é {} litros.'.format(area, tinta)) |
5129f527113e00bb118249644dca1391fd0a09a6 | adam-nnl/AFootball | /Python Scripts/nflgame_weekly_stats-v1.1wQBselect.py | 7,380 | 3.578125 | 4 | """
Use nflgame api to pull out and compile stats. Export to .csv ready to be used with Erudite
"""
from decimal import Decimal, ROUND_DOWN
import nflgame
import csv
import itertools
print 'nflgame API loaded and updated'
week = raw_input('What week of the season, 1-17?: ')
filename = 'nfl_weeklystats_week' + str(wee... |
748825efefc202751e87b776381d332af0e8ebb1 | roisinod/password-generator | /password generator.py | 1,659 | 4.40625 | 4 | #Write a programme, which generates a random password for the user.
# Ask the user how long they want their password to be, and how many letters and numbers they want in their password.
import random
import string
lowercaseletters = list(string.ascii_lowercase) #creates a list of lowercase letters
uppercaseletters... |
b3c9dae68e4eb92eca3239d4f8810fa8e5765fac | IvanM1987/Algorithm | /Lesson_2/2.3.py | 545 | 4.34375 | 4 | # 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например,
# если введено число 3486, то надо вывести число 6843.
#
def endstart(newnumber, number):
newnumber = newnumber * 10 + number % 10
number = number // 10
if number == 0:
return print(newnumber... |
2b4761450e2f126281b903004a868ab39ee87ad8 | IvanM1987/Algorithm | /Lesson_3/3.2.py | 717 | 4.125 | 4 | # 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями
# 8, 3, 15, 6, 4, 2, то во второй массив надо заполнить значениями 1, 4, 5, 6 (или 0, 3, 4, 5 - если индексация
# начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа
import r... |
c66f32e740bf37584011cde15b355064e352118c | IvanM1987/Algorithm | /Lesson_1/1.5.py | 608 | 3.96875 | 4 | # 5. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят и сколько между ними находится букв.
a = ord(input('Введите 2 буквы англ. алфавита. \n'
'Введите букву, которая находится раньше по алфавиту: ')) - 96
b = ord(input('Вторая буква: ')) - 96
print(f'Номера этих букв: {a} и {b... |
aed7333d01df03d4231d7811eb3edf1254bd84e3 | Anupriya1500/FPS1 | /bmi_cal.py | 661 | 4.3125 | 4 | """
# Assignments - 1
"""
"""
Name:
Adult Body Mass Index Calculator
Problem Statement:
Assuming your weight in kilogram and height in meters
Calculate your BMI value and print it ?
Take the height and weight of the user from input
Hint:
Divide your weight in kilograms (kg) by your he... |
2d44014cb70ee7b47b7dc1422b64439a2bad1ea1 | SamayaA/bookkeeping | /main1.py | 2,821 | 3.796875 | 4 | from bookkeeping import Bookkeeping
documents = [
{
"type": "passport",
"number": "2207 876234",
"name": "Василий Гупкин"
},
{
"type": "invoice",
"number": "11-2",
"name": "Геннадий Покемонов"
},
{
"type": "insurance",
"number": "10... |
18fd69bdd6f6bebc842abedba72ca34631eb47e8 | kalyaniasthana/algorithms-II | /two_sum.py | 1,724 | 3.65625 | 4 | import sys
from min_heap import read_list
import threading
def array_to_hashtable(array):
hash_table = {}
for element in array:
hash_table[element] = False
return hash_table
'''
def two_sum_algorithm(hash_table, target, array):
for element in array:
complement = target - element
if complement in hash_tabl... |
4b10f0ac0f8534acd058a67d723e658501b05bf8 | johnsani/bc---python-xv | /assignments/notesapplication.py | 2,453 | 4.15625 | 4 | class NotesApplication(object):
"""class that defines a note taking application
Attributes: author: the author's name,
notes_list: A list containg all the notes
"""
def __init__(self, author):
self.author = author
self.notes_list = []
def create(self, note_content):... |
512efa06e161af1f249c76f0f8395a63a42dc1b5 | johnsani/bc---python-xv | /exercises/two_sum.py | 215 | 3.53125 | 4 | def two_sum(main_list, target):
for index, item in enumerate(main_list):
num = target - item
if num in main_list:
if num != item:
return [index, main_list.index(num)]
two_sum([1, 10, 33, 8, 6, 5, 4], 12) |
ba55f21e8a3c08aac653cb1a12ecd7b34da96a97 | mlanorero/4Geeks---Python-Beginner | /exercises/20-Russian-Roulette/app.py | 483 | 3.65625 | 4 | import random
bullet_position = 3
def spin_chamber():
chamber_position = random.randint(1,6)
return chamber_position
# DON'T CHANGE THE CODE ABOVE
def fire_gun():
# YOUR CODE HERE
#Round_Chambered = []
for i in range(1):
#students_array.append(get_color(random.randint(0,4)))
if spin_cham... |
f71bf224cf7c71bf5861da4bb997168588ef9025 | coldhair/DetectionSystem | /tmp/temp049.py | 401 | 3.609375 | 4 | # 获取 100 以内的质数
num=[]
i=2
for i in range(2,100):
j=2
for j in range(2,i):
if (i%j==0):
break
else:
num.append(i)
print(num)
# 方法2
import math
def func_get_prime(n):
return filter(lambda x: not[x%i for i in range(2,int(math.sqrt(x)+1)) if x%i==0],range(2,n+1))
print(list(fu... |
2a7dd9460727b5e024e490f586f98b51d5d6fb98 | coldhair/DetectionSystem | /tmp/temp030.py | 544 | 3.6875 | 4 | mylist = [1, 4, -5, 10, -7, 2, 3, -1]
larger = [n for n in mylist if n > 0]
smaller = [n for n in mylist if n < 0]
print(larger)
print(smaller)
pos = (n for n in mylist if n > 0)
print(pos)
# print(list(pos))
print(next(pos))
print('-' * 8)
for x in pos:
print(x)
vales = ['1', '2', '-3', '-', '4', 'N/A', '5']
de... |
b4224a20af16ff07d5d2594e31d9acae078f38a6 | coldhair/DetectionSystem | /tmp/temp005.py | 291 | 3.578125 | 4 | from _collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['b'].append(2)
d['c'].append(4)
d['a'].append(8)
print(d)
e = defaultdict(set)
e['a'].add(1)
e['b'].add(2)
e['c'].add(4)
e['a'].add(8)
print(e)
f = {
'a': {1, 2, 3},
'b': {4, 5}
}
f['a'].add(9)
print(f)
|
1d10516450aa1d80a46fe3c9da918397bc34ba46 | LesterTremens/Automatas | /ApipilhuascoRosasPractica02/Practica2.py | 3,132 | 3.6875 | 4 | import sys
import math
archivo = sys.argv[1] # Archivo que contiene la gramatica
cadena = sys.argv[2] # Cadena a verificar dada por el usuario.
#Clase que ayuda a guardar la gramaticay sea mas facil acceder a
#sus elementos.
class Produccion(object):
def __init__(self,simbolo,derivacion):
self.derivacion ... |
2f86be20f1012047aa63dfa0eb9a214a9ae6361e | riedert101/FinalProject | /Final Project.py | 3,854 | 4.125 | 4 | # import libraries for required for project
import turtle
import random
import time
# creating game display
console = turtle.Screen()
console.title('KILLER CENTIPEDE')
console.setup(width=700, height=700)
console.tracer(0)
turtle.bgcolor('green')
# setting the size dimensions
turtle.speed(5)
turtle.pens... |
c9feeba984284498c50333a7e60be50223ef5bb5 | radosz/Programming101-3 | /week7/2-SQL-Starter/create_company.py | 983 | 3.765625 | 4 | import sqlite3
conn = sqlite3.connect("company.db")
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY,name TEXT, monthly_salary FLOAT,
yearly_bonus FLOAT, position TEXT)
"""
insert_users_table = [
"INSERT INTO users(name, monthly_salary, yea... |
d567fb607a09e23ec51f224d5687931f195788c5 | AntonBeletsky/python_learn | /python/learn_python/basics/input.py | 262 | 3.5 | 4 | s1 = input("input data: ")
print("you data: " + s1)
a = 1; b = 2; print("ab", a, b)
c = 5; d = 6; pass
# if
if (a == 1 and b == 2 and
c == 3 and d == 4): # Не забываем про двоеточие
print('spam' * 3)
else:
print('lolka')
|
aade0839fbcabb4d04a94a72e8d29f1d8968b882 | dharshini-raman/Q1_Python | /digigon.py | 4,702 | 3.53125 | 4 | import random
import sys
class DigiPoke():
def __init__(self, Name, Type, Health, Record):
self.Name = N
self.Type = T
self.Health = 100
self.Record = 0
#def get_name(self):
# assigned_name = input("Please enter a name:\n")
# print(f'You entered ... |
a061673ca33b2fbaae5ecc7ac5c4e6eaa0c24fb4 | dharshini-raman/Q1_Python | /test_survey.py | 1,305 | 4.09375 | 4 | import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""Tests for the class AnonymousSurvey"""
def setUp(self):
"""
Create a survey and a set of responses for use in all test methods.
"""
question = "What city?"
... |
23a963d0ac744d62288d1b9989a3ce072f70dfbe | pnandini/Competitive-Coding-4 | /prob_55.py | 1,487 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
if not (head):
return True
"""
:type head: ListNode
:rtype: boo... |
6f57db8d47a7aa3218e2ca52a04242384b6bc798 | BrunoOMelo/Leaning_Python | /ex13.py | 269 | 4.09375 | 4 | #declaring and formatting variable as float
salary = float(input('Enter the salary: '))
#desclaring 'new salary' as result of this operation.
newSalary = salary*1.15
#presenting formatted 'new salary'.
print('New salary, with a 15% increase: {:.2f} '.format(newSalary)) |
f2a3defc5e40c863f82ca97cdf90b148d8d98656 | BrunoOMelo/Leaning_Python | /ex14.py | 364 | 3.921875 | 4 | #importing only one funciotion from library
from random import shuffle
#declaring variables as string
n1 = str(input('Fist name: '))
n2 = str(input('Second name: '))
n3 = str(input('Third name: '))
n4 = str(input('Fourth name: '))
#creating a list with this variables
lista = [n1,n2,n3,n4]
#using 'shufle' for change th... |
933bcd553b47c5aa1502028c48faf52565647a96 | BrunoOMelo/Leaning_Python | /ex03.py | 255 | 4.28125 | 4 | #declaring and formatting multiples variables as integer.
num01= int(input('Type the first number: '))
num02= int(input('Type the second number: '))
#showing to user the sum of numbers
print('The sum of the first and the second number is:', num01 + num02) |
612f1d7956b3e764f581f8bfdbb0e162051cd9eb | aaazz47/LPTHW_for_Python3_EXs | /ex4.py | 858 | 3.6875 | 4 | # 表示汽车数量的变量
cars = 100
# 表示车内空间的变量
space_in_a_car = 4.0
# 表示司机数量的变量
drivers = 30
# 表示乘客数量的变量
passengers = 90
# 变量表示无法行驶车辆数量的变量
cars_not_driven = cars - drivers
# 表示可以行驶车辆数量的变量
cars_driven = drivers
# 表示最大拼车容量的变量
carpool_capacity = cars_driven * space_in_a_car
# 表示平均每辆车中乘客数量的变量
average_passengers_per_car = passengers / ... |
acdad66f9e688db7397a95ff1a7d0b8dcd0e6158 | 4x1md/qth_locator_functions | /src/qth_locator.py | 3,981 | 3.765625 | 4 | """
Created on Mar 3, 2017
@author: 4X5DM
"""
from math import floor
# Constants
ASCII_0 = 48
ASCII_A = 65
ASCII_a = 97
def square_to_location(qth_locator):
"""
Converts QTH locator to latitude and longitude in decimal format.
Gets QTH locator as string.
Returns Tuple containing l... |
43e9e641ef288cdd646328bf3e4d94651382ece8 | ppdebreuck/Stage_Python | /Station_meteo/jour4.py | 228 | 3.6875 | 4 | fd = open("monfichier.txt","a")
fd.write("Bonjour \n")
fd.write("Ceci est un fichier text\n")
fd.close()
fd = open("monfichier.txt","r")
print("DEBUT DE LECTURE")
for line in fd:
print(line)
print("FIN DE LECTURE")
fd.close()
|
e4cb3617a7f9d2d84b0852e0d3898958c5f484c4 | ppdebreuck/Stage_Python | /act4.py | 88 | 3.84375 | 4 | print('Introduisez un chiffre')
x = input()
y = int(x)
print(x*2) #Concaténation!!
|
28155615c17d903dbf00ad11440427da28573235 | AmeyVanjare/PythonAssignments | /LabAssignment/LabAssignmentQ1-Calendar.py | 400 | 3.921875 | 4 | days=int(input("enter no of days in month : "))
startDay=int(input("Enter starting day no. monday-0 sunday-7 : "))
print("MON TUE WED THI FRI SAT SUN")
count=startDay
spaces= (7-startDay)*8
print(' '*spaces,end=" ")
for i in range(1,days+1):
count=count+1
print(i,end=" ")
print(" "*2,en... |
ee1b69c12aefbff7b64ac8f4aaf93b758cca1eb6 | AmeyVanjare/PythonAssignments | /Panagram.py | 310 | 4.25 | 4 | print("panagram check")
#The quick brown fox, jumps over the lazy dog!!!!.
str1=input("Enter String")
s=set()
for i in str1:
if i.isalpha():
s.update(i.lower())
if len(s)==26:
print("String is panagram")
else:
print("String is not panagram")
print(s)
print(len(s))
|
6fabdd21e008096fbf2ee1a727a970a8cd65ed84 | AmeyVanjare/PythonAssignments | /LabAssignment/LabAssignmentQ14.py | 772 | 4.28125 | 4 | def make_ing_form(verb):
vowels_list=['a','e','i','o','u']
last_char=verb[-1]
second_last_char=verb[-2]
if second_last_char=='i' and last_char=='e':
verb=verb[0:-2]+"ying"
elif last_char.lower()=="e":
verb=verb[0:-1]+"ing"
elif second_last_char in vowels_list and last_cha... |
47a84637bbdd5d27702712a3c168b6c26fc26ca8 | JuliaZhd/LightIt2 | /gamer.py | 2,562 | 3.796875 | 4 | import random
class Person:
def __init__(self, name, health):
self.name = name
self.health = health
self.mark1 = 1/3
self.mark2 = 2/3
def __repr__(self):
return f'У игрока {self.name} сейчас {self.health} здоровья'
''' Расчитывается нанесение вида и размера ущерба/лечения. Переменная x
принимает случ... |
0603a137f6664d276e0a4ae82df717ff2f2296e9 | pussydestroyer9000/my_homeworks | /hw11/4th_var.py | 1,411 | 3.96875 | 4 | import random
___NUMBER_OF_HINTS___ = 3
def opentodict (filename):
n = 0
dic = {}
with open(filename, 'r') as file:
lines = file.readlines()
random.shuffle(lines)
for line in lines:
dic[line.split(',')[0]] = line.split(',')[1:-1]
n+=1
return dic, n
def ... |
883eb147c4841f04516e0f55995b397f1c4145d5 | pussydestroyer9000/my_homeworks | /clw1/170117.py | 1,027 | 3.875 | 4 | #ключами могут быть не любыми типами данных (только неизменяемые: строка, число, число с плавающей точкой), не могут быть одинаковыми
#значения могут быть любыми типами данных, могут быть одинаковыми
#словари устроены так, чтобы они работали быстро
#
dict_= {1: 'a', 2: 'b'} #initialisation of the dictionary
... |
e5c7b1dda8dd1e8ef4828857026d693586c18703 | soham524/42h2s | /4205_bool.py | 792 | 3.9375 | 4 | ##!/usr/bin/env python
#true, false, and nil/none
from random import choice
number = 10
while number > 0:
def op(price,price1,price2):
if price1 == 'or':
return price or price2
if price1 == '==':
return price == price2
if price1 == '!=':
return price != price2
if price1 == 'and':
return price and p... |
8aa96243488d02ae3fe31a7c062c90bbf7d468d1 | Wison2017/leetcode | /python/234.py | 933 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None or head.next is None:
return True
step_1 = head
step_2 = head.nex... |
6352290320a806fa027651d702e5ea8e73dc1537 | Wison2017/leetcode | /python/70.py | 240 | 3.65625 | 4 | class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2: return n
ways = [0, 1, 2]
i = 3
while i <= n:
ways.append(ways[i - 1] + ways[i - 2])
i += 1
return ways[n]
|
2c4333fce345b1908988f757beb10a965fb5530d | mel-haya/42-AI-Bootcamp | /M01/ex05/eval.py | 875 | 3.515625 | 4 | class Evaluator:
def zip_evaluate(coefs, words):
ret = 0.0
if len(coefs) != len(words):
return -1
l = zip(coefs, words)
for i in l:
if not isinstance(i[1],str) or not isinstance(i[0],(int,float)):
print('here')
return -1
... |
3a198f19ddc9b07d377a12ba7dbc0736370c9ef1 | kyairem/Sirket_Yonetimi | /sirket_yonetimi.py | 1,382 | 3.59375 | 4 | class sirket():
def __init__(self,calisanSayisi,sirketIsmi,mudurler,mudurYrd,faliyet):
self.calisanSayisi=calisanSayisi
self.sirketIsmi=sirketIsmi
self.mudurler=mudurler
self.mudurYrd=mudurYrd
self.faliyet=faliyet
def calisanAl(self,sayi):
self.calisanSayi... |
ad4f714cc5f26e8e7739475420533764f7018d6e | alieu93/Comp-Simulation-Assignments | /Assignment 1/simulateFreeFall.py | 1,215 | 3.984375 | 4 | #name: Adam Lieu
#student ID: 100451790
#description: Part 1A of Assignment 1, just simulating free fall without
# friction or the effect of the bungee
import itertools as it
import numpy as np
import scipy as sp
import pylab as pl
import matplotlib.pyplot as plt
from numpy import arange
def simulateFre... |
8e98fd382ac8a2bdabc7ba2fffcb350209e26c33 | Fuyukine/Python-Java | /1.py | 454 | 3.9375 | 4 | import
def helloName():
print("Hello!")
print("May I ask what Your first name is dear user?")
firstName = str(input())
print("And Your last name please?")
lastName = input()
print("Welcome to the system " + firstName + " " + lastName + ".")
def areaCalculation():
n = input("Number of sid... |
d36884bc77afc0fd940ace4af130bd38c1f11e91 | HenriqueCCdA/coderbyte_questions | /q1/q1.py | 1,587 | 3.625 | 4 | def questions_marks(strParam: str) -> bool:
'''
Exemplos:
Test 1
>>> questions_marks("aa6?9")
False
Test 2
>>> questions_marks("arrb6???4xxbl5???eee5")
True
Test 3
>>> questions_marks("acc?7??sss?3rr1??????5")
True
Test 4
>>> questions_marks('5??aaaaaaaaaaaaaaaaa... |
869901bbef2cbe5b9b1886332c80581c302afcba | andrewlidong/uChicago-work | /WikiWork/NQueens/nqueens.py | 2,599 | 4.0625 | 4 | #!/usr/bin/env python3.4
# nqueens.py
# Output a solution to the n queens problem for given n
"""
The classic chessboard is comprised of an 8x8 grid. In chess, the queen piece can move up, down, left, right, and diagonally for as many moves as she wants until her path is either blocked by the edge of the board or an... |
9a28c647e461ff8fb7aae83ee6cceaf30ec2154f | alexxirou/Pythong | /7 erreurs.py | 719 | 3.921875 | 4 | def difference(list1,list2):
Listresultat=[]
assert len(list1)==len(list2) #verfier la taille de la liste
for e in range(0,len(list1)): # pour chaque element de list1 comparer avec l' element de list2 dans la meme position
res=list1[e]==list2[e]
Listresultat.append(res)
return List... |
ac36241daf60d4549711f73351b00be12c66afb9 | k-bodapati/UB_Masters_Courses | /CSE 573 - Computer Vision and Image Processing/Project 3 - Image Clustering/task1.py | 5,169 | 3.53125 | 4 | """
K-Means Segmentation Problem
(Due date: Nov. 25, 11:59 P.M., 2019)
The goal of this task is to segment image using k-means clustering.
Do NOT modify the code provided to you.
Do NOT import ANY library or API besides what has been listed.
Hint:
Please complete all the functions that are labeled with '#to do'.
You a... |
f58e20e390cecafc4cb665a745492959c7c2c17d | lord8266/chainreaction_py | /chainreaction.py | 725 | 3.546875 | 4 |
# doesnt do anything as of now just sets up the boxes and connecting surrounding
import pygame
pygame.init()
pygame.font.init()
from board import board
import conf
data=conf.data
# look at conf.py
# no of rows ,cols and the multiplier says the size of each box
# each box is a square
clock = pygame.time.Clock()
... |
4d1c9db470d5249e0c911def9d12760082884ca6 | Edudeiko/Hash-tables-module-project-CS | /notebooks/caching.py | 1,248 | 3.65625 | 4 | '''
# web client cache
# 'client' gets whatever URL we provide
# this client should cache the web page
# on first request, the client fetches the web page
# on subsequent request, the client gives you what it previously fetched
# why?
# speed
# especially for large pages or on a slow connection
# avoid database hi... |
e956a96e0c3926f1930bebcdee63cdd470b174a2 | PrashilAlva/Programs | /Practice/Data Analytics (Heraizen)/Assignment/Set 2/q3.py | 346 | 3.71875 | 4 | n=int(input())
prime=list()
for i in range(2,n+1):
flag=0
for j in range(2,i//2+1):
if i%j==0:
flag=1
break
if flag==0:
prime.append(i)
print(prime)
sum=0
for ele in prime:
sum=sum+ele
print(sum)
squareprime=list()
for ele in prime:
squareprime.append(el... |
cbfb6b6a18e5c29526772042ac428d80ab4ce504 | PrashilAlva/Programs | /Practice/Data Analytics (Heraizen)/Assignment/Set 1/q4.py | 191 | 3.953125 | 4 | first=0
next=1
temp=0
print(first,next,end=",")
while(temp!=34):
temp=first+next
if temp==34:
print(temp)
break
print(temp,end=",")
first=next
next=temp
|
8a1b1e88cf07f7b7d5ce4ea1b979725c51a22a38 | teichert/torchtyping | /torchtyping/utils.py | 659 | 3.5 | 4 | class frozendict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Calling this immediately ensures that no unhashable types are used as
# entries.
# There's also no way this is an efficient hash algorithm, but we're only
# planning on using this... |
20f5df197248afe9914e6e82dc5c52e6d9ce54b9 | leonberlang/datasciencefundamentals | /week2-exercises/multidimension-snacknames.py | 392 | 4.0625 | 4 | apes = [
["Steyn"],
["Nick"],
["Yannick"]
]
for ape in apes:
name = ape[0]
name_length = len(name)
print(name + " has a name of " + str(name_length) + " characters long.")
snack = input(name + ", What's your fav snack? ")
ape.append(snack) #appending them into the name string, placing it on place ... |
250da105229ae0b0f0e74dba5d90ece189eb3042 | leonberlang/datasciencefundamentals | /week2-exercises/sentenceslicer.py | 615 | 3.953125 | 4 | sentence = input("your sentence here: ")
sentencelength = len(sentence)
calc25 = round(sentencelength * .25)
calc75 = round(sentencelength * .75)
slicedsentence = sentence[calc25:calc75]
print("Middle part of the string sentence is: " + slicedsentence)
#convert
listsentence = sentence.split()
#list doin... |
af5bb3927a4dfaa1b22064ade2b1f712a6c4aa87 | Adronhuman/test_task | /utils/unzipping.py | 1,320 | 3.578125 | 4 | import errno
import os
import shutil
import zipfile
import codecs
def convert_to_utf(path, file_name):
f = codecs.open(os.path.join(path, file_name), 'r', 'cp1251')
u = f.read() # now the contents have been transformed to a Unicode string
out = codecs.open(os.path.join(path, file_name), 'w', 'utf-8')
... |
13f6c6b8f6139935fa464a4d2f09697c62d1d8fb | jethrochan/Algorithms | /pythonPalindrome.py | 292 | 4.09375 | 4 | def isPalindrome(myStr):
myStr = myStr.lower()
#reverse string python
reversed = list(myStr)
reversed.reverse()
reversed = ''.join(reversed)
#end reversed string
if (myStr == reversed):
return True
else:
return False
print(isPalindrome('Madamadam'))
|
bd4d82b9ae9f8c816967a974494b87b8e8950d46 | OlegsIljanovs1/RTR105 | /sin_caur_summu_ver4_C05.py | 443 | 3.53125 | 4 | >>> #-*- coding: utf-8 -*-
from math import sin
x = 1. * input("Lietotāj, lūdzu, ievadi argumentu :" )
y = sin(x)
print "sin(%.2f) = %6.2f" %(x,y)
k=0
a = (-1)**0*x**1/(1)
S = a
print "a0 = %6.2f S0 = %6.2f" %(a,S)
k = 1
#a = a* (-1)*x*x/(2*3)
a = a* (-1)*x*x/((2*k)*(2*k+1))
S = S + a
#print "a1 = %6.2f S1 = %6.2f"... |
a34b22379ed08961fba432acf63934753d636609 | jonny536486040/Stock-Market-RNN-Genetic-Algorithm | /optimizer.py | 9,822 | 3.671875 | 4 | """
Class that holds a genetic algorithm for evolving a network.
Credit:
Most of this code was originally inspired by:
https://github.com/harvitronix/neural-network-genetic-algorithm/blob/master/optimizer.py
"""
import numpy as np
from operator import add
import random
from network import Network
class Optimi... |
5d6f744db82fbd3ed14bc265adfa70605eddc318 | MDCGP105-1718/portfolio-Jord159 | /Projects/ex4.py | 470 | 3.96875 | 4 | my_name = 'Jordan Carman'
my_age = 19
my_height = 72 # I think
my_weight = 210
my_eyes = 'Blue'
my_hair = 'Brown'
is_heavy = my_weight > 3000
print(f"Let's talk about {my_name}.")
print(f"He is {my_height} inches tall.")
print(f"He is {my_weight} pounds heavy.")
print(f"Is is {is_heavy} that he is overweight.")
print(... |
e2fa09a327a455d04bf0fba45f276fd83c15cef1 | MDCGP105-1718/portfolio-Jord159 | /Projects/ex14.py | 426 | 3.578125 | 4 | def remove_dups1(L1, L2):
for e in range(len(L1) - 1, -1, -1):
if L1[e] in L2:
L1.remove(L1[e])
print(L1, "\n", L2)
#print(L1, "\n", L2)
def remove_dups2(L1, L2):
index = 0
while index < len(L1):
if L1[index] in L2:
L1.remove(L1[index])
else:
... |
08c686a377e48e8fc44fff5e612711fe52656f0d | PiresMurilo/estudosPython | /ordenacao.py | 229 | 4.125 | 4 | x1 = int(input("Digite o primeiro número: "))
x2 = int(input("Digite o segundo número: "))
x3 = int(input("Digite o terceiro número: "))
if x1 < x2 < x3:
print("crescente")
else:
print("não está em ordem crescente") |
279b6571dd48a3272c0c7440010979a0087c63ec | PiresMurilo/estudosPython | /remove.py | 168 | 3.734375 | 4 | def remove_repetidos(lista):
lista2 = []
for x in lista:
if x not in lista2:
lista2.append(x)
lista3 = sorted(lista2)
return lista3
|
0daa21433163eadaa45167199491d38c5b546170 | Abbasa5251/Guess-the-Number | /app.py | 1,070 | 3.859375 | 4 | import random
class GuessNumber(object):
def __init__(self, min, max):
self.guesses = 0
self.min = min
self.max = max
self.number = random.randint(self.min, self.max)
def get_guess(self):
guess = input(f"Please guess a Number ({self.min} - {self.max}): ")
if sel... |
34a22a6a2f20e0610851556680c53568ecb37ab4 | sjhhh3/Leetcode | /Leecode/leetcode496.py | 256 | 3.6875 | 4 | nums1 = [4,1,2]
nums2 = [1,3,4,2]
res = []
for num in nums1:
flag = 1
for num2 in nums2[nums2.index(num)+1:]:
if num2 > num:
res.append(num2)
flag = 0
break
if flag:
res.append(-1)
print(res) |
6090b167873106d3d52f36760fa0d0b4e362270b | sjhhh3/Leetcode | /Leecode/hwcsv.py | 293 | 3.5 | 4 | import csv
with open('hw_data.csv') as data:
readdata = csv.reader(data, delimiter=',')
weightlist = []
for row in readdata:
print(row)
weight = row[2]
weightlist.append(weight)
aveweight = sum(weightlist[1:])/(len(weightlist)-1)
print(aveweight) |
4e08235af9c50930eb6277b64dc7c6e22bf43ca5 | sjhhh3/Leetcode | /Leecode/Leecode1.py | 635 | 3.625 | 4 | '''
def TwoSum(nums,target):
d={}
for i,nums in enumerate(nums):
if target-nums in d:
return i
d = nums
numbs = [3,2,4]
target = 6
d = {}
for i,num in enumerate(numbs):
if target-num in d:
print(target-num,d[target-num],i)
d[num] = i
print (d)
d = {1:'baby',5:'... |
7b83001e760cc26fde9bdc3cf4cb9bebaf426d6c | sjhhh3/Leetcode | /Leecode/tree897.py | 1,747 | 3.65625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def stringToTreeNode(input):
if not input:
return None
inputValues = input
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < ... |
0876b8b4d6a4e551918e9cf741e676c0cfd0643b | sjhhh3/Leetcode | /Leecode/leetcode687.py | 904 | 3.5625 | 4 | '''
def knightProbability(N, K, r, c):
list = []
positionR = r
positionC = c
able = 0
if K > 0:
if positionR - 2 >= 0 and positionC - 1 >= 0:
able += 1
list.append([positionR - 2, positionC - 1])
if positionR - 1 >= 0 and positionC - 2 >= 0:
able ... |
d09dea918c2eaf0e36f11950a3485a707234f258 | sjhhh3/Leetcode | /Leecode/leetcode28.py | 311 | 3.71875 | 4 | a = 'I love u us'
b = 'us'
def strStr(haystack, needle):
if haystack == needle or not needle:
return 0
ans = haystack.find(needle)
return ans
print(strStr(a,b))
'''
for i in range(len(haystack) - len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
''' |
b91be705f827d60310034c2c20fa6c652b13c5d5 | sjhhh3/Leetcode | /Leecode/leetcode283.py | 103 | 3.609375 | 4 | nums = [0,1,0,3,12]
for i in range(nums.count(0)):
nums.remove(0)
nums.append(0)
print(nums) |
164948d8118c3e9d13401f90262706106a2f6c8a | sjhhh3/Leetcode | /Leecode/codewar1.py | 717 | 3.65625 | 4 | a = 'xyaabbbccccdefww'
b = 'xxxxyyyyabklmopq'
def longest(s1, s2):
# # return ''.join(sorted(set(s1 + s2)))
# deleterep = set(s1 + s2) # set集合函数,去掉重复元素
# # 输出deleterep = {'f', 'c', 'b', 'w', 'y', 'l', 'o', 'd', 'q', 'x', 'a', 'e', 'p', 'k', 'm'}
# sortedlist = sorted(deleterep) # 字母排序,此时输出
# # s... |
2b708fc4e1d1521ed88278a78f6b0d8bb39b6bad | sjhhh3/Leetcode | /Leecode/leetcode654.py | 685 | 3.703125 | 4 | def constructMaximumBinaryTree(nums):
dummy = root = TreeNode(0)
def makemaxbst(node, left, right):
if right > left:
maxpos = nums.index(max(nums[left:right]))
node = TreeNode(nums[maxpos])
print(node.val)
makemaxbst(node.left, left, maxpos)
m... |
a75bd1d42031d214c8039b553b29e5df4907c64e | sjhhh3/Leetcode | /Leecode/leetcode83.py | 1,167 | 3.890625 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
cur = head
while cur:
print(cur.val)
while cur.next and cur.next.val == cur.val:
cur.next = cur.next.nex... |
a4b84bffdb0808aa44fbf0955789363f640be134 | madhuhaasnannaka/UNIVERSITY-PORTAL | /DevOps/pythonscripting/summing_a_aa_aaa_aaaa.py | 66 | 3.625 | 4 | num=input()
x=int(num)
sum=(x+(x*11)+(x*111)+(x*1111))
print(sum)
|
6efdfb921acabfcbb0efbd663e5be8448b225680 | madhuhaasnannaka/UNIVERSITY-PORTAL | /DevOps/pythonscripting/map_filter.py | 379 | 3.53125 | 4 | li=[1,2,3,4,5,6,7,8,9,10]
evennumber1=filter(lambda x:x%2==0,range(1,21))
print(evennumber1)
sqares=map(lambda x:x**2,filter(lambda x:x%2==0,li))
print(map(lambda x:x**2,filter(lambda x:x%2==0,li)))
class American(object):
@staticmethod
def printNationality():
print("America")
anAmerican = American()... |
a0bb77679e16bcb91af3f54cbc32effa50108d9c | obaid147/python_ds_algos | /math/Multiples_3or5.py | 89 | 3.875 | 4 | x = int(input("Enter a number: "))
a = 3
d = 3
n = x//a
sum1 = d*n*(n+1) // 2
print(sum1) |
d7ac53d7dc209e04a05e150d1a7e30e8b47f6688 | obaid147/python_ds_algos | /arrays/AlternateRemoveElements.py | 512 | 3.875 | 4 | def removeElements(arr):
size = len(arr)
for i in range(size):
if len(arr) == 1:
return arr
if i & 1 == 0:
arr.remove(max(arr))
elif i & 1 == 1:
arr.remove(min(arr))
def usingSort(arr):
n = len(arr)
arr.sort()
div = n // 2
if n % 2 ==... |
d86015a7689d435de9edfb0321faec1239889bf4 | obaid147/python_ds_algos | /String/SameCharsOrNot.py | 205 | 3.546875 | 4 | def charOfString():
for i in range(len(str1)):
for j in range(1, len(str1)):
if str1[i] != str1[j]:
return 'NO'
return 'Yes'
str1 = 'oom'
print(charOfString()) |
d6dff7765bb45c232436939b4088c9bd440f63ab | obaid147/python_ds_algos | /Stack/TowerSignalUsingStack.py | 701 | 3.53125 | 4 | from Stack.StackUsingArrays import Stack1
class Towers:
newStack = []
obj = Stack1()
obj.push(12)
obj.push(100)
obj.push(40)
obj.push(60)
obj.push(120)
obj.push(90)
def __init__(self):
self.count = 0
def towerSignal(self):
self.newStack.append(1)
for... |
42b64e510cb52daf1295dbbe023c925cb5f858ea | obaid147/python_ds_algos | /String/CheckPalindrome.py | 216 | 3.734375 | 4 | s = 'madam'
flag = True
j = -1
size = len(s)
for i in range(size):
if s[i] != s[j]:
flag = False
break
else:
j -= 1
if flag:
print('Palindrome')
else:
print('Not palindrome')
|
2e91462fd1013f2ee0339045bff5a4e3fc59a2b5 | obaid147/python_ds_algos | /arrays/Countfrequency.py | 825 | 3.640625 | 4 | # Method1
# Time complexity --> O(n*n) ; aux-space --> O(n)
# Method2
# Time complexity --> O(n) ; aux-space --> O(n)
def Method1(array, size, checkerArray):
for i in range(size):
count = 1
if checkerArray[i]:
continue
for j in range(i +... |
f942dc8096d19830c444e7d7f661595598497a20 | obaid147/python_ds_algos | /arrays/FriendsCompitition.py | 621 | 3.640625 | 4 | def competition(person1, person2, person1Score, person2Score):
if len(person1) != len(person2):
return 'Cannot Compare'
else:
for i in range(len(person1)):
if person1[i] > person2[i]:
person1Score += 1
elif person1[i] < person2[i]:
person2S... |
1f6b20be15e380b19b570da01c916f548bb47534 | askervin/tinytime | /tinytime | 3,729 | 3.765625 | 4 | #!/usr/bin/env python3
# tinytime, base 60 representation for time and date
#
# Command line interface
#
# Copyright 2018 Antti Kervinen <antti.kervinen@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms and conditions of the GNU Lesser General Public
# License, ve... |
cc403dbd348cbce3118ee1799afe319d524c3661 | CodeCreed21/Python1 | /sets.py | 327 | 3.75 | 4 | #Prima di tutto si crea il set vuoto. attribuendolo ad una variabile
s=set()
#Add some elements to the set
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3) #questo elemento non verra' ripetuto perche' nei sets non vengono ripetuti elementi esistenti
print(s)
s.remove(2)
print(s)
print(f"La nuova lista ha {len(s)} elemn... |
0989ac26ef693e8170db2e25c1963f5a68d52c27 | CodeCreed21/Python1 | /exceptions.py | 279 | 3.8125 | 4 | import sys
try:
x=int(input("Insert value of x: "))
y=int(input("Insert value of y: "))
except ValueError:
print("Invalid imput!")
sys.exit(1)
try:
result=x/y
except ZeroDivisionError:
print("Error! You can't divide by zero.")
sys.exit(1)
print(result) |
d4d783dd4334dffeba7e89a6424a06ebc00c6e47 | LyWangPX/Reinforcement-Learning-2nd-Edition-by-Sutton-Exercise-Solutions | /Chapter 6/Example 6.5 code by Maxime.py | 5,177 | 3.734375 | 4 | # Example 6.5 of the book "Reinforcement Learning: an Introduction"
# Maxime Xuereb - Python implementation
import numpy as np
class Windy_Gridworld:
def __init__(self):
self.world = np.zeros((7, 10)) # World
# The world contains in each cell the power of the wind
# Positive means it will... |
9f9169703f4b93dc5867f0b50aaff093e1db7858 | JonathanMaran/TP_Python | /main.py | 3,908 | 3.609375 | 4 | # TP ZCasino - Jeu de roulette
import random
import time
bankroll = 1000
game = True
print(" ")
print("Bonjour et bienvenue à la roulette du ZCasino !")
print(" ")
# Tant que le jeu est sur True, on peut jouer
while game:
# pour pouvoir revenir au début du while
numero = -1
while numero < 0 or numero > ... |
f6f13ab4b2ea9a35d3371a3ccf1e12a6bcccc54e | Knightslayerism/PythonTicTacToe | /main.py | 3,469 | 4.09375 | 4 | def tic_tac_toe():
# Enter names of players that will be playing the game
player1 = input("Enter name for player 1: ")
player2 = input("Enter name for player 2: ")
# initialize variables
choices = []
checkturns = []
for x in range(0, 9):
choices.append(str(x + 1))
play... |
0fa689f0b205bf294a0ba2f0788016c0940a6a87 | shivaniarbat/pytorch-101 | /Linear-Models/linear-model.py | 630 | 4.09375 | 4 | """
A Simple Linear model using Linear module in pytorch
"""
import torch
from torch.nn import Linear
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# set random seed
torch.manual_seed(1)
lr = Linear(in_features=2, out_features=1, bias=True)
print("Parameter w and b:", list(lr.parameters()))
... |
17d0ffbd93ee27bb8e6785ecf7055374a5bd8aef | wangJI1127/learnPython | /lintcode/_139_Word_Break.py | 2,008 | 4.03125 | 4 | """
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "appl... |
b5797a18b7cfcfcdb36a87330d7f648328b42bad | wangJI1127/learnPython | /leetcode/_32_Longest_Valid_Parentheses.py | 1,608 | 3.96875 | 4 | """
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses subs... |
8ce9b705017c506820638a0737060b86a9d73d57 | codingnest/flask-restapi | /flask_db_jwt/create_table.py | 365 | 3.53125 | 4 | import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
create_users_table = "CREATE TABLE users (id INTEGER PRIMARY KEY, username text, password text)"
cursor.execute(create_users_table)
create_items_table = "CREATE TABLE items (name text PRIMARY KEY, price real)"
cursor.execute(create_... |
395191f0b86fdc0dab008c73986064d94df682e0 | sbn-psi/data-provider-tools | /csv_merge/csvmerge.py | 1,535 | 3.765625 | 4 | #!/usr/bin/env python3
import sys
import argparse
import csv
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("basefile", help="The file to merge onto")
parser.add_argument("addfile", help="The file to merge from")
parser.add_argument("result", help="The that will hold the r... |
dde5767c7e14a0ba04f39022fb41cd228247e659 | Gilbertsb/Bank_Software-Dangote-Bank-_Python | /Account_function.py | 13,994 | 3.71875 | 4 | from saving_acc import*
from current_account import*
from datetime import *
acc=0
def choices():
global acc
print("+----------+")
print('|1.SAVING |')
print('|2.CURRENT |')
print("+----------+")
acc=eval(input('CHOOSE ACCOUNT (ex: 2): '))
Account_saving = []
Account_current =[]
def create_ne... |
4e26271d3a651a2e4aa2631f228c303d80baeea7 | philipwoodward/Practicals | /Prac01/electricityBillEstimator.py | 534 | 4.34375 | 4 | """
Program to calculate and display
the electricity bill. Inputs will be price per kWh in cents,
daily use in kWh and the number of days in the billing period
"""
electricity_price = int(input("Enter the price of electricity in cents per kilowatt hour: "))
daily_use = float(input("Enter the kilowatt hours of electrici... |
a28cfebb127d562713c0cb71fafe03730b744182 | philipwoodward/Practicals | /Prac02/exceptions.py | 596 | 4.46875 | 4 | try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
except ValueError:
print ("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print ("Cannot divide by zero!")
print ("Finished.")
"""... |
962f1e24e9a6fcf4d302bebbc92232233045ae29 | philipwoodward/Practicals | /Prac03/fixedScore_functions.py | 876 | 3.921875 | 4 | """
CP1404/CP5632 - Practical
Broken program to determine score status
"""
def main():
score = float(input("Enter score between 1 and 100: "))
score_result = score_status(score)
if score_result == 6:
print ("Invalid score")
elif score_result == 5:
print ("Bad")
elif score_result == 4:
print ("Passable")
#e... |
90783797db641eb9de2676819f9d9f1738c290bd | RaunakDey/Image-processing | /blue_filter.py | 651 | 3.640625 | 4 | # to provide a blue filter to the image, note you can put any filter just tweeking with the values, and the filter can be also given to specific regions of the code, if wanted
import Image
im=Image.open("1.png") #provide the name of the file your want to choose
rgb_im=im.convert("RGB")
(a,c)=im.size
red=[]
green... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.