blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
41c2a70d3b4b707d50c3b291bd769c7da7e2324b | YuriiKhomych/ITEA_AC | /Salvador_Sakho/l_8_software_engineering/Creational/abstract_entity/Robot.py | 894 | 3.75 | 4 | from abc import ABC
class Robot(ABC):
def _go(self, distance):
passed_distance = 0
while distance > passed_distance:
print('Walking...')
if passed_distance + self._speed > distance:
passed_distance = distance - passed_distance
return passed_d... |
89cd829f0f168cd9c431aafab629c95a2dd8a487 | SamyT-code/Scrabble-helper | /Scrabble helper/a4_part1_300184721.py | 11,070 | 4.4375 | 4 | def is_valid_file_name():
'''()->str or None'''
file_name = None
try:
file_name=input("Enter the name of the file: ").strip()
f=open(file_name)
f.close()
except FileNotFoundError:
print("There is no file with that name. Try again.")
file_name=None
return file_... |
b07408934d215304b66a38c0550304391fd0c2fa | yashikajotwani12/python_learning | /learning_python/elif.py | 153 | 3.90625 | 4 | names=["yashika","sanya","vedant","sakshi","betu"]
name=input("enter any name \n")
if(name in names):
print("woww")
else:
print("hmmkkk")
|
51c08633750bb024dc9e3a8484e99981df2bc204 | kazamari/Stepik | /course_431/5.22_Anagram.py | 1,002 | 3.578125 | 4 | '''
Напишите программу, которая проверяет, являются ли два введённых слова анаграммами.
Программа должна вывести True в случае, если введённые слова являются анаграммами, и False в остальных случаях.
Формат ввода:
Два слова, каждое на отдельной строке. Слово может состоять только из латинских символов произвольного р... |
ecce067dfd465af0c2e82e87a459a74cbfff8bd8 | jesperschaap/programming1final | /Les_8/Final Assignment Bagagekluizen.py | 1,674 | 3.65625 | 4 | aantal = 12;
file = open('kluizen.txt', 'r+')
lines = file.readlines()
def toon_aantal_kluizen_vrij():
count = 0;
for i in enumerate(lines):
count += 1;
print("Er zijn nog " + str(aantal - count) + " kluizen beschikbaar")
file.close();
def nieuwe_kluis():
kluizen = list(range(1, 13, 1)... |
2ca6b2669d609a1538809b027c1c7a95c60d037b | nojhan/pyxshell | /src/pyxshell/pipeline.py | 10,029 | 4.3125 | 4 | # -*- coding: utf-8 -*-
from functools import wraps
import itertools
class PipeLine(object):
"""
A coroutine wrapper which enables pipelining syntax.
:class:`PipeLine` allows you to flatten once-nested code just by wrapping
your generators. The class provides combinators in the form of operators,
... |
c03a666bc82309a59cbd4a889fb90b542e4f0f76 | praneethreddypanyam/DataStructures-Algorithms | /Trees/BinaryTree/maximumLevelSum.py | 1,039 | 3.765625 | 4 | class Node:
def __init__(self,data):
self.data = data
self.right = None
self.left = None
class Tree:
def maxLevelSum(self,root):
if root == None:
return 0
que = []
que.append(root)
que.append(None)
level = maxlevel = maxSum = currentSu... |
7abb9e8be1fd2177a3971fd8f9dcccb7d7ea9798 | lh-13/pytorch_test | /101numpy_practice.py | 829 | 3.65625 | 4 | '''
@version : 1.0
@Author : lh-13
@Date : 2021-02-07 13:39:13
@LastEditors : lh-13
@LastEditTime : 2021-02-07 13:39:13
@Descripttion : 101道numpy 练习题
@FilePath : \pytorch_test/101numpy_practice.py
'''
import numpy as np
#1.import numpy and print the version number
print(np.__... |
a5ad4a5035a98b4f3a6d35bf3b33716307940fe7 | KApilBD/python | /basiccomfundamental/exceptions.py | 614 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Kapil
"""
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("Input not an integer; try again")
print("Correct input of an integer!")
data = []
file_name = input("Provide ... |
0dfd4782bd769360ff3f24914ed5fdd30fc3e6ef | outofboundscommunications/courserapython | /9Dics/exercise9_2.py | 1,306 | 4.09375 | 4 | __author__ = 'outofboundscommunications'
#To change this template use Tools | Templates.
'''
Exercise 9.2 Write a program that categorizes each mail message by which day
of the week the commit was done. To do this look for lines that start with From
then look for the third word and keep a running count of each of the ... |
76461606fa35697c5b373e8c590dd5dbba067906 | weizt/python100case | /python100例/实例009:暂停一秒输出.py | 344 | 3.84375 | 4 | #### 实例009:暂停一秒输出
#**题目:**暂停一秒输出。
#**程序分析:**使用 time 模块的 sleep() 函数。
import time
a = '这是一段文字,用来测试暂停一秒输出'
for i in a:
print(i,end = '')
time.sleep(1)
import time
for i in range(4):
print(str(int(time.time()))[-2:])
time.sleep(1) |
46dffc67184df79c369339ddd0d7b067f9ab3c9c | zemial85/zaawansowany | /scrap.py | 153 | 3.75 | 4 | def numbers(a, b):
c = a/b
if c%2 == 0:
return c
for number in n:
yield number
print(number)
n = numbers(10, 2)
|
d0e8f0b5eb5be188df4dc778de1d3c5dfdf2b0b0 | Tabinka/MorseCodeConverter | /main.py | 1,578 | 4.15625 | 4 | import json
START = True
print("Welcome to my first Python project - Morse Code Converter")
while START:
response = input(
"What do you want to do? If you wish to convert text to morse enter '1'. If you wish to convert morse to text type '2' and for exitting the program type '3': ")
if response == '1... |
d7281078793a3e93eaa2cfe1b85ff14cdf05c5f6 | mLenehan1/EE514-DataAnalysisAndMachineLearning | /PythonPractice/PythonIntro/mypackage/mymodule.py | 530 | 3.96875 | 4 | def square(x):
return x**2
class Particle(object):
"""
This class models a particle with a name and a speed.
"""
def __init__(self, name, speed=1):
self.name = name
self.speed = speed
def speed_up(self):
self.speed += 1.0
def slow_down(self):
self.spee... |
6506763657189c9b64d3d955b6f1f31476ccee87 | gdaPythonProjects/training2019 | /4/yield.py | 318 | 4.125 | 4 | numbers = [1, 2, 8, 4]
def multiply_two(lst):
for num in lst:
yield num * 2
result = multiply_two(numbers)
print(next(result))
print(next(result))
print(next(result))
print(next(result))
result = multiply_two(numbers)
print(list(result))
result = multiply_two(numbers)
for i in result:
print(i)
|
de64d1cc83048d97202e219c261d9ce7ff3b16ed | sdas13/DSA-Problems | /string/easy/13. path-crossing.py | 1,478 | 4.0625 | 4 | """
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return True if the path crosses itself at any point, that is, if at any time you are on a locat... |
6ec95ee3c953a0b9acd06e8119096d6486f1ee33 | akshatk16/EulerProject | /Problem059.py | 3,446 | 4.1875 | 4 | # Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
#
# A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byt... |
7c9a6b8c68f76f4c5733c38da99f3a37cb6c4e0a | fabiano-teichmann/bioinformactic | /recursive_relation.py | 353 | 3.984375 | 4 |
def reproduction_recursive(month: int, initate_sequence: int) -> int:
if month == 0:
return 0
elif month == 1:
return 1
return reproduction_recursive(month - 1, initate_sequence) + initate_sequence * reproduction_recursive(month - 2, initate_sequence)
if __name__ == "__main__":
prin... |
2464b26bdcbe7871c1134b0e4e575ddc07853d6d | ravi4all/PythonOnlineJan_2021 | /prime_number_3.py | 308 | 4.0625 | 4 | min_range = int(input("Enter min range : "))
max_range = int(input("Enter max range : "))
for num in range(min_range, max_range):
for i in range(2,num):
if num % i == 0:
#print("Not Prime Number")
break
else:
print("{} is Prime Number".format(num))
|
7df45eeecfaadd6ef2046eeecfaedaf90cab257d | piyush2896/Simulated-Annealing | /tour_manager.py | 1,849 | 3.53125 | 4 | import numpy as np
import random
class City:
def __init__(self, coords=None):
if coords == None:
self.coords = 250 * np.array(np.random.random_sample((1, 2)), astype('uint32')) + 50
else:
self.coords = np.array(coords)
def distance_to_city(self, city):
sq_abs_... |
65372d399fb5a40cb5f334c4618d2e530090c5c9 | wangpanqiao/2015-05-05-AvrRvi5_candidate_transcript_validation | /lib/gene_shapes.py | 5,471 | 3.65625 | 4 | """ Shapes for drawing genes and gene features. """
from matplotlib.path import Path
import numpy as np
from math import sin
from math import radians
class Shape(object):
""" Base class for drawing genomic features. """
def __init__(
self,
angle=0,
x_offset=0,
... |
471b7eb7e25cd57904461ea461278a16b8fcc65a | JamBro22/numpy-exercises | /numpy_exercise1.py | 799 | 4.28125 | 4 | # import modules
import matplotlib.pyplot as plt
import numpy as np
# create numpy arrays
nums = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1])
bins = np.array([0, 1, 2, 3])
# print output
print("nums: ", nums)
print("bins: ", bins)
print("Result:", np.histogram(nums, bins))
# creating axes labels and title
plt.xlabel("nu... |
985dc1b4ac3aa662b6952cb0141d31e73fc2fb53 | parmarjitendra/Python | /package01/Practical39.py | 256 | 3.78125 | 4 | d = { 'A':'Java', 'B':'J2EE', 'C':'Android',
'D':'Python', 'E':'Hadoop', 'Key':'Value'}
print( "dictionary = ", d )
d['F'] = 'JAPAN'
print( "dictionary = ", d )
d['B'] = 'INDIA'
print( d )
del d['E']
print(d)
#print( d[0] ) #Error
|
acfa47d81ca06137994c74929b3311decf15950a | NBESS/Python_105 | /small_exercise.py | 3,481 | 4.5 | 4 | # Instrutions:
# The starter code provides you with the main menu for a command-line
# based grocery list application.
# The user should be able to add, update, and remove items.
# Small exercise ------------------------------------------------
# Using this starter code, you're going to combine the pieces of code
# ... |
70c7bdd44b33b8e907800b87ab591d43c23b2704 | renatamoon/python_classes_poo | /impacta_poo2_ex2.py | 857 | 4.03125 | 4 | """
PESSOA
nome = STR
idade = int
carro = Carro
-metodo = comprar carro(carro)
CARRO
marca = STR
Modelo = str
placa = str
ano = int
"""
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
self.carro = None
def comprar_carro(self, carro)... |
5a5f4898224ae3eca27187ca01fcf81b57b92740 | charliedmiller/coding_challenges | /count_sorted_vowel_strings.py | 1,456 | 4.03125 | 4 | # Charlie Miller
# Leetcode - 1641. Count Sorted Vowel Strings
# https://leetcode.com/problems/count-sorted-vowel-strings/
# Written 2020-12-06
"""
Dynamic program approach. Find out how many sort vowel strings
there are of length n-1, if we use each of the available vowels
available to us, then add it up. When we us... |
c170f0fb85bb407520a6b764ff803cdb5c4f2a3a | W-Sarakul/hangman | /hangman.py | 1,899 | 4.03125 | 4 | # Write your code here
import random
word_list = ['python', 'java', 'kotlin', 'javascript']
chosen_word = random.choice(word_list)
print('H A N G M A N')
print()
choice = input('Type "play" to play the game, "exit" to quit:')
if choice == 'play':
tries = 8
ans = list('-' * len(chosen_word))
guess_set = s... |
93374f70086bb352a7d0b11dee103b3761edd19c | austinv11/MLExperiments | /ch2_preprocessing/categories.py | 1,053 | 4.125 | 4 | from typing import List
from numpy import *
from scipy import *
def categories_to_numbers(data: ndarray) -> List['ndarray[int]']:
"""Takes a list of discrete categories and converts them into numerical binary feature arrays.
NOTE: This is unnecessary for certain algorithms which can accept categorical d... |
c1c9a350e3f29a081af8031b3b73c0cd91c44ac5 | poojasinghal9927/NPTEL-Python-Course | /DAP3.py | 4,356 | 4.0625 | 4 | 'Week 3 Practice Programming Assignment'
def descending(L):
'List must be monotonically descending'
'L[i-1] >= L[i]'
for i in range(1,len(L)):
if L[i-1]<L[i]:
return False
else: # else of loop executes, if terminates from top, not inbetween 'break'
return True
def valley(L)... |
ef265c978a50ecb60c18bcbdb13928afa6f31518 | estraviz/IntermediatePythonProgramming | /02_Wordplay_warm-up/words_longest_palindrome.py | 395 | 4.125 | 4 | import scrabble
def is_palindrome(word):
return word == word[::-1]
count_palindromes = 0
longest = ""
for word in scrabble.wordlist:
if is_palindrome(word):
count_palindromes += 1
if len(word) > len(longest):
longest = word
print("\nTotal number of palindromes: {:d}".format(count... |
e1fbb21de4034ad2a92c200ae7318bb572cc3b90 | derekcollins84/myProjectEulerSolutions | /problem0024/problem24.py | 613 | 3.90625 | 4 | '''
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
Wh... |
e853b860178fa57c8b031c007de2a4762f0b1fec | zhongsibang/ZSB | /my/shuangseqiu/test.py | 94 | 3.78125 | 4 | a = [1,2,3]
b = [[1,1],[2,2],[3,3]]
c = {}
for i in range(len(a)):
c[a[i]] =b[i]
print(c) |
9a9a755c73b57908a1140b07b03227e3a35df8ae | GuoYunZheSE/Leetcode | /Easy/129/129.py | 714 | 3.546875 | 4 | # @Date : 20:57 04/01/2021
# @Author : ClassicalPi
# @FileName: 129.py
# @Software: PyCharm
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
... |
10bc38dd9188812c795ecd9260b0d63104674a8d | ZenenHornstein/3522_A01185704 | /Labs/Lab3/item.py | 5,673 | 3.8125 | 4 | import abc
class Item(abc.ABC):
def __init__(self, call_number, title, num_copies=1):
self._call_number = call_number
self._num_copies = num_copies
self._title = title
def get_title(self):
return self._title
def increment_number_of_copies(self):
"""
Set's ... |
6b0e16930b4eaa93eacf1e1341e5816dabc7ad98 | abdalrahmansamara/snakes-cafe | /snakes_cafe/snakes_cafe.py | 1,108 | 4.125 | 4 | print("""
**************************************
** Welcome to the Snakes Cafe! **
** Please see our menu below. **
**
** To quit at any time, type "quit" **
**************************************
Appetizers
----------
Wings
Cookies
Spring Rolls
Entrees
-------
Salmon
Steak
Meat Tornado
A Literal Garden
D... |
15fe8e216f9a83caea4c18547dc0cd494d7f1c85 | yuzhecd/al_py | /Array_py/find_max.py | 249 | 3.75 | 4 | def max_find(num):
local = maximum = 0
for i in num:
local = local + 1 if i == 1 else 0
maximum = max(local, maximum)
print(maximum)
if __name__ == '__main__':
num = [1,1,1,1,0,1,1,0,1,1,1,1,1,1,1]
max_find(num) |
fc09677a9a2e133d354ec43a017bd1187ef5b8fa | jackrdavies1/MMGame | /game.py | 8,109 | 3.75 | 4 | #!/usr/bin/python3
import time
from map import rooms
from player import *
from items import *
from gameparser import *
from people import *
def print_inventory_items(items):
"""This function takes a list of inventory items and displays it nicely, in a
manner similar to print_room_items(). The only di... |
ab009c523ee0e7fdc07d257fa296ce81f239f9d4 | zhaurora/idcp | /testbed/study/tianchi/codestructures.py | 26,092 | 3.765625 | 4 | '''
Created on 2018年9月30日
@author: banshu
'''
import random
if __name__ == '__main__':
pass
'''
第4章 Python外壳,代码结构
CHAPTER 4 Py Crust: Code Structures
'''
# 4.1 4.2 注释与连接
# 使用 # 可以注释单行
# 使用 \ 可以连接多行
# 我是注释,別理我
print('===========4.1 4.2 注释与连接===========')
print('两种不同的连接多行方法:')
alphabet = ''
alphabet += 'abcdefg'
... |
d92fcc07165a76ad6378dace7c7c953bc8f080e0 | marcosfelipp/TAP_exercises | /F2.py | 683 | 3.90625 | 4 | def find_circle(element, dic_dominace, visited_nodes):
visited_nodes.append(element)
for children in dic_dominace[element]:
if children in visited_nodes:
print("There is a dominating circle.")
exit();
else:
find_circle(children, dic_dominace, visited_nodes)
n = int(input())
vector_strings = []
dic_do... |
6338865ac104f89d9cf5d1f31527fd2148d0f898 | karimkalimu/Machine_learning_Algorithms | /Linear-QuadraticRegression/QuadraticRegression.py | 4,029 | 3.671875 | 4 | #quadratic regession
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import imageio
#Hyperparameter
MaxIteration = 145
learning_rate = 0.0000000000000000000001 #Much more sensitive here than in linear regression
#Data
x = np.linspace(100, 1000 , 1000)
#The line we want to ... |
bb799d0818d73398042b6e568a397485b97692fe | attainu/project-Avinash-reddy-au13 | /Junk_File_Project/organize_files1.py | 915 | 3.515625 | 4 | import os
from pathlib import Path
def organize_files1(paath,FILE_FORMATS):
direct = paath
os.chdir(direct)
for entry in os.scandir():
if entry.is_dir():
continue
file_path = Path(entry.name)
file_format = file_path.suffix.lower()
if file_format in FILE_... |
e44d58cc003ffc4951b6ee827516142b4c8c66e2 | zhou-chenxi/kerneleval | /sigmoid.py | 3,962 | 3.765625 | 4 | import numpy as np
from check_data_compatibility import *
class Sigmoid:
"""
This is a class of evaluating the sigmoid kernel function.
Attributes
----------
data : numpy.ndarray
The array at which the sigmoid kernel function is to evaluated.
N, d : int, int
The shape of data array.
a : float
The coeff... |
c6dab4c9b74ad5a0496eeb68010aa505f9f0ee05 | mohitsudhakar/coding | /daily_coding_problem/24_locking_in_binary_tree.py | 2,643 | 4.21875 | 4 | """
This problem was asked by Google.
Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its
descendants or ancestors are not locked.
Design a binary tree node class with the following methods:
is_locked, which returns whether the node is locked
lock, which attempts to lo... |
68151b3875a91891599c40323a0b26e750f17dbf | Leo-Mun/CS | /Python/연산자 중복 정의.py | 530 | 3.765625 | 4 | class Matrix:
def __init__(self, row, col, data):
self.row=row
self.col=col
self.data=data
def __add__(self, other):
res = Matrix(2,2,[[0,0],[0,0]])
for r in range(self.row):
for c in range(self.col):
res.data[r][c] = self.data[r][c] + other.d... |
9925c3b7e67c24cbda50dbd18dbf98b326cee80a | VikramVikrant/Python-DS | /BitRep.py | 183 | 4 | 4 | #Find value of k-th bit in binary representation
# Python 3 program to find
# k-th bit from right
def printKthBit(n, k):
print(n & (1 << (k - 1)))
n = 13
k = 2
printKthBit(n, k) |
a171e8a1995cc2131fb539df1870949992333535 | TeresinaHerb/AventOfCode2018 | /day1/main.py | 764 | 3.5625 | 4 | startFreq = 0
currentFreq = startFreq
file = open('input.txt', 'r')
temp = file.read().strip()
file.close()
frequencies = list()
for x in temp.split():
frequencies.append(int(x))
# part 1
for frequency in frequencies:
currentFreq = currentFreq + frequency
print "Part 1: Resulting final frequency " + str... |
d0fba247794bea0d3e7ba3b6ea85362c5956e8f5 | Jdvakil/CoinGame | /CoinGame.py | 1,948 | 4.3125 | 4 | # This program is written to collect data values of coins and add them up to find see is the total amount of coins will match upto a
# dollar or be less than a dollar or exceed a dollar.
print("Please enter as a whole number")
# input section ...here we will collect data from the customer to proceed to the proccessi... |
515c617aaa1fd41f4f1f8954c27a90014950db9d | DU-ds/PythonDataAnalysisCourse | /hy-data-analysis-with-python-summer-2019/part03-e06_meeting_lines/src/meeting_lines.py | 541 | 3.6875 | 4 | #!/usr/bin/python3
import numpy as np
def meeting_lines(a1, b1, a2, b2):
# a1 *= -1
# a2 *= -1
A = np.array([[-b1, 1],[-b2, 1]])
b = np.array([a1, a2])
return np.linalg.solve(A, b)
def main():
a1=1
b1=4
a2=3
b2=2
x, y = meeting_lines(a1, b1, a2, b2)
print(f"Lines meet at... |
18bdbccac7943ea86c427e6acb637140a501e73d | Taewan-P/LeetCode_Repository | /summer_coding/559_maximum_depth_of_n-ary_tree.py | 374 | 3.515625 | 4 | class Solution:
def maxDepth(self, root: 'Node') -> int:
queue = [root]
depth = 0
if not root:
return depth
while queue:
l = len(queue)
for i in range(l):
queue += queue[0].children
queue.pop(0)
... |
30ad1663bea71552818e86a6a894ad65fc4169b6 | utsavtiwary/Cracking-The-Coding-Interview | /Chapter_3/sort_stack.py | 987 | 4.03125 | 4 | from class_stack import Stack
class SortStack:
def __init__(self):
self.sorted = Stack()
self.temp = Stack()
def push(self, item):
if self.sorted.isEmpty():
self.sorted.push(item)
while not self.sorted.isEmpty() and self.sorted.peek() < item:
self.temp.... |
7e957071b6bc3ba09f49bd514f5166c1cf00506a | nikulinyura/test-2 | /algorithmes/Graphs/breadth_first_seach.py | 1,934 | 4 | 4 | # ПОИСК В ШИРИНУ
# ключ - человек, аргумент - его друзья
# ЦЕЛЬ - поиск !!!ближайшего друга с именем заканчивающимся на 3
def is_it(name): # проверка последнего символа имени
if name[-1] == '3': #если последний символ 3 - то что ищем
return True
def seach(name):
from collections import deque #... |
0b919077f5b41dcc50bd2f9e49ea568045dedde3 | josharnoldjosh/personal-website | /sensor_helper.py | 764 | 3.828125 | 4 | import random
import requests
def send_temperature(temp_f):
"""
Sends a temperature as a numeric type
to the server, which from there propergates
the value to the mobile app.
temp_f : a numeric temperature in fahrenheit.
Example: send_temperature(92.7)
"""
requests.post(
... |
ae8cae913ce95b1cf6205913bead92f3fb4c8b53 | PythonWonderWoman/python-scripts | /r1_06 input int vs float.py | 367 | 3.625 | 4 | # zmiana input str na float i int
print("sprawdzamy dzialanie funkcji input")
dana1 = input("podaj dana liczbowa - int:")
print(dana1)
print(type(dana1))
dana_int= int(dana1)
print(dana_int)
print(type(dana_int))
dana2 = input("podaj dana przecinkowa - float:")
print(dana2)
print(type(dana2))
dana_float= float(dan... |
20ef281d49df619fdb161c4a3ece98eabb89db32 | AwuorMarvin/Day-Three-Bootcamp | /MaxandMin/max_min.py | 447 | 3.9375 | 4 | def find_max_min(argument):
max = 0
min = 1000000000 #The assumption is that there's no instance where the least number will be greater than this
result = []
for arg in argument:
if arg > max:
max = arg
if arg < min:
min = arg
if max == min:
number =... |
cd149db3fcd7d501916cea410bca3c0d88316d6c | CSC1-1101-TTh9-S21/samplecode | /week3/mathfunctions.py | 1,587 | 4.1875 | 4 | ### SOME COOL MATH FUNCTIONS ###
# This function prints out whether a number is odd or even.
# Argument must be an integer.
def oddoreven(n):
if n % 2 == 0:
print("even")
else:
print("odd")
# This function prints out whether a number greater than 10.
# Argument must be numeric.
def biggerthan1... |
39eaa4fce9294bd2ad996697398e37f735cc4c89 | prajwalpai/tkinter_training | /Frames.py | 671 | 3.5 | 4 | from tkinter import *
window = Tk()
window.title=("Frames")
frame=Frame(window,height=200,width=400,bg='red',bd='3',relief=SUNKEN)
frame.pack(fill=X)
button1=Button(frame,text="Butt1")
button1.pack(side=LEFT,padx=20,pady=20)
button2=Button(frame,text="Butt2")
button2.pack(side=RIGHT,padx=20,pady=20)
searchbar=Label... |
a7ca45c24ff6df499130457516b9721a5d7f598e | sdksfo/leetcode | /medium_275. H-Index II.py | 1,191 | 3.796875 | 4 | """
Move towards the number which will give the max citations possible
"""
# Approach 1 - where we also makes it obvious the thing that we could find something like [5,6] where 2 is hindex
class Solution(object):
def hIndex(self, arr):
"""
:type citations: List[int]
:rtype: int
"""... |
5746557b4817c75bd3193f94be316a8b7c79b9be | seenureddy/problems | /python-problems/counting_capital_give_rank.py | 1,190 | 3.90625 | 4 | """
Give ranking basing on the Capital Letters.
i) If two Capital Letters occurs it will be on top ranking
ii) Don't capital letters keep at bottom of the tables
iii) If capital letters matches then basing on index give ranking (
lowest index will have highest ranking)
INPUT:
------
4
Knight
indian
cHager
daReg
OUT... |
b80735a29cc9ade592a9e1a3b4e6c56146d5c5fb | stosik/coding-challenges | /daily-challenge/1-30/day-22.py | 1,233 | 4.375 | 4 | # This problem was asked by Microsoft.
# Given a dictionary of words and a string made up of those words (no spaces),
# return the original sentence in a list. If there is more than one possible reconstruction,
# return any of them. If there is no possible reconstruction, then return null.
# For example, given the se... |
6f13837ea35bbec037f9bc7144f7ff634268ba44 | AWOLASAP/compSciPrinciples | /python files/assingment7.py | 215 | 3.96875 | 4 | def convert_to_dec(b):
value, total = 1, 0
for i in reversed(str(b)):
if i == '1':
total += value
value *= 2
return total
binary = input("Give me an 8-bit binary number: ")
print(convert_to_dec(binary))
|
d5116f9f60d1175d63bbbb1225ecf8283fa4bf89 | BenFierro1/CSV_project | /sitka_3.py | 2,632 | 3.859375 | 4 | # 1) changing the file to include all the data for the year of 2019
# 2) change the title to - daily and low high temperatures - 2018
# 3) extract low temps from the file and add to chart
# 4) shade in the area between the high and low
import csv
from datetime import datetime
open_file = open("sitka_weather_2018_sim... |
fd73d5c26f9a4e0a0241cba6f558c9dee15192e8 | hujinrunali/LeetCode | /Simple/110_isBalanced.py | 2,094 | 3.734375 | 4 | #题目描述:leetcode110
# 给定一个二叉树,判断它是否是高度平衡的二叉树。
# 本题中,一棵高度平衡二叉树定义为:
# 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
#
# 示例 1:
# 给定二叉树 [3,9,20,null,null,15,7]
# 3
# / \
# 9 20
# / \
# 15 7
# 返回 true 。
#
# 示例 2:
# 给定二叉树 [1,2,2,3,3,null,null,4,4]
# 1
# / \
# 2 2
# / \
# 3 3
# / \
# 4 4
#... |
e6439b914b276fbefa7e1dde95c38f4e60442835 | katlegoJKS/Animals-Part1-OOP-Basics | /cat.py | 270 | 3.6875 | 4 | from animal import Animal
class Cat(Animal):
def __init__(self,name,sound):
super().__init__(name,sound)
def eats(self):
return self.name
def sounds(self):
return "Meow"
cat1 = Cat('','')
#print(cat1.eats())
#print(cat1.sounds()) |
41e7fa64f3225a7c4cef141ea1c5b2c770a941a9 | fudigit/Basic_Algorithm | /3.Two_Pointers/521.Remove_Duplicate_Numbers_in_Array.py | 1,496 | 3.78125 | 4 | class Solution:
"""
@param nums: an array of integers
@return: the number of unique integers
"""
def deduplication(self, nums):
# 1. sort the data first! So the same numbers are together!
# 2. slow pointer points to the last unique integer, fast pointer loop through the
... |
bcde7805d17f554b836fdf4a6ad784f0a773738d | Monisha94-jayamani/guvi | /Looping/#non repeated elements in a list.py | 423 | 3.734375 | 4 | #non repeated elements in a list
n=int(input())
list1=list(map(int,input().split()))
length=len(list1)
rep=[]
nonrep=[]
for i in range(0,length):
for j in range(i+1,length):
if(list1[i]==list1[j]):
rep.append(list1[i])
break
else:
nonrep.append(list1[i])
... |
98389bc53439b19725f6521f0f0b071ecfee2572 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_101_URLS_content.py | 314 | 3.65625 | 4 | """Write a Python program to access and print a URL's content to the console."""
import urllib.request
def my_url_content(path):
return print((urllib.request.urlopen(path).read()))
path = 'https://stackoverflow.com/questions/15138614/how-can-i-read-the-contents-of-an-url-with-python'
my_url_content(path) |
b3e76c4677bd73b07d689eee4294312493c8acab | AdityaAryan-1009/My_Pyfiles | /GAME_BASIC_2.py | 2,238 | 4.0625 | 4 | # CODE FOR SNAKE , WATER , GUN
# MADE BY ADITYA ARYAN
import random
import datetime
def gettime():
a= datetime.datetime.now()
return a
player_1=str(input("Enter your name- "))
ctr=0 # VARIABLE FOR RUNNING WHILE LOOPS FOR FIVE TIMES
a=0 #VARIABLE FOR STORING THE VALUE OF USER WINS
b=0 #VARIABLE FOR STORING ... |
67e80535432a6b7a0ddfd516e113ec71a44763cb | ankitsharma6652/HackerrankPractice | /Data Structures/01. Arrays/001. Arrays - DS.py | 261 | 3.71875 | 4 | # Problem: https://www.hackerrank.com/challenges/arrays-ds/problem
# Score: 10
def reverseArray(arr):
result = arr[::-1]
return result
arrСount = int(input())
arr = list(map(int, input().rstrip().split()))
result = reverseArray(arr)
print(*result)
|
d6953226786206adb286c0925d2e52dfa7442ccc | aatish17varma/algos.py | /trees/tries/lexographicallySort.py | 1,666 | 3.765625 | 4 | '''
Given a list of words sort them lexicographically
'''
dict = [
"lexicographic", "sorting", "of", "a", "set", "of", "keys", "can", "be",
"accomplished", "with", "a", "simple", "trie", "based", "algorithm",
"we", "insert", "all", "keys", "in", "a", "trie", "output", "all",
"keys", "in"... |
305b0c68e30af46b1434284b35ff5d4452ad88ae | haldanuj/EP219 | /linear_expansion.py | 2,900 | 3.765625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import math
file=open('linearexpansion.txt','r')
#code begins for drawing scatter plot of rod's length varying with temperature
#defined 2 lists x and y to store temperature and rod's length repectively
x= []
y =[]
i=0
while i<50:
[num, temp]=file.rea... |
3eb0bf7bdfcfdaa2d8e75998706ec891b63dc0a1 | theBrownBug/Algorithms | /src/python_implementations/sorting/selection_sort.py | 510 | 3.828125 | 4 | import math
def selection_sort(array):
largest = math.inf
for counter in range(0 , len(array)):
to_be_replaced_counter = counter
for counter2 in range(to_be_replaced_counter, len(array)):
if array[counter2] < array[to_be_replaced_counter]:
largest = to_be_replaced_c... |
7e49a3170de178ccebfa22196998f17ec1ae7338 | katharinepires/cursodepython | /estruturas_repeticao_condicional.py | 4,153 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Estruturas Condicionais:
# In[1]:
ava1 = float(input("Informe a nota da AVA1: "))
ava2 = float(input("Informe a nota da AVA2: "))
media = (ava1 + ava2) / 2
if media < 7:
print(f'Aluno foi REPROVADO com média {media}')
else:
print(f'Aluno foi APROVADO com média {med... |
b59e398b445236372b2f25b78731f90a502b5a2e | Oobhuntoo/Matthew_Mills_Portfolio | /Personal Projects/Udemy Machine Learning Course/Templates provided by Udemy for reference/Part 1 - Data Preprocessing Templates/data_preprocessing_template.py | 1,843 | 3.78125 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
#This code uses imputer to look for missing data and replace NaN values with their column's mean
X = dataset.iloc[:, :-1].values
y... |
e220f5214a727271cf55af6b8e666093b72de076 | SungMoY/CSE101 | /CSE 101/labs/CORRECTED-lab-4-starter-files/to submit/friendly.py | 1,391 | 4.03125 | 4 | # Your name: Sung Mo Yang
# Your SBU ID number: 112801117
# Your Stony Brook NetID: sungyang
# CSE 101, Fall 2019
# Lab 4
# In this part of the file it is very important that you ONLY write code inside
# the function below! If you write code anywhere else, then the grading system
# will not be able to read you... |
54f7efa4be54b7bfa4d320fc695d8ebaee3721de | YLyeliang/now_leet_code_practice | /tree/leaf-similar_trees.py | 2,193 | 4.15625 | 4 | # Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
#
# 3
# 5 1
# 6 2 9 8
# 7 4
# For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
#
# Two binary trees are considered leaf-simil... |
6aa7dce5afe7bcb253bd91411645aeb5d99b9783 | AaronLazarusGomes/Leetcode-Average-Levels-in-a-Binary-tree | /code.py | 927 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
hashmap = {}
tree_levels = self.ge... |
f543e6b001e9a068a86d6277d2b887b2d6b55d2b | tuyanshuai/pytorchlearning | /tutorial2.py | 237 | 3.53125 | 4 | """ automatic differenatiation """
import torch
x = torch.randn(3, requires_grad=True)
y = x*2
while y.data.norm() < 1e3:
y = y*2
print(y)
v = torch.tensor([0.1, 1.0, 0.00001], dtype=torch.float)
y.backward(v)
print(x.grad)
|
4a8a41e9917daa0633ccbf13e7b54f45810a9933 | Prince-linux/python_for_everyone | /polls/expenses.py | 288 | 4.03125 | 4 | #An example of a for statement implementation in python
#Author: Prince Oppong Boamah<regioths@gmail.com>
#Date: 1st June, 2021
exp = [800, 1000, 1500, 2000, 3000]
total = 0
for i in range(len(exp)):
print('Month:', (i+1), 'Expenses:', exp[i])
total = total + exp[i]
print('Total expenses:', total)
|
84a2a4de0b61a8a9b9f11f06221a98f36d723a61 | aleciodalpra/aprendizado | /CursoZ/fibonacci.py | 180 | 4 | 4 | # fibonacci de um nro
nro = int(input('Informe um nro: '))
a = 1
b = 1
cont = 1
while cont <= nro - 2:
a, b = b, a + b
cont = cont + 1
print('Fib(%d) = %d' %(nro, b))
|
b68d291f39a32e6d2adbd2a5d6cdb56a1b2b946f | hizkiawilliam/random-python-programs | /dec to oct.py | 274 | 3.921875 | 4 | num_input = int(input("Input integer : "))
num = num_input
rem = []
while num != 0:
rem.append(num % 8)
num = num//8
rem = rem[::-1]
print(num_input,"dec to oct is ",end="")
for i in range(0,len(rem)):
print(rem[i],end="")
print("\n")
|
7ff4de719d9593b1a83aad014e0aa076c82e7027 | Praful-Pasarkar/Praful-Pasarkar | /AI_ML_Project/classifying_images.py | 1,320 | 3.953125 | 4 | # Basic class to read the arguments
# three types of arguments:
# 1. python3 train_test <train object name> abc.jpg
# 2. python3 train_test <train object name> abc.jpg, pqr.jpg, poir.jpg (look at the comma)
# 3. python3 train_test <train object name> abc.jpg pqr.jpr poir.jpg (look at the space can be 1+ spaces)
#... |
312751a704afbbd67d075c635fb27cb6bd11f9eb | Esawyer25/email_cleaner | /Source/main.py | 1,555 | 3.53125 | 4 | from email_address import EmailAddress
from validator import Validator
# replace with path to csv file
INPUT_FILE = "suspicious.csv"
#get emails
unedited_emails = []
with open(INPUT_FILE) as data:
for i, line in enumerate(data):
email = EmailAddress(line, i)
unedited_emails.append(email)
#validat... |
435aaafab7b4c96b161580ef81f2c86928b31e0d | zaynzayn-au/guess_number | /guess_number.py | 299 | 3.59375 | 4 | import random
r = random.randint(1,100)
r = str(r)
while True:
number = input('请猜一下数字是多少吧:')
if number == r:
print('恭喜你猜对了!')
break
else:
if number > r:
print('不对哦,还要再小一点!')
else:
print('不对哦,还要再大一点哦') |
a606862424dc05966b4dd88f33fd29b36e750e76 | alanaalfeche/python-sandbox | /miscellaneous/calculator_revamp.py | 235 | 3.734375 | 4 | print('Welcome to Addition Land.')
while True:
statement = input('input> ')
addends = [addend.strip() for addend in statement.split('+')]
print(sum(map(float if any('.' in addend for addend in addends) else int, addends)))
|
6cb0f00a049f0f7f413d548e4b258ed74e41f697 | bada0707/hellopython | /문제/ch4/pch03ex02.py | 61 | 3.53125 | 4 | a = 'apple' + 'grape'
b= 'apple' * 3
print(a)
print(b)
|
6375bebad18ccb1857de9a87fbd5ff411cbfff41 | miloshIra/webStuff | /Django/flask-login/app.py | 131 | 3.640625 | 4 |
number = "5234111321344446"
for i in range(0,13):
print(i)
print(number[i] == number[i+1] == number[i+2] == number[i+3])
|
306b699ab00f8cb1e5688cab5cc90034f6c16c7b | AlvaroBejar/AMLAssignment-new- | /helper_functions.py | 5,815 | 3.75 | 4 | import matplotlib.pyplot as plt
import numpy as np
import itertools
from sklearn.model_selection import learning_curve
import pandas as pd
import constants
import pickle
# Plots learning curve for model
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=None, train_sizes... |
645ec504bb02f0ec2ce0a49b3a5939f9e27fb902 | voyagerdva/Algorithms | /Lection_13_check_brackets_sequence/Lection_13_back_poland_notation.py | 711 | 3.65625 | 4 | # ==================================================
#
# Lection 13.
#
# asymptotics: O(N)
#
# ==================================================
from module import A_stack
import ast
def isint(item):
try:
int(item)
return True
except ValueError:
return False
def backPolandNotatio... |
9820bfab94b5658860b944ad95feceded2828406 | RoyLizhiyu/Leetocde | /66. Plus One.py | 620 | 3.640625 | 4 | class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
i = len(digits) - 1
while i >= 0:
# set all the nines to zero
if digits[i] == 9:
digits[i] = 0
# m... |
7b003fe2644a3d96388f26c5b46b8b1dbfd413e6 | hahahayden/CPE101 | /LAB5/map.py | 917 | 4.03125 | 4 | #Name: Hayden Tam
# Instructor: S. Einakian
# Class: CPE 101-05
#Signature: list->list
#Purpose: Takes in a list and returns a list that only has positive integers
def are_positive(list):
c=[]
c=[list[x] for x in range(len(list))if (list[x]>0)] #element that goes in the list is first
return c
... |
3a71bd09f1c52d1e83569b0e3c19d533a1d03cfd | KokosTech/Python-Classwork | /18-12-20/rock.py | 765 | 4 | 4 | def rock(p1, p2):
if p1 == "rock":
if p2 == "paper":
return "P2"
elif p2 == "scissors":
return "P1"
elif p2 == "rock":
return "tie"
else:
return "WRONG INPUT BY P2"
elif p1 == "scissors":
if p2 == "rock":
return ... |
9ef687412d3deda130931ed40f66aa34a27cfb3e | MenNianShi/leetcode148 | /数组/121. 买卖股票的最佳时机.py | 993 | 3.515625 | 4 | # 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
#
# 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
#
# 注意你不能在买入股票前卖出股票。
#
# 示例 1:
#
# 输入: [7,1,5,3,6,4]
# 输出: 5
# 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
# 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
class Solution(object):
def maxProfit(self, prices):
... |
e17a619c585a9dfc932c43a322b938b6b70b8386 | Adanel/ReinforcementLearningProject | /ESS.py | 2,928 | 3.515625 | 4 | import numpy as np
import random
import pickle
from time import time
class Game:
def __init__(self, levels, nb_pieces, init_bottom=False):
self.levels = levels
self.nb_pieces = nb_pieces
self.locations = np.zeros(self.levels)
if init_bottom:
self.l... |
e2a6a0cd721a99c26efcb258ab86cb8422d55bc3 | sjs7007/Algorithm-Implementations | /Merge_Sort/merge_sort.py | 328 | 3.703125 | 4 | # this is a python example of a mergesort generator
# (list.sort() is much faster)
from heapq import merge
def merge_sort(foo):
length = len(foo)
first_half = merge_sort(foo[:length/2]) if length > 1 else foo
second_half = merge_sort(foo[length/2:]) if length > 1 else []
return merge(first_half, secon... |
af938c3303b1f4015ded1a6823ec9662341da400 | piroquai/python | /task3.py | 438 | 3.5 | 4 | random_list = [5, 0, 10, 6, 1, 0, 3, -7, 4, 2]
print(random_list)
def func1(list):
for x in range(len(random_list)):
if random_list[x] == 0:
last_zero_pos = x
num = 0
summa = 0
for x in range(last_zero_pos, len(random_list)):
if random_list[x] > 0:
s... |
bc58a72a5e47874b79e47bc39732ad7359ac8162 | YusiZhang/leetcode-python | /python-builtin/MapReduce.py | 715 | 4.28125 | 4 | if __name__ == '__main__':
# map() can be applied to more than one list.
# The lists have to have the same length.
# map() will apply its lambda function to the elements of the argument lists,
# i.e. it first applies to the elements with the 0th index,
# then to the elements with the 1st index until... |
20477d142248fdec3c497f5defb24f96559f4f5c | Bhaktibj/Python_Programs | /DataStructure/Calender.py | 605 | 3.640625 | 4 | from Week2.Utility_ds.utilitis import Cal_Methods
def calendar_runner():
"""
THIS METHOD DISPLAYS THE CALENDAR
"""
logic_obj = Cal_Methods() # creating object of the method class
try:
month = int(input('Enter month: ')) # enter the month number
except ValueError:
print("En... |
2a67eb9df39bead4057500cbdbaa6e930676c222 | pawanyaddanapudi/python-for-beginners | /PFB_Session8.py | 1,235 | 3.984375 | 4 | ############ FOR loops ######################
orskl_List = [ 10, 20, 30, 40, 50]
orskl_list2 = []
for list_element in orskl_List:
print(list_element)
orskl_list2 += [list_element*3]
orskl_list2
list_element
Orskl_List2 = ["Hello", "ORSKL", "Class", "Python"]
for var1 in Orskl_List2:
print(var1)
range... |
046d3558bc3491f890ccae2943c72cee7a819729 | renacin/GradientDescent_From_Scratch | /Practice/GD_Basics.py | 6,638 | 4.15625 | 4 | # Name: Renacin Matadeen
# Student Number: N/A
# Date: 09/21/2018
# Course: N/A
# Title Understanding Gradien... |
8115dc502e15b34facb1c3382dae93d22cf4b4f5 | imedqq/Contextual-Chatbot | /model.py | 797 | 3.96875 | 4 | import torch
import torch.nn as nn
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
# create three linear layers
self.l1 = nn.Linear(input_size, hidden_size)
self.l2 = nn.Linear(hidden_size, hidden_size)
self.l3 = nn.Linear(hidden_size, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.