blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2b4e37df98e5fbe101bd2fb9fecacf470f8167cd | YatinGupta777/Python-Programs | /Gfg/TriangleArea.py | 420 | 4.15625 | 4 | # Python Program to find the biggest triangle
# which can be inscribed within the rectangle
# Function to find the area
# of the triangle
def trianglearea(l, b) :
# a and b cannot be negative
if (l < 0 or b < 0) :
return -1
# area of the triangle
area = (l * b) / 2
return ar... |
e6d2189fc9979025f32d115a9328ebbca5280c5c | FloncDev/RandomProjects | /Dice.py | 553 | 3.859375 | 4 | import random
randomnumber = random.randint(1, 6)
if randomnumber == 1:
print("""
•
""")
elif randomnumber == 2:
print("""
•
•
""")
elif randomnumber == 3:
print("""
•
•
•
""")
elif randomnumber == 4:
print("""
• •
• ... |
f0c538809e4de94428871e37684f68b047b3940a | jiroblea/Self-Taught-Programmer-Book | /Text-Based-Game/Tic-Tac-Toe-Game.py | 2,016 | 3.9375 | 4 | # A TIC-TAC-TOE GAME!
# print(board[1], board[5], board[9])
# print(board[13], board[17], board[21])
# print(board[25], board[29], board[33])
def checker(board, player, plyr_symbol):
if (plyr_symbol == board[1] == board[5] == board[9]) or (plyr_symbol == board[13] == board[17] == board[21]) or (plyr_symbol == boa... |
249ec79c52a76d2501e51f8b70a7183a074ef182 | Marco9412/PyMusicServer3 | /src/utils/rpcutils.py | 565 | 3.84375 | 4 |
def intDictToStringDict(dictionary):
"""
Converts dictionary keys into strings.
:param dictionary:
:return:
"""
result = {}
for k in dictionary:
result[str(k)] = dictionary[k]
return result
def stringDictToIntDict(dictionary):
"""
Converts dictionary keys into integers... |
8c940287e50bd9ab33726df6f31e77ab6d55acef | harry671003/coursera-algorithmic-toolbox | /week-3/min_groups.py | 1,613 | 4.0625 | 4 | """Min Groups Module"""
def min_groups(points, max_segment_length):
"""Minimum Groups
Divides a set of points of segments of MaxSegmentLength
returns the count of minimum groups
Uses Greedy Approach
"""
group_count = 0 # the count of groups
segments = [] # The map of segments
... |
dde095d241ac959641d8cee1bfe671b0a79f07df | mehman96/PythonThinkBigger | /task02/run.py | 1,081 | 4.0625 | 4 | # magicMethod(param) adında bir metod yazın.Bu ele bir metod olsun ki argument olaraq verilən param
# arraydirsə onun içindəki bütün elementləri ekrana çap elesin
# obyektdirsə onun properylerini ekrana cap etsin
# rəqəmdirsə kvadratını ekrana çap etsin
# stringdirsə cüt yerdə duran hərfləri böyük hərfə çevirsin
# 1
... |
95122c98985e6bd3e51530d2a5796dd695bf30fa | GiaDieu/Python-exercises | /exercises/ex3_6.py | 1,914 | 3.6875 | 4 | #!/usr/bin/env python3
'''
Input: một số nguyên trong range(1,13).
Output: tên tương ứng của tháng đó bằng tiếng Anh, và số ngày trong tháng đó.
Tháng 2 tính 28 ngày.
Ví dụ:
- input_data: 2
- output: February 28
'''
# def solve(input_data):
# '''Trả về 1 `tuple` chứa 2 phần tử, ví dụ:
# input_data: 2... |
521db94aef58d8a3ced6d011c569b85a0f2aee4b | nguyenhoangson/Final-Year-Project | /tensorflow/basic_tensorflow.py | 1,733 | 4.0625 | 4 | ### Play and experiment with TensorFlow basic concepts:
### Link: https://www.tensorflow.org/versions/r0.12/get_started/basic_usage.html
### 1. Computation graph
### 2. Variables
### 3. Fetch
import tensorflow as tf
### Create ops node in computation graph
### tensorflow ops node will return an object
### which rep... |
4cbdc41c14f2bd1a50487543c917f74e0432fdec | heimi520/myLearn | /Meorient/my_part01/to_cat_test.py | 3,439 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 12 11:49:16 2019
@author: heimi
"""
import pandas as pd
import numpy as np
#
#def to_categorical(y, num_classes=None, dtype='float32'):
# """Converts a class vector (integers) to binary class matrix.
#
# E.g. for use with categorical_crosse... |
b7d19dbe822f906d45e58c163054a8a153481a5c | fexxsuku/sukumar | /prime.py | 180 | 3.84375 | 4 | s=int(input())
flag=1
for x in range(2,s//2):
if(s%x==0):
flag=1
break
else:
flag=0
if(flag==0 or s==2):
print("yes")
else:
print("no")
|
b8850c6c8378aa06318dc9c4547f0e8fb6c9ecff | Inabiel/Codewars_Answer | /answer_python/replace_word.py | 182 | 3.5625 | 4 | def alphabet_position(text):
text = text.lower()
word = " ,.':`!@#$%^&*()1234567890-_=+"
res = [str(ord(i) - 96) for i in text if i not in word]
return " ".join(res)
|
9352903711402fd58fc0fbf2e50434a50395c195 | redbearsw/redbearsw | /euler/p41.py | 1,425 | 3.875 | 4 | import math
# What is the largest n-digits pandigital prime?
# original idea:
# start with n = 9, and go down
# start with 987654321, then 987654312, keep permuting in order
# check if number is prime
# revised idea:
# run through numbers starting at 987654321
# check if it's a permutation, then check if it's prime
... |
89642a819fa931a114a1b16fd89968c3a8b23a83 | AbhinavSingh-21f1002369/ns_21t2_cs1002-ProgrammingAssignments | /week3/activity/n1_n2.py | 210 | 3.609375 | 4 | n1 = int(input())
n2 = int(input())
n1_count = 0
n2_count = 0
while n1>0:
n1 = n1 // 10
n1_count += 1
while n2>0:
n2 = n2 //10
n2_count += 1
if n1_count==n2_count:
print("True")
else:
print("False") |
fd6e8bb7dcf42ab96fd24efc75b3d7d32b371c17 | metanoia1989/PythonStudy | /DesignPattern/14_状态模式/curses_demo.py | 914 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python3没有适用的版本非常可惜
"""
import time
import curses
if __name__ == "__main__":
win = curses.initscr()
curses.noecho()
win.addstr(0, 0, "press the keys w a s d to initiate actions")
win.addstr(1, 0, "press x to exit")
win.addstr(2, 0, "> ")
win.m... |
3a0bab4a8e222248139399f6d48dcc61a73de9e0 | lycsjm/acgnmanager | /src/lib/util.py | 775 | 3.953125 | 4 | import datetime
def getSeason(date=datetime.date.today()):
'''
return 2-tuple of datetime.date as anime start date range.
consider some anime will start some days before season of given days,
return will not exectally as same as season.
example:
>>> getSeason(datetime.date(2014, 1, 13))
(... |
52ae30a53a891918628178bc1738e8e576288dca | iampkuhz/OnlineJudge_cpp | /leetcode/python/passedProblems/49-anagram.py | 1,021 | 4.09375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note:
For the return value, each inner list's elements must follow the lexicographic order.
Al... |
9a02a60468845a948c4bf33a70068233214cc781 | anantkaushik/Competitive_Programming | /Python/GeeksforGeeks/repeated_id.py | 1,036 | 3.890625 | 4 | """
Raghav is given a task to select at most 10 employees for a company project.
Each employee is represented by a single digit I.D. number which is unique for all the
selected employees of the project. Raghav has a technical problem in his system which
printed I.D. number multiple times. Help him to get rid of the... |
71f6f00677adc6b8dc70f58ab46074d7da62291e | sglavoie/code-snippets | /python/csv/unique_values_from_columns.py | 2,507 | 3.984375 | 4 | """
E.g., input (as CSV):
COL1 COL2 COL3
A B C
A B D
A B E
A B F
Output:
COL1 COL2 COL3
A B C
D
E
F
Or merge on COL1 and COL2:
MERGED_COL COL3
A C
B D
E
F
"""
import csv
COLUMNS_TO_TRACK_UNIQUE_V... |
d6f414fda727e1038573789170522a4736615b81 | oldmud0/steam-friends-crawler | /steamuser.py | 742 | 3.65625 | 4 |
class SteamUser:
"""Represents a local, out-of-database copy of a Steam user.
No guarantees are made on whether or not a SteamUser has already been
copied to the database or not.
"""
def __init__(self, steamid, private=False):
self.steamid = steamid
self.private = private
... |
e91f2cf9c62170eb5a3d8c258cd6c325601ec87c | kjgalvan/maze-scripting-puzzle | /src/300_Puzzle/file6.py | 411 | 3.765625 | 4 | #!/bin/usr/python
board = [["X","X","X","X","X","X","X"],
["X","X","X","X"," "," "," "],
["X","X","X","X","o","X"," "],
["X","X","X","-","X","X"," "],
["X","X","X"," "," "," "," "],
["X","X","X","X","X","X","X"]]
def getBoard():
return board
def printBoard():
prin... |
ac15bf274ae7a67d8c1ecf691435b6cce66b6d3d | Takerhythm/learning | /CLRS/data_structure/binary_search_tree.py | 3,161 | 3.8125 | 4 | import random
class TreeNode:
def __init__(self, val=None, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
class BinarySearchTree:
def __init__(self, root):
self.root = root
def in_order_tree_walk(self,... |
6e75bd97ce0efbf97258c6a9dedcc100622c040f | Omar-Jamal/Tulip-School- | /TimeZone.py | 2,341 | 4 | 4 | t = ("1.istanbul")
i = ("2.london")
j = ("3.tokyo")
u = ("4.newyork")
print("this program helps the user to know the times of these cities")
print(t, i, j, u)
print("please enter choice (1,2,3,4)")
que1 = input("where are you live ?")
if que1 == "1":
print(" Now the time in Istanbul is ")
from datet... |
5311bc4c94bb0af585eea4974653651ff43c6d4e | saurabh896/v3 | /languages/python/exercises/concept/comments/.meta/example.py | 398 | 3.734375 | 4 | # I am single line comment
""""
This is multi line comment
Program Build Date: 13-05-2020
Author:Saurabh
Team:Developer
Project: exercism"""
bank_name = "State Bank of India " # This line denotes bank name
print(bank_name) # Bank name printed with out comment on line 3
def looper(): # This program iterate from nu... |
6bff507646d727623a2b04e655880639886e397e | vishrutkmr7/DailyPracticeProblemsDIP | /2023/03 March/db03222023.py | 897 | 4 | 4 | """
Given an array of integers, nums, return the “equality index” if it exists and negative one otherwise.
Note: The equality index of the array is the index where the sum of all elements to the left of the
index is equal to the sum of all elements to the right of the index.
Ex: Given the following nums…
nums = [1, 2... |
775356a20a5f744a1f4c2835efa0d3ccc9863776 | tr1503/LeetCode | /Stack/indexDiff.py | 582 | 3.625 | 4 | # get the index difference of first number after this element that is larger than this element
# if there is no number larger than this element, return -1
def indexDiff(nums):
if len(nums) == 0:
return []
res = [-1 for _ in range(len(nums))]
stack = [] # add [number, index]
for i, num in enumerate(nums):
while... |
db937c00d9a687766e32c13d52b167692b26d429 | jczhangwei/leetcode_py | /199.二叉树的右视图.py | 2,202 | 3.84375 | 4 | #
# @lc app=leetcode.cn id=199 lang=python3
#
# [199] 二叉树的右视图
#
# https://leetcode-cn.com/problems/binary-tree-right-side-view/description/
#
# algorithms
# Medium (64.40%)
# Likes: 356
# Dislikes: 0
# Total Accepted: 73K
# Total Submissions: 113.2K
# Testcase Example: '[1,2,3,null,5,null,4]'
#
# 给定一棵二叉树,想象自己站在它... |
7151e1aea3895c5b0f31728c73106de059483304 | xico2001pt/feup-fpro | /Play/Py11/count_zeros.py | 641 | 4.3125 | 4 | """
Write a Python function count_zeros(f) that receives a function f that when called produces a list of integers alist. This list has several 1s followed by 0s (for example, alist=[1, 1, 1, 0, 0]). Your function must count the number of zeros on that list.
The naive solution would iterate through the list in O(n) ti... |
184cd25bd1259bb7c02fc0251336cabf803196be | adithyanarayanan/CTCI-Python-Solutions | /Question_2_1_with_buffer.py | 647 | 4.0625 | 4 | from LinkedList_Helpers import *
# With extra space allowed
# We will assume we have a doubly linked list
def removeDuplicates(head):
if head is None:
return head
duplicates = set()
node = head
while node is not None:
if node.value in duplicates:
# this will not be entered when node = head
node.prev.nex... |
8b0367ba1c31c194c3bd456a59f95b570fd053a3 | atsnova/Python-Crash-Course | /Cases.py | 279 | 3.71875 | 4 | name = " Atish"
surname = " parshotam "
middle = "ashOk "
title = "mr"
print(name.title())
print(name.lower())
print(middle.upper())
print(title.upper() + name.title() + surname.upper().rstrip().ljust(1, "-"))
print("\t Atish")
# THIS IS A COMMENT
print(5+8) |
c737d277944d85cb198c3a10effd6c85ec7957d2 | nzokereke/Giraffe | /09_while&forLoop.py | 680 | 4.28125 | 4 | """ --------- Condition Statement: While Loop ---------------
1. Here you iterate a statement as long as the condition is true
2. usually when the number of times to iterate is unknown
2. A variable is declared where that condition is tested (counter)
"""
# x = 0
#
# while x < 5:
# print('loop,... |
9c23f95c0566812444bb1d4e99fceb23fe34cc4e | maximvs-fit/DevOps-EAD | /Extensões/Python/Testes/idAlunos.py | 209 | 3.515625 | 4 | #pessoas = {1:"zezinho",2:"Huguinho",3:"Luizinho"}
#print(len(pessoas))
#print(list(pessoas.values()))
#print(list(pessoas))
valores = [1,2]
novo = []
for i in valores:
novo.append(1%2)
print(novo)
|
fd8a4c1a67571a4c655b56be009b23711ad616cf | Shiozaki91/pythonPractice | /Object/findID.py | 1,022 | 4.09375 | 4 | # Pythonでは、生成されたオブジェクト全てにユニークなIDが割り振られる
# IDはid()組み込み関数で調べることができる
# stringクラスのオブジェクトを生成する
name = "Hello Python!"
# id()により、取得したID番号を出力する
print(id(name))
# ちなみに、pythonではプリテミィブな値は基本的にイミュータブルである
number1 = 10
number1 = number1 + 5
# とすると、一見ミュータブルに見えるが生成直後と計算直後のidをみると
number1 = 10
print(id(number1))
number1 = number1 + ... |
c266eb276df78426f33f7b5149a58eb6e65b9594 | mattyr3200/python | /testing/password cracker.py | 679 | 3.59375 | 4 | import string
import random
password = "Strek123!"
already_done = []
def logic_logarithm():
cracker = ""
while 1:
if cracker != password:
size = 9
chars = string.digits + string.punctuation + string.ascii_letters
cracker = ''.join(random.choice(chars) for _ in range... |
42e26d8864ddc14af71fcbfd98dfe030b03c1730 | Marlrero/2019_Python | /chap09_tkinter/chap09_canvas_arc.py | 217 | 3.546875 | 4 | from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
canvas.create_arc(10, 10, 200, 150, extent=90, style=ARC)
# extent 매개변수는 각도를 지정
window.mainloop() |
bfb73fb2634a16574d0592d20f183c7bcb819a93 | pengwenfan012836/day1 | /day1/shopCart/shopCart.py | 1,283 | 3.765625 | 4 | #! D:/table/python3/python
# 所有产品的信息
# 下面使用的是python3的语法
import time
info = {
1: {
'name': 'banner',
'price': 20,
},
2: {
'name': 'origin',
'price': 30,
},
3: {
'name': 'chestnut',
'price': 50,
}
}
print('\t\t\t\t\t\t\t欢迎来到水果商城!')
print('\t\t\t\t\... |
b582198eaa2401472ef64d8ff94b3260fc20dad4 | Licho59/Licho-repository | /inne_projekty/problem_solving_with_algorithms/4_3_liter_jugs.py | 691 | 3.90625 | 4 | '''Write a program to solve the following problem: You have two jugs: a 4-gallon jug and a 3-gallon jug. Neither of the jugs have markings on them. There is a pump that can be used to fill the jugs with water. How can you get exactly two gallons of water in the 4-gallon jug?'''
def fill_water(big, small, task):
b... |
1052511e41c877118216ab114d96cc21d3846a5b | jianhui-ben/leetcode_python | /67. Add Binary.py | 1,199 | 3.875 | 4 | #67. Add Binary
#Given two binary strings, return their sum (also a binary string).
#The input strings are both non-empty and contains only characters 1 or 0.
#Example 1:
#Input: a = "11", b = "1"
#Output: "100"
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
... |
ddb28000c77698399ca50f202f80ca80fbb2c21d | srinivasskc/Python-Programming-Learning | /Python150Challenges/Strings/20-26 Challenges/Challenge24.py | 132 | 4.46875 | 4 | # 024 Ask the user to type in any word and display it in upper case.
word = input("Enter any country name: ")
print(word.upper())
|
f2a6b1ffd7c7c556a3bd6688a50a2ca9deaf692e | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/308.py | 167 | 3.578125 | 4 | def word_count(strings):
d = {}
for s in strings.split():
if d.has_key(s):
d[s] = d[s] + 1
else:
d[s] = 1
return d
|
dc4a16bacdbd40050c9c135923ba24adb43cb9d6 | shivamthapar/coding-problems | /power.py | 497 | 4.4375 | 4 | """
Given two positive integers x and y, find x^y.
"""
"""
Runtime complexity: O(log y)
Space complexity: O(1)
Reference: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
Use the fact that:
x ^ y = { x(x^2)^((y-1)/2) if y is odd
(x^2)^(y/2) if y is even
}
"""
def power(x,y):
ret ... |
02c902ebb6e29c7e423a0ec27f79b23e7bc39534 | SupremeDin/My_Material | /ML/coursera/1.Linear_Regression/gradientDescent.py | 593 | 3.8125 | 4 | # batch gradient descent
# 批量梯度下降算法:每迭代一次,即同步更新所有的theta。
import numpy as np
from computeCost import *
def gradientDescent(X,y,theta,alpha,epoch):
temp = np.matrix(np.zeros(theta.shape)) #temp为(1,2)的矩阵,为了同步更新
cost = np.zeros(epoch) #存放每次迭代完成后计算出的cost,迭代epoch次,存放epoch个值
m = X.shape[0]
for i in range(e... |
f13ad92cdaaf4a48c18a3fa1c28dcac22b050268 | Sandesh-Thapa/Assignment-I-Data-Types-and-Functions | /Data Types/q16.py | 214 | 4.15625 | 4 | # Write a Python program to sum all the items in a list.
list = []
sum = 0
n = int(input('Enter Number of Items: '))
for i in range(0,n):
num = int(input(f'Enter {i+1}th number: '))
sum += num
print(sum) |
b7cc3cc1c1e71647115f2ceb22f108d5bb287639 | dimitar-daskalov/SoftUni-Courses | /python_advanced/exams/exam_preparation/exam_14_february_2021/problem_02.py | 1,720 | 3.84375 | 4 | from math import floor
def is_in_range(moving_position_row, moving_position_col, size):
if 0 <= moving_position_row < size and 0 <= moving_position_col < size:
return True
return False
matrix_size = int(input())
coins = 0
matrix = []
player = "P"
player_starting_position = 0
POSITIONS = {"up": (-1, ... |
91d7b7fd3ccdd7f1c7f4c688d1f25bfb63702270 | ms-shakil/52-problems-and-solve | /problem_thirty.py | 321 | 3.625 | 4 | # perfect number 2
value = int(input("Enter the number:"))
def MyFunction(value):
lst =[]
for i in range(1,value,1):
count=0
for j in range(1,i,1):
if i % j == 0:
count+=j
if count == i:
lst.append(i)
return lst
print(MyFunction(value)... |
e666beb81c96b71e3fda8e0d06b200d3756def24 | arakinyemi/restart-projects | /script.py | 1,358 | 4.375 | 4 | #!bin/python3
from random import randint
def dice_rolling_simulator():
dice = randint(1, 6)
print ("This program is a simulator that rolls a six faced die and outputs the number of the side facing up")
guess = input("Do you want to guess what side is facing up? ")
if guess == "Yes" or guess == "y... |
19ac0cfec65e0a079a329e976467bc1dbe55255e | zhangwang0537/LeetCode-Notebook | /source/Clarification/Design/170.两数之和 III - 数据结构设计.py | 1,326 | 4 | 4 | # 设计并实现一个 TwoSum 的类,使该类需要支持 add 和 find 的操作。
#
# add 操作 - 对内部数据结构增加一个数。
# find 操作 - 寻找内部数据结构中是否存在一对整数,使得两数之和与给定的数相等。
#
# 示例 1:
#
# add(1); add(3); add(5);
# find(4) -> true
# find(7) -> false
# 示例 2:
#
# add(3); add(1); add(2);
# find(3) -> true
# find(6) -> false
class TwoSum:
def __init__(se... |
2c382d20dc4cde5a9b2ee4791508c5e8c5d156ac | nitinverma99/Codeforces---1000 | /Arpa’s hard exam and Mehrdad’s naive cheat.py | 228 | 3.578125 | 4 | n = int(input())
if n == 0:
print('1')
else:
remain = n%4
if remain == 1:
print('8')
elif remain == 2:
print('4')
elif remain == 3:
print('2')
elif remain == 0:
print('6') |
0ca3cf05ed159387ed3c1d96eec01e260a98edd5 | Barbmc1/python_work | /dimensions.py | 377 | 3.703125 | 4 | dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
print("\n")
for dimension in dimensions:
print(dimensions)
print("\n")
print("Original Dimensions: ")
for dimension in dimensions:
print(dimension)
#This stores a new tuple in the variable dimensions
dimensions = (400, 100)
print("\nModified dimen... |
f6550975337a433cb0770df2777446957b822ce1 | aaronmorgenegg/cs5050 | /assn6/binary_string_generator.py | 510 | 3.546875 | 4 | import random
from constants import BINARY_STRING_LENGTH
def generateString(length=BINARY_STRING_LENGTH, p=0.5):
"""Generates a random string of 0's and 1's, with regularity defined by p"""
string = [str(random.randint(0, 1))]
for i in range(1, length):
if random.uniform(0, 1) < p:
st... |
bf4e7e305bb0e69989b548bb594ddb3c4eb62179 | unnatural-X/Study_Introduction | /Introduction to Practice/forloop.py | 1,415 | 4.5 | 4 | # -*- coding:utf-8 -*-
"""
Author:Daniel Xu
Date:2020/11/27
"""
# for 循环
# 注意for末尾的冒号和缩进
# magicians = ['alice', 'david', 'tom']
# for magician in magicians:
# print(f'{magician.title()}, that was a great trick.')
# print(f"I can't wait to see your next trick, {magician.title()}.\n")
# print('Thank you, that wa... |
ffdc9cef8c2f8ded92138236961b8595018c1ba6 | timothypearson/learning-python | /training/course_1/try_except_blocks.py | 857 | 4.0625 | 4 | # Learn python - Full Course for Beginners [Tutorial]
# https://www.youtube.com/watch?v=rfscVS0vtbw
# freeCodeCamp.org
# Course developed by Mike Dane.
# Exercise: Try / Except
# Date: 31 Aug 2021
# Try / Except blocks (to protect our program to catch invalid inputs)
# Below showing when use puts a string instead o... |
a25d6bf2e6b1f01fc6d5977d7fe2a32cb05e6575 | Gramotei-vlad/Self-drivingCarNd | /find_line.py | 3,090 | 3.515625 | 4 | import matplotlib.image as mpimg
import numpy as np
import cv2
# Наше изображение
image = mpimg.imread('test_images/solidWhiteRight.jpg', 0)
print('This image is: ', type(image), 'with dimensions: ', image.shape)
def grayscale(img):
"""
Трансформируем наше изображение в один цветовой канал,
то есть проще... |
7e940216eec18171dfe5089b24167f109d72df3d | Jagadeshwaran-D/Python_Basic_programs | /find_area_and_perimeter_triangle.py | 401 | 4.09375 | 4 | """python program for find area & perimeter of triangle """
##function for calculate area of triangle
def get_areaof_triangle(base,height):
area=(base*height)/2
return area
###get input from the user
base=int(input("enter the base"))
height=int(input("enter the height"))
##calling the... |
570b85577fcc8343c1d9fa11d8e0bd95eb3a4e3f | kulsuri/playground | /daily_coding_problem/solutions/problem_9.py | 611 | 4.1875 | 4 | # Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
# For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
def largest_sum(l):
inclusive = 0
exclusive = 0
... |
b35a8be1a5184e339585b089e4e00188b12fc27d | bliiir/ras_python_core | /week_03/labs/12_files/reverse.py | 824 | 4.25 | 4 | # Reverse list using only one other variable that cannot be a list
#
# Take the fist item from the list and store it in t
# Replace the first item with the last
# Replace the last with t
#
# Take the second item from the list and store it in t
# Replace the second item with the second to last
# Replace the second to la... |
8f86d4b58c77af56028908268b27474175475fea | juneepa/LeetCode-Algorithms | /693. Binary Number with Alternating Bits.py | 382 | 3.546875 | 4 | ## https://leetcode.com/problems/binary-number-with-alternating-bits/description/
## Check website above for more details
## Easy, 55ms, 84.33%
class Solution:
def hasAlternatingBits(self, n):
n = bin(n)[2:]
for i in range(1, len(n)):
if n[i-1] == n[i]:
return ... |
6dc6aa5f859869bcd5892f483a321109bf091faa | sciencecasey/learnPy | /learnpytutorial_riceuniv_youtube.py | 1,844 | 4.34375 | 4 | #Shane Neeley video: https://youtu.be/oYTs9HwFGbY
import numpy as np
#create 1 dimensional arrays (vectors)
my_array = np.array([0,1,2,3])
my_array
my_array.dtype #see what type of array it is saved as (integer)
str_array=my_array.astype(str)
str_array #make a string array
#see the difference in how string or intege... |
3cde691dd4b0688c2c514ef345540c60d3e4d786 | MiloVoorhout/hu_lingo_backend | /openapi_server/core/domain/game/validation.py | 1,817 | 3.71875 | 4 | """
Validation domain where all validation analyses is done
"""
from pathlib import Path
def validate_word(guess, game_language):
"""
Validates if the guess exists/has correct grammer
:param game_language: Gets the right dictionary
:param guess: String = users guessed word
:return: Nothing
... |
08a9cc5c25fff4870089f545a82a1b4aa9a7509b | Abdurrahmans/Uri-problem-solving | /URI_1079.py | 142 | 3.546875 | 4 | n = int(input())
for x in range(n):
a,b,c = map(float,input().split())
avg = (a*2+b*3+c*5)/(2+3+5)
print('{:.1f}'.format(avg)) |
2020582083ba8c5f624dc6e7da75ff8703a4b1d9 | RichardLukeThomson/Thomson-2.2-2.5 | /Thomson no 1.1/hangman.py | 2,272 | 4.1875 | 4 | # A simple game of hangman
# Created by Thomson on 26 Sep 21
#import the uniform library
import random
# open the word list and send the contents to a list called words
f = open("word_list.txt","r")
words = f.readlines()
# pick a random word from the words list
random_number = int(random.uniform(0.0, 99.0))
word = (... |
76e4bc0aa5749f042aed8d6a3143a94f03223249 | ed1rac/AulasEstruturasDados | /2019/## Python/Ordenacao e Busca/bubblesort_simples.py | 545 | 4.125 | 4 | # -*- encoding: utf-8 -*-
"""
Bubble-Sort sem Flag em Python
by Ed
"""
def bubble_sort(lista):
for i in range(0, len(lista)-1):
for j in range(0, len(lista)-1-i):
if lista[ j ] > lista[j + 1]:
lista[j], lista[j + 1] = lista[j + 1], lista[j]
#print(lis... |
96c749dec383fbc21dd80c7f4f0ed79e740dfa3f | vavilon/Python3 | /Example/prim/def_.py | 507 | 3.828125 | 4 | # -*- coding: utf-8 -*-
def hello():
print("def Ok")
def add(x, y):
return x + y
def newfunc(n):
def func(z):
return z + n
return func
def prim(str):
print(str)
return
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
... |
d51d0f1181338d093c16c2e2aa3d73bc07cd9c3e | StudioPuzzle/Python3-Junior | /lesson 10/primer_7.py | 564 | 4.3125 | 4 | #Определить позицию (номер) первого вхождения некоторой подстроки в заданную строку
#(если подстроки в строке нет, то вывести соответствующее сообщение).
st = input('Введите строку ')
podst = input('Введите подстроку ')
ind = st.find(podst) #Функция find() вызывается как метод
if ind != -1:
print(ind + 1)
else:
... |
d6048ef777964866afbd98bb69754dd52c329d05 | Mahleat17/Module-4-Lab-Activity | /M4P3.py | 1,142 | 4.34375 | 4 | # This code returns some mad libs text based on the user input
# Is the code always returning the correct input?
# What do you think I did to write this code that I shouldn't have done?
#Answer ---> return causes the function to exit or terminate immediately, even if it is not the last statement of the function.
de... |
18f2af29d56d1a322d5bc624861b090568fa154f | visu1025/Fuzzy-Match-Lookup-Application | /Fuzzy search Project code.py | 6,185 | 3.65625 | 4 | #author: Venkatga Kasi Viswanath Yeleswarapu
#Fuzzy search of excel sheet
#written in Python 3.4.3 might not be compatible with other versions of Python
import csv
from difflib import SequenceMatcher as SM
#thresholds for key words and names
THETA1=0.60 #threshold for names
THETA=0.60 #threshold for key words
... |
ffe84a1b79a7de0ac3f53c252ee3374bf85461e3 | devsave/docs | /Python实验室/类装饰器/class_decorator.py | 5,814 | 4.0625 | 4 | # class Add:
# def __init__(self, value1):
# self.value1 = value1
# def __call__(self, value2):
# return self.value1 + value2
# add = Add(1)
# result = add(3)
# print(result)
# # 无参类装饰器修饰无参函数
# class Decorate:
# def __init__(self):
# pass
# def __call__(self, func):
# ... |
24f63c5855e639c9ef2db6740888873d43d5d158 | jana-choi/PythonCodingTest | /14.Tree/14.construct-binary-tree-from-preorder-and-inorder-traversal/1_divide_and_conquer.py | 1,019 | 3.65625 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
from collections import deque
def serialize(root):
queue = deque([root])
result = ["#"]
while queue:
node = queue.popleft()
if node:
qu... |
3813ac09ff80b204ab94f4107b299a5f367c6806 | Jinsung-Jeon/GyeonggiBigData | /python_exam/calculator.py | 370 | 3.828125 | 4 | a = float(input("a를 입력하시오:"))
b = float(input("b를 입력하시오:"))
c = input("연산자를 입력하시오(+,-,*,/):")
if c == "+" :
print(a,c,b,"=", a+b)
elif c =="-" :
print(a,c,b,"=", a-b)
elif c =="*":
print(a,c,b,"=", a*b)
elif c =="/":
if b ==0:
print("안돼요")
else:
print(a,c,b,"=",float(a%b))
8000... |
ba3042a6cfd4b378054ef9f75307d460204d5202 | Shazam00/Project-Euler | /problem58.py | 1,619 | 4 | 4 | import time
tStart = time.time()
def isPrime(n):
'''check if integer n is a prime'''
n = abs(int(n)) # make sure n is a positive integer
if n < 2: # 0 and 1 are not primes
return False
if n == 2: # 2 is the only even prime number
return True
if not n & 1: ... |
dc43bd5fed0d30aeb4eaf2cecd413d8eb8845b3a | ssaurav123/Daily-Ds-and-Algo | /DoublyLinkedList.py | 1,237 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 16 20:01:28 2018
@author: shubham
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def push(self, ne... |
83bc079d75d4db2364db4f105958db6c6a1ab1c3 | as2569/Simple-Calc | /tests/calc_div_test.py | 343 | 3.59375 | 4 | from Calculator import Calculator
from FileReader import FileReader
def test_calc_div():
calc = Calculator()
fr = FileReader()
fr.openFile('csvFiles/UnitTestDivision.csv')
for row in fr.reader:
if calc.div(int(row['Value 2']), int(row['Value 1'])) == round(float(row['Result']),3):
continue
else:
assert... |
9d193ae66085c8de0abf947a1fe82f7ba05484f7 | AntonPushkash/ITEA_hw | /hw9/grade_journal.py | 1,195 | 3.953125 | 4 | """
Пользователь вводит количество студентов n.
После чего вводит n строк, в которых записана фамилия и балл через пробел.
Программа выводит список фамилий, отсортированный по их баллам по убыванию.
Пример:
[out] Введите количество студентов:
[in] 3
[out] Введите фамилию и балл:
[in... |
bfa47c1bdc738059f98e24e45a4c204879d35931 | VulturARG/Katas | /Python/Codewars/Meeting/meeting.py | 537 | 3.625 | 4 | def meeting(s):
listString = s.upper().split(';')
for i,name in enumerate(listString):
listString[i] = name.split(':')
listString[i].reverse()
sortedList = sorted(sorted(listString,key=lambda x: x[1]),key=lambda x: x[0])
sortedString = ''
for name in sortedList:
sortedString ... |
a513c2f73bab46bc9ff835240299322903e9ce2b | dsanch1120/checkersEngine | /drawBoard.py | 1,539 | 3.5 | 4 | import pygame
import board
class DrawBoard:
size = 0
boardLength = 0
currentPlayer = 0
white, black, red = (255, 255, 255), (0, 0, 0), (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
b = None
def __init__(self):
self.size = 65
self.boardLength = 8
self... |
c3c7ecc1a9a934987acf561eb17ec14ecbc763a7 | dixitomkar1809/DailyCodingProblemSolutions | /DCP4.py | 1,420 | 3.71875 | 4 | # This problem was asked by Stripe.
# Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
# For example, the input [3, 4,... |
0ce1562d7d1b3a8771d4913a7360c6637e208ca9 | lazpz61/lmp-coding-challenges | /LeetCode/Python/richest-customer-wealth.py | 670 | 3.859375 | 4 | """
You are given an m x n integer grid accounts where accounts[i][j] is
the amount of money the ith customer has in the jth bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts.
The richest customer is th... |
0fe0a37d6921bf86f28b8e14062bb2ccb4f2c761 | BXMethodist/H3K4me3Saturation | /cumulative.py | 3,903 | 3.65625 | 4 | """
This module is to prepare the table the draw the cumulative curve
"""
import pandas as pd, numpy as np
def cumulative_cluster(stat_table, distance_table):
"""
prepare the table for cumulative curve for each cluster
:param stat_table:
:param distance_table:
:return:
"""
stat_df = pd.read... |
456b3dc30a042825e5432707fc51b14f9855f0b3 | abhigun1234/jsstolearnpython | /decorators/decoratorex.py | 692 | 4.1875 | 4 | def decor(fun):
def inner():
value=fun()
return value +2
return inner
@decor
def num():
return 10
# what is decoraror how to write decorator
# def getName():
# return 'akash'
print(num())
# result_func=decor(num)
# print(result_func())
# def greet(fun):
# def inner():
# v... |
fed61994a0c755e0295708f221c16c80786b7f50 | verowardana/Python-Projects-Protek | /Python Project/Chapter 5/Praktikum 2/latihan05.py | 608 | 3.6875 | 4 | from random import randint
print("Hai..! Selamat datang di permainan tebak angka!")
print("Saya sudah memilih sebuah bilangan bulat secara acak antara 0 s/d 100.")
print("Coba tebak yaa!!!XD")
komputer = randint(0,100)
player = int(input("Masukkan angka: "))
while player >= 0:
if player > komputer:
print... |
9dc2bd42787bf598b1f75d4d34b7d1e4e78042bd | salonzo-juarez/chem160module6 | /celltest.py | 268 | 3.515625 | 4 | from ising_class import*
acell=cell(3,3,10) # Args: i, j, n
print(acell.cellspin())
acell.spin.flip() # Reaching through cell to inner spin object
print(acell.left) # Directly accessing the neighbor indices
print(acell.right)
print(acell.up)
print(acell.down)
|
432bb6a5ab9e3f26f66756a90fe5ab4c7453d5c7 | Simochenko/ITVDN_Python_oop | /OOP_3/2_методы класса, параметр self, конструктор и деструктор.py | 386 | 4.03125 | 4 | class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __del__(self):
print("Удаление экземпляра: " + self.__str__())
x = 1; y = 1
def setCoords(self, x, y):
self.a = x
self.b = y
pt = Point()
pt2 = Point(5)
pt3 = Point(5, 10)
print(pt.__dict_... |
5a0e3cabf87e302545edf10d3a24d115146abd44 | Aminaba123/LeetCode | /340 Longest Substring with At Most K Distinct Characters.py | 1,049 | 3.78125 | 4 | """
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example, Given s = "eceba" and k = 2,
T is "ece" which its length is 3.
Show Company Tags
Show Tags
Show Similar Problems
"""
from collections import defaultdict
__author__ = 'Daniel'
class Solution(obj... |
566dd8a5611419ba12effaa3300d3bd0f582cb86 | LiviuSosu/Aldebaran-Apps | /Interaction/handshake/lib/RandomSentences.py | 1,138 | 3.5625 | 4 | from random import randint
class RandomSentences:
hello = ['hi', 'howdy', 'hello']
shakeHandsPart1 = ["Come on, let's shake hands", "Come on, don't be shy", "I want to shake hands with you"]
shakeHandsPart2 = [" Are you going to make me wait all day long like this?", "Why are you so shy",
... |
5924f3f2bd5bf26d5a3753603f52469b4d43b1ba | sivaneshl/deep_learning_course | /neural_networks/implementing_gradient_descent/multilayer_perceptron.py | 761 | 4 | 4 | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Network size
N_input = 4
N_hidden = 3
N_output = 2
np.random.seed(42)
# Make some fake data
X = np.random.randn(N_input)
weight_input_to_hidden = np.random.normal(0, scale=0.1, size=(N_input, N_hidden))
weight_hidden_to_output = np.... |
da60811b56a1d95d6273f3cf43d3f849467c1165 | PravalikaPuppala/fibonacci-series.py | /fibonaci series.py | 183 | 3.6875 | 4 | j=int(input("enter the number where the series should:"))
i=0
a=0
b=1
c=0
print(a)
print(b)
for i in range(i,j):
c=a+b
a=b
b=c
print(c)
|
ed205c40cc0d22e9c8bd79081e752b8546aed582 | kotarott/python_exercise004 | /exercise.py | 3,764 | 4.3125 | 4 | # クラスの作成
class Test:
x = 1
y = 2
def test_method1(self):
print(self.x)
def test_method2(self, hennsu1):
print('引数:', hennsu1)
# インスタンス化
x = Test()
# x.test_method1()
# x.test_method2("test")
# コンストラクタ:初期値の設定
class Test2:
val = []
def __init__(self):... |
e757ae8ba14c1e46013bd54343005f55cb1ee072 | emreuslu/Python | /strings.py | 3,335 | 4.46875 | 4 | ##### string formatting
result = 200/700
print('The result is {}\n'.format(result)) # -> output : The result is 0.2857142857142857
print('The result is {r}\n'.format(r=result)) # -> output : The result is 0.2857142857142857
print('The result is {r:1.3}\n'.format(r=result)) #-> output : The result is 0.286
p... |
08cdd59bff6453d1961b737524e11a23165ca737 | ameernormie/100-days-of-python | /hackerrank/Simple/jumping-on-clouds.py | 1,300 | 4.125 | 4 | #!/bin/python3
"""
Emma is playing a new mobile game that starts with consecutively numbered clouds.
Some of the clouds are thunderheads and others are cumulus.
She can jump on any cumulus cloud having a number that is equal to the number of the
current cloud plus or . She must avoid the thunderheads.
Determine the mi... |
38fa1f2cd0d76ee2d4f3db42f94adff5c4b6d39e | Arulkp/Python | /Python_Copy.py | 572 | 4.28125 | 4 | # Python Shallow Copy and Deep Copy
#Shallow Copy
# Shallow copy is copy the object and also stored nested object refrences which means it is not copied nested object and it is copied only main objects
import copy
a = [[0,0],[1,1]]
b = copy.copy(a)
b[0][0] = 22
print(a) #[[22, 0], [1, 1]]
print(b) #[[22, 0], ... |
184d9223fe3d77357b12bf88538d1f959a570dd2 | sfagnon/stephane_fagnon_test | /QuestionB/MainQB.py | 1,052 | 4.375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from VersionComparisonLibrary import *
#Main
print("\nWelcome to Question B's test program \n")
"""Test Cases
- Input does not have a software version standard format (X or X.X or X.X.X or X.X.X.X)
- Input is negative
- Version format designating development stage (a... |
b87d286494617fbe7662ac6c52a353392fb46972 | sorin-66/Hackathon_V1 | /Hackathon_1.py | 590 | 4.59375 | 5 | """
1 - Write a program that will take multiple user inputs, the first being the user's name, followed by
the user's location and finally take something the user likes. Then output a string that contains
this information. e.g.
Output > Hello my name is Jordan, I live in the UK and I like classical music.
"""
... |
7e61f55d6fcefbe736cc1a29976d349d7ef3237d | openworm/WormsenseLab_ASH | /src/utils.py | 593 | 3.53125 | 4 | import roman
from datetime import datetime
def get_base_filename(experiment_info):
"""
get_dat_filename: converts string in dd-mm-yy format with the month stored
as roman numerals into yy_mm_dd format with all integer values
"""
date_raw = experiment_info['Recording Date'].values[0]
# conver... |
e26ed98d667eb3faffcda781bc6bd8e3972620ac | mrifqy-abdallah/python-exercises | /medium/003_clock/clock.py | 628 | 3.765625 | 4 | class Clock:
def __init__(self, hour: int, minute: int):
self.total_minutes = (hour * 60 + minute) % 1440 # 1440 is 60x24
self.hour = str(self.total_minutes // 60)
self.minute = str(self.total_minutes % 60)
def __repr__(self):
hour = self.hour.zfill(2)
minute = self.min... |
9710d70398b7b3f9897219ecb60e2c14acef775a | Bruno-Dzk/pygame-pong | /collision.py | 2,178 | 4.25 | 4 | """A module for collision detecting in a pong-type game
Contains functions for detecting collisions between two rectangles
and between a circle and a rectangle.
Also contains a CollisionSystem class that stores lists of game objects
and checks the collision between them.
"""
def collided_circle_rectangle(circle, recta... |
17ba79a67fcf5be4838ded748bf314df660e63a0 | JasonMace/Tic-Tac-Toe_final | /Problems/Running total/main.py | 112 | 3.65625 | 4 | tmp = 0
mylist = list()
for num in input():
mylist.append(int(num) + tmp)
tmp += int(num)
print(mylist)
|
4c323f832216cd541e8d0f445d253122a4170105 | AminArshadi/Python-Codes | /ITI/a3_300189176/a3_part1_300189176.py | 2,641 | 4 | 4 | def is_up_monotone(X, d):
'''(str,str)->(None,None)
Preconditions: This function has two parameters, a string X and a string d. These two strings can
be assumed to be such that each looks like a positive integer and such that the number of digits in x is
divisible by the integer represented by d.
Th... |
024c230e66cc73f4a94b249b64b75f58c7e3a6dc | SolomonAnn/IDA_Homework | /src/preprocess/count_attributes.py | 4,395 | 4.09375 | 4 | # -*- coding: utf-8 -*-
import csv
from operator import itemgetter
from itertools import groupby
def main():
records = []
read_csv(records)
count_age(records)
count_race(records)
count_gender(records)
# count_weight(records)
count_admission_type(records)
count_diagnosis(records)
cou... |
ce202bafe1a48c6390a680b164120e62c4725ef7 | radmosley/lab_assignments | /lab_assignments/list_doubles.py | 101 | 3.609375 | 4 | #List Doubles
lst = [1, 2, 3, 4, 5, 6, 7]
m = 2
lst_2 = [i * m for i in lst]
print(lst)
print(lst_2) |
0e64862e74e5b42f44477854781c4325b8acc1eb | nummy/exec | /words/pivoting_die.py | 2,010 | 3.984375 | 4 | def main():
'''main function'''
loop = True # loop flag
while loop:
goal = input("Enter the desired goal cell number:")
if not goal.isdigit():
print("Incorrect value, try again")
else:
goal = int(goal)
if goal <= 0:
print("Incorrec... |
19b9d374d4777e062b8a37a596daeb3bcb76970f | HenriqueCoelho1/Python-Exercises | /11_loops/for_loop_count.py | 155 | 3.65625 | 4 | grades = [35, 67, 69, 100, 140]
total = 0
amount = len(grades)
for grade in grades:
total += grade
print(total)
print(amount)
print(total / amount)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.