blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
e38e2d771340ac0843aef8cb25dd0b6fa960755b | pascee/physics_learning_app | /velocity/calculations.py | 1,239 | 3.71875 | 4 | from sympy import *
x = Symbol('x')
#takes in an equation for displacement as a string and derives it to find velocity
def differentiate(your_equation):
your_equation = your_equation.replace("^", "**")
f_prime = diff(your_equation)
f_prime = str(f_prime)
if "x" not in f_prime:
f_prime = 'y=' +... |
025e4b39d4981efa90b2414fa3a5e59276d83012 | crunchypi/Sudoku-Solver | /sudoku_helper_GUI.py | 8,717 | 3.765625 | 4 | import tkinter as tk
from tkinter.ttk import Separator, Style
import sudoku_tools
class GUIInterface():
""" A GUI interface for a Sudoku solver.
Requires:
- Tkinter.
- Sudoku loader and solver.
Has two main views/frames:
- Top for loading a Sudoku board.
... |
cb77261c3c3db53f0a7067e749f1b10a06fbeb63 | DandyCV/SoftServeITAcademy | /L07/L07_HW1_4.py | 306 | 4.0625 | 4 | def season(month):
"""Returns - string (season of year).
Argument - integer from 1 to 12 (number of month)."""
if 0 < month < 3 or month == 12: return "Winter"
if 2 < month < 6: return "Spring"
if 5 < month < 9: return "Summer"
if 8 < month < 12: return "Autumn"
print(season(7)) |
3a6fa89d2f42f9b264fc509e02c13c8222e8d76c | DandyCV/SoftServeITAcademy | /L07/L07_HW1_3.py | 321 | 4.15625 | 4 | def square(size):
"""Function returns tuple with float {[perimeter], [area], [diagonal]}
Argument - integer/float (side of square)"""
perimeter = 4 * size
area = size ** 2
diagonal = round((2 * area) ** 0.5, 2)
square_tuple = (perimeter, area, diagonal)
return square_tuple
print(square(3))... |
97d0ccc3d5c0bd1f9d84c1201695309d49c09fb9 | DandyCV/SoftServeITAcademy | /L07/L07_HW1_1.py | 473 | 4.5 | 4 | def arithmetic(value_1, value_2, operation):
"""Function makes mathematical operations with 2 numbers.
First and second arguments - int/float numbers
Third argument - string operator(+, -, *, /)"""
if operation == "+": return value_1 + value_2
if operation == "-": return value_1 - value_2
if ope... |
80c45c7f70d8f318b41146d4d8ec521cff44b331 | DandyCV/SoftServeITAcademy | /L08/L08_HW2_4.py | 1,302 | 3.578125 | 4 | #Задано символьний рядок,. Розробити програму, яка знаходить групи цифр, записаних підряд, і вилучає із них всі
# початкові нулі, крім останнього, якщо за ним знаходиться крапка. Друкує модифікований масив по сорок символів у рядку.
from random import randint
random_string = "000.001jh000.550opk00023.000dfe70000.0001"... |
cf22428c9b7c74168b938c045c472490fcdd777e | DandyCV/SoftServeITAcademy | /L06/L06_HW1_8.py | 394 | 3.640625 | 4 | from random import randint
random_list = []
for number in range(10):
random_list.append(randint(-100, 100))
print("Random list 1:", random_list)
index_max = random_list.index(max(random_list))
index_min = random_list.index(min(random_list))
temp = random_list[index_min]
random_list[index_min] = random_list[index... |
5a3e85770875b03396a7a0f19fcd53dfdab290df | devangi2000/HacktoberFest2020-1 | /Interview Based/Anagram.py | 1,315 | 4.09375 | 4 | """ Given two strings a and b consisting of lowercase characters.
The task is to check whether two given strings are anagram of each other or not.
An anagram of a string is another string that contains same characters,
only the order of characters can be different. For example, “act” and “tac” are anagram of each ot... |
4aea4fa53d3b15c6535d109b58eaa36840778e95 | devangi2000/HacktoberFest2020-1 | /Interview Based/Longest Palindrome in a String.py | 805 | 3.984375 | 4 | """ Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least ... |
c5c25d3d8be7abf375018cdfa1e6a75ac48438e1 | devangi2000/HacktoberFest2020-1 | /Interview Based/Missing number in array.py | 763 | 3.796875 | 4 | """ Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing,
the missing number is to be found.
Input:
The first line of input contains an integer T denoting the number of test cases.
For each test case first line contains N(size of array). The subsequent line contains N-1 ... |
3de63dc10bf4adab4fca2f8da4704652a2e1a3cf | jasonjiang001/LeetCode | /1TwoSum.py | 780 | 3.734375 | 4 | """
1.两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
def getTowSum(nums, target):
sum = []
for i in range(len(nums)):
for j in range(len(nums)-1, -... |
aa33cf7e6eca200e41c461c00a48a7f3bafde728 | aaherrera3/Lab-3- | /Binary_Tree.py | 3,838 | 4.09375 | 4 | # Code to implement a binary search tree
# Programmed by Olac Fuentes
# Last modified February 27, 2019
class BST(object):
# Constructor
def __init__(self, item, left=None, right=None):
self.item = item
self.left = left
self.right = right
def Insert(T, newItem):
if T ... |
8a05ce56e01f8c822283574871f22ec5ea5fe1dc | chengyaojun/FindDuplicateFile | /find_duplicate_file.py | 1,498 | 3.8125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
find duplicate file
"""
import os
from collections import Counter
import sys
def get_all_files(abspath):
"""
@abspath: get all files from path of 'abspath'
@return: get list of all files
"""
all_files = []
for _, _, files in os.walk(abspath):
... |
9fe71b923d902d03dab882fe161d38d3bd122d81 | albornoz440/trabajo-informatica | /programacion 2/punto 3.py | 117 | 3.828125 | 4 | name = input("¿Cómo te llamas?: ")
num = input("Introduce un número entero: ")
print((name + "\n") * int(num))
|
97a4605437a98334fb3b356944b504f2ca457588 | natemago/advent-of-code-2019 | /day-2-program-alarm/solution.py | 1,331 | 3.5625 | 4 | def exec(program):
pc = 0
while True:
if pc < 0 or pc >= len(program):
print('PC outside range')
break
instr = program[pc]
if instr == 99:
print('Normal HALT')
break
a = program[pc + 1]
b = program[pc + 2]
dest = pr... |
bc23a915700dd7c8f593f9e27e17035e59987e7b | Percy-Cucumber/IND3156 | /homework_7/parabola.py | 314 | 3.5625 | 4 | #import
import random
#code
random.seed(42)
total=1000000*1000
out = 0
for i in range(total):
x = random.random()
y = random.random()
if ((-x)*x) + x > 1:
out = out + 1
#print
print( 4.0*(1.0-float(out)/float(total)))
#referenced https://pythonprogramming.net/monte-carlo-simulator-python/ |
b7f773a51b49ad7512c4dee4a860c49d2e600ba7 | ramalho/modernoopy | /examples/tombola/ibingo.py | 814 | 4.34375 | 4 | """
Class ``IBingo`` is an iterable that yields items at random from
a collection of items, like to a bingo cage.
To create an ``IBingo`` instance, provide an iterable with the items::
>>> balls = set(range(3))
>>> cage = IBingo(balls)
The instance is iterable::
>>> results = [item for item in cage]
... |
d77391b2a500f484e0438d722b683f76077610e5 | ramalho/modernoopy | /examples/countries/countries.py | 287 | 3.859375 | 4 | import dataclasses
@dataclasses.dataclass
class Country:
"""Represents a country with some metadata"""
name: str
population: float
area: float
def density(self) -> float:
"""population density in persons/km²"""
return self.population / self.area
|
3a8597f3280a8a10dff9731e090596fc79e0b67c | SLongofono/Python-Misc | /multiprocessing/multiprocessing_pools.py | 2,446 | 3.640625 | 4 | """
This demonstrates the use of asynchronous pools of workers using the multiprocessing
module. Due to some unfortunate choices on the back end, anonymous functions and
closures will not work. Similar constraints apply to the pool.map() construct. Things
like logging and shared queues are built in to the module, b... |
53bd12eb151b9514575a8958560352ddb44bd941 | SLongofono/Python-Misc | /python2/properties.py | 1,250 | 4.125 | 4 | """
This demonstrates the use of object properties as a way to give the illusion of private members and
getters/setters per object oriented programming. Variables prefixed by underscore are a signal to other
programmers that they should be changing them directly, but there really isn't any enforcement. There are
still... |
ab4a89539958603ec6a8b0586b1218ca6602b60c | marcimarc1/Pydoku | /Interface/classes.py | 3,525 | 3.6875 | 4 | import pygame
import time
pygame.font.init()
class Sudoku:
def __init__(self, board, width, height):
self.board = board
self.rows = 9
self.cols = 9
self.cubes = [[Cube(self.board[i][j], width, height) for j in range(self.cols)] for i in range(self.rows)]
self.width = width
... |
3aa2076bc76d17d5cb2c903e5089f9dc6c913a13 | acemourya/D_S | /C_1/Chatper-01 DataScience Modules-stats-Example/Module-numpy-example.py | 1,100 | 4.15625 | 4 | #numpy: numerical python which provides function to manage multiple dimenssion array
#array : collection of similar type data or values
import numpy as np
#create array from given range
x = np.arange(1,10)
print(x)
y = x*2
print(y)
#show data type
print(type(x))
print(type(y))
#convert list to array
d = [11,22,4... |
803761ecc916ed783192a842385ff34d1fffce5c | vibhor-vibhav-au6/CVRaman-solutions | /week04/day03.py | 1,153 | 4.09375 | 4 |
# Q1.
# Write a Python program to round the numbers of a given list, print the minimum
# and maximum numbers and multiply the numbers by 5. Print the unique numbers
# in ascending order separated by space.
# Original list: [22.4, 4.0, 16.22, 9.1, 11.0, 12.22, 14.2, 5.2, 17.5]
# Minimum value: 4
# Maximum value: 22
# R... |
bfa28ab12a8a5da15f46ea7daf625b9d26d75757 | sam98na/consolidatedCollegeWork | /cs188/python_basics/listcomp.py | 229 | 3.75 | 4 | nums = [1, 2, 3, 4, 5, 6]
oddNums = [x for x in nums if x % 2 == 1]
print(oddNums)
oddNumsPlusOne = [x + 1 for x in nums if x % 2 == 1]
print(oddNumsPlusOne)
def listcomp(lst):
return [i.lower() for i in lst if len(i) >= 5]
|
ae0009a76b00c9000d4cf023b55461676b6706b8 | cakmakaf/Project_Euler_Challenges | /sum_of_multiplies_3_or_5.py | 140 | 3.75 | 4 | total_sum = 0
for i in range(1000):
if (i % 3 == 0 or i % 5 ==0):
total_sum = total_sum + i
print(total_sum)
|
b9b836dffee50eea89374a9978eeb48a86431187 | vladosed/PY_LABS_1 | /3-4/3-4.py | 730 | 4.3125 | 4 | #create random string with lower and upper case and with numbers
str_var = "asdjhJVYGHV42315gvghvHGV214HVhjjJK"
print(str_var)
#find first symbol of string
first_symbol = str_var[0]
print(first_symbol)
#find the last symbol of string
last_symbol = str_var[-1]
print(last_symbol)
#slice first 8 symbols
print(str_var[s... |
46710e021657795e54522f6820ae99429b93b0bb | DinoSubbu/SmartEnergyManagementSystem | /backend/gasBoiler/hot_water_demand_api.py | 3,911 | 3.65625 | 4 | from datetime import datetime
import config
import csv
import os
############################################### Formula Explanation ##############################################
# Formula to calculate Heat Energy required :
# Heat Energy (Joule) = Density_Water (kg/l) * Specific_Heat_water (J/Kg/degree Celsius)... |
4b96b2b9227aa69affad957b559437872e1ed3ff | SpencerOfwiti/machine-learning-algorithms | /Neural Networks/image_classifier.py | 1,850 | 3.796875 | 4 | # import libraries
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
# load dataset
data = keras.datasets.fashion_mnist
# splitting data into training and testing data
(train_images, train_labels), (test_images, test_labels) = data.load_data()
# defining a list o... |
092484419e6ca5d7ea8c70c89c183c74cfffa743 | jisheng1997/pythontest | /main/list.py | 2,549 | 3.890625 | 4 | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
"""
@File : list.py
@Time : 2020/8/6 22:53
@Author : jisheng
"""
#列表索引从0开始。列表可以进行截取、组合
#列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
#列表的数据项不需要具有相同的类型
#变量表
list1 = ['Google', 'python', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list5 = ['b','a','h',... |
5af8ab9e91bc331bd64ac43aaaf6be59ac95c949 | divij-pherwani/Algorithms | /Corona Tracking App/Code.py | 1,189 | 3.5625 | 4 | import sys
def trackerApp(n, d, event):
ret = [""] * n
position = dict()
pairs = 0
for k, i in enumerate(event):
if i[0] == 1:
# Adding element
position[i[1]] = "Value"
# Adding number of pairs formed using the element
pairs = pairs... |
078677cc461c3047153af9b95bf1f94280fa2855 | wayhive/python_course | /python_course/demo1.py | 553 | 3.859375 | 4 | def print_name():
print("My name is Sey")
print_name()#calling a function
def print_country(country_name):
print("My country is " + country_name)
print_country("Kenya")
developer = "William and Sey"
def get_dev(The_string):
for x in The_string:
print(x)
get_dev(developer)
stuff = ["hospitals... |
b07283832e229a7e1b45f59784c7abc499dd8fce | davidwrpayne/PythonScripting | /postmasscustomers.py | 1,521 | 3.515625 | 4 | import urllib2
import json
import sys
import random
import base64
def main():
if len(sys.argv) == 1 :
print "Usage:"
print "Please provide an api host, for example 'https://s1409077295.bcapp.dev'"
print "create a legacy api user and token"
print sys.argv[0] + " <API_Host> <API_UserName> <APIToken>"
sys.ex... |
06368e81ea8b2e85b99fba1d001d6509eeec6a2c | cohn-julian/algorithms | /insertionSort.py | 372 | 3.515625 | 4 | #Insertion Sort. Best O(n) (nearly sorted) - worts/avg O(n^2)
import random
def sort(arr):
for i in range(1, len(arr) ):
val = arr[i]
j = i - 1
while (j >= 0) and (arr[j] > val):
arr[j+1] = arr[j]
j = j - 1
arr[j+1] = val
a = []
for i in range(50):
a.ap... |
39c9a51126bf6a3a8fe5d69b7ab180d279c647b3 | willyii/CS235-New-York-Airbnb | /Util/FillNa.py | 1,509 | 3.671875 | 4 | import pandas as pd
class FillNa:
def __init__(self):
self.fill_value = 0
def fit(self, data: pd.DataFrame, column_name: str, method ="mean" ):
"""
Fill the missing value, default use mean to fill
:param data: Dataset with missing value. Dataframe format
:param column... |
dcc1cb77098649757c8bc62c5820b002cde8a3b0 | Celia-xy/AIPathPlaning | /A_star.py | 11,435 | 4.25 | 4 | # The A* algorithm is for shortest path from start to goal in a grid maze
# The algorithm has many different choices:
# choose large or small g when f values are equal; forward or backward; adaptive or not
from GridWorlds import create_maze_dfs, set_state, get_grid_size, draw_grid
from classes import Heap, State
impo... |
1cab18caa6822e5a164a198ec77b243086b6a840 | phoenix1796/algorithms-practice | /mergeSort.py | 783 | 4.03125 | 4 | def merge(l1,l2):
ind1 = ind2 = 0
list = []
while ind1<len(l1) and ind2<len(l2):
if l1[ind1]<l2[ind2]:
list.append(l1[ind1])
ind1+=1
else:
list.append(l2[ind2])
ind2+=1
while ind1<len(l1):
list.append(l1[ind1])
ind1+=1
w... |
1874acb1d4c7dc6c1d0e3e90df8f303698e6bb20 | ssong319/Dicts-word-count | /wordcount.py | 924 | 3.765625 | 4 | # put your code here.
import sys
def count_words(filename):
the_file = open(filename)
word_counts = {}
for line in the_file:
#line = line.rstrip('?')
list_per_line = line.rstrip().lower().split(" ")
# out = [c for c in list_per_line if c not in ('!','.',':', '?')]
# print ... |
8e668075fd8ddc7f0209e8fcb24689eb2c3af0da | Noahprog/DataProcessing | /Homework/Week_3/convertCSV2JSON.py | 557 | 3.578125 | 4 | # Noah van Grinsven
# 10501916
# week 3
# convert csv to json format
import csv
import json
# specific values
def csv2json(filename):
csvfilename = filename
jsonfilename = csvfilename.split('.')[0] + '.json'
delimiter = ","
# open and read csv file
with open(filename, 'r') as csvfile:
rea... |
bc21452d6fe5e22f5580c172737d2cecea07dee5 | DimaLevchenko/intro_python | /homework_5/task_7.py | 739 | 4.15625 | 4 | # Написать функцию `is_date`, принимающую 3 аргумента — день, месяц и год.
# Вернуть `True`, если дата корректная (надо учитывать число месяца. Например 30.02 - дата не корректная,
# так же 31.06 или 32.07 и т.д.), и `False` иначе.
# (можно использовать модуль calendar или datetime)
from datetime import datetime
d = ... |
09a6e8d8e627becba4124c4fe37bbcc94020da82 | DimaLevchenko/intro_python | /homework_5/task_4.py | 763 | 3.875 | 4 | # Дан список случайных целых чисел. Замените все нечетные числа списка нулями. И выведете их количество.
import random
def randomspis():
list = []
c = 0
while c < 10:
i = random.randint(0, 100)
list.append(i)
c += 1
print('Список случайных чисел: ', list)
return list
spis =... |
0e68170f1d26748450f78365d974c7d052f67d52 | DimaLevchenko/intro_python | /homework_15/task_3.py | 1,288 | 4.0625 | 4 | # Вводимый пользователем пароль должен соответсвовать требованиям,
# 1. Как минимум 1 символ от a-z
# 2. Как минимум 1 символ от A-Z
# 3. Как минимум 1 символ от 0-9
# 4. Как минимум 1 символ из $#@-+=
# 5. Минимальная длина пароля 8 символов.
# Программа принимает на ввод строку, в случае если пароль не верный -
# пиш... |
46c58187e7ad3f322958c60ba51f4332cb0eaea9 | DimaLevchenko/intro_python | /homework_4/task_4.py | 353 | 4.03125 | 4 | # По данному натуральному `n ≤ 9` выведите лесенку из `n` ступенек,
# `i`-я ступенька состоит из чисел от 1 до `i` без пробелов.
n = int(input('Введите число: '))
for i in range(1, n+1):
for x in range(1, i+1):
print(x, end='')
print()
|
50b6fdeb9324f95234d1d15d3345e728f0c2d5d5 | goldiekapur/algorithm-snacks | /leetcode_python/22.Generate_Parentheses.py | 1,683 | 3.546875 | 4 | # https://leetcode.com/problems/generate-parentheses/
# 回溯. 逐个字符添加, 生成每一种组合.
# 一个状态需要记录的有: 当前字符串本身, 左括号数量, 右括号数量.
# 递归过程中解决:
# 如果当前右括号数量等于括号对数 n, 那么当前字符串即是一种组合, 放入解中.
# 如果当前左括号数量等于括号对数 n, 那么当前字符串后续填充满右括号, 即是一种组合.
# 如果当前左括号数量未超过 n:
# 如果左括号多于右括号, 那么此时可以添加一个左括号或右括号, 递归进入下一层
# 如果左括号不多于右括号, 那么此时只能添加一个左括号, 递归进入下一层
class ... |
5e39352eeb9519b9b17408456592cd4fc585473f | goldiekapur/algorithm-snacks | /leetcode_python/528.RandomPick_with_Weight.py | 792 | 3.65625 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Time complexity: O()
# Space complexity: O()
# https://leetcode.com/problems/random-pick-with-weight/
class Solution:
# 1 8 9 3 6
# 1 9 18 21 27
# 20
def __init__(self, w: List[int]):
for i in range(1, len(w)):
w[i] += w[i - 1]
... |
1d7e96d1abce1a5f23c20b18890761cabd363df0 | goldiekapur/algorithm-snacks | /leetcode_python/480.Sliding_Window_Median.py | 743 | 3.625 | 4 | #!/usr/bin/env python3
# coding: utf-8
# https://leetcode.com/problems/sliding-window-median/
import bisect
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
heap = nums[:k]
heap.sort()
mid = k // 2
if k % 2 == 0:
res = [(heap[mid] ... |
1e03ddfbc1e14e81606b805b55234686b2ccadd1 | goldiekapur/algorithm-snacks | /leetcode_python/417.Pacific_Atlantic_Water_Flow.py | 3,364 | 3.765625 | 4 | #!/usr/bin/env python3
# coding: utf-8
# https://leetcode.com/problems/pacific-atlantic-water-flow/
# 这道题的意思是说让找到所有点既可以走到左面,上面(pacific)又可以走到右面,下面(atlantic)
# dfs的思路就是,逆向思维,找到从左边,上面(就是第一列&第一排,已经是pacific的点)出发,能到的地方都记录下来.
# 同时右面,下面(就是最后一列,最后一排,已经是Atlantic的点)出发,能到的地方记录下来。
# 综合两个visited矩阵,两个True,证明反过来这个点可以到两个海洋。
# Time co... |
b9bd0caf3cb168ad51c9f36ab8390890ad50d9d4 | goldiekapur/algorithm-snacks | /leetcode_python/410.Split_Array_Largest_Sum.py | 940 | 3.625 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Time complexity: O()
# Space complexity: O()
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def valid(mid):
count = 1
total = 0
for num in nums:
total += num
if total > mid... |
74cb46e1099bbcd6f6c8a5c2be93829e6207fa14 | vnikhila/PythonClass | /operators.py | 606 | 4.0625 | 4 | a = int(input('Enter value for a\n'))
b = int(input('Enter value for b\n'))
print('\n')
print('Arithmetic Operators')
print('Sum: ',a+b)
print('Diff: ',a-b)
print('Prod: ',a*b)
print('Quot: ',b/a)
print('Remnder: ',b%a)
print('Floor Divisn: ',b//a)
print('Exponent: ',a**b)
print('\n')
print('Relational Operators')
pr... |
3d773a08b8a163465cc06cfccb597a47e809a17d | vnikhila/PythonClass | /listexamples.py | 1,797 | 4.1875 | 4 | # --------Basic Addition of two matrices-------
a = [[1,2],[3,4]]
b = [[5,6],[7,8]]
c= [[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(a[0])):
c[i][j] = a[i][j]+b[i][j]
print(c)
# -------Taking values of nested lists from user--------
n = int(input('Enter no of row and column: '))
a = [[0 for i in range(n)... |
9a0ceda7765af0638ec2a3c31f2665b7b7d7075a | vnikhila/PythonClass | /conditional.py | 207 | 4.34375 | 4 | #if else ODD EVEN EXAMPLE
a = int(input('Enter a number\n'))
if a%2==0:
print('Even')
else:
print('Odd')
# if elif else example
if a>0:
print('Positive')
elif a<0:
print('Negative')
else:
print('Zero') |
fe7c10f251dc3f5c806709a006ed1e853fffe240 | tarah-tamayo/aoc-2020 | /day20/20a.py | 11,881 | 3.5 | 4 | import sys
import re
from copy import deepcopy
class monster:
monster = None
def __init__(self):
self.monster = []
lines = [" # ", "# ## ## ###", " # # # # # # "]
for line in lines:
print(line)
m = ['1' if x == "#" else '0' for x... |
b5418dbfb626ef9a83a73a5de00da17e8e3822b5 | Kristjamar/Verklegt-namskei- | /Breki/Add_to_dict.py | 233 | 4.1875 | 4 | x = {}
def add_to_dict(x):
key = input("Key: ")
value = input("Value: ")
if key in x:
print("Error. Key already exists.")
return x
else:
x[key] = value
return x
add_to_dict(x)
print(x) |
2f6070d909963b329e87f5a220c3c9b65c4e9a24 | diksha-zodape/Miniproject | /generatePassword.py | 361 | 3.640625 | 4 | import random
import string
def generatePassword(stringLength=10):
password_characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(password_characters) for i in range(stringLength))
print("Random String password is generating...\n", generatePassword())
pri... |
6c3ef65cf9d656edcec4dc65982a7fcc8c1527fb | codewithpom/Factor-finder | /main.py | 171 | 3.90625 | 4 | factors = []
i = 0
number = int(input("Enter the number"))
while i <= number:
i = i+1
if number % i == 0:
factors.append(i)
print(factors)
|
130f575d861172289c27e110441b5719a1adda61 | kwax21/secu | /petite.py | 983 | 3.671875 | 4 | def premier(a):
if a == 1:
return False
for i in range(a - 1, 1, -1):
if a % i == 0:
return False
return True
def findEverythingForTheWin(a):
p = 2
q = 2
while 1 == 1:
if premier(p) and (n % p == 0):
q = int(n/p)
print("P : ", p)
... |
2cbf2c0fc7ba8e74f40c1bcf6c1e9fbaf50af798 | Talalkanjo01/GlobalAIHubPythonCourse | /Homeworks/HW2.py | 528 | 4.03125 | 4 | #Explain your work
first i took value from user then i used for loop to check numbers between 0 and number user has entered if are odd or even then i printed to screen
#Question 1
n = int(input("Entre single digit integer: "))
for number in range(1, int(n+1)):
if (number%2==0):
print(number)
#Question 2
my_list = [1,... |
b7da43bd8f29aab4f61c7a9d4e6e918ce606eef0 | gachiemchiep/source_code | /courses/problem_solving_with_algorithm_and_data_structures_using_python/4.5.stack.py | 2,590 | 3.90625 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(s... |
a1a96cb2f60c516e63b861e96479ae5c9937f857 | ritopa08/30-Days-Coding-Challenge | /day_26.py | 556 | 4.0625 | 4 | #-----Day 25: Running Time and Complexity-------#
import math
def isprime(data):
x=int(math.ceil(math.sqrt(data)))
if data==1:
return "Not prime"
elif data==2:
return"Prime"
else:
for i in range(2,x+1):
if data%i==0:
return "Not prime"... |
95d846c051abad8b7a718db79dd33c5f5e308923 | sabian2008/speciation_patterns | /analyze_interactive.py | 3,852 | 3.765625 | 4 | import numpy as np
import pickle
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
def gen_dist(genes):
"""Computes the genetic distance between individuals.
Inputs:
- genes: NxB matrix with the genome of each individual.
Output:
- out: NxN symmetric matrix with (out_ij)... |
935a2a6d789116d14739fc3572f1c283b0ea020d | akshatfulfagar12345/EDUYEAR-PYTHON-20 | /day 3.py | 176 | 3.8125 | 4 | int=a,b,c
b = int(input('enter the year for which you want to calculate'))
print(b)
c = int(input('enter your birth year'))
a = int((b-c))
print('your current age is',a)
|
58a8258c74f852fb7d0e44c79827ea23cd25bbbd | akshatfulfagar12345/EDUYEAR-PYTHON-20 | /day 6( Remove duplicate elements ).py | 266 | 3.609375 | 4 | data = [10,20,30,30,40,50,50,60,60,70,40,80,90]
def remove_duplicates(duplist):
noduplist = []
for element in duplist:
if element not in noduplist:
noduplist.append(element)
return noduplist
print(remove_duplicates(data))
|
32caa7eb3f40feade5b973c7b3f3c0b1b5650ca1 | Jordan71214/PythonPractice | /0425/pyPrac0425_02.py | 263 | 3.890625 | 4 | a = range(10)
print(a)
for i in a:
print(i)
name = (1, 2, 3, 5, 4, 6)
for i in range(len(name)):
print('第%s個資料是:%s' % (i, name[i]))
for i in range(1, 10, 2):
print(i)
b = list(range(10))
print(b)
print(type(b))
c = [1, 2]
print(type(c))
|
3141cca11b98778e6a419ec614939839ef906b3e | Jordan71214/PythonPractice | /0419/hello.py | 372 | 3.5 | 4 | import math
r = 15
print('半徑 %.0f 的圓面積= %.4f' % (r, r * r * math.pi))
print('半徑15的圓面積=', math.ceil(15 * 15 * math.pi))
print('半徑15的圓面積=', math.floor(15 * 15 * math.pi))
#math.ceil() -> 向上取整 換言之 >= 的最小整數
print(math.ceil(10.5))
#math.floor() -> 向下取整 換言之 <= 的最大整數
print(math.floor(10.5)) |
a181420a345cd7cb8a9d8ec6cc8a9fbd5624492c | RoncoGit/Uniquindio | /CondicionalesAnidadas.py | 1,434 | 4.03125 | 4 | print("================")
print("Conversor")
print("================ \n")
print("Menú de opciones: \n")
print("Presiona 1 para convertir de número a palabra.")
print("Presiona 2 para convertir de palabra a número. \n")
conversor = int(input("¿Cuál es tu opción deseada?:"))
if conversor == 1:
print("... |
bdc16e91fac7d1045b84f248b0fbb929e44bff0e | RoncoGit/Uniquindio | /CondicionalesMultiples.py | 571 | 4.1875 | 4 | print("===================================")
print("¡¡Convertidor de números a letras!!")
print("===================================")
num = int(input("Cuál es el número que deseas convertit?:"))
if num == 4 :
print("El número es 'Cuatro'")
elif num == 1 :
print("El número es 'Cinco'")
elif num == 2... |
0d2653d959843341a061b39ae6150472d43297dd | PWalis/Graphs | /projects/ancestor/ancestor.py | 1,915 | 3.90625 | 4 | from graph import Graph
from util import Queue
def bfs(graph, starting_vertex):
"""
Return a list containing the longest path
from starting_vertex
"""
earliest_an = None
# Create an empty queue and enqueue A PATH TO the starting vertex ID
q = Queue()
initial_path = [starting_vertex]... |
68683ee483f4bf0d25de8e9c6d8ae3d89c057be3 | syamms/Deep-Learning-Projects | /Deep Learning A-Z/Volume 1 - Supervised Deep Learning/Part 3 - Recurrent Neural Networks (RNN)/Recurrent_Neural_Networks/rnn_pratice.py | 2,416 | 4 | 4 | # -*- coding: utf-8 -*-
"""
08:08:21 2017
@author: SHRADDHA
"""
#Recurrent Neural Network
#PART 1 DATA PREPROCESSING
#importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing training set
training_set = pd.read_csv('Google_Stock_Price_Train.csv')
training_set = training... |
d199f3982f11b3c74a62f2ae3184acf486f990db | arren1234/Turtle-Race-Ultimate | /turtle race ultimate.py | 2,403 | 3.75 | 4 | import turtle #adds turtle functions
import random #adds random functions
t3 = turtle.Turtle()
t1 = turtle.Turtle()
t4 = turtle.Turtle() #adds turtles 3,1,4,6,7
t6 = turtle.Turtle()
t7 = turtle.Turtle()
wn = turtle.Screen() #adds screen
t1.shape("turtle")
t1.color("green") #colors and shapes bg an... |
683d036de36a774b4c26ff328c0ab1c6aa722bbb | houjf/PycharmProjects | /进阶/字典.py | 664 | 3.828125 | 4 | # class Student(object):
# def __init__(self, name, score):
# self.__name = name
# self.__score = score
#
# def print_score(self):
# print('%s, %s'%(self.__name, self.__score))
#
# def get_grade(self):
# if self.__score > 90:
# return print('A')
# elif 90 ... |
956d9f7797c6c5294ea475fc30cf8fec65ef0c3c | Vitoria0/Notepad | /Observações-07.py | 440 | 3.921875 | 4 | #Tratamento de Erros e Exceções
try: #-------tente
a = int(input('Numerador: '))
b = int(input('Dennominador: '))
r = a / b
except ZeroDivisionError:
print('Não se pode dividir por zero')
except Exception as erro:
print(f'O erro encontrado foi {erro.__cause__}')
else: #------Se não... |
df86c8f38f511f08aa08938abba0c79875727eb9 | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/conditionals/odd_even.py | 234 | 4.46875 | 4 | # Write a program that reads a number from the standard input,
# then prints "Odd" if the number is odd, or "Even" if it is even.
number = int(input("enter an integer: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
|
39147e634f16988b71a0aee7d825d8e93def5359 | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/user_input/average_of_input.py | 316 | 4.34375 | 4 | # Write a program that asks for 5 integers in a row,
# then it should print the sum and the average of these numbers like:
#
# Sum: 22, Average: 4.4
sum = 0
number_of_numbers = 5
for x in range(number_of_numbers):
sum += int(input("enter an integer: "))
print("sum:", sum, "average:", sum / number_of_numbers)
|
a314a1eef3981612f213986b9d261adaf2ff85ce | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/arrays/reverse_list.py | 327 | 4.46875 | 4 | # - Create a variable named `numbers`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements of `numbers`
# - Print the elements of the reversed `numbers`
numbers = [3, 4, 5, 6, 7]
temp = []
for i in range(len(numbers)):
temp.append(numbers[len(numbers)-i-1])
numbers = temp
print(n... |
31170eab6926b9a475fe8fb1b7258571d762b96e | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/data_structures/list_introduction_1.py | 1,247 | 4.78125 | 5 | # # List introduction 1
#
# We are going to play with lists. Feel free to use the built-in methods where
# possible.
#
# - Create an empty list which will contain names (strings)
# - Print out the number of elements in the list
# - Add William to the list
# - Print out whether the list is empty or not
# - Add John to t... |
e5da5de6c4ab02f17214140dfff12d23b5d9d4ba | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_03/oop/blog_post/blog_post.py | 1,713 | 3.890625 | 4 | # # BlogPost
#
# - Create a `BlogPost` class that has
# - an `authorName`
# - a `title`
# - a `text`
# - a `publicationDate`
class BlogPost:
def __init__(self, author_name, title, text, publication_date):
self.author_name = author_name
self.title = title
self.text = text
self... |
e10add30914bc94d9ce15807c45746ad49175d5b | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_03/oop/pokemon/pokemon.py | 1,164 | 4 | 4 | class Pokemon(object):
def __init__(self, name, type, effective_against):
self.name = name
self.type = type
self.effectiveAgainst = effective_against
def is_effective_against(self, another_pokemon):
return self.effectiveAgainst == another_pokemon.type
def initialize_pokemons()... |
238f272124f13645a7e58e8de1aaee8d9a433967 | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/loops/count_from_to.py | 634 | 4.28125 | 4 | # Create a program that asks for two numbers
# If the second number is not bigger than the first one it should print:
# "The second number should be bigger"
#
# If it is bigger it should count from the first number to the second by one
#
# example:
#
# first number: 3, second number: 6, should print:
#
# 3
# 4
# 5
a = ... |
ca2c31265c491c989bdd6b34fb2e66f05614750f | ec36339/evescripts | /evepraisal.py | 2,223 | 4.03125 | 4 | """
Convert JSON output from https://evepraisal.com/ into CSV data that can be pasted into Excel.
The script arranges the output in the same order as the input list of items,
so the price data can be easily combined with existing data already in the spreadsheet
(such as average prices, market volume, etc.)
It requ... |
eacc98d8a0ccf38be757c6693c93ebdaf33848c1 | carrillobenjamin/Carrillo_B_Dataviz | /data/medalprogress.py | 484 | 3.5 | 4 | import matplotlib.pyplot as plt
years = [1924, 1928, 1932, 1936, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1994, 1998, 2002, 2006, 2010, 2014]
medals = [9, 12, 20, 13, 20, 17, 20, 21, 7, 20, 1, 3, 2, 4, 6, 37, 40, 49, 75, 68, 91, 90]
plt.plot(years, medals, color=(255/255, 100/255, 100/... |
598836e5e5920d1ba4c73c4e4b9e143690a0af95 | Lord-Chronos/DoorBellBotPlus | /tictactoe.py | 970 | 3.953125 | 4 | def game(player1, player2):
turn = 1
game_over = False
start_board = ('```'
' 1 | 2 | 3 \n'
' - + - + - \n'
' 4 | 5 | 6 \n'
' - + - + - \n'
' 7 | 8 | 9 '
'```')
while not game_over:
... |
99dc9f1f0571c4511567a1d5e6bd83d2e7ab2a96 | Vitor-Aguiar/TheTools | /Wordlist-Gen.py | 1,436 | 3.796875 | 4 | import os
import sys
# -t @,%^
# Specifies a pattern, eg: @@god@@@@ where the only the @'s, ,'s,
# %'s, and ^'s will change.
# @ will insert lower case characters
# , will insert upper case characters
# % will insert numbers
# ^ will... |
27a458c5355a32cf2bc9eb53cef586a8120e9e36 | hr4official/python-basic | /td.py | 840 | 4.53125 | 5 | # nested list
#my_list = ["mouse", [8, 4, 6], ['a']]
#print(my_list[1])
# empty list
my_list1 = []
# list of integers
my_list2 = [1, 2, 3]
# list with mixed datatypes
my_list3 = [1, "Hello", 3.4]
#slice lists
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
... |
38277e97e74594103b4eb709affdbfb99d3c3457 | hr4official/python-basic | /dict.py | 544 | 4.09375 | 4 | # empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
"""
marks = {... |
8971b06f5b722e21f4f48faf778e4ffa758146a4 | CircuitLaunch/colab_reachy_ros | /src/head_motor_control.py | 4,983 | 3.6875 | 4 | #!/usr/bin/env python3
# creates a ros node that controls two servo motors
# on a arduino running ros serial
# this node accepts JointState which is
# ---------------
# would the datastructure look like
# jointStateObj.name = ["neck_yaw", "neck_tilt"]
# jointStateObj.position = [180,0]
# jointStateObj.velocity# unused... |
03ffdbf920e309ebb68d396e033b44d8848a6952 | bk2coady/ProjectEuler | /ProjectEulerS1.py | 499 | 4.03125 | 4 | #Problem1
#Find sum of all numbers which are multiples of more than one value (ie 3 and 5)
#remember to not double-count numbers that are multiples of both 3 and 5 (ie multiples of 15)
def sumofmultiples(value, max_value):
total = 0
for i in range(1,max_value):
if i % value == 0:
#print(i)
total =... |
6d09a3651b149aad6a6d4c96626062b969ca88db | bk2coady/ProjectEuler | /ProjectEulerS9.py | 444 | 3.890625 | 4 | #Problem9
#find pythagorean triplet where a + b + c = 1000
def pythag_check(a, b):
c = (a*a + b*b) ** 0.5
#print(c)
if c == int(c):
return True
return False
def pythag_triplet(k):
for i in range(1,k-1):
for j in range(1,k-i):
if pythag_check(i,j):
c = int((i*i + j*j) ** 0.5)
if i + ... |
c0355b2269c01bed993270e4472d1771ffab9527 | sharikgrg/week3.Python-Theory | /104_data_type_casting.py | 316 | 4.25 | 4 | # casting
# casting is when you change an object data type to a specific data type
#string to integer
my_var = '10'
print(type(my_var))
my_casted_var = int(my_var)
print(type(my_casted_var))
# Integer/Floats to string
my_int_vaar = 14
my_casted_str = str(my_int_vaar)
print('my_casted_str:', type(my_casted_str)) |
cff7d4a762f14e761f3c3c46c2e656f74cb19403 | sharikgrg/week3.Python-Theory | /exercises/exercise1.py | 745 | 4.375 | 4 | # Define the following variable
# name, last name, age, eye_colour, hair_colour
# Prompt user for input and reassign these
# Print them back to the user as conversation
# Eg: Hello Jack! Welcome, your age is 26, you eyes are green and your hair_colour are grey
name = input('What is your name?')
last_name = input('Wh... |
cda99da103298b6c26c29b9083038a732826be11 | sharikgrg/week3.Python-Theory | /102_data_types.py | 1,736 | 4.5 | 4 | # Numerical Data Types
# - Int, long, float, complex
# These are numerical data types which we can use numerical operators.
# Complex and long we don't use as much
# complex brings an imaginary type of number
# long - are integers of unlimited size
# Floats
# int - stmads for integers
# Whole numbers
my_int = 20
prin... |
d42b8c1bfab1011862b843d6166ee0bb41f857b8 | pranjay04/algorithms-and-data-structures | /search/python/binarysearch_rec.py | 393 | 3.796875 | 4 | def binarysearch_rec(array, key):
l = 0
h = len(array) - 1
def search(array, l, h, key):
if l > h:
return False
mid = (l + h)//2
if array[mid] == key:
return mid
if key < array[mid]:
h = mid - 1
else:
l = mid + 1
... |
f56178664ed321ef7b8ad9a3696f5fe7cf0cee10 | clarkmyfancy/Hangman | /Console.py | 1,033 | 3.703125 | 4 | class Console:
def printStartupSequence(self):
print("Let's play Hangman!")
def printScoreboardFor(self, game):
word = game.secretWord
isLetterRevealed = game.lettersRevealed
outputString = ""
for x in range(0, len(word)):
outputString += word[x] if isLetterRevealed[x] == True else "_"
outputString ... |
a826b8384e312b2ccfdeb01f0d84446870734b5c | knutss/PyWake | /py_wake/deflection_models/deflection_model.py | 1,068 | 3.5 | 4 | from abc import ABC, abstractmethod
class DeflectionModel(ABC):
args4deflection = ["ct_ilk"]
@abstractmethod
def calc_deflection(self, dw_ijl, hcw_ijl, dh_ijl, **kwargs):
"""Calculate deflection
This method must be overridden by subclass
Arguments required by this method must be... |
4173a8b376cb1c007c103999e1f352299bb8f810 | TeresaRem/CodingDojo | /Python/selectionSort.py | 829 | 3.84375 | 4 | ## selectionSort.py
import random, datetime
def selectionSort(arr):
a = datetime.datetime.now()
min = arr[0]
start = 0
for i in range(0,len(arr)-1):
for j in range(start,len(arr)):
if arr[j] < min:
min = arr[j]
index = j
# print "current minimum is {} at index {}".format(min,index)
if arr[start] ... |
54ce45e8ca61bcdbe1df2a33b3abf1250dac665a | TeresaRem/CodingDojo | /Python/animal.py | 1,006 | 3.890625 | 4 | # animal.py
class Animal(object):
def __init__(self,name):
self.name = name
self.health = 100
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print "name is {}".format(self.name)
print "health is {}".format(self.health)
return self... |
a0cd809b0d43cbb95f2e80b7459959e23c76d4c2 | TeresaRem/CodingDojo | /pylot/restful_routes/app/models/Product.py | 1,414 | 3.703125 | 4 | from system.core.model import Model
class Product(Model):
def __init__(self):
super(Product, self).__init__()
"""
Below is an example of a model method that queries the database for all users in a fictitious application
Every model has access to the "self.db.query_db" method which allows y... |
e9d15c1e46656bbed8240b591c5c848d6bc13dcf | TeresaRem/CodingDojo | /pylot/login/app/controllers/Users.py | 3,002 | 4.125 | 4 | """
Sample Controller File
A Controller should be in charge of responding to a request.
Load models to interact with the database and load views to render them to the client.
Create a controller using this template
"""
from system.core.controller import *
class Users(Controller):
def __init__(sel... |
5cba492f9034b07ca9bc7d266dca716ea684ba3c | sdhanendra/coding_practice | /DataStructures/linkedlist/linkedlist_classtest.py | 1,647 | 4.5 | 4 | # This program is to test the LinkedList class
from DataStructures.linkedlist.linkedlist_class import LinkedList
def main():
ll = LinkedList()
# Insert 10 nodes in linked list
print('linked list with 10 elements')
for i in range(10):
ll.insert_node_at_end(i)
ll.print_list()
# delete... |
518b0d4700b932388532ed42c21614a78006015c | jaxmandev/Python_OOP | /python.py | 815 | 4.09375 | 4 | # Creating a python class as child class of our Snake class
from snake import Snake
class Python(Snake):
def __init__(self):
super().__init__()
self.large = True
self.two_lungs = True
self.venom = False
# creating functions for our python class
def digest_large_prey(self... |
058dc3932000b0d290652ff758d3d8653ac1c5f5 | GIS-PuppetMaster/EVO-TSP | /Selection.py | 2,796 | 3.78125 | 4 | from math import *
import random
import copy
def fitnessProportional(problem, population):
"""
# because our fitness is the distance of the traveling salesman
# so we need to replace 'fitness' with '1/fitness' to make sure the better individual
# get greater chance to be selected
:param problem: t... |
804ebb78ded35b6817a5a1a32b15f8bfa7b0605a | tonimk/testi | /myscript.py | 814 | 3.8125 | 4 | # Kommentti esimerkin vuoksi tähän
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Anna ikä kokonaislukuna, kiitos!")
continue
else:
return userInput
break
i = 0
while i < 3:
nimi = input("Anna nimesi: "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.